code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
perl Tie::RefHash Tie::RefHash
============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE](#EXAMPLE)
* [THREAD SUPPORT](#THREAD-SUPPORT)
* [STORABLE SUPPORT](#STORABLE-SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [AUTHORS](#AUTHORS)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENCE](#COPYRIGHT-AND-LICENCE)
NAME
----
Tie::RefHash - Use references as hash keys
VERSION
-------
version 1.40
SYNOPSIS
--------
```
require 5.004;
use Tie::RefHash;
tie HASHVARIABLE, 'Tie::RefHash', LIST;
tie HASHVARIABLE, 'Tie::RefHash::Nestable', LIST;
untie HASHVARIABLE;
```
DESCRIPTION
-----------
This module provides the ability to use references as hash keys if you first `tie` the hash variable to this module. Normally, only the keys of the tied hash itself are preserved as references; to use references as keys in hashes-of-hashes, use Tie::RefHash::Nestable, included as part of Tie::RefHash.
It is implemented using the standard perl TIEHASH interface. Please see the `tie` entry in perlfunc(1) and perltie(1) for more information.
The Nestable version works by looking for hash references being stored and converting them to tied hashes so that they too can have references as keys. This will happen without warning whenever you store a reference to one of your own hashes in the tied hash.
EXAMPLE
-------
```
use Tie::RefHash;
tie %h, 'Tie::RefHash';
$a = [];
$b = {};
$c = \*main;
$d = \"gunk";
$e = sub { 'foo' };
%h = ($a => 1, $b => 2, $c => 3, $d => 4, $e => 5);
$a->[0] = 'foo';
$b->{foo} = 'bar';
for (keys %h) {
print ref($_), "\n";
}
tie %h, 'Tie::RefHash::Nestable';
$h{$a}->{$b} = 1;
for (keys %h, keys %{$h{$a}}) {
print ref($_), "\n";
}
```
THREAD SUPPORT
---------------
<Tie::RefHash> fully supports threading using the `CLONE` method.
STORABLE SUPPORT
-----------------
[Storable](storable) hooks are provided for semantically correct serialization and cloning of tied refhashes.
SEE ALSO
---------
perl(1), perlfunc(1), perltie(1)
SUPPORT
-------
Bugs may be submitted through [the RT bug tracker](https://rt.cpan.org/Public/Dist/Display.html?Name=Tie-RefHash) (or [[email protected]](mailto:[email protected])).
AUTHORS
-------
Gurusamy Sarathy <[email protected]>
Tie::RefHash::Nestable by Ed Avis <[email protected]>
CONTRIBUTORS
------------
* Yuval Kogman <[email protected]>
* Karen Etheridge <[email protected]>
* Florian Ragwitz <[email protected]>
* Jerry D. Hedden <[email protected]>
COPYRIGHT AND LICENCE
----------------------
This software is copyright (c) 2006 by ืืืื ืงืื'ืื (Yuval Kogman) <[email protected]>.
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 MIME::Base64 MIME::Base64
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
MIME::Base64 - Encoding and decoding of base64 strings
SYNOPSIS
--------
```
use MIME::Base64;
$encoded = encode_base64('Aladdin:open sesame');
$decoded = decode_base64($encoded);
```
DESCRIPTION
-----------
This module provides functions to encode and decode strings into and from the base64 encoding specified in RFC 2045 - *MIME (Multipurpose Internet Mail Extensions)*. The base64 encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable. A 65-character subset ([A-Za-z0-9+/=]) of US-ASCII is used, enabling 6 bits to be represented per printable character.
The following primary functions are provided:
encode\_base64( $bytes )
encode\_base64( $bytes, $eol ); Encode data by calling the encode\_base64() function. The first argument is the byte string to encode. The second argument is the line-ending sequence to use. It is optional and defaults to "\n". The returned encoded string is broken into lines of no more than 76 characters each and it will end with $eol unless it is empty. Pass an empty string as second argument if you do not want the encoded string to be broken into lines.
The function will croak with "Wide character in subroutine entry" if $bytes contains characters with code above 255. The base64 encoding is only defined for single-byte characters. Use the Encode module to select the byte encoding you want.
decode\_base64( $str ) Decode a base64 string by calling the decode\_base64() function. This function takes a single argument which is the string to decode and returns the decoded data.
Any character not part of the 65-character base64 subset is silently ignored. Characters occurring after a '=' padding character are never decoded.
If you prefer not to import these routines into your namespace, you can call them as:
```
use MIME::Base64 ();
$encoded = MIME::Base64::encode($decoded);
$decoded = MIME::Base64::decode($encoded);
```
Additional functions not exported by default:
encode\_base64url( $bytes )
decode\_base64url( $str ) Encode and decode according to the base64 scheme for "URL applications" [1]. This is a variant of the base64 encoding which does not use padding, does not break the string into multiple lines and use the characters "-" and "\_" instead of "+" and "/" to avoid using reserved URL characters.
encoded\_base64\_length( $bytes )
encoded\_base64\_length( $bytes, $eol ) Returns the length that the encoded string would have without actually encoding it. This will return the same value as `length(encode_base64($bytes))`, but should be more efficient.
decoded\_base64\_length( $str ) Returns the length that the decoded string would have without actually decoding it. This will return the same value as `length(decode_base64($str))`, but should be more efficient.
EXAMPLES
--------
If you want to encode a large file, you should encode it in chunks that are a multiple of 57 bytes. This ensures that the base64 lines line up and that you do not end up with padding in the middle. 57 bytes of data fills one complete base64 line (76 == 57\*4/3):
```
use MIME::Base64 qw(encode_base64);
open(FILE, "/var/log/wtmp") or die "$!";
while (read(FILE, $buf, 60*57)) {
print encode_base64($buf);
}
```
or if you know you have enough memory
```
use MIME::Base64 qw(encode_base64);
local($/) = undef; # slurp
print encode_base64(<STDIN>);
```
The same approach as a command line:
```
perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' <file
```
Decoding does not need slurp mode if every line contains a multiple of four base64 chars:
```
perl -MMIME::Base64 -ne 'print decode_base64($_)' <file
```
Perl v5.8 and better allow extended Unicode characters in strings. Such strings cannot be encoded directly, as the base64 encoding is only defined for single-byte characters. The solution is to use the Encode module to select the byte encoding you want. For example:
```
use MIME::Base64 qw(encode_base64);
use Encode qw(encode);
$encoded = encode_base64(encode("UTF-8", "\x{FFFF}\n"));
print $encoded;
```
COPYRIGHT
---------
Copyright 1995-1999, 2001-2004, 2010 Gisle Aas.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Distantly based on LWP::Base64 written by Martijn Koster <[email protected]> and Joerg Reichelt <[email protected]> and code posted to comp.lang.perl <[email protected]> by Hans Mulder <[email protected]>
The XS implementation uses code from metamail. Copyright 1991 Bell Communications Research, Inc. (Bellcore)
SEE ALSO
---------
<MIME::QuotedPrint>
[1] <http://en.wikipedia.org/wiki/Base64#URL_applications>
perl TAP::Parser::Result::Bailout TAP::Parser::Result::Bailout
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDDEN METHODS](#OVERRIDDEN-METHODS)
+ [Instance Methods](#Instance-Methods)
- [explanation](#explanation)
NAME
----
TAP::Parser::Result::Bailout - Bailout 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 bail out line is encountered.
```
1..5
ok 1 - woo hooo!
Bail out! Well, so much for "woo hooo!"
```
OVERRIDDEN METHODS
-------------------
Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night.
* `as_string`
###
Instance Methods
#### `explanation`
```
if ( $result->is_bailout ) {
my $explanation = $result->explanation;
print "We bailed out because ($explanation)";
}
```
If, and only if, a token is a bailout token, you can get an "explanation" via this method. The explanation is the text after the mystical "Bail out!" words which appear in the tap output.
perl Test2::Event::Fail Test2::Event::Fail
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Fail - Event for a simple failed assertion
DESCRIPTION
-----------
This is an optimal representation of a failed assertion.
SYNOPSIS
--------
```
use Test2::API qw/context/;
sub fail {
my ($name) = @_;
my $ctx = context();
$ctx->fail($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 Unicode::UCD Unicode::UCD
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [code point argument](#code-point-argument)
+ [charinfo()](#charinfo())
+ [charprop()](#charprop())
+ [charprops\_all()](#charprops_all())
+ [charblock()](#charblock())
+ [charscript()](#charscript())
+ [charblocks()](#charblocks())
+ [charscripts()](#charscripts())
+ [charinrange()](#charinrange())
+ [general\_categories()](#general_categories())
+ [bidi\_types()](#bidi_types())
+ [compexcl()](#compexcl())
+ [casefold()](#casefold())
+ [all\_casefolds()](#all_casefolds())
+ [casespec()](#casespec())
+ [namedseq()](#namedseq())
+ [num()](#num())
+ [prop\_aliases()](#prop_aliases())
+ [prop\_values()](#prop_values())
+ [prop\_value\_aliases()](#prop_value_aliases())
+ [prop\_invlist()](#prop_invlist())
+ [prop\_invmap()](#prop_invmap())
- [Getting every available name](#Getting-every-available-name)
+ [search\_invlist()](#search_invlist())
+ [Unicode::UCD::UnicodeVersion](#Unicode::UCD::UnicodeVersion)
+ [Blocks versus Scripts](#Blocks-versus-Scripts)
+ [Matching Scripts and Blocks](#Matching-Scripts-and-Blocks)
+ [Old-style versus new-style block names](#Old-style-versus-new-style-block-names)
+ [Use with older Unicode versions](#Use-with-older-Unicode-versions)
* [AUTHOR](#AUTHOR)
NAME
----
Unicode::UCD - Unicode character database
SYNOPSIS
--------
```
use Unicode::UCD 'charinfo';
my $charinfo = charinfo($codepoint);
use Unicode::UCD 'charprop';
my $value = charprop($codepoint, $property);
use Unicode::UCD 'charprops_all';
my $all_values_hash_ref = charprops_all($codepoint);
use Unicode::UCD 'casefold';
my $casefold = casefold($codepoint);
use Unicode::UCD 'all_casefolds';
my $all_casefolds_ref = all_casefolds();
use Unicode::UCD 'casespec';
my $casespec = casespec($codepoint);
use Unicode::UCD 'charblock';
my $charblock = charblock($codepoint);
use Unicode::UCD 'charscript';
my $charscript = charscript($codepoint);
use Unicode::UCD 'charblocks';
my $charblocks = charblocks();
use Unicode::UCD 'charscripts';
my $charscripts = charscripts();
use Unicode::UCD qw(charscript charinrange);
my $range = charscript($script);
print "looks like $script\n" if charinrange($range, $codepoint);
use Unicode::UCD qw(general_categories bidi_types);
my $categories = general_categories();
my $types = bidi_types();
use Unicode::UCD 'prop_aliases';
my @space_names = prop_aliases("space");
use Unicode::UCD 'prop_value_aliases';
my @gc_punct_names = prop_value_aliases("Gc", "Punct");
use Unicode::UCD 'prop_values';
my @all_EA_short_names = prop_values("East_Asian_Width");
use Unicode::UCD 'prop_invlist';
my @puncts = prop_invlist("gc=punctuation");
use Unicode::UCD 'prop_invmap';
my ($list_ref, $map_ref, $format, $missing)
= prop_invmap("General Category");
use Unicode::UCD 'search_invlist';
my $index = search_invlist(\@invlist, $code_point);
# The following function should be used only internally in
# implementations of the Unicode Normalization Algorithm, and there
# are better choices than it.
use Unicode::UCD 'compexcl';
my $compexcl = compexcl($codepoint);
use Unicode::UCD 'namedseq';
my $namedseq = namedseq($named_sequence_name);
my $unicode_version = Unicode::UCD::UnicodeVersion();
my $convert_to_numeric =
Unicode::UCD::num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
```
DESCRIPTION
-----------
The Unicode::UCD module offers a series of functions that provide a simple interface to the Unicode Character Database.
###
code point argument
Some of the functions are called with a *code point argument*, which is either a decimal or a hexadecimal scalar designating a code point in the platform's native character set (extended to Unicode), or a string containing `U+` followed by hexadecimals designating a Unicode code point. A leading 0 will force a hexadecimal interpretation, as will a hexadecimal digit that isn't a decimal digit.
Examples:
```
223 # Decimal 223 in native character set
0223 # Hexadecimal 223, native (= 547 decimal)
0xDF # Hexadecimal DF, native (= 223 decimal)
'0xDF' # String form of hexadecimal (= 223 decimal)
'U+DF' # Hexadecimal DF, in Unicode's character set
(= LATIN SMALL LETTER SHARP S)
```
Note that the largest code point in Unicode is U+10FFFF.
###
**charinfo()**
```
use Unicode::UCD 'charinfo';
my $charinfo = charinfo(0x41);
```
This returns information about the input ["code point argument"](#code-point-argument) as a reference to a hash of fields as defined by the Unicode standard. If the ["code point argument"](#code-point-argument) is not assigned in the standard (i.e., has the general category `Cn` meaning `Unassigned`) or is a non-character (meaning it is guaranteed to never be assigned in the standard), `undef` is returned.
Fields that aren't applicable to the particular code point argument exist in the returned hash, and are empty.
For results that are less "raw" than this function returns, or to get the values for any property, not just the few covered by this function, use the ["charprop()"](#charprop%28%29) function.
The keys in the hash with the meanings of their values are:
**code** the input native ["code point argument"](#code-point-argument) expressed in hexadecimal, with leading zeros added if necessary to make it contain at least four hexdigits
**name** name of *code*, all IN UPPER CASE. Some control-type code points do not have names. This field will be empty for `Surrogate` and `Private Use` code points, and for the others without a name, it will contain a description enclosed in angle brackets, like `<control>`.
**category** The short name of the general category of *code*. This will match one of the keys in the hash returned by ["general\_categories()"](#general_categories%28%29).
The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the category name.
**combining** the combining class number for *code* used in the Canonical Ordering Algorithm. For Unicode 5.1, this is described in Section 3.11 `Canonical Ordering Behavior` available at <http://www.unicode.org/versions/Unicode5.1.0/>
The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the combining class number.
**bidi** bidirectional type of *code*. This will match one of the keys in the hash returned by ["bidi\_types()"](#bidi_types%28%29).
The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the bidi type name.
**decomposition** is empty if *code* has no decomposition; or is one or more codes (separated by spaces) that, taken in order, represent a decomposition for *code*. Each has at least four hexdigits. The codes may be preceded by a word enclosed in angle brackets, then a space, like `<compat>` , giving the type of decomposition
This decomposition may be an intermediate one whose components are also decomposable. Use <Unicode::Normalize> to get the final decomposition in one step.
**decimal** if *code* represents a decimal digit this is its integer numeric value
**digit** if *code* represents some other digit-like number, this is its integer numeric value
**numeric** if *code* represents a whole or rational number, this is its numeric value. Rational values are expressed as a string like `1/4`.
**mirrored** `Y` or `N` designating if *code* is mirrored in bidirectional text
**unicode10** name of *code* in the Unicode 1.0 standard if one existed for this code point and is different from the current name
**comment** As of Unicode 6.0, this is always empty.
**upper** is, if non-empty, the uppercase mapping for *code* expressed as at least four hexdigits. This indicates that the full uppercase mapping is a single character, and is identical to the simple (single-character only) mapping. When this field is empty, it means that the simple uppercase mapping is *code* itself; you'll need some other means, (like ["charprop()"](#charprop%28%29) or ["casespec()"](#casespec%28%29) to get the full mapping.
**lower** is, if non-empty, the lowercase mapping for *code* expressed as at least four hexdigits. This indicates that the full lowercase mapping is a single character, and is identical to the simple (single-character only) mapping. When this field is empty, it means that the simple lowercase mapping is *code* itself; you'll need some other means, (like ["charprop()"](#charprop%28%29) or ["casespec()"](#casespec%28%29) to get the full mapping.
**title** is, if non-empty, the titlecase mapping for *code* expressed as at least four hexdigits. This indicates that the full titlecase mapping is a single character, and is identical to the simple (single-character only) mapping. When this field is empty, it means that the simple titlecase mapping is *code* itself; you'll need some other means, (like ["charprop()"](#charprop%28%29) or ["casespec()"](#casespec%28%29) to get the full mapping.
**block** the block *code* belongs to (used in `\p{Blk=...}`). The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the block name.
See ["Blocks versus Scripts"](#Blocks-versus-Scripts).
**script** the script *code* belongs to. The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the script name. Note that this is the older "Script" property value, and not the improved "Script\_Extensions" value.
See ["Blocks versus Scripts"](#Blocks-versus-Scripts).
Note that you cannot do (de)composition and casing based solely on the *decomposition*, *combining*, *lower*, *upper*, and *title* fields; you will need also the ["casespec()"](#casespec%28%29) function and the `Composition_Exclusion` property. (Or you could just use the [lc()](perlfunc#lc), [uc()](perlfunc#uc), and [ucfirst()](perlfunc#ucfirst) functions, and the <Unicode::Normalize> module.)
###
**charprop()**
```
use Unicode::UCD 'charprop';
print charprop(0x41, "Gc"), "\n";
print charprop(0x61, "General_Category"), "\n";
prints
Lu
Ll
```
This returns the value of the Unicode property given by the second parameter for the ["code point argument"](#code-point-argument) given by the first.
The passed-in property may be specified as any of the synonyms returned by ["prop\_aliases()"](#prop_aliases%28%29).
The return value is always a scalar, either a string or a number. For properties where there are synonyms for the values, the synonym returned by this function is the longest, most descriptive form, the one returned by ["prop\_value\_aliases()"](#prop_value_aliases%28%29) when called in a scalar context. Of course, you can call ["prop\_value\_aliases()"](#prop_value_aliases%28%29) on the result to get other synonyms.
The return values are more "cooked" than the ["charinfo()"](#charinfo%28%29) ones. For example, the `"uc"` property value is the actual string containing the full uppercase mapping of the input code point. You have to go to extra trouble with `charinfo` to get this value from its `upper` hash element when the full mapping differs from the simple one.
Special note should be made of the return values for a few properties:
Block The value returned is the new-style (see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
Decomposition\_Mapping Like ["charinfo()"](#charinfo%28%29), the result may be an intermediate decomposition whose components are also decomposable. Use <Unicode::Normalize> to get the final decomposition in one step.
Unlike ["charinfo()"](#charinfo%28%29), this does not include the decomposition type. Use the `Decomposition_Type` property to get that.
Name\_Alias If the input code point's name has more than one synonym, they are returned joined into a single comma-separated string.
Numeric\_Value If the result is a fraction, it is converted into a floating point number to the accuracy of your platform.
Script\_Extensions If the result is multiple script names, they are returned joined into a single comma-separated string.
When called with a property that is a Perl extension that isn't expressible in a compound form, this function currently returns `undef`, as the only two possible values are *true* or *false* (1 or 0 I suppose). This behavior may change in the future, so don't write code that relies on it. `Present_In` is a Perl extension that is expressible in a bipartite or compound form (for example, `\p{Present_In=4.0}`), so `charprop` accepts it. But `Any` is a Perl extension that isn't expressible that way, so `charprop` returns `undef` for it. Also `charprop` returns `undef` for all Perl extensions that are internal-only.
###
**charprops\_all()**
```
use Unicode::UCD 'charprops_all';
my $%properties_of_A_hash_ref = charprops_all("U+41");
```
This returns a reference to a hash whose keys are all the distinct Unicode (no Perl extension) properties, and whose values are the respective values for those properties for the input ["code point argument"](#code-point-argument).
Each key is the property name in its longest, most descriptive form. The values are what ["charprop()"](#charprop%28%29) would return.
This function is expensive in time and memory.
###
**charblock()**
```
use Unicode::UCD 'charblock';
my $charblock = charblock(0x41);
my $charblock = charblock(1234);
my $charblock = charblock(0x263a);
my $charblock = charblock("U+263a");
my $range = charblock('Armenian');
```
With a ["code point argument"](#code-point-argument) `charblock()` returns the *block* the code point belongs to, e.g. `Basic Latin`. The old-style block name is returned (see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)). The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the block name.
If the code point is unassigned, this returns the block it would belong to if it were assigned. (If the Unicode version being used is so early as to not have blocks, all code points are considered to be in `No_Block`.)
See also ["Blocks versus Scripts"](#Blocks-versus-Scripts).
If supplied with an argument that can't be a code point, `charblock()` tries to do the opposite and interpret the argument as an old-style block name. On an ASCII platform, the return value is a *range set* with one range: an anonymous array with a single element that consists of another anonymous array whose first element is the first code point in the block, and whose second element is the final code point in the block. On an EBCDIC platform, the first two Unicode blocks are not contiguous. Their range sets are lists containing *start-of-range*, *end-of-range* code point pairs. You can test whether a code point is in a range set using the ["charinrange()"](#charinrange%28%29) function. (To be precise, each *range set* contains a third array element, after the range boundary ones: the old\_style block name.)
If the argument to `charblock()` is not a known block, `undef` is returned.
###
**charscript()**
```
use Unicode::UCD 'charscript';
my $charscript = charscript(0x41);
my $charscript = charscript(1234);
my $charscript = charscript("U+263a");
my $range = charscript('Thai');
```
With a ["code point argument"](#code-point-argument), `charscript()` returns the *script* the code point belongs to, e.g., `Latin`, `Greek`, `Han`. If the code point is unassigned or the Unicode version being used is so early that it doesn't have scripts, this function returns `"Unknown"`. The ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function can be used to get all the synonyms of the script name.
Note that the Script\_Extensions property is an improved version of the Script property, and you should probably be using that instead, with the ["charprop()"](#charprop%28%29) function.
If supplied with an argument that can't be a code point, charscript() tries to do the opposite and interpret the argument as a script name. The return value is a *range set*: an anonymous array of arrays that contain *start-of-range*, *end-of-range* code point pairs. You can test whether a code point is in a range set using the ["charinrange()"](#charinrange%28%29) function. (To be precise, each *range set* contains a third array element, after the range boundary ones: the script name.)
If the `charscript()` argument is not a known script, `undef` is returned.
See also ["Blocks versus Scripts"](#Blocks-versus-Scripts).
###
**charblocks()**
```
use Unicode::UCD 'charblocks';
my $charblocks = charblocks();
```
`charblocks()` returns a reference to a hash with the known block names as the keys, and the code point ranges (see ["charblock()"](#charblock%28%29)) as the values.
The names are in the old-style (see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
[prop\_invmap("block")](#prop_invmap%28%29) can be used to get this same data in a different type of data structure.
[prop\_values("Block")](#prop_values%28%29) can be used to get all the known new-style block names as a list, without the code point ranges.
See also ["Blocks versus Scripts"](#Blocks-versus-Scripts).
###
**charscripts()**
```
use Unicode::UCD 'charscripts';
my $charscripts = charscripts();
```
`charscripts()` returns a reference to a hash with the known script names as the keys, and the code point ranges (see ["charscript()"](#charscript%28%29)) as the values.
[prop\_invmap("script")](#prop_invmap%28%29) can be used to get this same data in a different type of data structure. Since the Script\_Extensions property is an improved version of the Script property, you should instead use [prop\_invmap("scx")](#prop_invmap%28%29).
[`prop_values("Script")`](#prop_values%28%29) can be used to get all the known script names as a list, without the code point ranges.
See also ["Blocks versus Scripts"](#Blocks-versus-Scripts).
###
**charinrange()**
In addition to using the `\p{Blk=...}` and `\P{Blk=...}` constructs, you can also test whether a code point is in the *range* as returned by ["charblock()"](#charblock%28%29) and ["charscript()"](#charscript%28%29) or as the values of the hash returned by ["charblocks()"](#charblocks%28%29) and ["charscripts()"](#charscripts%28%29) by using `charinrange()`:
```
use Unicode::UCD qw(charscript charinrange);
$range = charscript('Hiragana');
print "looks like hiragana\n" if charinrange($range, $codepoint);
```
###
**general\_categories()**
```
use Unicode::UCD 'general_categories';
my $categories = general_categories();
```
This returns a reference to a hash which has short general category names (such as `Lu`, `Nd`, `Zs`, `S`) as keys and long names (such as `UppercaseLetter`, `DecimalNumber`, `SpaceSeparator`, `Symbol`) as values. The hash is reversible in case you need to go from the long names to the short names. The general category is the one returned from ["charinfo()"](#charinfo%28%29) under the `category` key.
The ["prop\_values()"](#prop_values%28%29) and ["prop\_value\_aliases()"](#prop_value_aliases%28%29) functions can be used as an alternative to this function; the first returning a simple list of the short category names; and the second gets all the synonyms of a given category name.
###
**bidi\_types()**
```
use Unicode::UCD 'bidi_types';
my $categories = bidi_types();
```
This returns a reference to a hash which has the short bidi (bidirectional) type names (such as `L`, `R`) as keys and long names (such as `Left-to-Right`, `Right-to-Left`) as values. The hash is reversible in case you need to go from the long names to the short names. The bidi type is the one returned from ["charinfo()"](#charinfo%28%29) under the `bidi` key. For the exact meaning of the various bidi classes the Unicode TR9 is recommended reading: <http://www.unicode.org/reports/tr9/> (as of Unicode 5.0.0)
The ["prop\_values()"](#prop_values%28%29) and ["prop\_value\_aliases()"](#prop_value_aliases%28%29) functions can be used as an alternative to this function; the first returning a simple list of the short bidi type names; and the second gets all the synonyms of a given bidi type name.
###
**compexcl()**
WARNING: Unicode discourages the use of this function or any of the alternative mechanisms listed in this section (the documentation of `compexcl()`), except internally in implementations of the Unicode Normalization Algorithm. You should be using <Unicode::Normalize> directly instead of these. Using these will likely lead to half-baked results.
```
use Unicode::UCD 'compexcl';
my $compexcl = compexcl(0x09dc);
```
This routine returns `undef` if the Unicode version being used is so early that it doesn't have this property.
`compexcl()` is included for backwards compatibility, but as of Perl 5.12 and more modern Unicode versions, for most purposes it is probably more convenient to use one of the following instead:
```
my $compexcl = chr(0x09dc) =~ /\p{Comp_Ex};
my $compexcl = chr(0x09dc) =~ /\p{Full_Composition_Exclusion};
```
or even
```
my $compexcl = chr(0x09dc) =~ /\p{CE};
my $compexcl = chr(0x09dc) =~ /\p{Composition_Exclusion};
```
The first two forms return **true** if the ["code point argument"](#code-point-argument) should not be produced by composition normalization. For the final two forms to return **true**, it is additionally required that this fact not otherwise be determinable from the Unicode data base.
This routine behaves identically to the final two forms. That is, it does not return **true** if the code point has a decomposition consisting of another single code point, nor if its decomposition starts with a code point whose combining class is non-zero. Code points that meet either of these conditions should also not be produced by composition normalization, which is probably why you should use the `Full_Composition_Exclusion` property instead, as shown above.
The routine returns **false** otherwise.
###
**casefold()**
```
use Unicode::UCD 'casefold';
my $casefold = casefold(0xDF);
if (defined $casefold) {
my @full_fold_hex = split / /, $casefold->{'full'};
my $full_fold_string =
join "", map {chr(hex($_))} @full_fold_hex;
my @turkic_fold_hex =
split / /, ($casefold->{'turkic'} ne "")
? $casefold->{'turkic'}
: $casefold->{'full'};
my $turkic_fold_string =
join "", map {chr(hex($_))} @turkic_fold_hex;
}
if (defined $casefold && $casefold->{'simple'} ne "") {
my $simple_fold_hex = $casefold->{'simple'};
my $simple_fold_string = chr(hex($simple_fold_hex));
}
```
This returns the (almost) locale-independent case folding of the character specified by the ["code point argument"](#code-point-argument). (Starting in Perl v5.16, the core function `fc()` returns the `full` mapping (described below) faster than this does, and for entire strings.)
If there is no case folding for the input code point, `undef` is returned.
If there is a case folding for that code point, a reference to a hash with the following fields is returned:
**code** the input native ["code point argument"](#code-point-argument) expressed in hexadecimal, with leading zeros added if necessary to make it contain at least four hexdigits
**full** one or more codes (separated by spaces) that, taken in order, give the code points for the case folding for *code*. Each has at least four hexdigits.
**simple** is empty, or is exactly one code with at least four hexdigits which can be used as an alternative case folding when the calling program cannot cope with the fold being a sequence of multiple code points. If *full* is just one code point, then *simple* equals *full*. If there is no single code point folding defined for *code*, then *simple* is the empty string. Otherwise, it is an inferior, but still better-than-nothing alternative folding to *full*.
**mapping** is the same as *simple* if *simple* is not empty, and it is the same as *full* otherwise. It can be considered to be the simplest possible folding for *code*. It is defined primarily for backwards compatibility.
**status** is `C` (for `common`) if the best possible fold is a single code point (*simple* equals *full* equals *mapping*). It is `S` if there are distinct folds, *simple* and *full* (*mapping* equals *simple*). And it is `F` if there is only a *full* fold (*mapping* equals *full*; *simple* is empty). Note that this describes the contents of *mapping*. It is defined primarily for backwards compatibility.
For Unicode versions between 3.1 and 3.1.1 inclusive, *status* can also be `I` which is the same as `C` but is a special case for dotted uppercase I and dotless lowercase i:
**\*** If you use this `I` mapping the result is case-insensitive, but dotless and dotted I's are not distinguished
**\*** If you exclude this `I` mapping the result is not fully case-insensitive, but dotless and dotted I's are distinguished
**turkic** contains any special folding for Turkic languages. For versions of Unicode starting with 3.2, this field is empty unless *code* has a different folding in Turkic languages, in which case it is one or more codes (separated by spaces) that, taken in order, give the code points for the case folding for *code* in those languages. Each code has at least four hexdigits. Note that this folding does not maintain canonical equivalence without additional processing.
For Unicode versions between 3.1 and 3.1.1 inclusive, this field is empty unless there is a special folding for Turkic languages, in which case *status* is `I`, and *mapping*, *full*, *simple*, and *turkic* are all equal.
Programs that want complete generality and the best folding results should use the folding contained in the *full* field. But note that the fold for some code points will be a sequence of multiple code points.
Programs that can't cope with the fold mapping being multiple code points can use the folding contained in the *simple* field, with the loss of some generality. In Unicode 5.1, about 7% of the defined foldings have no single code point folding.
The *mapping* and *status* fields are provided for backwards compatibility for existing programs. They contain the same values as in previous versions of this function.
Locale is not completely independent. The *turkic* field contains results to use when the locale is a Turkic language.
For more information about case mappings see <http://www.unicode.org/reports/tr21>
###
**all\_casefolds()**
```
use Unicode::UCD 'all_casefolds';
my $all_folds_ref = all_casefolds();
foreach my $char_with_casefold (sort { $a <=> $b }
keys %$all_folds_ref)
{
printf "%04X:", $char_with_casefold;
my $casefold = $all_folds_ref->{$char_with_casefold};
# Get folds for $char_with_casefold
my @full_fold_hex = split / /, $casefold->{'full'};
my $full_fold_string =
join "", map {chr(hex($_))} @full_fold_hex;
print " full=", join " ", @full_fold_hex;
my @turkic_fold_hex =
split / /, ($casefold->{'turkic'} ne "")
? $casefold->{'turkic'}
: $casefold->{'full'};
my $turkic_fold_string =
join "", map {chr(hex($_))} @turkic_fold_hex;
print "; turkic=", join " ", @turkic_fold_hex;
if (defined $casefold && $casefold->{'simple'} ne "") {
my $simple_fold_hex = $casefold->{'simple'};
my $simple_fold_string = chr(hex($simple_fold_hex));
print "; simple=$simple_fold_hex";
}
print "\n";
}
```
This returns all the case foldings in the current version of Unicode in the form of a reference to a hash. Each key to the hash is the decimal representation of a Unicode character that has a casefold to other than itself. The casefold of a semi-colon is itself, so it isn't in the hash; likewise for a lowercase "a", but there is an entry for a capital "A". The hash value for each key is another hash, identical to what is returned by ["casefold()"](#casefold%28%29) if called with that code point as its argument. So the value `all_casefolds()->{ord("A")}'` is equivalent to `casefold(ord("A"))`;
###
**casespec()**
```
use Unicode::UCD 'casespec';
my $casespec = casespec(0xFB00);
```
This returns the potentially locale-dependent case mappings of the ["code point argument"](#code-point-argument). The mappings may be longer than a single code point (which the basic Unicode case mappings as returned by ["charinfo()"](#charinfo%28%29) never are).
If there are no case mappings for the ["code point argument"](#code-point-argument), or if all three possible mappings (*lower*, *title* and *upper*) result in single code points and are locale independent and unconditional, `undef` is returned (which means that the case mappings, if any, for the code point are those returned by ["charinfo()"](#charinfo%28%29)).
Otherwise, a reference to a hash giving the mappings (or a reference to a hash of such hashes, explained below) is returned with the following keys and their meanings:
The keys in the bottom layer hash with the meanings of their values are:
**code** the input native ["code point argument"](#code-point-argument) expressed in hexadecimal, with leading zeros added if necessary to make it contain at least four hexdigits
**lower** one or more codes (separated by spaces) that, taken in order, give the code points for the lower case of *code*. Each has at least four hexdigits.
**title** one or more codes (separated by spaces) that, taken in order, give the code points for the title case of *code*. Each has at least four hexdigits.
**upper** one or more codes (separated by spaces) that, taken in order, give the code points for the upper case of *code*. Each has at least four hexdigits.
**condition** the conditions for the mappings to be valid. If `undef`, the mappings are always valid. When defined, this field is a list of conditions, all of which must be true for the mappings to be valid. The list consists of one or more *locales* (see below) and/or *contexts* (explained in the next paragraph), separated by spaces. (Other than as used to separate elements, spaces are to be ignored.) Case distinctions in the condition list are not significant. Conditions preceded by "NON\_" represent the negation of the condition.
A *context* is one of those defined in the Unicode standard. For Unicode 5.1, they are defined in Section 3.13 `Default Case Operations` available at <http://www.unicode.org/versions/Unicode5.1.0/>. These are for context-sensitive casing.
The hash described above is returned for locale-independent casing, where at least one of the mappings has length longer than one. If `undef` is returned, the code point may have mappings, but if so, all are length one, and are returned by ["charinfo()"](#charinfo%28%29). Note that when this function does return a value, it will be for the complete set of mappings for a code point, even those whose length is one.
If there are additional casing rules that apply only in certain locales, an additional key for each will be defined in the returned hash. Each such key will be its locale name, defined as a 2-letter ISO 3166 country code, possibly followed by a "\_" and a 2-letter ISO language code (possibly followed by a "\_" and a variant code). You can find the lists of all possible locales, see <Locale::Country> and <Locale::Language>. (In Unicode 6.0, the only locales returned by this function are `lt`, `tr`, and `az`.)
Each locale key is a reference to a hash that has the form above, and gives the casing rules for that particular locale, which take precedence over the locale-independent ones when in that locale.
If the only casing for a code point is locale-dependent, then the returned hash will not have any of the base keys, like `code`, `upper`, etc., but will contain only locale keys.
For more information about case mappings see <http://www.unicode.org/reports/tr21/>
###
**namedseq()**
```
use Unicode::UCD 'namedseq';
my $namedseq = namedseq("KATAKANA LETTER AINU P");
my @namedseq = namedseq("KATAKANA LETTER AINU P");
my %namedseq = namedseq();
```
If used with a single argument in a scalar context, returns the string consisting of the code points of the named sequence, or `undef` if no named sequence by that name exists. If used with a single argument in a list context, it returns the list of the ordinals of the code points.
If used with no arguments in a list context, it returns a hash with the names of all the named sequences as the keys and their sequences as strings as the values. Otherwise, it returns `undef` or an empty list depending on the context.
This function only operates on officially approved (not provisional) named sequences.
Note that as of Perl 5.14, `\N{KATAKANA LETTER AINU P}` will insert the named sequence into double-quoted strings, and `charnames::string_vianame("KATAKANA LETTER AINU P")` will return the same string this function does, but will also operate on character names that aren't named sequences, without you having to know which are which. See <charnames>.
###
**num()**
```
use Unicode::UCD 'num';
my $val = num("123");
my $one_quarter = num("\N{VULGAR FRACTION ONE QUARTER}");
my $val = num("12a", \$valid_length); # $valid_length contains 2
```
`num()` returns the numeric value of the input Unicode string; or `undef` if it doesn't think the entire string has a completely valid, safe numeric value. If called with an optional second parameter, a reference to a scalar, `num()` will set the scalar to the length of any valid initial substring; or to 0 if none.
If the string is just one character in length, the Unicode numeric value is returned if it has one, or `undef` otherwise. If the optional scalar ref is passed, it would be set to 1 if the return is valid; or 0 if the return is `undef`. Note that the numeric value returned need not be a whole number. `num("\N{TIBETAN DIGIT HALF ZERO}")`, for example returns -0.5.
If the string is more than one character, `undef` is returned unless all its characters are decimal digits (that is, they would match `\d+`), from the same script. For example if you have an ASCII '0' and a Bengali '3', mixed together, they aren't considered a valid number, and `undef` is returned. A further restriction is that the digits all have to be of the same form. A half-width digit mixed with a full-width one will return `undef`. The Arabic script has two sets of digits; `num` will return `undef` unless all the digits in the string come from the same set. In all cases, the optional scalar ref parameter is set to how long any valid initial substring of digits is; hence it will be set to the entire string length if the main return value is not `undef`.
`num` errs on the side of safety, and there may be valid strings of decimal digits that it doesn't recognize. Note that Unicode defines a number of "digit" characters that aren't "decimal digit" characters. "Decimal digits" have the property that they have a positional value, i.e., there is a units position, a 10's position, a 100's, etc, AND they are arranged in Unicode in blocks of 10 contiguous code points. The Chinese digits, for example, are not in such a contiguous block, and so Unicode doesn't view them as decimal digits, but merely digits, and so `\d` will not match them. A single-character string containing one of these digits will have its decimal value returned by `num`, but any longer string containing only these digits will return `undef`.
Strings of multiple sub- and superscripts are not recognized as numbers. You can use either of the compatibility decompositions in Unicode::Normalize to change these into digits, and then call `num` on the result.
###
**prop\_aliases()**
```
use Unicode::UCD 'prop_aliases';
my ($short_name, $full_name, @other_names) = prop_aliases("space");
my $same_full_name = prop_aliases("Space"); # Scalar context
my ($same_short_name) = prop_aliases("Space"); # gets 0th element
print "The full name is $full_name\n";
print "The short name is $short_name\n";
print "The other aliases are: ", join(", ", @other_names), "\n";
prints:
The full name is White_Space
The short name is WSpace
The other aliases are: Space
```
Most Unicode properties have several synonymous names. Typically, there is at least a short name, convenient to type, and a long name that more fully describes the property, and hence is more easily understood.
If you know one name for a Unicode property, you can use `prop_aliases` to find either the long name (when called in scalar context), or a list of all of the names, somewhat ordered so that the short name is in the 0th element, the long name in the next element, and any other synonyms are in the remaining elements, in no particular order.
The long name is returned in a form nicely capitalized, suitable for printing.
The input parameter name is loosely matched, which means that white space, hyphens, and underscores are ignored (except for the trailing underscore in the old\_form grandfathered-in `"L_"`, which is better written as `"LC"`, and both of which mean `General_Category=Cased Letter`).
If the name is unknown, `undef` is returned (or an empty list in list context). Note that Perl typically recognizes property names in regular expressions with an optional `"Is_`" (with or without the underscore) prefixed to them, such as `\p{isgc=punct}`. This function does not recognize those in the input, returning `undef`. Nor are they included in the output as possible synonyms.
`prop_aliases` does know about the Perl extensions to Unicode properties, such as `Any` and `XPosixAlpha`, and the single form equivalents to Unicode properties such as `XDigit`, `Greek`, `In_Greek`, and `Is_Greek`. The final example demonstrates that the `"Is_"` prefix is recognized for these extensions; it is needed to resolve ambiguities. For example, `prop_aliases('lc')` returns the list `(lc, Lowercase_Mapping)`, but `prop_aliases('islc')` returns `(Is_LC, Cased_Letter)`. This is because `islc` is a Perl extension which is short for `General_Category=Cased Letter`. The lists returned for the Perl extensions will not include the `"Is_"` prefix (whether or not the input had it) unless needed to resolve ambiguities, as shown in the `"islc"` example, where the returned list had one element containing `"Is_"`, and the other without.
It is also possible for the reverse to happen: `prop_aliases('isc')` returns the list `(isc, ISO_Comment)`; whereas `prop_aliases('c')` returns `(C, Other)` (the latter being a Perl extension meaning `General_Category=Other`. ["Properties accessible through Unicode::UCD" in perluniprops](perluniprops#Properties-accessible-through-Unicode%3A%3AUCD) lists the available forms, including which ones are discouraged from use.
Those discouraged forms are accepted as input to `prop_aliases`, but are not returned in the lists. `prop_aliases('isL&')` and `prop_aliases('isL_')`, which are old synonyms for `"Is_LC"` and should not be used in new code, are examples of this. These both return `(Is_LC, Cased_Letter)`. Thus this function allows you to take a discouraged form, and find its acceptable alternatives. The same goes with single-form Block property equivalences. Only the forms that begin with `"In_"` are not discouraged; if you pass `prop_aliases` a discouraged form, you will get back the equivalent ones that begin with `"In_"`. It will otherwise look like a new-style block name (see. ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
`prop_aliases` does not know about any user-defined properties, and will return `undef` if called with one of those. Likewise for Perl internal properties, with the exception of "Perl\_Decimal\_Digit" which it does know about (and which is documented below in ["prop\_invmap()"](#prop_invmap%28%29)).
###
**prop\_values()**
```
use Unicode::UCD 'prop_values';
print "AHex values are: ", join(", ", prop_values("AHex")),
"\n";
prints:
AHex values are: N, Y
```
Some Unicode properties have a restricted set of legal values. For example, all binary properties are restricted to just `true` or `false`; and there are only a few dozen possible General Categories. Use `prop_values` to find out if a given property is one such, and if so, to get a list of the values:
```
print join ", ", prop_values("NFC_Quick_Check");
prints:
M, N, Y
```
If the property doesn't have such a restricted set, `undef` is returned.
There are usually several synonyms for each possible value. Use ["prop\_value\_aliases()"](#prop_value_aliases%28%29) to access those.
Case, white space, hyphens, and underscores are ignored in the input property name (except for the trailing underscore in the old-form grandfathered-in general category property value `"L_"`, which is better written as `"LC"`).
If the property name is unknown, `undef` is returned. Note that Perl typically recognizes property names in regular expressions with an optional `"Is_`" (with or without the underscore) prefixed to them, such as `\p{isgc=punct}`. This function does not recognize those in the property parameter, returning `undef`.
For the block property, new-style block names are returned (see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
`prop_values` does not know about any user-defined properties, and will return `undef` if called with one of those.
###
**prop\_value\_aliases()**
```
use Unicode::UCD 'prop_value_aliases';
my ($short_name, $full_name, @other_names)
= prop_value_aliases("Gc", "Punct");
my $same_full_name = prop_value_aliases("Gc", "P"); # Scalar cntxt
my ($same_short_name) = prop_value_aliases("Gc", "P"); # gets 0th
# element
print "The full name is $full_name\n";
print "The short name is $short_name\n";
print "The other aliases are: ", join(", ", @other_names), "\n";
prints:
The full name is Punctuation
The short name is P
The other aliases are: Punct
```
Some Unicode properties have a restricted set of legal values. For example, all binary properties are restricted to just `true` or `false`; and there are only a few dozen possible General Categories.
You can use ["prop\_values()"](#prop_values%28%29) to find out if a given property is one which has a restricted set of values, and if so, what those values are. But usually each value actually has several synonyms. For example, in Unicode binary properties, *truth* can be represented by any of the strings "Y", "Yes", "T", or "True"; and the General Category "Punctuation" by that string, or "Punct", or simply "P".
Like property names, there is typically at least a short name for each such property-value, and a long name. If you know any name of the property-value (which you can get by ["prop\_values()"](#prop_values%28%29), you can use `prop_value_aliases`() to get the long name (when called in scalar context), or a list of all the names, with the short name in the 0th element, the long name in the next element, and any other synonyms in the remaining elements, in no particular order, except that any all-numeric synonyms will be last.
The long name is returned in a form nicely capitalized, suitable for printing.
Case, white space, hyphens, and underscores are ignored in the input parameters (except for the trailing underscore in the old-form grandfathered-in general category property value `"L_"`, which is better written as `"LC"`).
If either name is unknown, `undef` is returned. Note that Perl typically recognizes property names in regular expressions with an optional `"Is_`" (with or without the underscore) prefixed to them, such as `\p{isgc=punct}`. This function does not recognize those in the property parameter, returning `undef`.
If called with a property that doesn't have synonyms for its values, it returns the input value, possibly normalized with capitalization and underscores, but not necessarily checking that the input value is valid.
For the block property, new-style block names are returned (see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
To find the synonyms for single-forms, such as `\p{Any}`, use ["prop\_aliases()"](#prop_aliases%28%29) instead.
`prop_value_aliases` does not know about any user-defined properties, and will return `undef` if called with one of those.
###
**prop\_invlist()**
`prop_invlist` returns an inversion list (described below) that defines all the code points for the binary Unicode property (or "property=value" pair) given by the input parameter string:
```
use feature 'say';
use Unicode::UCD 'prop_invlist';
say join ", ", prop_invlist("Any");
prints:
0, 1114112
```
If the input is unknown `undef` is returned in scalar context; an empty-list in list context. If the input is known, the number of elements in the list is returned if called in scalar context.
[perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D) gives the list of properties that this function accepts, as well as all the possible forms for them (including with the optional "Is\_" prefixes). (Except this function doesn't accept any Perl-internal properties, some of which are listed there.) This function uses the same loose or tighter matching rules for resolving the input property's name as is done for regular expressions. These are also specified in [perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D). Examples of using the "property=value" form are:
```
say join ", ", prop_invlist("Script_Extensions=Shavian");
prints:
66640, 66688
say join ", ", prop_invlist("ASCII_Hex_Digit=No");
prints:
0, 48, 58, 65, 71, 97, 103
say join ", ", prop_invlist("ASCII_Hex_Digit=Yes");
prints:
48, 58, 65, 71, 97, 103
```
Inversion lists are a compact way of specifying Unicode property-value definitions. The 0th item in the list is the lowest code point that has the property-value. The next item (item [1]) is the lowest code point beyond that one that does NOT have the property-value. And the next item beyond that ([2]) is the lowest code point beyond that one that does have the property-value, and so on. Put another way, each element in the list gives the beginning of a range that has the property-value (for even numbered elements), or doesn't have the property-value (for odd numbered elements). The name for this data structure stems from the fact that each element in the list toggles (or inverts) whether the corresponding range is or isn't on the list.
In the final example above, the first ASCII Hex digit is code point 48, the character "0", and all code points from it through 57 (a "9") are ASCII hex digits. Code points 58 through 64 aren't, but 65 (an "A") through 70 (an "F") are, as are 97 ("a") through 102 ("f"). 103 starts a range of code points that aren't ASCII hex digits. That range extends to infinity, which on your computer can be found in the variable `$Unicode::UCD::MAX_CP`. (This variable is as close to infinity as Perl can get on your platform, and may be too high for some operations to work; you may wish to use a smaller number for your purposes.)
Note that the inversion lists returned by this function can possibly include non-Unicode code points, that is anything above 0x10FFFF. Unicode properties are not defined on such code points. You might wish to change the output to not include these. Simply add 0x110000 at the end of the non-empty returned list if it isn't already that value; and pop that value if it is; like:
```
my @list = prop_invlist("foo");
if (@list) {
if ($list[-1] == 0x110000) {
pop @list; # Defeat the turning on for above Unicode
}
else {
push @list, 0x110000; # Turn off for above Unicode
}
}
```
It is a simple matter to expand out an inversion list to a full list of all code points that have the property-value:
```
my @invlist = prop_invlist($property_name);
die "empty" unless @invlist;
my @full_list;
for (my $i = 0; $i < @invlist; $i += 2) {
my $upper = ($i + 1) < @invlist
? $invlist[$i+1] - 1 # In range
: $Unicode::UCD::MAX_CP; # To infinity.
for my $j ($invlist[$i] .. $upper) {
push @full_list, $j;
}
}
```
`prop_invlist` does not know about any user-defined nor Perl internal-only properties, and will return `undef` if called with one of those.
The ["search\_invlist()"](#search_invlist%28%29) function is provided for finding a code point within an inversion list.
###
**prop\_invmap()**
```
use Unicode::UCD 'prop_invmap';
my ($list_ref, $map_ref, $format, $default)
= prop_invmap("General Category");
```
`prop_invmap` is used to get the complete mapping definition for a property, in the form of an inversion map. An inversion map consists of two parallel arrays. One is an ordered list of code points that mark range beginnings, and the other gives the value (or mapping) that all code points in the corresponding range have.
`prop_invmap` is called with the name of the desired property. The name is loosely matched, meaning that differences in case, white-space, hyphens, and underscores are not meaningful (except for the trailing underscore in the old-form grandfathered-in property `"L_"`, which is better written as `"LC"`, or even better, `"Gc=LC"`).
Many Unicode properties have more than one name (or alias). `prop_invmap` understands all of these, including Perl extensions to them. Ambiguities are resolved as described above for ["prop\_aliases()"](#prop_aliases%28%29) (except if a property has both a complete mapping, and a binary `Y`/`N` mapping, then specifying the property name prefixed by `"is"` causes the binary one to be returned). The Perl internal property "Perl\_Decimal\_Digit, described below, is also accepted. An empty list is returned if the property name is unknown. See ["Properties accessible through Unicode::UCD" in perluniprops](perluniprops#Properties-accessible-through-Unicode%3A%3AUCD) for the properties acceptable as inputs to this function.
It is a fatal error to call this function except in list context.
In addition to the two arrays that form the inversion map, `prop_invmap` returns two other values; one is a scalar that gives some details as to the format of the entries of the map array; the other is a default value, useful in maps whose format name begins with the letter `"a"`, as described [below in its subsection](#a); and for specialized purposes, such as converting to another data structure, described at the end of this main section.
This means that `prop_invmap` returns a 4 element list. For example,
```
my ($blocks_ranges_ref, $blocks_maps_ref, $format, $default)
= prop_invmap("Block");
```
In this call, the two arrays will be populated as shown below (for Unicode 6.0):
```
Index @blocks_ranges @blocks_maps
0 0x0000 Basic Latin
1 0x0080 Latin-1 Supplement
2 0x0100 Latin Extended-A
3 0x0180 Latin Extended-B
4 0x0250 IPA Extensions
5 0x02B0 Spacing Modifier Letters
6 0x0300 Combining Diacritical Marks
7 0x0370 Greek and Coptic
8 0x0400 Cyrillic
...
233 0x2B820 No_Block
234 0x2F800 CJK Compatibility Ideographs Supplement
235 0x2FA20 No_Block
236 0xE0000 Tags
237 0xE0080 No_Block
238 0xE0100 Variation Selectors Supplement
239 0xE01F0 No_Block
240 0xF0000 Supplementary Private Use Area-A
241 0x100000 Supplementary Private Use Area-B
242 0x110000 No_Block
```
The first line (with Index [0]) means that the value for code point 0 is "Basic Latin". The entry "0x0080" in the @blocks\_ranges column in the second line means that the value from the first line, "Basic Latin", extends to all code points in the range from 0 up to but not including 0x0080, that is, through 127. In other words, the code points from 0 to 127 are all in the "Basic Latin" block. Similarly, all code points in the range from 0x0080 up to (but not including) 0x0100 are in the block named "Latin-1 Supplement", etc. (Notice that the return is the old-style block names; see ["Old-style versus new-style block names"](#Old-style-versus-new-style-block-names)).
The final line (with Index [242]) means that the value for all code points above the legal Unicode maximum code point have the value "No\_Block", which is the term Unicode uses for a non-existing block.
The arrays completely specify the mappings for all possible code points. The final element in an inversion map returned by this function will always be for the range that consists of all the code points that aren't legal Unicode, but that are expressible on the platform. (That is, it starts with code point 0x110000, the first code point above the legal Unicode maximum, and extends to infinity.) The value for that range will be the same that any typical unassigned code point has for the specified property. (Certain unassigned code points are not "typical"; for example the non-character code points, or those in blocks that are to be written right-to-left. The above-Unicode range's value is not based on these atypical code points.) It could be argued that, instead of treating these as unassigned Unicode code points, the value for this range should be `undef`. If you wish, you can change the returned arrays accordingly.
The maps for almost all properties are simple scalars that should be interpreted as-is. These values are those given in the Unicode-supplied data files, which may be inconsistent as to capitalization and as to which synonym for a property-value is given. The results may be normalized by using the ["prop\_value\_aliases()"](#prop_value_aliases%28%29) function.
There are exceptions to the simple scalar maps. Some properties have some elements in their map list that are themselves lists of scalars; and some special strings are returned that are not to be interpreted as-is. Element [2] (placed into `$format` in the example above) of the returned four element list tells you if the map has any of these special elements or not, as follows:
**`s`** means all the elements of the map array are simple scalars, with no special elements. Almost all properties are like this, like the `block` example above.
**`sl`** means that some of the map array elements have the form given by `"s"`, and the rest are lists of scalars. For example, here is a portion of the output of calling `prop_invmap`() with the "Script Extensions" property:
```
@scripts_ranges @scripts_maps
...
0x0953 Devanagari
0x0964 [ Bengali, Devanagari, Gurumukhi, Oriya ]
0x0966 Devanagari
0x0970 Common
```
Here, the code points 0x964 and 0x965 are both used in Bengali, Devanagari, Gurmukhi, and Oriya, but no other scripts.
The Name\_Alias property is also of this form. But each scalar consists of two components: 1) the name, and 2) the type of alias this is. They are separated by a colon and a space. In Unicode 6.1, there are several alias types:
`correction` indicates that the name is a corrected form for the original name (which remains valid) for the same code point.
`control` adds a new name for a control character.
`alternate` is an alternate name for a character
`figment` is a name for a character that has been documented but was never in any actual standard.
`abbreviation` is a common abbreviation for a character
The lists are ordered (roughly) so the most preferred names come before less preferred ones.
For example,
```
@aliases_ranges @alias_maps
...
0x009E [ 'PRIVACY MESSAGE: control', 'PM: abbreviation' ]
0x009F [ 'APPLICATION PROGRAM COMMAND: control',
'APC: abbreviation'
]
0x00A0 'NBSP: abbreviation'
0x00A1 ""
0x00AD 'SHY: abbreviation'
0x00AE ""
0x01A2 'LATIN CAPITAL LETTER GHA: correction'
0x01A3 'LATIN SMALL LETTER GHA: correction'
0x01A4 ""
...
```
A map to the empty string means that there is no alias defined for the code point.
**`a`** is like `"s"` in that all the map array elements are scalars, but here they are restricted to all being integers, and some have to be adjusted (hence the name `"a"`) to get the correct result. For example, in:
```
my ($uppers_ranges_ref, $uppers_maps_ref, $format, $default)
= prop_invmap("Simple_Uppercase_Mapping");
```
the returned arrays look like this:
```
@$uppers_ranges_ref @$uppers_maps_ref Note
0 0
97 65 'a' maps to 'A', b => B ...
123 0
181 924 MICRO SIGN => Greek Cap MU
182 0
...
```
and `$default` is 0.
Let's start with the second line. It says that the uppercase of code point 97 is 65; or `uc("a")` == "A". But the line is for the entire range of code points 97 through 122. To get the mapping for any code point in this range, you take the offset it has from the beginning code point of the range, and add that to the mapping for that first code point. So, the mapping for 122 ("z") is derived by taking the offset of 122 from 97 (=25) and adding that to 65, yielding 90 ("Z"). Likewise for everything in between.
Requiring this simple adjustment allows the returned arrays to be significantly smaller than otherwise, up to a factor of 10, speeding up searching through them.
Ranges that map to `$default`, `"0"`, behave somewhat differently. For these, each code point maps to itself. So, in the first line in the example, `ord(uc(chr(0)))` is 0, `ord(uc(chr(1)))` is 1, .. `ord(uc(chr(96)))` is 96.
**`al`** means that some of the map array elements have the form given by `"a"`, and the rest are ordered lists of code points. For example, in:
```
my ($uppers_ranges_ref, $uppers_maps_ref, $format, $default)
= prop_invmap("Uppercase_Mapping");
```
the returned arrays look like this:
```
@$uppers_ranges_ref @$uppers_maps_ref
0 0
97 65
123 0
181 924
182 0
...
0x0149 [ 0x02BC 0x004E ]
0x014A 0
0x014B 330
...
```
This is the full Uppercase\_Mapping property (as opposed to the Simple\_Uppercase\_Mapping given in the example for format `"a"`). The only difference between the two in the ranges shown is that the code point at 0x0149 (LATIN SMALL LETTER N PRECEDED BY APOSTROPHE) maps to a string of two characters, 0x02BC (MODIFIER LETTER APOSTROPHE) followed by 0x004E (LATIN CAPITAL LETTER N).
No adjustments are needed to entries that are references to arrays; each such entry will have exactly one element in its range, so the offset is always 0.
The fourth (index [3]) element (`$default`) in the list returned for this format is 0.
**`ae`** This is like `"a"`, but some elements are the empty string, and should not be adjusted. The one internal Perl property accessible by `prop_invmap` is of this type: "Perl\_Decimal\_Digit" returns an inversion map which gives the numeric values that are represented by the Unicode decimal digit characters. Characters that don't represent decimal digits map to the empty string, like so:
```
@digits @values
0x0000 ""
0x0030 0
0x003A: ""
0x0660: 0
0x066A: ""
0x06F0: 0
0x06FA: ""
0x07C0: 0
0x07CA: ""
0x0966: 0
...
```
This means that the code points from 0 to 0x2F do not represent decimal digits; the code point 0x30 (DIGIT ZERO) represents 0; code point 0x31, (DIGIT ONE), represents 0+1-0 = 1; ... code point 0x39, (DIGIT NINE), represents 0+9-0 = 9; ... code points 0x3A through 0x65F do not represent decimal digits; 0x660 (ARABIC-INDIC DIGIT ZERO), represents 0; ... 0x07C1 (NKO DIGIT ONE), represents 0+1-0 = 1 ...
The fourth (index [3]) element (`$default`) in the list returned for this format is the empty string.
**`ale`** is a combination of the `"al"` type and the `"ae"` type. Some of the map array elements have the forms given by `"al"`, and the rest are the empty string. The property `NFKC_Casefold` has this form. An example slice is:
```
@$ranges_ref @$maps_ref Note
...
0x00AA 97 FEMININE ORDINAL INDICATOR => 'a'
0x00AB 0
0x00AD SOFT HYPHEN => ""
0x00AE 0
0x00AF [ 0x0020, 0x0304 ] MACRON => SPACE . COMBINING MACRON
0x00B0 0
...
```
The fourth (index [3]) element (`$default`) in the list returned for this format is 0.
**`ar`** means that all the elements of the map array are either rational numbers or the string `"NaN"`, meaning "Not a Number". A rational number is either an integer, or two integers separated by a solidus (`"/"`). The second integer represents the denominator of the division implied by the solidus, and is actually always positive, so it is guaranteed not to be 0 and to not be signed. When the element is a plain integer (without the solidus), it may need to be adjusted to get the correct value by adding the offset, just as other `"a"` properties. No adjustment is needed for fractions, as the range is guaranteed to have just a single element, and so the offset is always 0.
If you want to convert the returned map to entirely scalar numbers, you can use something like this:
```
my ($invlist_ref, $invmap_ref, $format) = prop_invmap($property);
if ($format && $format eq "ar") {
map { $_ = eval $_ if $_ ne 'NaN' } @$map_ref;
}
```
Here's some entries from the output of the property "Nv", which has format `"ar"`.
```
@numerics_ranges @numerics_maps Note
0x00 "NaN"
0x30 0 DIGIT 0 .. DIGIT 9
0x3A "NaN"
0xB2 2 SUPERSCRIPTs 2 and 3
0xB4 "NaN"
0xB9 1 SUPERSCRIPT 1
0xBA "NaN"
0xBC 1/4 VULGAR FRACTION 1/4
0xBD 1/2 VULGAR FRACTION 1/2
0xBE 3/4 VULGAR FRACTION 3/4
0xBF "NaN"
0x660 0 ARABIC-INDIC DIGIT ZERO .. NINE
0x66A "NaN"
```
The fourth (index [3]) element (`$default`) in the list returned for this format is `"NaN"`.
**`n`** means the Name property. All the elements of the map array are simple scalars, but some of them contain special strings that require more work to get the actual name.
Entries such as:
```
CJK UNIFIED IDEOGRAPH-<code point>
```
mean that the name for the code point is "CJK UNIFIED IDEOGRAPH-" with the code point (expressed in hexadecimal) appended to it, like "CJK UNIFIED IDEOGRAPH-3403" (similarly for `CJK COMPATIBILITY IDEOGRAPH-<code point>`).
Also, entries like
```
<hangul syllable>
```
means that the name is algorithmically calculated. This is easily done by the function ["charnames::viacode(code)" in charnames](charnames#charnames%3A%3Aviacode%28code%29).
Note that for control characters (`Gc=cc`), Unicode's data files have the string "`<control>`", but the real name of each of these characters is the empty string. This function returns that real name, the empty string. (There are names for these characters, but they are considered aliases, not the Name property name, and are contained in the `Name_Alias` property.)
**`ad`** means the Decomposition\_Mapping property. This property is like `"al"` properties, except that one of the scalar elements is of the form:
```
<hangul syllable>
```
This signifies that this entry should be replaced by the decompositions for all the code points whose decomposition is algorithmically calculated. (All of them are currently in one range and no others outside the range are likely to ever be added to Unicode; the `"n"` format has this same entry.) These can be generated via the function [Unicode::Normalize::NFD()](Unicode::Normalize).
Note that the mapping is the one that is specified in the Unicode data files, and to get the final decomposition, it may need to be applied recursively. Unicode in fact discourages use of this property except internally in implementations of the Unicode Normalization Algorithm.
The fourth (index [3]) element (`$default`) in the list returned for this format is 0.
Note that a format begins with the letter "a" if and only the property it is for requires adjustments by adding the offsets in multi-element ranges. For all these properties, an entry should be adjusted only if the map is a scalar which is an integer. That is, it must match the regular expression:
```
/ ^ -? \d+ $ /xa
```
Further, the first element in a range never needs adjustment, as the adjustment would be just adding 0.
A binary search such as that provided by ["search\_invlist()"](#search_invlist%28%29), can be used to quickly find a code point in the inversion list, and hence its corresponding mapping.
The final, fourth element (index [3], assigned to `$default` in the "block" example) in the four element list returned by this function is used with the `"a"` format types; it may also be useful for applications that wish to convert the returned inversion map data structure into some other, such as a hash. It gives the mapping that most code points map to under the property. If you establish the convention that any code point not explicitly listed in your data structure maps to this value, you can potentially make your data structure much smaller. As you construct your data structure from the one returned by this function, simply ignore those ranges that map to this value. For example, to convert to the data structure searchable by ["charinrange()"](#charinrange%28%29), you can follow this recipe for properties that don't require adjustments:
```
my ($list_ref, $map_ref, $format, $default) = prop_invmap($property);
my @range_list;
# Look at each element in the list, but the -2 is needed because we
# look at $i+1 in the loop, and the final element is guaranteed to map
# to $default by prop_invmap(), so we would skip it anyway.
for my $i (0 .. @$list_ref - 2) {
next if $map_ref->[$i] eq $default;
push @range_list, [ $list_ref->[$i],
$list_ref->[$i+1],
$map_ref->[$i]
];
}
print charinrange(\@range_list, $code_point), "\n";
```
With this, `charinrange()` will return `undef` if its input code point maps to `$default`. You can avoid this by omitting the `next` statement, and adding a line after the loop to handle the final element of the inversion map.
Similarly, this recipe can be used for properties that do require adjustments:
```
for my $i (0 .. @$list_ref - 2) {
next if $map_ref->[$i] eq $default;
# prop_invmap() guarantees that if the mapping is to an array, the
# range has just one element, so no need to worry about adjustments.
if (ref $map_ref->[$i]) {
push @range_list,
[ $list_ref->[$i], $list_ref->[$i], $map_ref->[$i] ];
}
else { # Otherwise each element is actually mapped to a separate
# value, so the range has to be split into single code point
# ranges.
my $adjustment = 0;
# For each code point that gets mapped to something...
for my $j ($list_ref->[$i] .. $list_ref->[$i+1] -1 ) {
# ... add a range consisting of just it mapping to the
# original plus the adjustment, which is incremented for the
# next time through the loop, as the offset increases by 1
# for each element in the range
push @range_list,
[ $j, $j, $map_ref->[$i] + $adjustment++ ];
}
}
}
```
Note that the inversion maps returned for the `Case_Folding` and `Simple_Case_Folding` properties do not include the Turkic-locale mappings. Use ["casefold()"](#casefold%28%29) for these.
`prop_invmap` does not know about any user-defined properties, and will return `undef` if called with one of those.
The returned values for the Perl extension properties, such as `Any` and `Greek` are somewhat misleading. The values are either `"Y"` or `"N`". All Unicode properties are bipartite, so you can actually use the `"Y"` or `"N`" in a Perl regular expression for these, like `qr/\p{ID_Start=Y/}` or `qr/\p{Upper=N/}`. But the Perl extensions aren't specified this way, only like `/qr/\p{Any}`, *etc*. You can't actually use the `"Y"` and `"N`" in them.
####
Getting every available name
Instead of reading the Unicode Database directly from files, as you were able to do for a long time, you are encouraged to use the supplied functions. So, instead of reading `Name.pl` directly, which changed formats in 5.32, and may do so again without notice in the future or even disappear, you ought to use ["prop\_invmap()"](#prop_invmap%28%29) like this:
```
my (%name, %cp, %cps, $n);
# All codepoints
foreach my $cat (qw( Name Name_Alias )) {
my ($codepoints, $names, $format, $default) = prop_invmap($cat);
# $format => "n", $default => ""
foreach my $i (0 .. @$codepoints - 2) {
my ($cp, $n) = ($codepoints->[$i], $names->[$i]);
# If $n is a ref, the same codepoint has multiple names
foreach my $name (ref $n ? @$n : $n) {
$name{$cp} //= $name;
$cp{$name} //= $cp;
}
}
}
# Named sequences
{ my %ns = namedseq();
foreach my $name (sort { $ns{$a} cmp $ns{$b} } keys %ns) {
$cp{$name} //= [ map { ord } split "" => $ns{$name} ];
}
}
```
###
**search\_invlist()**
```
use Unicode::UCD qw(prop_invmap prop_invlist);
use Unicode::UCD 'search_invlist';
my @invlist = prop_invlist($property_name);
print $code_point, ((search_invlist(\@invlist, $code_point) // -1) % 2)
? " isn't"
: " is",
" in $property_name\n";
my ($blocks_ranges_ref, $blocks_map_ref) = prop_invmap("Block");
my $index = search_invlist($blocks_ranges_ref, $code_point);
print "$code_point is in block ", $blocks_map_ref->[$index], "\n";
```
`search_invlist` is used to search an inversion list returned by `prop_invlist` or `prop_invmap` for a particular ["code point argument"](#code-point-argument). `undef` is returned if the code point is not found in the inversion list (this happens only when it is not a legal ["code point argument"](#code-point-argument), or is less than the list's first element). A warning is raised in the first instance.
Otherwise, it returns the index into the list of the range that contains the code point.; that is, find `i` such that
```
list[i]<= code_point < list[i+1].
```
As explained in ["prop\_invlist()"](#prop_invlist%28%29), whether a code point is in the list or not depends on if the index is even (in) or odd (not in). And as explained in ["prop\_invmap()"](#prop_invmap%28%29), the index is used with the returned parallel array to find the mapping.
###
Unicode::UCD::UnicodeVersion
This returns the version of the Unicode Character Database, in other words, the version of the Unicode standard the database implements. The version is a string of numbers delimited by dots (`'.'`).
###
**Blocks versus Scripts**
The difference between a block and a script is that scripts are closer to the linguistic notion of a set of code points required to represent languages, while block is more of an artifact of the Unicode code point numbering and separation into blocks of consecutive code points (so far the size of a block is some multiple of 16, like 128 or 256).
For example the Latin **script** is spread over several **blocks**, such as `Basic Latin`, `Latin 1 Supplement`, `Latin Extended-A`, and `Latin Extended-B`. On the other hand, the Latin script does not contain all the characters of the `Basic Latin` block (also known as ASCII): it includes only the letters, and not, for example, the digits nor the punctuation.
For blocks see <http://www.unicode.org/Public/UNIDATA/Blocks.txt>
For scripts see UTR #24: <http://www.unicode.org/reports/tr24/>
###
**Matching Scripts and Blocks**
Scripts are matched with the regular-expression construct `\p{...}` (e.g. `\p{Tibetan}` matches characters of the Tibetan script), while `\p{Blk=...}` is used for blocks (e.g. `\p{Blk=Tibetan}` matches any of the 256 code points in the Tibetan block).
###
Old-style versus new-style block names
Unicode publishes the names of blocks in two different styles, though the two are equivalent under Unicode's loose matching rules.
The original style uses blanks and hyphens in the block names (except for `No_Block`), like so:
```
Miscellaneous Mathematical Symbols-B
```
The newer style replaces these with underscores, like this:
```
Miscellaneous_Mathematical_Symbols_B
```
This newer style is consistent with the values of other Unicode properties. To preserve backward compatibility, all the functions in Unicode::UCD that return block names (except as noted) return the old-style ones. ["prop\_value\_aliases()"](#prop_value_aliases%28%29) returns the new-style and can be used to convert from old-style to new-style:
```
my $new_style = prop_values_aliases("block", $old_style);
```
Perl also has single-form extensions that refer to blocks, `In_Cyrillic`, meaning `Block=Cyrillic`. These have always been written in the new style.
To convert from new-style to old-style, follow this recipe:
```
$old_style = charblock((prop_invlist("block=$new_style"))[0]);
```
(which finds the range of code points in the block using `prop_invlist`, gets the lower end of the range (0th element) and then looks up the old name for its block using `charblock`).
Note that starting in Unicode 6.1, many of the block names have shorter synonyms. These are always given in the new style.
###
Use with older Unicode versions
The functions in this module work as well as can be expected when used on earlier Unicode versions. But, obviously, they use the available data from that Unicode version. For example, if the Unicode version predates the definition of the script property (Unicode 3.1), then any function that deals with scripts is going to return `undef` for the script portion of the return value.
AUTHOR
------
Jarkko Hietaniemi. Now maintained by perl5 porters.
| programming_docs |
perl autodie::exception::system autodie::exception::system
==========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [stringify](#stringify)
* [LICENSE](#LICENSE)
* [AUTHOR](#AUTHOR)
NAME
----
autodie::exception::system - Exceptions from autodying system().
SYNOPSIS
--------
```
eval {
use autodie qw(system);
system($cmd, @args);
};
if (my $E = $@) {
say "Ooops! ",$E->caller," had problems: $@";
}
```
DESCRIPTION
-----------
This is a <autodie::exception> class for failures from the `system` command.
Presently there is no way to interrogate an `autodie::exception::system` object for the command, exit status, and other information you'd expect such an object to hold. The interface will be expanded to accommodate this in the future.
### stringify
When stringified, `autodie::exception::system` objects currently use the message generated by <IPC::System::Simple>.
LICENSE
-------
Copyright (C)2008 Paul Fenwick
This is free software. You may modify and/or redistribute this code under the same terms as Perl 5.10 itself, or, at your option, any later version of Perl 5.
AUTHOR
------
Paul Fenwick <[email protected]>
perl perlunifaq perlunifaq
==========
CONTENTS
--------
* [NAME](#NAME)
* [Q and A](#Q-and-A)
+ [perlunitut isn't really a Unicode tutorial, is it?](#perlunitut-isn't-really-a-Unicode-tutorial,-is-it?)
+ [What character encodings does Perl support?](#What-character-encodings-does-Perl-support?)
+ [Which version of perl should I use?](#Which-version-of-perl-should-I-use?)
+ [What about binary data, like images?](#What-about-binary-data,-like-images?)
+ [When should I decode or encode?](#When-should-I-decode-or-encode?)
+ [What if I don't decode?](#What-if-I-don't-decode?)
+ [What if I don't encode?](#What-if-I-don't-encode?)
- [Output via a filehandle](#Output-via-a-filehandle)
- [Other output mechanisms (e.g., exec, chdir, ..)](#Other-output-mechanisms-(e.g.,-exec,-chdir,-..))
+ [Is there a way to automatically decode or encode?](#Is-there-a-way-to-automatically-decode-or-encode?)
+ [What if I don't know which encoding was used?](#What-if-I-don't-know-which-encoding-was-used?)
+ [Can I use Unicode in my Perl sources?](#Can-I-use-Unicode-in-my-Perl-sources?)
+ [Data::Dumper doesn't restore the UTF8 flag; is it broken?](#Data::Dumper-doesn't-restore-the-UTF8-flag;-is-it-broken?)
+ [Why do regex character classes sometimes match only in the ASCII range?](#Why-do-regex-character-classes-sometimes-match-only-in-the-ASCII-range?)
+ [Why do some characters not uppercase or lowercase correctly?](#Why-do-some-characters-not-uppercase-or-lowercase-correctly?)
+ [How can I determine if a string is a text string or a binary string?](#How-can-I-determine-if-a-string-is-a-text-string-or-a-binary-string?)
+ [How do I convert from encoding FOO to encoding BAR?](#How-do-I-convert-from-encoding-FOO-to-encoding-BAR?)
+ [What are decode\_utf8 and encode\_utf8?](#What-are-decode_utf8-and-encode_utf8?)
+ [What is a "wide character"?](#What-is-a-%22wide-character%22?)
* [INTERNALS](#INTERNALS)
+ [What is "the UTF8 flag"?](#What-is-%22the-UTF8-flag%22?)
+ [What about the use bytes pragma?](#What-about-the-use-bytes-pragma?)
+ [What about the use encoding pragma?](#What-about-the-use-encoding-pragma?)
+ [What is the difference between :encoding and :utf8?](#What-is-the-difference-between-:encoding-and-:utf8?)
+ [What's the difference between UTF-8 and utf8?](#What's-the-difference-between-UTF-8-and-utf8?)
+ [I lost track; what encoding is the internal format really?](#I-lost-track;-what-encoding-is-the-internal-format-really?)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlunifaq - Perl Unicode FAQ
Q and A
--------
This is a list of questions and answers about Unicode in Perl, intended to be read after <perlunitut>.
###
perlunitut isn't really a Unicode tutorial, is it?
No, and this isn't really a Unicode FAQ.
Perl has an abstracted interface for all supported character encodings, so this is actually a generic `Encode` tutorial and `Encode` FAQ. But many people think that Unicode is special and magical, and I didn't want to disappoint them, so I decided to call the document a Unicode tutorial.
###
What character encodings does Perl support?
To find out which character encodings your Perl supports, run:
```
perl -MEncode -le "print for Encode->encodings(':all')"
```
###
Which version of perl should I use?
Well, if you can, upgrade to the most recent, but certainly `5.8.1` or newer. The tutorial and FAQ assume the latest release.
You should also check your modules, and upgrade them if necessary. For example, HTML::Entities requires version >= 1.32 to function correctly, even though the changelog is silent about this.
###
What about binary data, like images?
Well, apart from a bare `binmode $fh`, you shouldn't treat them specially. (The binmode is needed because otherwise Perl may convert line endings on Win32 systems.)
Be careful, though, to never combine text strings with binary strings. If you need text in a binary stream, encode your text strings first using the appropriate encoding, then join them with binary strings. See also: "What if I don't encode?".
###
When should I decode or encode?
Whenever you're communicating text with anything that is external to your perl process, like a database, a text file, a socket, or another program. Even if the thing you're communicating with is also written in Perl.
###
What if I don't decode?
Whenever your encoded, binary string is used together with a text string, Perl will assume that your binary string was encoded with ISO-8859-1, also known as latin-1. If it wasn't latin-1, then your data is unpleasantly converted. For example, if it was UTF-8, the individual bytes of multibyte characters are seen as separate characters, and then again converted to UTF-8. Such double encoding can be compared to double HTML encoding (`&gt;`), or double URI encoding (`%253E`).
This silent implicit decoding is known as "upgrading". That may sound positive, but it's best to avoid it.
###
What if I don't encode?
It depends on what you output and how you output it.
####
Output via a filehandle
* If the string's characters are all code point 255 or lower, Perl outputs bytes that match those code points. This is what happens with encoded strings. It can also, though, happen with unencoded strings that happen to be all code point 255 or lower.
* Otherwise, Perl outputs the string encoded as UTF-8. This only happens with strings you neglected to encode. Since that should not happen, Perl also throws a "wide character" warning in this case.
####
Other output mechanisms (e.g., `exec`, `chdir`, ..)
Your text string will be sent using the bytes in Perl's internal format.
Because the internal format is often UTF-8, these bugs are hard to spot, because UTF-8 is usually the encoding you wanted! But don't be lazy, and don't use the fact that Perl's internal format is UTF-8 to your advantage. Encode explicitly to avoid weird bugs, and to show to maintenance programmers that you thought this through.
###
Is there a way to automatically decode or encode?
If all data that comes from a certain handle is encoded in exactly the same way, you can tell the PerlIO system to automatically decode everything, with the `encoding` layer. If you do this, you can't accidentally forget to decode or encode anymore, on things that use the layered handle.
You can provide this layer when `open`ing the file:
```
open my $fh, '>:encoding(UTF-8)', $filename; # auto encoding on write
open my $fh, '<:encoding(UTF-8)', $filename; # auto decoding on read
```
Or if you already have an open filehandle:
```
binmode $fh, ':encoding(UTF-8)';
```
Some database drivers for DBI can also automatically encode and decode, but that is sometimes limited to the UTF-8 encoding.
###
What if I don't know which encoding was used?
Do whatever you can to find out, and if you have to: guess. (Don't forget to document your guess with a comment.)
You could open the document in a web browser, and change the character set or character encoding until you can visually confirm that all characters look the way they should.
There is no way to reliably detect the encoding automatically, so if people keep sending you data without charset indication, you may have to educate them.
###
Can I use Unicode in my Perl sources?
Yes, you can! If your sources are UTF-8 encoded, you can indicate that with the `use utf8` pragma.
```
use utf8;
```
This doesn't do anything to your input, or to your output. It only influences the way your sources are read. You can use Unicode in string literals, in identifiers (but they still have to be "word characters" according to `\w`), and even in custom delimiters.
###
Data::Dumper doesn't restore the UTF8 flag; is it broken?
No, Data::Dumper's Unicode abilities are as they should be. There have been some complaints that it should restore the UTF8 flag when the data is read again with `eval`. However, you should really not look at the flag, and nothing indicates that Data::Dumper should break this rule.
Here's what happens: when Perl reads in a string literal, it sticks to 8 bit encoding as long as it can. (But perhaps originally it was internally encoded as UTF-8, when you dumped it.) When it has to give that up because other characters are added to the text string, it silently upgrades the string to UTF-8.
If you properly encode your strings for output, none of this is of your concern, and you can just `eval` dumped data as always.
###
Why do regex character classes sometimes match only in the ASCII range?
Starting in Perl 5.14 (and partially in Perl 5.12), just put a `use feature 'unicode_strings'` near the beginning of your program. Within its lexical scope you shouldn't have this problem. It also is automatically enabled under `use feature ':5.12'` or `use v5.12` or using `-E` on the command line for Perl 5.12 or higher.
The rationale for requiring this is to not break older programs that rely on the way things worked before Unicode came along. Those older programs knew only about the ASCII character set, and so may not work properly for additional characters. When a string is encoded in UTF-8, Perl assumes that the program is prepared to deal with Unicode, but when the string isn't, Perl assumes that only ASCII is wanted, and so those characters that are not ASCII characters aren't recognized as to what they would be in Unicode. `use feature 'unicode_strings'` tells Perl to treat all characters as Unicode, whether the string is encoded in UTF-8 or not, thus avoiding the problem.
However, on earlier Perls, or if you pass strings to subroutines outside the feature's scope, you can force Unicode rules by changing the encoding to UTF-8 by doing `utf8::upgrade($string)`. This can be used safely on any string, as it checks and does not change strings that have already been upgraded.
For a more detailed discussion, see <Unicode::Semantics> on CPAN.
###
Why do some characters not uppercase or lowercase correctly?
See the answer to the previous question.
###
How can I determine if a string is a text string or a binary string?
You can't. Some use the UTF8 flag for this, but that's misuse, and makes well behaved modules like Data::Dumper look bad. The flag is useless for this purpose, because it's off when an 8 bit encoding (by default ISO-8859-1) is used to store the string.
This is something you, the programmer, has to keep track of; sorry. You could consider adopting a kind of "Hungarian notation" to help with this.
###
How do I convert from encoding FOO to encoding BAR?
By first converting the FOO-encoded byte string to a text string, and then the text string to a BAR-encoded byte string:
```
my $text_string = decode('FOO', $foo_string);
my $bar_string = encode('BAR', $text_string);
```
or by skipping the text string part, and going directly from one binary encoding to the other:
```
use Encode qw(from_to);
from_to($string, 'FOO', 'BAR'); # changes contents of $string
```
or by letting automatic decoding and encoding do all the work:
```
open my $foofh, '<:encoding(FOO)', 'example.foo.txt';
open my $barfh, '>:encoding(BAR)', 'example.bar.txt';
print { $barfh } $_ while <$foofh>;
```
###
What are `decode_utf8` and `encode_utf8`?
These are alternate syntaxes for `decode('utf8', ...)` and `encode('utf8', ...)`. Do not use these functions for data exchange. Instead use `decode('UTF-8', ...)` and `encode('UTF-8', ...)`; see ["What's the difference between UTF-8 and utf8?"](#What%27s-the-difference-between-UTF-8-and-utf8%3F) below.
###
What is a "wide character"?
This is a term used for characters occupying more than one byte.
The Perl warning "Wide character in ..." is caused by such a character. With no specified encoding layer, Perl tries to fit things into a single byte. When it can't, it emits this warning (if warnings are enabled), and uses UTF-8 encoded data instead.
To avoid this warning and to avoid having different output encodings in a single stream, always specify an encoding explicitly, for example with a PerlIO layer:
```
binmode STDOUT, ":encoding(UTF-8)";
```
INTERNALS
---------
###
What is "the UTF8 flag"?
Please, unless you're hacking the internals, or debugging weirdness, don't think about the UTF8 flag at all. That means that you very probably shouldn't use `is_utf8`, `_utf8_on` or `_utf8_off` at all.
The UTF8 flag, also called SvUTF8, is an internal flag that indicates that the current internal representation is UTF-8. Without the flag, it is assumed to be ISO-8859-1. Perl converts between these automatically. (Actually Perl usually assumes the representation is ASCII; see ["Why do regex character classes sometimes match only in the ASCII range?"](#Why-do-regex-character-classes-sometimes-match-only-in-the-ASCII-range%3F) above.)
One of Perl's internal formats happens to be UTF-8. Unfortunately, Perl can't keep a secret, so everyone knows about this. That is the source of much confusion. It's better to pretend that the internal format is some unknown encoding, and that you always have to encode and decode explicitly.
###
What about the `use bytes` pragma?
Don't use it. It makes no sense to deal with bytes in a text string, and it makes no sense to deal with characters in a byte string. Do the proper conversions (by decoding/encoding), and things will work out well: you get character counts for decoded data, and byte counts for encoded data.
`use bytes` is usually a failed attempt to do something useful. Just forget about it.
###
What about the `use encoding` pragma?
Don't use it. Unfortunately, it assumes that the programmer's environment and that of the user will use the same encoding. It will use the same encoding for the source code and for STDIN and STDOUT. When a program is copied to another machine, the source code does not change, but the STDIO environment might.
If you need non-ASCII characters in your source code, make it a UTF-8 encoded file and `use utf8`.
If you need to set the encoding for STDIN, STDOUT, and STDERR, for example based on the user's locale, `use open`.
###
What is the difference between `:encoding` and `:utf8`?
Because UTF-8 is one of Perl's internal formats, you can often just skip the encoding or decoding step, and manipulate the UTF8 flag directly.
Instead of `:encoding(UTF-8)`, you can simply use `:utf8`, which skips the encoding step if the data was already represented as UTF8 internally. This is widely accepted as good behavior when you're writing, but it can be dangerous when reading, because it causes internal inconsistency when you have invalid byte sequences. Using `:utf8` for input can sometimes result in security breaches, so please use `:encoding(UTF-8)` instead.
Instead of `decode` and `encode`, you could use `_utf8_on` and `_utf8_off`, but this is considered bad style. Especially `_utf8_on` can be dangerous, for the same reason that `:utf8` can.
There are some shortcuts for oneliners; see [-C in perlrun](perlrun#-C-%5Bnumber%2Flist%5D).
###
What's the difference between `UTF-8` and `utf8`?
`UTF-8` is the official standard. `utf8` is Perl's way of being liberal in what it accepts. If you have to communicate with things that aren't so liberal, you may want to consider using `UTF-8`. If you have to communicate with things that are too liberal, you may have to use `utf8`. The full explanation is in ["UTF-8 vs. utf8 vs. UTF8" in Encode](encode#UTF-8-vs.-utf8-vs.-UTF8).
`UTF-8` is internally known as `utf-8-strict`. The tutorial uses UTF-8 consistently, even where utf8 is actually used internally, because the distinction can be hard to make, and is mostly irrelevant.
For example, utf8 can be used for code points that don't exist in Unicode, like 9999999, but if you encode that to UTF-8, you get a substitution character (by default; see ["Handling Malformed Data" in Encode](encode#Handling-Malformed-Data) for more ways of dealing with this.)
Okay, if you insist: the "internal format" is utf8, not UTF-8. (When it's not some other encoding.)
###
I lost track; what encoding is the internal format really?
It's good that you lost track, because you shouldn't depend on the internal format being any specific encoding. But since you asked: by default, the internal format is either ISO-8859-1 (latin-1), or utf8, depending on the history of the string. On EBCDIC platforms, this may be different even.
Perl knows how it stored the string internally, and will use that knowledge when you `encode`. In other words: don't try to find out what the internal encoding for a certain string is, but instead just encode it into the encoding that you want.
AUTHOR
------
Juerd Waalboer <#####@juerd.nl>
SEE ALSO
---------
<perlunicode>, <perluniintro>, [Encode](encode)
perl File::Basename File::Basename
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Basename - Parse file paths into directory, filename and suffix.
SYNOPSIS
--------
```
use File::Basename;
($name,$path,$suffix) = fileparse($fullname,@suffixlist);
$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$dirname = dirname($fullname);
```
DESCRIPTION
-----------
These routines allow you to parse file paths into their directory, filename and suffix.
**NOTE**: `dirname()` and `basename()` emulate the behaviours, and quirks, of the shell and C functions of the same name. See each function's documentation for details. If your concern is just parsing paths it is safer to use <File::Spec>'s `splitpath()` and `splitdir()` methods.
It is guaranteed that
```
# Where $path_separator is / for Unix, \ for Windows, etc...
dirname($path) . $path_separator . basename($path);
```
is equivalent to the original path for all systems but VMS.
`fileparse`
```
my($filename, $dirs, $suffix) = fileparse($path);
my($filename, $dirs, $suffix) = fileparse($path, @suffixes);
my $filename = fileparse($path, @suffixes);
```
The `fileparse()` routine divides a file path into its $dirs, $filename and (optionally) the filename $suffix.
$dirs contains everything up to and including the last directory separator in the $path including the volume (if applicable). The remainder of the $path is the $filename.
```
# On Unix returns ("baz", "/foo/bar/", "")
fileparse("/foo/bar/baz");
# On Windows returns ("baz", 'C:\foo\bar\', "")
fileparse('C:\foo\bar\baz');
# On Unix returns ("", "/foo/bar/baz/", "")
fileparse("/foo/bar/baz/");
```
If @suffixes are given each element is a pattern (either a string or a `qr//`) matched against the end of the $filename. The matching portion is removed and becomes the $suffix.
```
# On Unix returns ("baz", "/foo/bar/", ".txt")
fileparse("/foo/bar/baz.txt", qr/\.[^.]*/);
```
If type is non-Unix (see ["fileparse\_set\_fstype"](#fileparse_set_fstype)) then the pattern matching for suffix removal is performed case-insensitively, since those systems are not case-sensitive when opening existing files.
You are guaranteed that `$dirs . $filename . $suffix` will denote the same location as the original $path.
`basename`
```
my $filename = basename($path);
my $filename = basename($path, @suffixes);
```
This function is provided for compatibility with the Unix shell command `basename(1)`. It does **NOT** always return the file name portion of a path as you might expect. To be safe, if you want the file name portion of a path use `fileparse()`.
`basename()` returns the last level of a filepath even if the last level is clearly directory. In effect, it is acting like `pop()` for paths. This differs from `fileparse()`'s behaviour.
```
# Both return "bar"
basename("/foo/bar");
basename("/foo/bar/");
```
@suffixes work as in `fileparse()` except all regex metacharacters are quoted.
```
# These two function calls are equivalent.
my $filename = basename("/foo/bar/baz.txt", ".txt");
my $filename = fileparse("/foo/bar/baz.txt", qr/\Q.txt\E/);
```
Also note that in order to be compatible with the shell command, `basename()` does not strip off a suffix if it is identical to the remaining characters in the filename.
`dirname` This function is provided for compatibility with the Unix shell command `dirname(1)` and has inherited some of its quirks. In spite of its name it does **NOT** always return the directory name as you might expect. To be safe, if you want the directory name of a path use `fileparse()`.
Only on VMS (where there is no ambiguity between the file and directory portions of a path) and AmigaOS (possibly due to an implementation quirk in this module) does `dirname()` work like `fileparse($path)`, returning just the $dirs.
```
# On VMS and AmigaOS
my $dirs = dirname($path);
```
When using Unix or MSDOS syntax this emulates the `dirname(1)` shell function which is subtly different from how `fileparse()` works. It returns all but the last level of a file path even if the last level is clearly a directory. In effect, it is not returning the directory portion but simply the path one level up acting like `chop()` for file paths.
Also unlike `fileparse()`, `dirname()` does not include a trailing slash on its returned path.
```
# returns /foo/bar. fileparse() would return /foo/bar/
dirname("/foo/bar/baz");
# also returns /foo/bar despite the fact that baz is clearly a
# directory. fileparse() would return /foo/bar/baz/
dirname("/foo/bar/baz/");
# returns '.'. fileparse() would return 'foo/'
dirname("foo/");
```
Under VMS, if there is no directory information in the $path, then the current default device and directory is used.
`fileparse_set_fstype`
```
my $type = fileparse_set_fstype();
my $previous_type = fileparse_set_fstype($type);
```
Normally File::Basename will assume a file path type native to your current operating system (ie. /foo/bar style on Unix, \foo\bar on Windows, etc...). With this function you can override that assumption.
Valid $types are "MacOS", "VMS", "AmigaOS", "OS2", "RISCOS", "MSWin32", "DOS" (also "MSDOS" for backwards bug compatibility), "Epoc" and "Unix" (all case-insensitive). If an unrecognized $type is given "Unix" will be assumed.
If you've selected VMS syntax, and the file specification you pass to one of these routines contains a "/", they assume you are using Unix emulation and apply the Unix syntax rules instead, for that function call only.
SEE ALSO
---------
[dirname(1)](http://man.he.net/man1/dirname), [basename(1)](http://man.he.net/man1/basename), <File::Spec>
| programming_docs |
perl perlplan9 perlplan9
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Invoking Perl](#Invoking-Perl)
+ [What's in Plan 9 Perl](#What's-in-Plan-9-Perl)
+ [What's not in Plan 9 Perl](#What's-not-in-Plan-9-Perl)
+ [Perl5 Functions not currently supported in Plan 9 Perl](#Perl5-Functions-not-currently-supported-in-Plan-9-Perl)
+ [Signals in Plan 9 Perl](#Signals-in-Plan-9-Perl)
* [COMPILING AND INSTALLING PERL ON PLAN 9](#COMPILING-AND-INSTALLING-PERL-ON-PLAN-9)
+ [Installing Perl Documentation on Plan 9](#Installing-Perl-Documentation-on-Plan-9)
* [BUGS](#BUGS)
* [Revision date](#Revision-date)
* [AUTHOR](#AUTHOR)
NAME
----
perlplan9 - Plan 9-specific documentation for Perl
DESCRIPTION
-----------
These are a few notes describing features peculiar to Plan 9 Perl. As such, it is not intended to be a replacement for the rest of the Perl 5 documentation (which is both copious and excellent). If you have any questions to which you can't find answers in these man pages, contact Luther Huffman at [email protected] and we'll try to answer them.
###
Invoking Perl
Perl is invoked from the command line as described in <perl>. Most perl scripts, however, do have a first line such as "#!/usr/local/bin/perl". This is known as a shebang (shell-bang) statement and tells the OS shell where to find the perl interpreter. In Plan 9 Perl this statement should be "#!/bin/perl" if you wish to be able to directly invoke the script by its name. Alternatively, you may invoke perl with the command "Perl" instead of "perl". This will produce Acme-friendly error messages of the form "filename:18".
Some scripts, usually identified with a \*.PL extension, are self-configuring and are able to correctly create their own shebang path from config information located in Plan 9 Perl. These you won't need to be worried about.
###
What's in Plan 9 Perl
Although Plan 9 Perl currently only provides static loading, it is built with a number of useful extensions. These include Opcode, FileHandle, Fcntl, and POSIX. Expect to see others (and DynaLoading!) in the future.
###
What's not in Plan 9 Perl
As mentioned previously, dynamic loading isn't currently available nor is MakeMaker. Both are high-priority items.
###
Perl5 Functions not currently supported in Plan 9 Perl
Some, such as `chown` and `umask` aren't provided because the concept does not exist within Plan 9. Others, such as some of the socket-related functions, simply haven't been written yet. Many in the latter category may be supported in the future.
The functions not currently implemented include:
```
chown, chroot, dbmclose, dbmopen, getsockopt,
setsockopt, recvmsg, sendmsg, getnetbyname,
getnetbyaddr, getnetent, getprotoent, getservent,
sethostent, setnetent, setprotoent, setservent,
endservent, endnetent, endprotoent, umask
```
There may be several other functions that have undefined behavior so this list shouldn't be considered complete.
###
Signals in Plan 9 Perl
For compatibility with perl scripts written for the Unix environment, Plan 9 Perl uses the POSIX signal emulation provided in Plan 9's ANSI POSIX Environment (APE). Signal stacking isn't supported. The signals provided are:
```
SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGABRT,
SIGFPE, SIGKILL, SIGSEGV, SIGPIPE, SIGPIPE, SIGALRM,
SIGTERM, SIGUSR1, SIGUSR2, SIGCHLD, SIGCONT,
SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU
```
COMPILING AND INSTALLING PERL ON PLAN 9
----------------------------------------
WELCOME to Plan 9 Perl, brave soul!
```
This is a preliminary alpha version of Plan 9 Perl. Still to be
implemented are MakeMaker and DynaLoader. Many perl commands are
missing or currently behave in an inscrutable manner. These gaps will,
with perseverance and a modicum of luck, be remedied in the near
future.To install this software:
```
1. Create the source directories and libraries for perl by running the plan9/setup.rc command (i.e., located in the plan9 subdirectory). Note: the setup routine assumes that you haven't dearchived these files into /sys/src/cmd/perl. After running setup.rc you may delete the copy of the source you originally detarred, as source code has now been installed in /sys/src/cmd/perl. If you plan on installing perl binaries for all architectures, run "setup.rc -a".
2. After making sure that you have adequate privileges to build system software, from /sys/src/cmd/perl/5.00301 (adjust version appropriately) run:
```
mk install
```
If you wish to install perl versions for all architectures (68020, mips, sparc and 386) run:
```
mk installall
```
3. Wait. The build process will take a \*long\* time because perl bootstraps itself. A 75MHz Pentium, 16MB RAM machine takes roughly 30 minutes to build the distribution from scratch.
###
Installing Perl Documentation on Plan 9
This perl distribution comes with a tremendous amount of documentation. To add these to the built-in manuals that come with Plan 9, from /sys/src/cmd/perl/5.00301 (adjust version appropriately) run:
```
mk man
```
To begin your reading, start with:
```
man perl
```
This is a good introduction and will direct you towards other man pages that may interest you.
(Note: "mk man" may produce some extraneous noise. Fear not.)
BUGS
----
"As many as there are grains of sand on all the beaches of the world . . ." - Carl Sagan
Revision date
--------------
This document was revised 09-October-1996 for Perl 5.003\_7.
AUTHOR
------
Direct questions, comments, and the unlikely bug report (ahem) direct comments toward:
Luther Huffman, [email protected], Strategic Computer Solutions, Inc.
perl perlootut perlootut
=========
CONTENTS
--------
* [NAME](#NAME)
* [DATE](#DATE)
* [DESCRIPTION](#DESCRIPTION)
* [OBJECT-ORIENTED FUNDAMENTALS](#OBJECT-ORIENTED-FUNDAMENTALS)
+ [Object](#Object)
+ [Class](#Class)
- [Blessing](#Blessing)
- [Constructor](#Constructor)
+ [Methods](#Methods)
+ [Attributes](#Attributes)
+ [Polymorphism](#Polymorphism)
+ [Inheritance](#Inheritance)
- [Overriding methods and method resolution](#Overriding-methods-and-method-resolution)
+ [Encapsulation](#Encapsulation)
+ [Composition](#Composition)
+ [Roles](#Roles)
+ [When to Use OO](#When-to-Use-OO)
* [PERL OO SYSTEMS](#PERL-OO-SYSTEMS)
+ [Moose](#Moose)
- [Moo](#Moo)
+ [Class::Accessor](#Class::Accessor)
+ [Class::Tiny](#Class::Tiny)
+ [Role::Tiny](#Role::Tiny)
+ [OO System Summary](#OO-System-Summary)
+ [Other OO Systems](#Other-OO-Systems)
* [CONCLUSION](#CONCLUSION)
NAME
----
perlootut - Object-Oriented Programming in Perl Tutorial
DATE
----
This document was created in February, 2011, and the last major revision was in February, 2013.
If you are reading this in the future then it's possible that the state of the art has changed. We recommend you start by reading the perlootut document in the latest stable release of Perl, rather than this version.
DESCRIPTION
-----------
This document provides an introduction to object-oriented programming in Perl. It begins with a brief overview of the concepts behind object oriented design. Then it introduces several different OO systems from [CPAN](https://www.cpan.org) which build on top of what Perl provides.
By default, Perl's built-in OO system is very minimal, leaving you to do most of the work. This minimalism made a lot of sense in 1994, but in the years since Perl 5.0 we've seen a number of common patterns emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich ecosystem of Perl OO systems to flourish.
If you want to know how Perl OO works under the hood, the <perlobj> document explains the nitty gritty details.
This document assumes that you already understand the basics of Perl syntax, variable types, operators, and subroutine calls. If you don't understand these concepts yet, please read <perlintro> first. You should also read the <perlsyn>, <perlop>, and <perlsub> documents.
OBJECT-ORIENTED FUNDAMENTALS
-----------------------------
Most object systems share a number of common concepts. You've probably heard terms like "class", "object, "method", and "attribute" before. Understanding the concepts will make it much easier to read and write object-oriented code. If you're already familiar with these terms, you should still skim this section, since it explains each concept in terms of Perl's OO implementation.
Perl's OO system is class-based. Class-based OO is fairly common. It's used by Java, C++, C#, Python, Ruby, and many other languages. There are other object orientation paradigms as well. JavaScript is the most popular language to use another paradigm. JavaScript's OO system is prototype-based.
### Object
An **object** is a data structure that bundles together data and subroutines which operate on that data. An object's data is called **attributes**, and its subroutines are called **methods**. An object can be thought of as a noun (a person, a web service, a computer).
An object represents a single discrete thing. For example, an object might represent a file. The attributes for a file object might include its path, content, and last modification time. If we created an object to represent */etc/hostname* on a machine named "foo.example.com", that object's path would be "/etc/hostname", its content would be "foo\n", and it's last modification time would be 1304974868 seconds since the beginning of the epoch.
The methods associated with a file might include `rename()` and `write()`.
In Perl most objects are hashes, but the OO systems we recommend keep you from having to worry about this. In practice, it's best to consider an object's internal data structure opaque.
### Class
A **class** defines the behavior of a category of objects. A class is a name for a category (like "File"), and a class also defines the behavior of objects in that category.
All objects belong to a specific class. For example, our */etc/hostname* object belongs to the `File` class. When we want to create a specific object, we start with its class, and **construct** or **instantiate** an object. A specific object is often referred to as an **instance** of a class.
In Perl, any package can be a class. The difference between a package which is a class and one which isn't is based on how the package is used. Here's our "class declaration" for the `File` class:
```
package File;
```
In Perl, there is no special keyword for constructing an object. However, most OO modules on CPAN use a method named `new()` to construct a new object:
```
my $hostname = File->new(
path => '/etc/hostname',
content => "foo\n",
last_mod_time => 1304974868,
);
```
(Don't worry about that `->` operator, it will be explained later.)
#### Blessing
As we said earlier, most Perl objects are hashes, but an object can be an instance of any Perl data type (scalar, array, etc.). Turning a plain data structure into an object is done by **blessing** that data structure using Perl's `bless` function.
While we strongly suggest you don't build your objects from scratch, you should know the term **bless**. A **blessed** data structure (aka "a referent") is an object. We sometimes say that an object has been "blessed into a class".
Once a referent has been blessed, the `blessed` function from the <Scalar::Util> core module can tell us its class name. This subroutine returns an object's class when passed an object, and false otherwise.
```
use Scalar::Util 'blessed';
print blessed($hash); # undef
print blessed($hostname); # File
```
#### Constructor
A **constructor** creates a new object. In Perl, a class's constructor is just another method, unlike some other languages, which provide syntax for constructors. Most Perl classes use `new` as the name for their constructor:
```
my $file = File->new(...);
```
### Methods
You already learned that a **method** is a subroutine that operates on an object. You can think of a method as the things that an object can *do*. If an object is a noun, then methods are its verbs (save, print, open).
In Perl, methods are simply subroutines that live in a class's package. Methods are always written to receive the object as their first argument:
```
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
}
$file->print_info;
# The file is at /etc/hostname
```
What makes a method special is *how it's called*. The arrow operator (`->`) tells Perl that we are calling a method.
When we make a method call, Perl arranges for the method's **invocant** to be passed as the first argument. **Invocant** is a fancy name for the thing on the left side of the arrow. The invocant can either be a class name or an object. We can also pass additional arguments to the method:
```
sub print_info {
my $self = shift;
my $prefix = shift // "This file is at ";
print $prefix, ", ", $self->path, "\n";
}
$file->print_info("The file is located at ");
# The file is located at /etc/hostname
```
### Attributes
Each class can define its **attributes**. When we instantiate an object, we assign values to those attributes. For example, every `File` object has a path. Attributes are sometimes called **properties**.
Perl has no special syntax for attributes. Under the hood, attributes are often stored as keys in the object's underlying hash, but don't worry about this.
We recommend that you only access attributes via **accessor** methods. These are methods that can get or set the value of each attribute. We saw this earlier in the `print_info()` example, which calls `$self->path`.
You might also see the terms **getter** and **setter**. These are two types of accessors. A getter gets the attribute's value, while a setter sets it. Another term for a setter is **mutator**
Attributes are typically defined as read-only or read-write. Read-only attributes can only be set when the object is first created, while read-write attributes can be altered at any time.
The value of an attribute may itself be another object. For example, instead of returning its last mod time as a number, the `File` class could return a [DateTime](datetime) object representing that value.
It's possible to have a class that does not expose any publicly settable attributes. Not every class has attributes and methods.
### Polymorphism
**Polymorphism** is a fancy way of saying that objects from two different classes share an API. For example, we could have `File` and `WebPage` classes which both have a `print_content()` method. This method might produce different output for each class, but they share a common interface.
While the two classes may differ in many ways, when it comes to the `print_content()` method, they are the same. This means that we can try to call the `print_content()` method on an object of either class, and **we don't have to know what class the object belongs to!**
Polymorphism is one of the key concepts of object-oriented design.
### Inheritance
**Inheritance** lets you create a specialized version of an existing class. Inheritance lets the new class reuse the methods and attributes of another class.
For example, we could create an `File::MP3` class which **inherits** from `File`. An `File::MP3` **is-a** *more specific* type of `File`. All mp3 files are files, but not all files are mp3 files.
We often refer to inheritance relationships as **parent-child** or `superclass`/`subclass` relationships. Sometimes we say that the child has an **is-a** relationship with its parent class.
`File` is a **superclass** of `File::MP3`, and `File::MP3` is a **subclass** of `File`.
```
package File::MP3;
use parent 'File';
```
The <parent> module is one of several ways that Perl lets you define inheritance relationships.
Perl allows multiple inheritance, which means that a class can inherit from multiple parents. While this is possible, we strongly recommend against it. Generally, you can use **roles** to do everything you can do with multiple inheritance, but in a cleaner way.
Note that there's nothing wrong with defining multiple subclasses of a given class. This is both common and safe. For example, we might define `File::MP3::FixedBitrate` and `File::MP3::VariableBitrate` classes to distinguish between different types of mp3 file.
####
Overriding methods and method resolution
Inheritance allows two classes to share code. By default, every method in the parent class is also available in the child. The child can explicitly **override** a parent's method to provide its own implementation. For example, if we have an `File::MP3` object, it has the `print_info()` method from `File`:
```
my $cage = File::MP3->new(
path => 'mp3s/My-Body-Is-a-Cage.mp3',
content => $mp3_data,
last_mod_time => 1304974868,
title => 'My Body Is a Cage',
);
$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3
```
If we wanted to include the mp3's title in the greeting, we could override the method:
```
package File::MP3;
use parent 'File';
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
print "Its title is ", $self->title, "\n";
}
$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3
# Its title is My Body Is a Cage
```
The process of determining what method should be used is called **method resolution**. What Perl does is look at the object's class first (`File::MP3` in this case). If that class defines the method, then that class's version of the method is called. If not, Perl looks at each parent class in turn. For `File::MP3`, its only parent is `File`. If `File::MP3` does not define the method, but `File` does, then Perl calls the method in `File`.
If `File` inherited from `DataSource`, which inherited from `Thing`, then Perl would keep looking "up the chain" if necessary.
It is possible to explicitly call a parent method from a child:
```
package File::MP3;
use parent 'File';
sub print_info {
my $self = shift;
$self->SUPER::print_info();
print "Its title is ", $self->title, "\n";
}
```
The `SUPER::` bit tells Perl to look for the `print_info()` in the `File::MP3` class's inheritance chain. When it finds the parent class that implements this method, the method is called.
We mentioned multiple inheritance earlier. The main problem with multiple inheritance is that it greatly complicates method resolution. See <perlobj> for more details.
### Encapsulation
**Encapsulation** is the idea that an object is opaque. When another developer uses your class, they don't need to know *how* it is implemented, they just need to know *what* it does.
Encapsulation is important for several reasons. First, it allows you to separate the public API from the private implementation. This means you can change that implementation without breaking the API.
Second, when classes are well encapsulated, they become easier to subclass. Ideally, a subclass uses the same APIs to access object data that its parent class uses. In reality, subclassing sometimes involves violating encapsulation, but a good API can minimize the need to do this.
We mentioned earlier that most Perl objects are implemented as hashes under the hood. The principle of encapsulation tells us that we should not rely on this. Instead, we should use accessor methods to access the data in that hash. The object systems that we recommend below all automate the generation of accessor methods. If you use one of them, you should never have to access the object as a hash directly.
### Composition
In object-oriented code, we often find that one object references another object. This is called **composition**, or a **has-a** relationship.
Earlier, we mentioned that the `File` class's `last_mod_time` accessor could return a [DateTime](datetime) object. This is a perfect example of composition. We could go even further, and make the `path` and `content` accessors return objects as well. The `File` class would then be **composed** of several other objects.
### Roles
**Roles** are something that a class *does*, rather than something that it *is*. Roles are relatively new to Perl, but have become rather popular. Roles are **applied** to classes. Sometimes we say that classes **consume** roles.
Roles are an alternative to inheritance for providing polymorphism. Let's assume we have two classes, `Radio` and `Computer`. Both of these things have on/off switches. We want to model that in our class definitions.
We could have both classes inherit from a common parent, like `Machine`, but not all machines have on/off switches. We could create a parent class called `HasOnOffSwitch`, but that is very artificial. Radios and computers are not specializations of this parent. This parent is really a rather ridiculous creation.
This is where roles come in. It makes a lot of sense to create a `HasOnOffSwitch` role and apply it to both classes. This role would define a known API like providing `turn_on()` and `turn_off()` methods.
Perl does not have any built-in way to express roles. In the past, people just bit the bullet and used multiple inheritance. Nowadays, there are several good choices on CPAN for using roles.
###
When to Use OO
Object Orientation is not the best solution to every problem. In *Perl Best Practices* (copyright 2004, Published by O'Reilly Media, Inc.), Damian Conway provides a list of criteria to use when deciding if OO is the right fit for your problem:
* The system being designed is large, or is likely to become large.
* The data can be aggregated into obvious structures, especially if there's a large amount of data in each aggregate.
* The various types of data aggregate form a natural hierarchy that facilitates the use of inheritance and polymorphism.
* You have a piece of data on which many different operations are applied.
* You need to perform the same general operations on related types of data, but with slight variations depending on the specific type of data the operations are applied to.
* It's likely you'll have to add new data types later.
* The typical interactions between pieces of data are best represented by operators.
* The implementation of individual components of the system is likely to change over time.
* The system design is already object-oriented.
* Large numbers of other programmers will be using your code modules.
PERL OO SYSTEMS
----------------
As we mentioned before, Perl's built-in OO system is very minimal, but also quite flexible. Over the years, many people have developed systems which build on top of Perl's built-in system to provide more features and convenience.
We strongly recommend that you use one of these systems. Even the most minimal of them eliminates a lot of repetitive boilerplate. There's really no good reason to write your classes from scratch in Perl.
If you are interested in the guts underlying these systems, check out <perlobj>.
### Moose
[Moose](moose) bills itself as a "postmodern object system for Perl 5". Don't be scared, the "postmodern" label is a callback to Larry's description of Perl as "the first postmodern computer language".
`Moose` provides a complete, modern OO system. Its biggest influence is the Common Lisp Object System, but it also borrows ideas from Smalltalk and several other languages. `Moose` was created by Stevan Little, and draws heavily from his work on the Raku OO design.
Here is our `File` class using `Moose`:
```
package File;
use Moose;
has path => ( is => 'ro' );
has content => ( is => 'ro' );
has last_mod_time => ( is => 'ro' );
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
}
```
`Moose` provides a number of features:
* Declarative sugar
`Moose` provides a layer of declarative "sugar" for defining classes. That sugar is just a set of exported functions that make declaring how your class works simpler and more palatable. This lets you describe *what* your class is, rather than having to tell Perl *how* to implement your class.
The `has()` subroutine declares an attribute, and `Moose` automatically creates accessors for these attributes. It also takes care of creating a `new()` method for you. This constructor knows about the attributes you declared, so you can set them when creating a new `File`.
* Roles built-in
`Moose` lets you define roles the same way you define classes:
```
package HasOnOffSwitch;
use Moose::Role;
has is_on => (
is => 'rw',
isa => 'Bool',
);
sub turn_on {
my $self = shift;
$self->is_on(1);
}
sub turn_off {
my $self = shift;
$self->is_on(0);
}
```
* A miniature type system
In the example above, you can see that we passed `isa => 'Bool'` to `has()` when creating our `is_on` attribute. This tells `Moose` that this attribute must be a boolean value. If we try to set it to an invalid value, our code will throw an error.
* Full introspection and manipulation
Perl's built-in introspection features are fairly minimal. `Moose` builds on top of them and creates a full introspection layer for your classes. This lets you ask questions like "what methods does the File class implement?" It also lets you modify your classes programmatically.
* Self-hosted and extensible
`Moose` describes itself using its own introspection API. Besides being a cool trick, this means that you can extend `Moose` using `Moose` itself.
* Rich ecosystem
There is a rich ecosystem of `Moose` extensions on CPAN under the [MooseX](https://metacpan.org/search?q=MooseX) namespace. In addition, many modules on CPAN already use `Moose`, providing you with lots of examples to learn from.
* Many more features
`Moose` is a very powerful tool, and we can't cover all of its features here. We encourage you to learn more by reading the `Moose` documentation, starting with [Moose::Manual](https://metacpan.org/pod/Moose::Manual).
Of course, `Moose` isn't perfect.
`Moose` can make your code slower to load. `Moose` itself is not small, and it does a *lot* of code generation when you define your class. This code generation means that your runtime code is as fast as it can be, but you pay for this when your modules are first loaded.
This load time hit can be a problem when startup speed is important, such as with a command-line script or a "plain vanilla" CGI script that must be loaded each time it is executed.
Before you panic, know that many people do use `Moose` for command-line tools and other startup-sensitive code. We encourage you to try `Moose` out first before worrying about startup speed.
`Moose` also has several dependencies on other modules. Most of these are small stand-alone modules, a number of which have been spun off from `Moose`. `Moose` itself, and some of its dependencies, require a compiler. If you need to install your software on a system without a compiler, or if having *any* dependencies is a problem, then `Moose` may not be right for you.
#### Moo
If you try `Moose` and find that one of these issues is preventing you from using `Moose`, we encourage you to consider [Moo](moo) next. `Moo` implements a subset of `Moose`'s functionality in a simpler package. For most features that it does implement, the end-user API is *identical* to `Moose`, meaning you can switch from `Moo` to `Moose` quite easily.
`Moo` does not implement most of `Moose`'s introspection API, so it's often faster when loading your modules. Additionally, none of its dependencies require XS, so it can be installed on machines without a compiler.
One of `Moo`'s most compelling features is its interoperability with `Moose`. When someone tries to use `Moose`'s introspection API on a `Moo` class or role, it is transparently inflated into a `Moose` class or role. This makes it easier to incorporate `Moo`-using code into a `Moose` code base and vice versa.
For example, a `Moose` class can subclass a `Moo` class using `extends` or consume a `Moo` role using `with`.
The `Moose` authors hope that one day `Moo` can be made obsolete by improving `Moose` enough, but for now it provides a worthwhile alternative to `Moose`.
###
Class::Accessor
<Class::Accessor> is the polar opposite of `Moose`. It provides very few features, nor is it self-hosting.
It is, however, very simple, pure Perl, and it has no non-core dependencies. It also provides a "Moose-like" API on demand for the features it supports.
Even though it doesn't do much, it is still preferable to writing your own classes from scratch.
Here's our `File` class with `Class::Accessor`:
```
package File;
use Class::Accessor 'antlers';
has path => ( is => 'ro' );
has content => ( is => 'ro' );
has last_mod_time => ( is => 'ro' );
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
}
```
The `antlers` import flag tells `Class::Accessor` that you want to define your attributes using `Moose`-like syntax. The only parameter that you can pass to `has` is `is`. We recommend that you use this Moose-like syntax if you choose `Class::Accessor` since it means you will have a smoother upgrade path if you later decide to move to `Moose`.
Like `Moose`, `Class::Accessor` generates accessor methods and a constructor for your class.
###
Class::Tiny
Finally, we have <Class::Tiny>. This module truly lives up to its name. It has an incredibly minimal API and absolutely no dependencies on any recent Perl. Still, we think it's a lot easier to use than writing your own OO code from scratch.
Here's our `File` class once more:
```
package File;
use Class::Tiny qw( path content last_mod_time );
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
}
```
That's it!
With `Class::Tiny`, all accessors are read-write. It generates a constructor for you, as well as the accessors you define.
You can also use <Class::Tiny::Antlers> for `Moose`-like syntax.
###
Role::Tiny
As we mentioned before, roles provide an alternative to inheritance, but Perl does not have any built-in role support. If you choose to use Moose, it comes with a full-fledged role implementation. However, if you use one of our other recommended OO modules, you can still use roles with <Role::Tiny>
`Role::Tiny` provides some of the same features as Moose's role system, but in a much smaller package. Most notably, it doesn't support any sort of attribute declaration, so you have to do that by hand. Still, it's useful, and works well with `Class::Accessor` and `Class::Tiny`
###
OO System Summary
Here's a brief recap of the options we covered:
* [Moose](moose)
`Moose` is the maximal option. It has a lot of features, a big ecosystem, and a thriving user base. We also covered [Moo](moo) briefly. `Moo` is `Moose` lite, and a reasonable alternative when Moose doesn't work for your application.
* <Class::Accessor>
`Class::Accessor` does a lot less than `Moose`, and is a nice alternative if you find `Moose` overwhelming. It's been around a long time and is well battle-tested. It also has a minimal `Moose` compatibility mode which makes moving from `Class::Accessor` to `Moose` easy.
* <Class::Tiny>
`Class::Tiny` is the absolute minimal option. It has no dependencies, and almost no syntax to learn. It's a good option for a super minimal environment and for throwing something together quickly without having to worry about details.
* <Role::Tiny>
Use `Role::Tiny` with `Class::Accessor` or `Class::Tiny` if you find yourself considering multiple inheritance. If you go with `Moose`, it comes with its own role implementation.
###
Other OO Systems
There are literally dozens of other OO-related modules on CPAN besides those covered here, and you're likely to run across one or more of them if you work with other people's code.
In addition, plenty of code in the wild does all of its OO "by hand", using just the Perl built-in OO features. If you need to maintain such code, you should read <perlobj> to understand exactly how Perl's built-in OO works.
CONCLUSION
----------
As we said before, Perl's minimal OO system has led to a profusion of OO systems on CPAN. While you can still drop down to the bare metal and write your classes by hand, there's really no reason to do that with modern Perl.
For small systems, <Class::Tiny> and <Class::Accessor> both provide minimal object systems that take care of basic boilerplate for you.
For bigger projects, [Moose](moose) provides a rich set of features that will let you focus on implementing your business logic. [Moo](moo) provides a nice alternative to [Moose](moose) when you want a lot of features but need faster compile time or to avoid XS.
We encourage you to play with and evaluate [Moose](moose), [Moo](moo), <Class::Accessor>, and <Class::Tiny> to see which OO system is right for you.
| programming_docs |
perl perlref perlref
=======
CONTENTS
--------
* [NAME](#NAME)
* [NOTE](#NOTE)
* [DESCRIPTION](#DESCRIPTION)
+ [Making References](#Making-References)
- [Backslash Operator](#Backslash-Operator)
- [Square Brackets](#Square-Brackets)
- [Curly Brackets](#Curly-Brackets)
- [Anonymous Subroutines](#Anonymous-Subroutines)
- [Constructors](#Constructors)
- [Autovivification](#Autovivification)
- [Typeglob Slots](#Typeglob-Slots)
+ [Using References](#Using-References)
- [Simple Scalar](#Simple-Scalar)
- [Block](#Block)
- [Arrow Notation](#Arrow-Notation)
- [Objects](#Objects)
- [Miscellaneous Usage](#Miscellaneous-Usage)
+ [Circular References](#Circular-References)
+ [Symbolic references](#Symbolic-references)
+ [Not-so-symbolic references](#Not-so-symbolic-references)
+ [Pseudo-hashes: Using an array as a hash](#Pseudo-hashes:-Using-an-array-as-a-hash)
+ [Function Templates](#Function-Templates)
+ [Postfix Dereference Syntax](#Postfix-Dereference-Syntax)
+ [Postfix Reference Slicing](#Postfix-Reference-Slicing)
+ [Assigning to References](#Assigning-to-References)
+ [Declaring a Reference to a Variable](#Declaring-a-Reference-to-a-Variable)
* [WARNING: Don't use references as hash keys](#WARNING:-Don't-use-references-as-hash-keys)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlref - Perl references and nested data structures
NOTE
----
This is complete documentation about all aspects of references. For a shorter, tutorial introduction to just the essential features, see <perlreftut>.
DESCRIPTION
-----------
Before release 5 of Perl it was difficult to represent complex data structures, because all references had to be symbolic--and even then it was difficult to refer to a variable instead of a symbol table entry. Perl now not only makes it easier to use symbolic references to variables, but also lets you have "hard" references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on.
Hard references are smart--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see ["Circular References"](#Circular-References) for a detailed explanation.) If that thing happens to be an object, the object is destructed. See <perlobj> for more about objects. (In a sense, everything in Perl is an object, but we usually reserve the word for references to objects that have been officially "blessed" into a class package.)
Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The `*glob` notation is something of a symbolic reference. (Symbolic references are sometimes called "soft references", but please don't call them that; references are confusing enough without useless synonyms.)
In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word "reference" is used without an adjective, as in the following paragraph, it is usually talking about a hard reference.
References are easy to use in Perl. There is just one overriding principle: in general, Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it.
###
Making References
References can be created in several ways.
####
Backslash Operator
By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates *another* reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples:
```
$scalarref = \$foo;
$arrayref = \@ARGV;
$hashref = \%ENV;
$coderef = \&handler;
$globref = \*foo;
```
It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the `*foo{THING}` syntax below. However, you can still use type globs and globrefs as though they were IO handles.
####
Square Brackets
A reference to an anonymous array can be created using square brackets:
```
$arrayref = [1, 2, ['a', 'b', 'c']];
```
Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, `$arrayref->[2][1]` would have the value "b".)
Taking a reference to an enumerated list is not the same as using square brackets--instead it's the same as creating a list of references!
```
@list = (\$a, \@b, \%c);
@list = \($a, @b, %c); # same thing!
```
As a special case, `\(@foo)` returns a list of references to the contents of `@foo`, not a reference to `@foo` itself. Likewise for `%foo`, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars).
####
Curly Brackets
A reference to an anonymous hash can be created using curly brackets:
```
$hashref = {
'Adam' => 'Eve',
'Clyde' => 'Bonnie',
};
```
Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within local() or my()) are executable statements, not compile-time declarations.
Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a `+` or a `return` in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.
For example, if you wanted a function to make a new hash and return a reference to it, you have these options:
```
sub hashem { { @_ } } # silently wrong
sub hashem { +{ @_ } } # ok
sub hashem { return { @_ } } # ok
```
On the other hand, if you want the other meaning, you can do this:
```
sub showem { { @_ } } # ambiguous (currently ok,
# but may change)
sub showem { {; @_ } } # ok
sub showem { { return @_ } } # ok
```
The leading `+{` and `{;` always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK.
####
Anonymous Subroutines
A reference to an anonymous subroutine can be created by using `sub` without a subname:
```
$coderef = sub { print "Boink!\n" };
```
Note the semicolon. Except for the code inside not being immediately executed, a `sub {}` is not so much a declaration as it is an operator, like `do{}` or `eval{}`. (However, no matter how many times you execute that particular line (unless you're in an `eval("...")`), $coderef will still have a reference to the *same* anonymous subroutine.)
Anonymous subroutines act as closures with respect to my() variables, that is, variables lexically visible within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside the context.
In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see <perlobj>.
You might also think of closure as a way to write a subroutine template without using eval(). Here's a small example of how closures work:
```
sub newprint {
my $x = shift;
return sub { my $y = shift; print "$x, $y!\n"; };
}
$h = newprint("Howdy");
$g = newprint("Greetings");
# Time passes...
&$h("world");
&$g("earthlings");
```
This prints
```
Howdy, world!
Greetings, earthlings!
```
Note particularly that $x continues to refer to the value passed into newprint() *despite* "my $x" having gone out of scope by the time the anonymous subroutine runs. That's what a closure is all about.
This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with.
#### Constructors
References are often returned by special subroutines called constructors. Perl objects are just references to a special type of object that happens to know which package it's associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it's also being an object. Constructors are often named `new()`. You *can* call them indirectly:
```
$objref = new Doggie( Tail => 'short', Ears => 'long' );
```
But that can produce ambiguous syntax in certain cases, so it's often better to use the direct method invocation approach:
```
$objref = Doggie->new(Tail => 'short', Ears => 'long');
use Term::Cap;
$terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
use Tk;
$main = MainWindow->new();
$menubar = $main->Frame(-relief => "raised",
-borderwidth => 2)
```
This indirect object syntax is only available when [`use feature "indirect"`](feature#The-%27indirect%27-feature) is in effect, and that is not the case when [`use v5.36`](perlfunc#use-VERSION) (or higher) is requested, it is best to avoid indirect object syntax entirely.
#### Autovivification
References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet.
####
Typeglob Slots
A reference can be created by using a special syntax, lovingly known as the \*foo{THING} syntax. \*foo{THING} returns a reference to the THING slot in \*foo (which is the symbol table entry which holds everything known as foo).
```
$scalarref = *foo{SCALAR};
$arrayref = *ARGV{ARRAY};
$hashref = *ENV{HASH};
$coderef = *handler{CODE};
$ioref = *STDIN{IO};
$globref = *foo{GLOB};
$formatref = *foo{FORMAT};
$globname = *foo{NAME}; # "foo"
$pkgname = *foo{PACKAGE}; # "main"
```
Most of these are self-explanatory, but `*foo{IO}` deserves special attention. It returns the IO handle, used for file handles (["open" in perlfunc](perlfunc#open)), sockets (["socket" in perlfunc](perlfunc#socket) and ["socketpair" in perlfunc](perlfunc#socketpair)), and directory handles (["opendir" in perlfunc](perlfunc#opendir)). For compatibility with previous versions of Perl, `*foo{FILEHANDLE}` is a synonym for `*foo{IO}`, though it is discouraged, to encourage a consistent use of one name: IO. On perls between v5.8 and v5.22, it will issue a deprecation warning, but this deprecation has since been rescinded.
`*foo{THING}` returns undef if that particular THING hasn't been used yet, except in the case of scalars. `*foo{SCALAR}` returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release.
`*foo{NAME}` and `*foo{PACKAGE}` are the exception, in that they return strings, rather than references. These return the package and name of the typeglob itself, rather than one that has been assigned to it. So, after `*foo=*Foo::bar`, `*foo` will become "\*Foo::bar" when used as a string, but `*foo{PACKAGE}` and `*foo{NAME}` will continue to produce "main" and "foo", respectively.
`*foo{IO}` is an alternative to the `*HANDLE` mechanism given in ["Typeglobs and Filehandles" in perldata](perldata#Typeglobs-and-Filehandles) for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won't create a new filehandle for you. Its advantage is that you have less risk of clobbering more than you want to with a typeglob assignment. (It still conflates file and directory handles, though.) However, if you assign the incoming value to a scalar instead of a typeglob as we do in the examples below, there's no risk of that happening.
```
splutter(*STDOUT); # pass the whole glob
splutter(*STDOUT{IO}); # pass both file and dir handles
sub splutter {
my $fh = shift;
print $fh "her um well a hmmm\n";
}
$rec = get_rec(*STDIN); # pass the whole glob
$rec = get_rec(*STDIN{IO}); # pass both file and dir handles
sub get_rec {
my $fh = shift;
return scalar <$fh>;
}
```
###
Using References
That's it for creating references. By now you're probably dying to know how to use references to get back to your long-lost data. There are several basic methods.
####
Simple Scalar
Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type:
```
$bar = $$scalarref;
push(@$arrayref, $filename);
$$arrayref[0] = "January";
$$hashref{"KEY"} = "VALUE";
&$coderef(1,2,3);
print $globref "output\n";
```
It's important to understand that we are specifically *not* dereferencing `$arrayref[0]` or `$hashref{"KEY"}` there. The dereference of the scalar variable happens *before* it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a "simple scalar" includes an identifier that itself uses method 1 recursively. Therefore, the following prints "howdy".
```
$refrefref = \\\"howdy";
print $$$$refrefref;
```
#### Block
Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type. In other words, the previous examples could be written like this:
```
$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = "January";
${$hashref}{"KEY"} = "VALUE";
&{$coderef}(1,2,3);
$globref->print("output\n"); # iff IO::Handle is loaded
```
Admittedly, it's a little silly to use the curlies in this case, but the BLOCK can contain any arbitrary expression, in particular, subscripted expressions:
```
&{ $dispatch{$index} }(1,2,3); # call correct routine
```
Because of being able to omit the curlies for the simple case of `$$x`, people often make the mistake of viewing the dereferencing symbols as proper operators, and wonder about their precedence. If they were, though, you could use parentheses instead of braces. That's not the case. Consider the difference below; case 0 is a short-hand version of case 1, *not* case 2:
```
$$hashref{"KEY"} = "VALUE"; # CASE 0
${$hashref}{"KEY"} = "VALUE"; # CASE 1
${$hashref{"KEY"}} = "VALUE"; # CASE 2
${$hashref->{"KEY"}} = "VALUE"; # CASE 3
```
Case 2 is also deceptive in that you're accessing a variable called %hashref, not dereferencing through $hashref to the hash it's presumably referencing. That would be case 3.
####
Arrow Notation
Subroutine calls and lookups of individual array elements arise often enough that it gets cumbersome to use method 2. As a form of syntactic sugar, the examples for method 2 may be written:
```
$arrayref->[0] = "January"; # Array element
$hashref->{"KEY"} = "VALUE"; # Hash element
$coderef->(1,2,3); # Subroutine call
```
The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that `$array[$x]` is *not* the same thing as `$array->[$x]` here:
```
$array[$x]->{"foo"}->[0] = "January";
```
This is one of the cases we mentioned earlier in which references could spring into existence when in an lvalue context. Before this statement, `$array[$x]` may have been undefined. If so, it's automatically defined with a hash reference so that we can look up `{"foo"}` in it. Likewise `$array[$x]->{"foo"}` will automatically get defined with an array reference so that we can look up `[0]` in it. This process is called *autovivification*.
One more thing here. The arrow is optional *between* brackets subscripts, so you can shrink the above down to
```
$array[$x]{"foo"}[0] = "January";
```
Which, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays just like C's:
```
$score[$x][$y][$z] += 42;
```
Well, okay, not entirely like C's arrays, actually. C doesn't know how to grow its arrays on demand. Perl does.
#### Objects
If a reference happens to be a reference to an object, then there are probably methods to access the things referred to, and you should probably stick to those methods unless you're in the class package that defines the object's methods. In other words, be nice, and don't violate the object's encapsulation without a very good reason. Perl does not enforce encapsulation. We are not totalitarians here. We do expect some basic civility though.
####
Miscellaneous Usage
Using a string or number as a reference produces a symbolic reference, as explained above. Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two references numerically to see whether they refer to the same location.
```
if ($ref1 == $ref2) { # cheap numeric compare of references
print "refs 1 and 2 refer to the same thing\n";
}
```
Using a reference as a string produces both its referent's type, including any package blessing as described in <perlobj>, as well as the numeric address expressed in hex. The ref() operator returns just the type of thing the reference is pointing to, without the address. See ["ref" in perlfunc](perlfunc#ref) for details and examples of its use.
The bless() operator may be used to associate the object a reference points to with a package functioning as an object class. See <perlobj>.
A typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the type of reference desired. So `${*foo}` and `${\$foo}` both indicate the same scalar variable.
Here's a trick for interpolating a subroutine call into a string:
```
print "My sub returned @{[mysub(1,2,3)]} that time.\n";
```
The way it works is that when the `@{...}` is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to `mysub(1,2,3)`. So the whole block returns a reference to an array, which is then dereferenced by `@{...}` and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions:
```
print "That yields @{[$n + 5]} widgets\n";
```
Similarly, an expression that returns a reference to a scalar can be dereferenced via `${...}`. Thus, the above expression may be written as:
```
print "That yields ${\($n + 5)} widgets\n";
```
###
Circular References
It is possible to create a "circular reference" in Perl, which can lead to memory leaks. A circular reference occurs when two references contain a reference to each other, like this:
```
my $foo = {};
my $bar = { foo => $foo };
$foo->{bar} = $bar;
```
You can also create a circular reference with a single variable:
```
my $foo;
$foo = \$foo;
```
In this case, the reference count for the variables will never reach 0, and the references will never be garbage-collected. This can lead to memory leaks.
Because objects in Perl are implemented as references, it's possible to have circular references with objects as well. Imagine a TreeNode class where each node references its parent and child nodes. Any node with a parent will be part of a circular reference.
You can break circular references by creating a "weak reference". A weak reference does not increment the reference count for a variable, which means that the object can go out of scope and be destroyed. You can weaken a reference with the `weaken` function exported by the <Scalar::Util> module, or available as `builtin::weaken` directly in Perl version 5.35.7 or later.
Here's how we can make the first example safer:
```
use Scalar::Util 'weaken';
my $foo = {};
my $bar = { foo => $foo };
$foo->{bar} = $bar;
weaken $foo->{bar};
```
The reference from `$foo` to `$bar` has been weakened. When the `$bar` variable goes out of scope, it will be garbage-collected. The next time you look at the value of the `$foo->{bar}` key, it will be `undef`.
This action at a distance can be confusing, so you should be careful with your use of weaken. You should weaken the reference in the variable that will go out of scope *first*. That way, the longer-lived variable will contain the expected reference until it goes out of scope.
###
Symbolic references
We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but *isn't* a hard reference. If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the *name* of a variable, rather than a direct link to a (possibly) anonymous value.
People frequently expect it to work like this. So it does.
```
$name = "foo";
$$name = 1; # Sets $foo
${$name} = 2; # Sets $foo
${$name x 2} = 3; # Sets $foofoo
$name->[0] = 4; # Sets $foo[0]
@$name = (); # Clears @foo
&$name(); # Calls &foo()
$pack = "THAT";
${"${pack}::$name"} = 5; # Sets $THAT::foo without eval
```
This is powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say
```
use strict 'refs';
```
and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand that with
```
no strict 'refs';
```
Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren't in a symbol table, and thus are invisible to this mechanism. For example:
```
local $value = 10;
$ref = "value";
{
my $value = 20;
print $$ref;
}
```
This will still print 10, not 20. Remember that local() affects package variables, which are all "global" to the package.
###
Not-so-symbolic references
Brackets around a symbolic reference can simply serve to isolate an identifier or variable name from the rest of an expression, just as they always have within a string. For example,
```
$push = "pop on ";
print "${push}over";
```
has always meant to print "pop on over", even though push is a reserved word. This is generalized to work the same without the enclosing double quotes, so that
```
print ${push} . "over";
```
and even
```
print ${ push } . "over";
```
will have the same effect. This construct is *not* considered to be a symbolic reference when you're using strict refs:
```
use strict 'refs';
${ bareword }; # Okay, means $bareword.
${ "bareword" }; # Error, symbolic reference.
```
Similarly, because of all the subscripting that is done using single words, the same rule applies to any bareword that is used for subscripting a hash. So now, instead of writing
```
$hash{ "aaa" }{ "bbb" }{ "ccc" }
```
you can write just
```
$hash{ aaa }{ bbb }{ ccc }
```
and not worry about whether the subscripts are reserved words. In the rare event that you do wish to do something like
```
$hash{ shift }
```
you can force interpretation as a reserved word by adding anything that makes it more than a bareword:
```
$hash{ shift() }
$hash{ +shift }
$hash{ shift @_ }
```
The `use warnings` pragma or the **-w** switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted.
###
Pseudo-hashes: Using an array as a hash
Pseudo-hashes have been removed from Perl. The 'fields' pragma remains available.
###
Function Templates
As explained above, an anonymous function with access to the lexical variables visible when that function was compiled, creates a closure. It retains access to those variables even though it doesn't get run until later, such as in a signal handler or a Tk callback.
Using a closure as a function template allows us to generate many functions that act similarly. Suppose you wanted functions named after the colors that generated HTML font changes for the various colors:
```
print "Be ", red("careful"), "with that ", green("light");
```
The red() and green() functions would be similar. To create these, we'll assign a closure to a typeglob of the name of the function we're trying to build.
```
@colors = qw(red blue green yellow orange purple violet);
for my $name (@colors) {
no strict 'refs'; # allow symbol table manipulation
*$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
}
```
Now all those different functions appear to exist independently. You can call red(), RED(), blue(), BLUE(), green(), etc. This technique saves on both compile time and memory use, and is less error-prone as well, since syntax checks happen at compile time. It's critical that any variables in the anonymous subroutine be lexicals in order to create a proper closure. That's the reasons for the `my` on the loop iteration variable.
This is one of the only places where giving a prototype to a closure makes much sense. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea for this particular example), you could have written it this way instead:
```
*$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
```
However, since prototype checking happens at compile time, the assignment above happens too late to be of much use. You could address this by putting the whole loop of assignments within a BEGIN block, forcing it to occur during compilation.
Access to lexicals that change over time--like those in the `for` loop above, basically aliases to elements from the surrounding lexical scopes-- only works with anonymous subs, not with named subroutines. Generally said, named subroutines do not nest properly and should only be declared in the main package scope.
This is because named subroutines are created at compile time so their lexical variables get assigned to the parent lexicals from the first execution of the parent block. If a parent scope is entered a second time, its lexicals are created again, while the nested subs still reference the old ones.
Anonymous subroutines get to capture each time you execute the `sub` operator, as they are created on the fly. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you'll have to work at it a bit in Perl. The intuitive coding of this type of thing incurs mysterious warnings about "will not stay shared" due to the reasons explained above. For example, this won't work:
```
sub outer {
my $x = $_[0] + 35;
sub inner { return $x * 19 } # WRONG
return $x + inner();
}
```
A work-around is the following:
```
sub outer {
my $x = $_[0] + 35;
local *inner = sub { return $x * 19 };
return $x + inner();
}
```
Now inner() can only be called from within outer(), because of the temporary assignments of the anonymous subroutine. But when it does, it has normal access to the lexical variable $x from the scope of outer() at the time outer is invoked.
This has the interesting effect of creating a function local to another function, something not normally supported in Perl.
###
Postfix Dereference Syntax
Beginning in v5.20.0, a postfix syntax for using references is available. It behaves as described in ["Using References"](#Using-References), but instead of a prefixed sigil, a postfixed sigil-and-star is used.
For example:
```
$r = \@a;
@b = $r->@*; # equivalent to @$r or @{ $r }
$r = [ 1, [ 2, 3 ], 4 ];
$r->[1]->@*; # equivalent to @{ $r->[1] }
```
In Perl 5.20 and 5.22, this syntax must be enabled with `use feature 'postderef'`. As of Perl 5.24, no feature declarations are required to make it available.
Postfix dereference should work in all circumstances where block (circumfix) dereference worked, and should be entirely equivalent. This syntax allows dereferencing to be written and read entirely left-to-right. The following equivalencies are defined:
```
$sref->$*; # same as ${ $sref }
$aref->@*; # same as @{ $aref }
$aref->$#*; # same as $#{ $aref }
$href->%*; # same as %{ $href }
$cref->&*; # same as &{ $cref }
$gref->**; # same as *{ $gref }
```
Note especially that `$cref->&*` is *not* equivalent to `$cref->()`, and can serve different purposes.
Glob elements can be extracted through the postfix dereferencing feature:
```
$gref->*{SCALAR}; # same as *{ $gref }{SCALAR}
```
Postfix array and scalar dereferencing *can* be used in interpolating strings (double quotes or the `qq` operator), but only if the `postderef_qq` feature is enabled.
###
Postfix Reference Slicing
Value slices of arrays and hashes may also be taken with postfix dereferencing notation, with the following equivalencies:
```
$aref->@[ ... ]; # same as @$aref[ ... ]
$href->@{ ... }; # same as @$href{ ... }
```
Postfix key/value pair slicing, added in 5.20.0 and documented in [the Key/Value Hash Slices section of perldata](perldata#Key%2FValue-Hash-Slices), also behaves as expected:
```
$aref->%[ ... ]; # same as %$aref[ ... ]
$href->%{ ... }; # same as %$href{ ... }
```
As with postfix array, postfix value slice dereferencing *can* be used in interpolating strings (double quotes or the `qq` operator), but only if the `postderef_qq` <feature> is enabled.
###
Assigning to References
Beginning in v5.22.0, the referencing operator can be assigned to. It performs an aliasing operation, so that the variable name referenced on the left-hand side becomes an alias for the thing referenced on the right-hand side:
```
\$a = \$b; # $a and $b now point to the same scalar
\&foo = \&bar; # foo() now means bar()
```
This syntax must be enabled with `use feature 'refaliasing'`. It is experimental, and will warn by default unless `no warnings 'experimental::refaliasing'` is in effect.
These forms may be assigned to, and cause the right-hand side to be evaluated in scalar context:
```
\$scalar
\@array
\%hash
\&sub
\my $scalar
\my @array
\my %hash
\state $scalar # or @array, etc.
\our $scalar # etc.
\local $scalar # etc.
\local our $scalar # etc.
\$some_array[$index]
\$some_hash{$key}
\local $some_array[$index]
\local $some_hash{$key}
condition ? \$this : \$that[0] # etc.
```
Slicing operations and parentheses cause the right-hand side to be evaluated in list context:
```
\@array[5..7]
(\@array[5..7])
\(@array[5..7])
\@hash{'foo','bar'}
(\@hash{'foo','bar'})
\(@hash{'foo','bar'})
(\$scalar)
\($scalar)
\(my $scalar)
\my($scalar)
(\@array)
(\%hash)
(\&sub)
\(&sub)
\($foo, @bar, %baz)
(\$foo, \@bar, \%baz)
```
Each element on the right-hand side must be a reference to a datum of the right type. Parentheses immediately surrounding an array (and possibly also `my`/`state`/`our`/`local`) will make each element of the array an alias to the corresponding scalar referenced on the right-hand side:
```
\(@a) = \(@b); # @a and @b now have the same elements
\my(@a) = \(@b); # likewise
\(my @a) = \(@b); # likewise
push @a, 3; # but now @a has an extra element that @b lacks
\(@a) = (\$a, \$b, \$c); # @a now contains $a, $b, and $c
```
Combining that form with `local` and putting parentheses immediately around a hash are forbidden (because it is not clear what they should do):
```
\local(@array) = foo(); # WRONG
\(%hash) = bar(); # WRONG
```
Assignment to references and non-references may be combined in lists and conditional ternary expressions, as long as the values on the right-hand side are the right type for each element on the left, though this may make for obfuscated code:
```
(my $tom, \my $dick, \my @harry) = (\1, \2, [1..3]);
# $tom is now \1
# $dick is now 2 (read-only)
# @harry is (1,2,3)
my $type = ref $thingy;
($type ? $type eq 'ARRAY' ? \@foo : \$bar : $baz) = $thingy;
```
The `foreach` loop can also take a reference constructor for its loop variable, though the syntax is limited to one of the following, with an optional `my`, `state`, or `our` after the backslash:
```
\$s
\@a
\%h
\&c
```
No parentheses are permitted. This feature is particularly useful for arrays-of-arrays, or arrays-of-hashes:
```
foreach \my @a (@array_of_arrays) {
frobnicate($a[0], $a[-1]);
}
foreach \my %h (@array_of_hashes) {
$h{gelastic}++ if $h{type} eq 'funny';
}
```
**CAVEAT:** Aliasing does not work correctly with closures. If you try to alias lexical variables from an inner subroutine or `eval`, the aliasing will only be visible within that inner sub, and will not affect the outer subroutine where the variables are declared. This bizarre behavior is subject to change.
###
Declaring a Reference to a Variable
Beginning in v5.26.0, the referencing operator can come after `my`, `state`, `our`, or `local`. This syntax must be enabled with `use feature 'declared_refs'`. It is experimental, and will warn by default unless `no warnings 'experimental::refaliasing'` is in effect.
This feature makes these:
```
my \$x;
our \$y;
```
equivalent to:
```
\my $x;
\our $x;
```
It is intended mainly for use in assignments to references (see ["Assigning to References"](#Assigning-to-References), above). It also allows the backslash to be used on just some items in a list of declared variables:
```
my ($foo, \@bar, \%baz); # equivalent to: my $foo, \my(@bar, %baz);
```
WARNING: Don't use references as hash keys
-------------------------------------------
You may not (usefully) use a reference as the key to a hash. It will be converted into a string:
```
$x{ \$a } = $a;
```
If you try to dereference the key, it won't do a hard dereference, and you won't accomplish what you're attempting. You might want to do something more like
```
$r = \@a;
$x{ $r } = $r;
```
And then at least you can use the values(), which will be real refs, instead of the keys(), which won't.
The standard Tie::RefHash module provides a convenient workaround to this.
SEE ALSO
---------
Besides the obvious documents, source code can be instructive. Some pathological examples of the use of references can be found in the *t/op/ref.t* regression test in the Perl source directory.
See also <perldsc> and <perllol> for how to use references to create complex data structures, and <perlootut> and <perlobj> for how to use them to create objects.
| programming_docs |
perl Search::Dict Search::Dict
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Search::Dict - look - search for key in dictionary file
SYNOPSIS
--------
```
use Search::Dict;
look *FILEHANDLE, $key, $dict, $fold;
use Search::Dict;
look *FILEHANDLE, $params;
```
DESCRIPTION
-----------
Sets file position in FILEHANDLE to be first line greater than or equal (stringwise) to *$key*. Returns the new file position, or -1 if an error occurs.
The flags specify dictionary order and case folding:
If *$dict* is true, search by dictionary order (ignore anything but word characters and whitespace). The default is honour all characters.
If *$fold* is true, ignore case. The default is to honour case.
If there are only three arguments and the third argument is a hash reference, the keys of that hash can have values `dict`, `fold`, and `comp` or `xfrm` (see below), and their corresponding values will be used as the parameters.
If a comparison subroutine (comp) is defined, it must return less than zero, zero, or greater than zero, if the first comparand is less than, equal, or greater than the second comparand.
If a transformation subroutine (xfrm) is defined, its value is used to transform the lines read from the filehandle before their comparison.
perl File::Spec::Functions File::Spec::Functions
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Exports](#Exports)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::Functions - portably perform operations on file names
SYNOPSIS
--------
```
use File::Spec::Functions;
$x = catfile('a','b');
```
DESCRIPTION
-----------
This module exports convenience functions for all of the class methods provided by File::Spec.
For a reference of available functions, please consult <File::Spec::Unix>, which contains the entire set, and which is inherited by the modules for other platforms. For further information, please see <File::Spec::Mac>, <File::Spec::OS2>, <File::Spec::Win32>, or <File::Spec::VMS>.
### Exports
The following functions are exported by default.
```
canonpath
catdir
catfile
curdir
rootdir
updir
no_upwards
file_name_is_absolute
path
```
The following functions are exported only by request.
```
devnull
tmpdir
splitpath
splitdir
catpath
abs2rel
rel2abs
case_tolerant
```
All the functions may be imported using the `:ALL` tag.
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.
SEE ALSO
---------
File::Spec, File::Spec::Unix, File::Spec::Mac, File::Spec::OS2, File::Spec::Win32, File::Spec::VMS, ExtUtils::MakeMaker
perl pl2pm pl2pm
=====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LIMITATIONS](#LIMITATIONS)
* [AUTHOR](#AUTHOR)
NAME
----
pl2pm - Rough tool to translate Perl4 .pl files to Perl5 .pm modules.
SYNOPSIS
--------
**pl2pm** *files*
DESCRIPTION
-----------
**pl2pm** is a tool to aid in the conversion of Perl4-style .pl library files to Perl5-style library modules. Usually, your old .pl file will still work fine and you should only use this tool if you plan to update your library to use some of the newer Perl 5 features, such as AutoLoading.
LIMITATIONS
-----------
It's just a first step, but it's usually a good first step.
AUTHOR
------
Larry Wall <[email protected]>
perl perlrun perlrun
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [#! and quoting on non-Unix systems](#%23!-and-quoting-on-non-Unix-systems)
+ [Location of Perl](#Location-of-Perl)
+ [Command Switches](#Command-Switches)
* [ENVIRONMENT](#ENVIRONMENT)
* [ORDER OF APPLICATION](#ORDER-OF-APPLICATION)
NAME
----
perlrun - how to execute the Perl interpreter
SYNOPSIS
--------
**perl** [ **-gsTtuUWX** ] [ **-h?v** ] [ **-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* ]...
DESCRIPTION
-----------
The normal way to run a Perl program is by making it directly executable, or else by passing the name of the source file as an argument on the command line. (An interactive Perl environment is also possible--see <perldebug> for details on how to do that.) Upon startup, Perl looks for your program in one of the following places:
1. Specified line by line via [-e](#-e-commandline) or [-E](#-E-commandline) switches on the command line.
2. Contained in the file specified by the first filename on the command line. (Note that systems supporting the `#!` notation invoke interpreters this way. See ["Location of Perl"](#Location-of-Perl).)
3. Passed in implicitly via standard input. This works only if there are no filename arguments--to pass arguments to a STDIN-read program you must explicitly specify a "-" for the program name.
With methods 2 and 3, Perl starts parsing the input file from the beginning, unless you've specified a ["-x"](#-x) switch, in which case it scans for the first line starting with `#!` and containing the word "perl", and starts there instead. This is useful for running a program embedded in a larger message. (In this case you would indicate the end of the program using the `__END__` token.)
The `#!` line is always examined for switches as the line is being parsed. Thus, if you're on a machine that allows only one argument with the `#!` line, or worse, doesn't even recognize the `#!` line, you still can get consistent switch behaviour regardless of how Perl was invoked, even if ["-x"](#-x) was used to find the beginning of the program.
Because historically some operating systems silently chopped off kernel interpretation of the `#!` line after 32 characters, some switches may be passed in on the command line, and some may not; you could even get a "-" without its letter, if you're not careful. You probably want to make sure that all your switches fall either before or after that 32-character boundary. Most switches don't actually care if they're processed redundantly, but getting a "-" instead of a complete switch could cause Perl to try to execute standard input instead of your program. And a partial [-I](#-Idirectory) switch could also cause odd results.
Some switches do care if they are processed twice, for instance combinations of [-l](#-l%5Boctnum%5D) and [-0](#-0%5Boctal%2Fhexadecimal%5D). Either put all the switches after the 32-character boundary (if applicable), or replace the use of **-0***digits* by `BEGIN{ $/ = "\0digits"; }`.
Parsing of the `#!` switches starts wherever "perl" is mentioned in the line. The sequences "-\*" and "- " are specifically ignored so that you could, if you were so inclined, say
```
#!/bin/sh
#! -*- perl -*- -p
eval 'exec perl -x -wS $0 ${1+"$@"}'
if 0;
```
to let Perl see the ["-p"](#-p) switch.
A similar trick involves the *env* program, if you have it.
```
#!/usr/bin/env perl
```
The examples above use a relative path to the perl interpreter, getting whatever version is first in the user's path. If you want a specific version of Perl, say, perl5.14.1, you should place that directly in the `#!` line's path.
If the `#!` line does not contain the word "perl" nor the word "indir", the program named after the `#!` is executed instead of the Perl interpreter. This is slightly bizarre, but it helps people on machines that don't do `#!`, because they can tell a program that their SHELL is */usr/bin/perl*, and Perl will then dispatch the program to the correct interpreter for them.
After locating your program, Perl compiles the entire program to an internal form. If there are any compilation errors, execution of the program is not attempted. (This is unlike the typical shell script, which might run part-way through before finding a syntax error.)
If the program is syntactically correct, it is executed. If the program runs off the end without hitting an exit() or die() operator, an implicit `exit(0)` is provided to indicate successful completion.
###
#! and quoting on non-Unix systems
Unix's `#!` technique can be simulated on other systems:
OS/2 Put
```
extproc perl -S -your_switches
```
as the first line in `*.cmd` file (["-S"](#-S) due to a bug in cmd.exe's `extproc' handling).
MS-DOS Create a batch file to run your program, and codify it in `ALTERNATE_SHEBANG` (see the *dosish.h* file in the source distribution for more information).
Win95/NT The Win95/NT installation, when using the ActiveState installer for Perl, will modify the Registry to associate the *.pl* extension with the perl interpreter. If you install Perl by other means (including building from the sources), you may have to modify the Registry yourself. Note that this means you can no longer tell the difference between an executable Perl program and a Perl library file.
VMS Put
```
$ perl -mysw 'f$env("procedure")' 'p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' !
$ exit++ + ++$status != 0 and $exit = $status = undef;
```
at the top of your program, where **-mysw** are any command line switches you want to pass to Perl. You can now invoke the program directly, by saying `perl program`, or as a DCL procedure, by saying `@program` (or implicitly via *DCL$PATH* by just using the name of the program).
This incantation is a bit much to remember, but Perl will display it for you if you say `perl "-V:startperl"`.
Command-interpreters on non-Unix systems have rather different ideas on quoting than Unix shells. You'll need to learn the special characters in your command-interpreter (`*`, `\` and `"` are common) and how to protect whitespace and these characters to run one-liners (see [-e](#-e-commandline) below).
On some systems, you may have to change single-quotes to double ones, which you must *not* do on Unix or Plan 9 systems. You might also have to change a single % to a %%.
For example:
```
# Unix
perl -e 'print "Hello world\n"'
# MS-DOS, etc.
perl -e "print \"Hello world\n\""
# VMS
perl -e "print ""Hello world\n"""
```
The problem is that none of this is reliable: it depends on the command and it is entirely possible neither works. If *4DOS* were the command shell, this would probably work better:
```
perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
```
**CMD.EXE** in Windows NT slipped a lot of standard Unix functionality in when nobody was looking, but just try to find documentation for its quoting rules.
There is no general solution to all of this. It's just a mess.
###
Location of Perl
It may seem obvious to say, but Perl is useful only when users can easily find it. When possible, it's good for both */usr/bin/perl* and */usr/local/bin/perl* to be symlinks to the actual binary. If that can't be done, system administrators are strongly encouraged to put (symlinks to) perl and its accompanying utilities into a directory typically found along a user's PATH, or in some other obvious and convenient place.
In this documentation, `#!/usr/bin/perl` on the first line of the program will stand in for whatever method works on your system. You are advised to use a specific path if you care about a specific version.
```
#!/usr/local/bin/perl5.14
```
or if you just want to be running at least version, place a statement like this at the top of your program:
```
use v5.14;
```
###
Command Switches
As with all standard commands, a single-character switch may be clustered with the following switch, if any.
```
#!/usr/bin/perl -spi.orig # same as -s -p -i.orig
```
A `--` signals the end of options and disables further option processing. Any arguments after the `--` are treated as filenames and arguments.
Switches include:
**-0**[*octal/hexadecimal*] specifies the input record separator (`$/`) as an octal or hexadecimal number. If there are no digits, the null character is the separator. Other switches may precede or follow the digits. For example, if you have a version of *find* which can print filenames terminated by the null character, you can say this:
```
find . -name '*.orig' -print0 | perl -n0e unlink
```
The special value 00 will cause Perl to slurp files in paragraph mode.
Any value 0400 or above will cause Perl to slurp files whole, but by convention the value 0777 is the one normally used for this purpose. The ["-g"](#-g) flag is a simpler alias for it.
You can also specify the separator character using hexadecimal notation: **-0x*HHH...***, where the `*H*` are valid hexadecimal digits. Unlike the octal form, this one may be used to specify any Unicode character, even those beyond 0xFF. So if you *really* want a record separator of 0777, specify it as **-0x1FF**. (This means that you cannot use the ["-x"](#-x) option with a directory name that consists of hexadecimal digits, or else Perl will think you have specified a hex number to **-0**.)
**-a** turns on autosplit mode when used with a ["-n"](#-n) or ["-p"](#-p). An implicit split command to the @F array is done as the first thing inside the implicit while loop produced by the ["-n"](#-n) or ["-p"](#-p).
```
perl -ane 'print pop(@F), "\n";'
```
is equivalent to
```
while (<>) {
@F = split(' ');
print pop(@F), "\n";
}
```
An alternate delimiter may be specified using [-F](#-Fpattern).
**-a** implicitly sets ["-n"](#-n).
**-C [*number/list*]** The **-C** flag controls some of the Perl Unicode features.
As of 5.8.1, the **-C** can be followed either by a number or a list of option letters. The letters, their numeric values, and effects are as follows; listing the letters is equal to summing the numbers.
```
I 1 STDIN is assumed to be in UTF-8
O 2 STDOUT will be in UTF-8
E 4 STDERR will be in UTF-8
S 7 I + O + E
i 8 UTF-8 is the default PerlIO layer for input streams
o 16 UTF-8 is the default PerlIO layer for output streams
D 24 i + o
A 32 the @ARGV elements are expected to be strings encoded
in UTF-8
L 64 normally the "IOEioA" are unconditional, the L makes
them conditional on the locale environment variables
(the LC_ALL, LC_CTYPE, and LANG, in the order of
decreasing precedence) -- if the variables indicate
UTF-8, then the selected "IOEioA" are in effect
a 256 Set ${^UTF8CACHE} to -1, to run the UTF-8 caching
code in debugging mode.
```
For example, **-COE** and **-C6** will both turn on UTF-8-ness on both STDOUT and STDERR. Repeating letters is just redundant, not cumulative nor toggling.
The `io` options mean that any subsequent open() (or similar I/O operations) in main program scope will have the `:utf8` PerlIO layer implicitly applied to them, in other words, UTF-8 is expected from any input stream, and UTF-8 is produced to any output stream. This is just the default set via [`${^OPEN}`](perlvar#%24%7B%5EOPEN%7D), with explicit layers in open() and with binmode() one can manipulate streams as usual. This has no effect on code run in modules.
**-C** on its own (not followed by any number or option list), or the empty string `""` for the ["PERL\_UNICODE"](#PERL_UNICODE) environment variable, has the same effect as **-CSDL**. In other words, the standard I/O handles and the default `open()` layer are UTF-8-fied *but* only if the locale environment variables indicate a UTF-8 locale. This behaviour follows the *implicit* (and problematic) UTF-8 behaviour of Perl 5.8.0. (See ["UTF-8 no longer default under UTF-8 locales" in perl581delta](https://perldoc.perl.org/5.36.0/perl581delta#UTF-8-no-longer-default-under-UTF-8-locales).)
You can use **-C0** (or `"0"` for `PERL_UNICODE`) to explicitly disable all the above Unicode features.
The read-only magic variable `${^UNICODE}` reflects the numeric value of this setting. This variable is set during Perl startup and is thereafter read-only. If you want runtime effects, use the three-arg open() (see ["open" in perlfunc](perlfunc#open)), the two-arg binmode() (see ["binmode" in perlfunc](perlfunc#binmode)), and the `open` pragma (see <open>).
(In Perls earlier than 5.8.1 the **-C** switch was a Win32-only switch that enabled the use of Unicode-aware "wide system call" Win32 APIs. This feature was practically unused, however, and the command line switch was therefore "recycled".)
**Note:** Since perl 5.10.1, if the **-C** option is used on the `#!` line, it must be specified on the command line as well, since the standard streams are already set up at this point in the execution of the perl interpreter. You can also use binmode() to set the encoding of an I/O stream.
**-c** causes Perl to check the syntax of the program and then exit without executing it. Actually, it *will* execute any `BEGIN`, `UNITCHECK`, or `CHECK` blocks and any `use` statements: these are considered as occurring outside the execution of your program. `INIT` and `END` blocks, however, will be skipped.
**-d**
**-dt**
runs the program under the Perl debugger. See <perldebug>. If **t** is specified, it indicates to the debugger that threads will be used in the code being debugged.
**-d:***MOD[=bar,baz]*
**-dt:***MOD[=bar,baz]*
runs the program under the control of a debugging, profiling, or tracing module installed as `Devel::*MOD*`. E.g., **-d:DProf** executes the program using the `Devel::DProf` profiler. As with the [-M](#-M%5B-%5Dmodule) flag, options may be passed to the `Devel::*MOD*` package where they will be received and interpreted by the `Devel::*MOD*::import` routine. Again, like **-M**, use -**-d:-*MOD*** to call `Devel::*MOD*::unimport` instead of import. The comma-separated list of options must follow a `=` character. If **t** is specified, it indicates to the debugger that threads will be used in the code being debugged. See <perldebug>.
**-D***letters*
**-D***number*
sets debugging flags. This switch is enabled only if your perl binary has been built with debugging enabled: normal production perls won't have been.
For example, to watch how perl executes your program, use **-Dtls**. Another nice value is **-Dx**, which lists your compiled syntax tree, and **-Dr** displays compiled regular expressions; the format of the output is explained in <perldebguts>.
As an alternative, specify a number instead of list of letters (e.g., **-D14** is equivalent to **-Dtls**):
```
1 p Tokenizing and parsing (with v, displays parse
stack)
2 s Stack snapshots (with v, displays all stacks)
4 l Context (loop) stack processing
8 t Trace execution
16 o Method and overloading resolution
32 c String/numeric conversions
64 P Print profiling info, source file input state
128 m Memory and SV allocation
256 f Format processing
512 r Regular expression parsing and execution
1024 x Syntax tree dump
2048 u Tainting checks
4096 U Unofficial, User hacking (reserved for private,
unreleased use)
8192 h Show hash randomization debug output (changes to
PL_hash_rand_bits and their origin)
16384 X Scratchpad allocation
32768 D Cleaning up
65536 S Op slab allocation
131072 T Tokenizing
262144 R Include reference counts of dumped variables
(eg when using -Ds)
524288 J show s,t,P-debug (don't Jump over) on opcodes within
package DB
1048576 v Verbose: use in conjunction with other flags to
increase the verbosity of the output. Is a no-op on
many of the other flags
2097152 C Copy On Write
4194304 A Consistency checks on internal structures
8388608 q quiet - currently only suppresses the "EXECUTING"
message
16777216 M trace smart match resolution
33554432 B dump suBroutine definitions, including special
Blocks like BEGIN
67108864 L trace Locale-related info; what gets output is very
subject to change
134217728 i trace PerlIO layer processing. Set PERLIO_DEBUG to
the filename to trace to.
268435456 y trace y///, tr/// compilation and execution
```
All these flags require **-DDEBUGGING** when you compile the Perl executable (but see `:opd` in <Devel::Peek> or ["'debug' mode" in re](re#%27debug%27-mode) which may change this). See the *INSTALL* file in the Perl source distribution for how to do this.
If you're just trying to get a print out of each line of Perl code as it executes, the way that `sh -x` provides for shell scripts, you can't use Perl's **-D** switch. Instead do this
```
# If you have "env" utility
env PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
# Bourne shell syntax
$ PERLDB_OPTS="NonStop=1 AutoTrace=1 frame=2" perl -dS program
# csh syntax
% (setenv PERLDB_OPTS "NonStop=1 AutoTrace=1 frame=2"; perl -dS program)
```
See <perldebug> for details and variations.
**-e** *commandline* may be used to enter one line of program. If **-e** is given, Perl will not look for a filename in the argument list. Multiple **-e** commands may be given to build up a multi-line script. Make sure to use semicolons where you would in a normal program.
**-E** *commandline* behaves just like [-e](#-e-commandline), except that it implicitly enables all optional features (in the main compilation unit). See <feature>.
**-f** Disable executing *$Config{sitelib}/sitecustomize.pl* at startup.
Perl can be built so that it by default will try to execute *$Config{sitelib}/sitecustomize.pl* at startup (in a BEGIN block). This is a hook that allows the sysadmin to customize how Perl behaves. It can for instance be used to add entries to the @INC array to make Perl find modules in non-standard locations.
Perl actually inserts the following code:
```
BEGIN {
do { local $!; -f "$Config{sitelib}/sitecustomize.pl"; }
&& do "$Config{sitelib}/sitecustomize.pl";
}
```
Since it is an actual `do` (not a `require`), *sitecustomize.pl* doesn't need to return a true value. The code is run in package `main`, in its own lexical scope. However, if the script dies, `$@` will not be set.
The value of `$Config{sitelib}` is also determined in C code and not read from `Config.pm`, which is not loaded.
The code is executed *very* early. For example, any changes made to `@INC` will show up in the output of `perl -V`. Of course, `END` blocks will be likewise executed very late.
To determine at runtime if this capability has been compiled in your perl, you can check the value of `$Config{usesitecustomize}`.
**-F***pattern* specifies the pattern to split on for ["-a"](#-a). The pattern may be surrounded by `//`, `""`, or `''`, otherwise it will be put in single quotes. You can't use literal whitespace or NUL characters in the pattern.
**-F** implicitly sets both ["-a"](#-a) and ["-n"](#-n).
**-g** undefines the input record separator (`[$/](perlvar#%24%2F)`) and thus enables the slurp mode. In other words, it causes Perl to read whole files at once, instead of line by line.
This flag is a simpler alias for [-0777](#-0%5Boctal%2Fhexadecimal%5D).
Mnemonics: gobble, grab, gulp.
**-h** prints a summary of the options.
**-?** synonym for **-h**: prints a summary of the options.
**-i**[*extension*] specifies that files processed by the `<>` construct are to be edited in-place. It does this by renaming the input file, opening the output file by the original name, and selecting that output file as the default for print() statements. The extension, if supplied, is used to modify the name of the old file to make a backup copy, following these rules:
If no extension is supplied, and your system supports it, the original *file* is kept open without a name while the output is redirected to a new file with the original *filename*. When perl exits, cleanly or not, the original *file* is unlinked.
If the extension doesn't contain a `*`, then it is appended to the end of the current filename as a suffix. If the extension does contain one or more `*` characters, then each `*` is replaced with the current filename. In Perl terms, you could think of this as:
```
($backup = $extension) =~ s/\*/$file_name/g;
```
This allows you to add a prefix to the backup file, instead of (or in addition to) a suffix:
```
$ perl -pi'orig_*' -e 's/bar/baz/' fileA # backup to
# 'orig_fileA'
```
Or even to place backup copies of the original files into another directory (provided the directory already exists):
```
$ perl -pi'old/*.orig' -e 's/bar/baz/' fileA # backup to
# 'old/fileA.orig'
```
These sets of one-liners are equivalent:
```
$ perl -pi -e 's/bar/baz/' fileA # overwrite current file
$ perl -pi'*' -e 's/bar/baz/' fileA # overwrite current file
$ perl -pi'.orig' -e 's/bar/baz/' fileA # backup to 'fileA.orig'
$ perl -pi'*.orig' -e 's/bar/baz/' fileA # backup to 'fileA.orig'
```
From the shell, saying
```
$ perl -p -i.orig -e "s/foo/bar/; ... "
```
is the same as using the program:
```
#!/usr/bin/perl -pi.orig
s/foo/bar/;
```
which is equivalent to
```
#!/usr/bin/perl
$extension = '.orig';
LINE: while (<>) {
if ($ARGV ne $oldargv) {
if ($extension !~ /\*/) {
$backup = $ARGV . $extension;
}
else {
($backup = $extension) =~ s/\*/$ARGV/g;
}
rename($ARGV, $backup);
open(ARGVOUT, ">$ARGV");
select(ARGVOUT);
$oldargv = $ARGV;
}
s/foo/bar/;
}
continue {
print; # this prints to original filename
}
select(STDOUT);
```
except that the **-i** form doesn't need to compare $ARGV to $oldargv to know when the filename has changed. It does, however, use ARGVOUT for the selected filehandle. Note that STDOUT is restored as the default output filehandle after the loop.
As shown above, Perl creates the backup file whether or not any output is actually changed. So this is just a fancy way to copy files:
```
$ perl -p -i'/some/file/path/*' -e 1 file1 file2 file3...
or
$ perl -p -i'.orig' -e 1 file1 file2 file3...
```
You can use `eof` without parentheses to locate the end of each input file, in case you want to append to each file, or reset line numbering (see example in ["eof" in perlfunc](perlfunc#eof)).
If, for a given file, Perl is unable to create the backup file as specified in the extension then it will skip that file and continue on with the next one (if it exists).
For a discussion of issues surrounding file permissions and **-i**, see ["Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in Perl?" in perlfaq5](perlfaq5#Why-does-Perl-let-me-delete-read-only-files%3F-Why-does-i-clobber-protected-files%3F-Isn%27t-this-a-bug-in-Perl%3F).
You cannot use **-i** to create directories or to strip extensions from files.
Perl does not expand `~` in filenames, which is good, since some folks use it for their backup files:
```
$ perl -pi~ -e 's/foo/bar/' file1 file2 file3...
```
Note that because **-i** renames or deletes the original file before creating a new file of the same name, Unix-style soft and hard links will not be preserved.
Finally, the **-i** switch does not impede execution when no files are given on the command line. In this case, no backup is made (the original file cannot, of course, be determined) and processing proceeds from STDIN to STDOUT as might be expected.
**-I***directory* Directories specified by **-I** are prepended to the search path for modules (`@INC`).
**-l**[*octnum*] enables automatic line-ending processing. It has two separate effects. First, it automatically chomps `$/` (the input record separator) when used with ["-n"](#-n) or ["-p"](#-p). Second, it assigns `$\` (the output record separator) to have the value of *octnum* so that any print statements will have that separator added back on. If *octnum* is omitted, sets `$\` to the current value of `$/`. For instance, to trim lines to 80 columns:
```
perl -lpe 'substr($_, 80) = ""'
```
Note that the assignment `$\ = $/` is done when the switch is processed, so the input record separator can be different than the output record separator if the **-l** switch is followed by a [-0](#-0%5Boctal%2Fhexadecimal%5D) switch:
```
gnufind / -print0 | perl -ln0e 'print "found $_" if -p'
```
This sets `$\` to newline and then sets `$/` to the null character.
**-m**[**-**]*module*
**-M**[**-**]*module*
**-M**[**-**]*'module ...'*
**-[mM]**[**-**]*module=arg[,arg]...*
**-m***module* executes `use` *module* `();` before executing your program. This loads the module, but does not call its `import` method, so does not import subroutines and does not give effect to a pragma.
**-M***module* executes `use` *module* `;` before executing your program. This loads the module and calls its `import` method, causing the module to have its default effect, typically importing subroutines or giving effect to a pragma. You can use quotes to add extra code after the module name, e.g., `'-M*MODULE* qw(foo bar)'`.
If the first character after the **-M** or **-m** is a dash (**-**) then the 'use' is replaced with 'no'. This makes no difference for **-m**.
A little builtin syntactic sugar means you can also say **-m*MODULE*=foo,bar** or **-M*MODULE*=foo,bar** as a shortcut for **'-M*MODULE* qw(foo bar)'**. This avoids the need to use quotes when importing symbols. The actual code generated by **-M*MODULE*=foo,bar** is `use module split(/,/,q{foo,bar})`. Note that the `=` form removes the distinction between **-m** and **-M**; that is, **-m*MODULE*=foo,bar** is the same as **-M*MODULE*=foo,bar**.
A consequence of the `split` formulation is that **-M*MODULE*=number** never does a version check, unless `*MODULE*::import()` itself is set up to do a version check, which could happen for example if *MODULE* inherits from [Exporter](exporter).
**-n** causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like *sed -n* or *awk*:
```
LINE:
while (<>) {
... # your program goes here
}
```
Note that the lines are not printed by default. See ["-p"](#-p) to have lines printed. If a file named by an argument cannot be opened for some reason, Perl warns you about it and moves on to the next file.
Also note that `<>` passes command line arguments to ["open" in perlfunc](perlfunc#open), which doesn't necessarily interpret them as file names. See <perlop> for possible security implications.
Here is an efficient way to delete all files that haven't been modified for at least a week:
```
find . -mtime +7 -print | perl -nle unlink
```
This is faster than using the **-exec** switch of *find* because you don't have to start a process on every filename found (but it's not faster than using the **-delete** switch available in newer versions of *find*. It does suffer from the bug of mishandling newlines in pathnames, which you can fix if you follow the example under [-0](#-0%5Boctal%2Fhexadecimal%5D).
`BEGIN` and `END` blocks may be used to capture control before or after the implicit program loop, just as in *awk*.
**-p** causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like *sed*:
```
LINE:
while (<>) {
... # your program goes here
} continue {
print or die "-p destination: $!\n";
}
```
If a file named by an argument cannot be opened for some reason, Perl warns you about it, and moves on to the next file. Note that the lines are printed automatically. An error occurring during printing is treated as fatal. To suppress printing use the ["-n"](#-n) switch. A **-p** overrides a **-n** switch.
`BEGIN` and `END` blocks may be used to capture control before or after the implicit loop, just as in *awk*.
**-s** enables rudimentary switch parsing for switches on the command line after the program name but before any filename arguments (or before an argument of **--**). Any switch found there is removed from @ARGV and sets the corresponding variable in the Perl program, in the main package. The following program prints "1" if the program is invoked with a **-xyz** switch, and "abc" if it is invoked with **-xyz=abc**.
```
#!/usr/bin/perl -s
if ($xyz) { print "$xyz\n" }
```
Do note that a switch like **--help** creates the variable `${-help}`, which is not compliant with `use strict "refs"`. Also, when using this option on a script with warnings enabled you may get a lot of spurious "used only once" warnings. For these reasons, use of **-s** is discouraged. See <Getopt::Long> for much more flexible switch parsing.
**-S** makes Perl use the ["PATH"](#PATH) environment variable to search for the program unless the name of the program contains path separators.
On some platforms, this also makes Perl append suffixes to the filename while searching for it. For example, on Win32 platforms, the ".bat" and ".cmd" suffixes are appended if a lookup for the original name fails, and if the name does not already end in one of those suffixes. If your Perl was compiled with `DEBUGGING` turned on, using the [-Dp](#-Dletters) switch to Perl shows how the search progresses.
Typically this is used to emulate `#!` startup on platforms that don't support `#!`. It's also convenient when debugging a script that uses `#!`, and is thus normally found by the shell's $PATH search mechanism.
This example works on many platforms that have a shell compatible with Bourne shell:
```
#!/usr/bin/perl
eval 'exec /usr/bin/perl -wS $0 ${1+"$@"}'
if 0; # ^ Run only under a shell
```
The system ignores the first line and feeds the program to */bin/sh*, which proceeds to try to execute the Perl program as a shell script. The shell executes the second line as a normal shell command, and thus starts up the Perl interpreter. On some systems $0 doesn't always contain the full pathname, so the ["-S"](#-S) tells Perl to search for the program if necessary. After Perl locates the program, it parses the lines and ignores them because the check 'if 0' is never true. If the program will be interpreted by csh, you will need to replace `${1+"$@"}` with `$*`, even though that doesn't understand embedded spaces (and such) in the argument list. To start up *sh* rather than *csh*, some systems may have to replace the `#!` line with a line containing just a colon, which will be politely ignored by Perl. Other systems can't control that, and need a totally devious construct that will work under any of *csh*, *sh*, or Perl, such as the following:
```
eval '(exit $?0)' && eval 'exec perl -wS $0 ${1+"$@"}'
& eval 'exec /usr/bin/perl -wS $0 $argv:q'
if 0; # ^ Run only under a shell
```
If the filename supplied contains directory separators (and so is an absolute or relative pathname), and if that file is not found, platforms that append file extensions will do so and try to look for the file with those extensions added, one by one.
On DOS-like platforms, if the program does not contain directory separators, it will first be searched for in the current directory before being searched for on the PATH. On Unix platforms, the program will be searched for strictly on the PATH.
**-t** Like ["-T"](#-T), but taint checks will issue warnings rather than fatal errors. These warnings can now be controlled normally with `no warnings qw(taint)`.
**Note: This is not a substitute for `-T`!** This is meant to be used *only* as a temporary development aid while securing legacy code: for real production code and for new secure code written from scratch, always use the real ["-T"](#-T).
This has no effect if your perl was built without taint support.
**-T** turns on "taint" so you can test them. Ordinarily these checks are done only when running setuid or setgid. It's a good idea to turn them on explicitly for programs that run on behalf of someone else whom you might not necessarily trust, such as CGI programs or any internet servers you might write in Perl. See <perlsec> for details. For security reasons, this option must be seen by Perl quite early; usually this means it must appear early on the command line or in the `#!` line for systems which support that construct.
**-u** This switch causes Perl to dump core after compiling your program. You can then in theory take this core dump and turn it into an executable file by using the *undump* program (not supplied). This speeds startup at the expense of some disk space (which you can minimize by stripping the executable). (Still, a "hello world" executable comes out to about 200K on my machine.) If you want to execute a portion of your program before dumping, use the `CORE::dump()` function instead. Note: availability of *undump* is platform specific and may not be available for a specific port of Perl.
**-U** allows Perl to do unsafe operations. Currently the only "unsafe" operations are attempting to unlink directories while running as superuser and running setuid programs with fatal taint checks turned into warnings. Note that warnings must be enabled along with this option to actually *generate* the taint-check warnings.
**-v** prints the version and patchlevel of your perl executable.
**-V** prints summary of the major perl configuration values and the current values of @INC.
**-V:***configvar*
Prints to STDOUT the value of the named configuration variable(s), with multiples when your `*configvar*` argument looks like a regex (has non-letters). For example:
```
$ perl -V:libc
libc='/lib/libc-2.2.4.so';
$ perl -V:lib.
libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
libc='/lib/libc-2.2.4.so';
$ perl -V:lib.*
libpth='/usr/local/lib /lib /usr/lib';
libs='-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lc';
lib_ext='.a';
libc='/lib/libc-2.2.4.so';
libperl='libperl.a';
....
```
Additionally, extra colons can be used to control formatting. A trailing colon suppresses the linefeed and terminator ";", allowing you to embed queries into shell commands. (mnemonic: PATH separator ":".)
```
$ echo "compression-vars: " `perl -V:z.*: ` " are here !"
compression-vars: zcat='' zip='zip' are here !
```
A leading colon removes the "name=" part of the response, this allows you to map to the name you need. (mnemonic: empty label)
```
$ echo "goodvfork="`./perl -Ilib -V::usevfork`
goodvfork=false;
```
Leading and trailing colons can be used together if you need positional parameter values without the names. Note that in the case below, the `PERL_API` params are returned in alphabetical order.
```
$ echo building_on `perl -V::osname: -V::PERL_API_.*:` now
building_on 'linux' '5' '1' '9' now
```
**-w** prints warnings about dubious constructs, such as variable names mentioned only once and scalar variables used before being set; redefined subroutines; references to undefined filehandles; filehandles opened read-only that you are attempting to write on; values used as a number that don't *look* like numbers; using an array as though it were a scalar; if your subroutines recurse more than 100 deep; and innumerable other things.
This switch really just enables the global `$^W` variable; normally, the lexically scoped `use warnings` pragma is preferred. You can disable or promote into fatal errors specific warnings using `__WARN__` hooks, as described in <perlvar> and ["warn" in perlfunc](perlfunc#warn). See also <perldiag> and <perltrap>. A fine-grained warning facility is also available if you want to manipulate entire classes of warnings; see <warnings>.
**-W** Enables all warnings regardless of `no warnings` or `$^W`. See <warnings>.
**-X** Disables all warnings regardless of `use warnings` or `$^W`. See <warnings>.
Forbidden in `["PERL5OPT"](#PERL5OPT)`.
**-x**
**-x***directory*
tells Perl that the program is embedded in a larger chunk of unrelated text, such as in a mail message. Leading garbage will be discarded until the first line that starts with `#!` and contains the string "perl". Any meaningful switches on that line will be applied.
All references to line numbers by the program (warnings, errors, ...) will treat the `#!` line as the first line. Thus a warning on the 2nd line of the program, which is on the 100th line in the file will be reported as line 2, not as line 100. This can be overridden by using the `#line` directive. (See ["Plain Old Comments (Not!)" in perlsyn](perlsyn#Plain-Old-Comments-%28Not%21%29))
If a directory name is specified, Perl will switch to that directory before running the program. The **-x** switch controls only the disposal of leading garbage. The program must be terminated with `__END__` if there is trailing garbage to be ignored; the program can process any or all of the trailing garbage via the `DATA` filehandle if desired.
The directory, if specified, must appear immediately following the **-x** with no intervening whitespace.
ENVIRONMENT
-----------
HOME Used if `chdir` has no argument.
LOGDIR Used if `chdir` has no argument and ["HOME"](#HOME) is not set.
PATH Used in executing subprocesses, and in finding the program if ["-S"](#-S) is used.
PERL5LIB A list of directories in which to look for Perl library files before looking in the standard library. Any architecture-specific and version-specific directories, such as *version/archname/*, *version/*, or *archname/* under the specified locations are automatically included if they exist, with this lookup done at interpreter startup time. In addition, any directories matching the entries in `$Config{inc_version_list}` are added. (These typically would be for older compatible perl versions installed in the same directory tree.)
If PERL5LIB is not defined, ["PERLLIB"](#PERLLIB) is used. Directories are separated (like in PATH) by a colon on Unixish platforms and by a semicolon on Windows (the proper path separator being given by the command `perl -V:*path\_sep*`).
When running taint checks, either because the program was running setuid or setgid, or the ["-T"](#-T) or ["-t"](#-t) switch was specified, neither PERL5LIB nor ["PERLLIB"](#PERLLIB) is consulted. The program should instead say:
```
use lib "/my/directory";
```
PERL5OPT Command-line options (switches). Switches in this variable are treated as if they were on every Perl command line. Only the **-[CDIMTUWdmtw]** switches are allowed. When running taint checks (either because the program was running setuid or setgid, or because the ["-T"](#-T) or ["-t"](#-t) switch was used), this variable is ignored. If PERL5OPT begins with **-T**, tainting will be enabled and subsequent options ignored. If PERL5OPT begins with **-t**, tainting will be enabled, a writable dot removed from @INC, and subsequent options honored.
PERLIO A space (or colon) separated list of PerlIO layers. If perl is built to use PerlIO system for IO (the default) these layers affect Perl's IO.
It is conventional to start layer names with a colon (for example, `:perlio`) to emphasize their similarity to variable "attributes". But the code that parses layer specification strings, which is also used to decode the PERLIO environment variable, treats the colon as a separator.
An unset or empty PERLIO is equivalent to the default set of layers for your platform; for example, `:unix:perlio` on Unix-like systems and `:unix:crlf` on Windows and other DOS-like systems.
The list becomes the default for *all* Perl's IO. Consequently only built-in layers can appear in this list, as external layers (such as `:encoding()`) need IO in order to load them! See ["open pragma"](open) for how to add external encodings as defaults.
Layers it makes sense to include in the PERLIO environment variable are briefly summarized below. For more details see [PerlIO](perlio).
:crlf A layer which does CRLF to `"\n"` translation distinguishing "text" and "binary" files in the manner of MS-DOS and similar operating systems, and also provides buffering similar to `:perlio` on these architectures.
:perlio This is a re-implementation of stdio-like buffering written as a PerlIO layer. As such it will call whatever layer is below it for its operations, typically `:unix`.
:stdio This layer provides a PerlIO interface by wrapping system's ANSI C "stdio" library calls. The layer provides both buffering and IO. Note that the `:stdio` layer does *not* do CRLF translation even if that is the platform's normal behaviour. You will need a `:crlf` layer above it to do that.
:unix Low-level layer that calls `read`, `write`, `lseek`, etc.
The default set of layers should give acceptable results on all platforms.
For Unix platforms that will be the equivalent of ":unix:perlio" or ":stdio". Configure is set up to prefer the ":stdio" implementation if the system's library provides for fast access to the buffer (not common on modern architectures); otherwise, it uses the ":unix:perlio" implementation.
On Win32 the default in this release (5.30) is ":unix:crlf". Win32's ":stdio" has a number of bugs/mis-features for Perl IO which are somewhat depending on the version and vendor of the C compiler. Using our own `:crlf` layer as the buffer avoids those issues and makes things more uniform.
This release (5.30) uses `:unix` as the bottom layer on Win32, and so still uses the C compiler's numeric file descriptor routines.
The PERLIO environment variable is completely ignored when Perl is run in taint mode.
PERLIO\_DEBUG If set to the name of a file or device when Perl is run with the [-Di](#-Dletters) command-line switch, the logging of certain operations of the PerlIO subsystem will be redirected to the specified file rather than going to stderr, which is the default. The file is opened in append mode. Typical uses are in Unix:
```
% env PERLIO_DEBUG=/tmp/perlio.log perl -Di script ...
```
and under Win32, the approximately equivalent:
```
> set PERLIO_DEBUG=CON
perl -Di script ...
```
This functionality is disabled for setuid scripts, for scripts run with ["-T"](#-T), and for scripts run on a Perl built without `-DDEBUGGING` support.
PERLLIB A list of directories in which to look for Perl library files before looking in the standard library. If ["PERL5LIB"](#PERL5LIB) is defined, PERLLIB is not used.
The PERLLIB environment variable is completely ignored when Perl is run in taint mode.
PERL5DB The command used to load the debugger code. The default is:
```
BEGIN { require "perl5db.pl" }
```
The PERL5DB environment variable is only used when Perl is started with a bare ["-d"](#-d) switch.
PERL5DB\_THREADED If set to a true value, indicates to the debugger that the code being debugged uses threads.
PERL5SHELL (specific to the Win32 port) On Win32 ports only, may be set to an alternative shell that Perl must use internally for executing "backtick" commands or system(). Default is `cmd.exe /x/d/c` on WindowsNT and `command.com /c` on Windows95. The value is considered space-separated. Precede any character that needs to be protected, like a space or backslash, with another backslash.
Note that Perl doesn't use COMSPEC for this purpose because COMSPEC has a high degree of variability among users, leading to portability concerns. Besides, Perl can use a shell that may not be fit for interactive use, and setting COMSPEC to such a shell may interfere with the proper functioning of other programs (which usually look in COMSPEC to find a shell fit for interactive use).
Before Perl 5.10.0 and 5.8.8, PERL5SHELL was not taint checked when running external commands. It is recommended that you explicitly set (or delete) `$ENV{PERL5SHELL}` when running in taint mode under Windows.
PERL\_ALLOW\_NON\_IFS\_LSP (specific to the Win32 port) Set to 1 to allow the use of non-IFS compatible LSPs (Layered Service Providers). Perl normally searches for an IFS-compatible LSP because this is required for its emulation of Windows sockets as real filehandles. However, this may cause problems if you have a firewall such as *McAfee Guardian*, which requires that all applications use its LSP but which is not IFS-compatible, because clearly Perl will normally avoid using such an LSP.
Setting this environment variable to 1 means that Perl will simply use the first suitable LSP enumerated in the catalog, which keeps *McAfee Guardian* happy--and in that particular case Perl still works too because *McAfee Guardian*'s LSP actually plays other games which allow applications requiring IFS compatibility to work.
PERL\_DEBUG\_MSTATS Relevant only if Perl is compiled with the `malloc` included with the Perl distribution; that is, if `perl -V:d_mymalloc` is "define".
If set, this dumps out memory statistics after execution. If set to an integer greater than one, also dumps out memory statistics after compilation.
PERL\_DESTRUCT\_LEVEL Controls the behaviour of global destruction of objects and other references. See ["PERL\_DESTRUCT\_LEVEL" in perlhacktips](perlhacktips#PERL_DESTRUCT_LEVEL) for more information.
PERL\_DL\_NONLAZY Set to `"1"` to have Perl resolve *all* undefined symbols when it loads a dynamic library. The default behaviour is to resolve symbols when they are used. Setting this variable is useful during testing of extensions, as it ensures that you get an error on misspelled function names even if the test suite doesn't call them.
PERL\_ENCODING If using the `use encoding` pragma without an explicit encoding name, the PERL\_ENCODING environment variable is consulted for an encoding name.
PERL\_HASH\_SEED (Since Perl 5.8.1, new semantics in Perl 5.18.0) Used to override the randomization of Perl's internal hash function. The value is expressed in hexadecimal, and may include a leading 0x. Truncated patterns are treated as though they are suffixed with sufficient 0's as required.
If the option is provided, and `PERL_PERTURB_KEYS` is NOT set, then a value of '0' implies `PERL_PERTURB_KEYS=0`/`PERL_PERTURB_KEYS=NO` and any other value implies `PERL_PERTURB_KEYS=2`/`PERL_PERTURB_KEYS=DETERMINISTIC`. See the documentation for [PERL\_PERTURB\_KEYS](#PERL_PERTURB_KEYS) for important caveats regarding the `DETERMINISTIC` mode.
**PLEASE NOTE: The hash seed is sensitive information**. Hashes are randomized to protect against local and remote attacks against Perl code. By manually setting a seed, this protection may be partially or completely lost.
See ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks), ["PERL\_PERTURB\_KEYS"](#PERL_PERTURB_KEYS), and ["PERL\_HASH\_SEED\_DEBUG"](#PERL_HASH_SEED_DEBUG) for more information.
PERL\_PERTURB\_KEYS (Since Perl 5.18.0) Set to `"0"` or `"NO"` then traversing keys will be repeatable from run to run for the same `PERL_HASH_SEED`. Insertion into a hash will not change the order, except to provide for more space in the hash. When combined with setting PERL\_HASH\_SEED this mode is as close to pre 5.18 behavior as you can get.
When set to `"1"` or `"RANDOM"` then traversing keys will be randomized. Every time a hash is inserted into the key order will change in a random fashion. The order may not be repeatable in a following program run even if the PERL\_HASH\_SEED has been specified. This is the default mode for perl when no PERL\_HASH\_SEED has been explicitly provided.
When set to `"2"` or `"DETERMINISTIC"` then inserting keys into a hash will cause the key order to change, but in a way that is repeatable from program run to program run, provided that the same hash seed is used, and that the code does not itself perform any non-deterministic operations and also provided exactly the same environment context. Adding or removing an environment variable may and likely will change the key order. If any part of the code builds a hash using non- deterministic keys, for instance a hash keyed by the stringified form of a reference, or the address of the objects it contains, then this may and likely will have a global effect on the key order of \*every\* hash in the process. To work properly this setting MUST be coupled with the [PERL\_HASH\_SEED](#PERL_HASH_SEED) to produce deterministic results, and in fact, if you do set the `PERL_HASH_SEED` explicitly you do not need to set this as well, it will be automatically set to this mode.
**NOTE:** Use of this option is considered insecure, and is intended only for debugging non-deterministic behavior in Perl's hash function. Do not use it in production.
See ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks) and ["PERL\_HASH\_SEED"](#PERL_HASH_SEED) and ["PERL\_HASH\_SEED\_DEBUG"](#PERL_HASH_SEED_DEBUG) for more information. You can get and set the key traversal mask for a specific hash by using the `hash_traversal_mask()` function from <Hash::Util>.
PERL\_HASH\_SEED\_DEBUG (Since Perl 5.8.1.) Set to `"1"` to display (to STDERR) information about the hash function, seed, and what type of key traversal randomization is in effect at the beginning of execution. This, combined with ["PERL\_HASH\_SEED"](#PERL_HASH_SEED) and ["PERL\_PERTURB\_KEYS"](#PERL_PERTURB_KEYS) is intended to aid in debugging nondeterministic behaviour caused by hash randomization.
**Note** that any information about the hash function, especially 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 [`hash_seed()`](Hash::Util#hash_seed) and [`hash_traversal_mask()`](Hash::Util#hash_traversal_mask).
An example output might be:
```
HASH_FUNCTION = ONE_AT_A_TIME_HARD HASH_SEED = 0x652e9b9349a7a032 PERTURB_KEYS = 1 (RANDOM)
```
PERL\_MEM\_LOG If your Perl was configured with **-Accflags=-DPERL\_MEM\_LOG**, setting the environment variable `PERL_MEM_LOG` enables logging debug messages. The value has the form `<*number*>[m][s][t]`, where `*number*` is the file descriptor number you want to write to (2 is default), and the combination of letters specifies that you want information about (m)emory and/or (s)v, optionally with (t)imestamps. For example, `PERL_MEM_LOG=1mst` logs all information to stdout. You can write to other opened file descriptors in a variety of ways:
```
$ 3>foo3 PERL_MEM_LOG=3m perl ...
```
PERL\_ROOT (specific to the VMS port) A translation-concealed rooted logical name that contains Perl and the logical device for the @INC path on VMS only. Other logical names that affect Perl on VMS include PERLSHR, PERL\_ENV\_TABLES, and SYS$TIMEZONE\_DIFFERENTIAL, but are optional and discussed further in <perlvms> and in *README.vms* in the Perl source distribution.
PERL\_SIGNALS Available in Perls 5.8.1 and later. If set to `"unsafe"`, the pre-Perl-5.8.0 signal behaviour (which is immediate but unsafe) is restored. If set to `safe`, then safe (but deferred) signals are used. See ["Deferred Signals (Safe Signals)" in perlipc](perlipc#Deferred-Signals-%28Safe-Signals%29).
PERL\_UNICODE Equivalent to the [-C](#-C-%5Bnumber%2Flist%5D) command-line switch. Note that this is not a boolean variable. Setting this to `"1"` is not the right way to "enable Unicode" (whatever that would mean). You can use `"0"` to "disable Unicode", though (or alternatively unset PERL\_UNICODE in your shell before starting Perl). See the description of the [-C](#-C-%5Bnumber%2Flist%5D) switch for more information.
PERL\_USE\_UNSAFE\_INC If perl has been configured to not have the current directory in [`@INC`](perlvar#%40INC) by default, this variable can be set to `"1"` to reinstate it. It's primarily intended for use while building and testing modules that have not been updated to deal with "." not being in `@INC` and should not be set in the environment for day-to-day use.
SYS$LOGIN (specific to the VMS port) Used if chdir has no argument and ["HOME"](#HOME) and ["LOGDIR"](#LOGDIR) are not set.
PERL\_INTERNAL\_RAND\_SEED Set to a non-negative integer to seed the random number generator used internally by perl for a variety of purposes.
Ignored if perl is run setuid or setgid. Used only for some limited startup randomization (hash keys) if `-T` or `-t` perl is started with tainting enabled.
Perl may be built to ignore this variable.
Perl also has environment variables that control how Perl handles data specific to particular natural languages; see <perllocale>.
Perl and its various modules and components, including its test frameworks, may sometimes make use of certain other environment variables. Some of these are specific to a particular platform. Please consult the appropriate module documentation and any documentation for your platform (like <perlsolaris>, <perllinux>, <perlmacosx>, <perlwin32>, etc) for variables peculiar to those specific situations.
Perl makes all environment variables available to the program being executed, and passes these along to any child processes it starts. However, programs running setuid would do well to execute the following lines before doing anything else, just to keep people honest:
```
$ENV{PATH} = "/bin:/usr/bin"; # or whatever you need
$ENV{SHELL} = "/bin/sh" if exists $ENV{SHELL};
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
```
ORDER OF APPLICATION
---------------------
Some options, in particular `-I`, `-M`, `PERL5LIB` and `PERL5OPT` can interact, and the order in which they are applied is important.
Note that this section does not document what *actually* happens inside the perl interpreter, it documents what *effectively* happens.
-I The effect of multiple `-I` options is to `unshift` them onto `@INC` from right to left. So for example:
```
perl -I 1 -I 2 -I 3
```
will first prepend `3` onto the front of `@INC`, then prepend `2`, and then prepend `1`. The result is that `@INC` begins with:
```
qw(1 2 3)
```
-M Multiple `-M` options are processed from left to right. So this:
```
perl -Mlib=1 -Mlib=2 -Mlib=3
```
will first use the <lib> pragma to prepend `1` to `@INC`, then it will prepend `2`, then it will prepend `3`, resulting in an `@INC` that begins with:
```
qw(3 2 1)
```
the PERL5LIB environment variable This contains a list of directories, separated by colons. The entire list is prepended to `@INC` in one go. This:
```
PERL5LIB=1:2:3 perl
```
will result in an `@INC` that begins with:
```
qw(1 2 3)
```
combinations of -I, -M and PERL5LIB `PERL5LIB` is applied first, then all the `-I` arguments, then all the `-M` arguments. This:
```
PERL5LIB=e1:e2 perl -I i1 -Mlib=m1 -I i2 -Mlib=m2
```
will result in an `@INC` that begins with:
```
qw(m2 m1 i1 i2 e1 e2)
```
the PERL5OPT environment variable This contains a space separated list of switches. We only consider the effects of `-M` and `-I` in this section.
After normal processing of `-I` switches from the command line, all the `-I` switches in `PERL5OPT` are extracted. They are processed from left to right instead of from right to left. Also note that while whitespace is allowed between a `-I` and its directory on the command line, it is not allowed in `PERL5OPT`.
After normal processing of `-M` switches from the command line, all the `-M` switches in `PERL5OPT` are extracted. They are processed from left to right, *i.e.* the same as those on the command line.
An example may make this clearer:
```
export PERL5OPT="-Mlib=optm1 -Iopti1 -Mlib=optm2 -Iopti2"
export PERL5LIB=e1:e2
perl -I i1 -Mlib=m1 -I i2 -Mlib=m2
```
will result in an `@INC` that begins with:
```
qw(
optm2
optm1
m2
m1
opti2
opti1
i1
i2
e1
e2
)
```
Other complications There are some complications that are ignored in the examples above:
arch and version subdirs All of `-I`, `PERL5LIB` and `use lib` will also prepend arch and version subdirs if they are present
sitecustomize.pl
| programming_docs |
perl fields fields
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
fields - compile-time class fields
SYNOPSIS
--------
```
{
package Foo;
use fields qw(foo bar _Foo_private);
sub new {
my Foo $self = shift;
unless (ref $self) {
$self = fields::new($self);
$self->{_Foo_private} = "this is Foo's secret";
}
$self->{foo} = 10;
$self->{bar} = 20;
return $self;
}
}
my $var = Foo->new;
$var->{foo} = 42;
# this will generate a run-time error
$var->{zap} = 42;
# this will generate a compile-time error
my Foo $foo = Foo->new;
$foo->{zap} = 24;
# subclassing
{
package Bar;
use base 'Foo';
use fields qw(baz _Bar_private); # not shared with Foo
sub new {
my $class = shift;
my $self = fields::new($class);
$self->SUPER::new(); # init base fields
$self->{baz} = 10; # init own fields
$self->{_Bar_private} = "this is Bar's secret";
return $self;
}
}
```
DESCRIPTION
-----------
The `fields` pragma enables compile-time and run-time verified class fields.
NOTE: The current implementation keeps the declared fields in the %FIELDS hash of the calling package, but this may change in future versions. Do **not** update the %FIELDS hash directly, because it must be created at compile-time for it to be fully useful, as is done by this pragma.
If a typed lexical variable (`my Class $var`) holding a reference is used to access a hash element and a package with the same name as the type has declared class fields using this pragma, then the hash key is verified at compile time. If the variables are not typed, access is only checked at run time.
The related `base` pragma will combine fields from base classes and any fields declared using the `fields` pragma. This enables field inheritance to work properly. Inherited fields can be overridden but will generate a warning if warnings are enabled.
**Only valid for Perl 5.8.x and earlier:** Field names that start with an underscore character are made private to the class and are not visible to subclasses.
Also, **in Perl 5.8.x and earlier**, this pragma uses pseudo-hashes, the effect being that you can have objects with named fields which are as compact and as fast arrays to access, as long as the objects are accessed through properly typed variables.
The following functions are supported:
new fields::new() creates and blesses a hash comprised of the fields declared using the `fields` pragma into the specified class. It is the recommended way to construct a fields-based object.
This makes it possible to write a constructor like this:
```
package Critter::Sounds;
use fields qw(cat dog bird);
sub new {
my $self = shift;
$self = fields::new($self) unless ref $self;
$self->{cat} = 'meow'; # scalar element
@$self{'dog','bird'} = ('bark','tweet'); # slice
return $self;
}
```
phash **This function only works in Perl 5.8.x and earlier.** Pseudo-hashes were removed from Perl as of 5.10. Consider using restricted hashes or fields::new() instead (which itself uses restricted hashes under 5.10+). See <Hash::Util>. Using fields::phash() under 5.10 or higher will cause an error.
fields::phash() can be used to create and initialize a plain (unblessed) pseudo-hash. This function should always be used instead of creating pseudo-hashes directly.
If the first argument is a reference to an array, the pseudo-hash will be created with keys from that array. If a second argument is supplied, it must also be a reference to an array whose elements will be used as the values. If the second array contains less elements than the first, the trailing elements of the pseudo-hash will not be initialized. This makes it particularly useful for creating a pseudo-hash from subroutine arguments:
```
sub dogtag {
my $tag = fields::phash([qw(name rank ser_num)], [@_]);
}
```
fields::phash() also accepts a list of key-value pairs that will be used to construct the pseudo hash. Examples:
```
my $tag = fields::phash(name => "Joe",
rank => "captain",
ser_num => 42);
my $pseudohash = fields::phash(%args);
```
SEE ALSO
---------
<base>, <Hash::Util>
perl perlmodlib perlmodlib
==========
CONTENTS
--------
* [NAME](#NAME)
* [THE PERL MODULE LIBRARY](#THE-PERL-MODULE-LIBRARY)
+ [Pragmatic Modules](#Pragmatic-Modules)
+ [Standard Modules](#Standard-Modules)
+ [Extension Modules](#Extension-Modules)
* [CPAN](#CPAN28)
* [Modules: Creation, Use, and Abuse](#Modules:-Creation,-Use,-and-Abuse)
+ [Guidelines for Module Creation](#Guidelines-for-Module-Creation)
+ [Guidelines for Converting Perl 4 Library Scripts into Modules](#Guidelines-for-Converting-Perl-4-Library-Scripts-into-Modules)
+ [Guidelines for Reusing Application Code](#Guidelines-for-Reusing-Application-Code)
* [NOTE](#NOTE)
NAME
----
perlmodlib - constructing new Perl modules and finding existing ones
THE PERL MODULE LIBRARY
------------------------
Many modules are included in the Perl distribution. These are described below, and all end in *.pm*. You may discover compiled library files (usually ending in *.so*) or small pieces of modules to be autoloaded (ending in *.al*); these were automatically generated by the installation process. You may also discover files in the library directory that end in either *.pl* or *.ph*. These are old libraries supplied so that old programs that use them still run. The *.pl* files will all eventually be converted into standard modules, and the *.ph* files made by **h2ph** will probably end up as extension modules made by **h2xs**. (Some *.ph* values may already be available through the POSIX, Errno, or Fcntl modules.) The **pl2pm** file in the distribution may help in your conversion, but it's just a mechanical process and therefore far from bulletproof.
###
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 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 Load subroutines only on demand
AutoSplit Split a package for autoloading
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 running times of Perl code
`IO::Socket::IP`
Family-neutral IP socket supporting both IPv4 and IPv6
`Socket` Networking constants and support functions
CORE Namespace for Perl's core routines
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 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 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 Get pathname of current working directory
DB Programmatic interface to the Perl debugging API
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 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 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 (obsolete) supply object methods for directory handles
Dumpvalue Provides screen dump of Perl data.
DynaLoader Dynamically load C libraries into Perl code
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 Use nice English (or awk) names for ugly punctuation variables
Env Perl module that imports environment variables as scalars or arrays
Errno System errno constants
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 Replace functions with equivalents which succeed or die
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 Keep more files open than the system permits
FileHandle Supply object methods for filehandles
Filter::Simple Simplified source filtering
Filter::Util::Call Perl Source Filter Utility Module
FindBin Locate directory of original perl script
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 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 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 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 Tied access to ndbm files
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 Generic interface to Perl Compiler backends
ODBM\_File Tied access to odbm files
Opcode Disable named opcodes when compiling perl code
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 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 Tied access to sdbm files
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 Save and restore selected file handle
SelfLoader Load functions only on demand
Storable Persistence for Perl data structures
Sub::Util A selection of utility subroutines for subs and CODE references
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 Provides a simple framework for writing test scripts
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 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 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 Interfaces to some Win32 API Functions
Win32API::File Low-level access to Win32 system API calls for files/dirs.
Win32CORE Win32 CORE function stubs
XS::APItest Test the perl C API
XS::Typemap Module to test the XS typemaps distributed with perl
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
To find out *all* modules installed on your system, including those without documentation or outside the standard release, just use the following command (under the default win32 shell, double quotes should be used instead of single quotes).
```
% perl -MFile::Find=find -MFile::Spec::Functions -Tlwe \
'find { wanted => sub { print canonpath $_ if /\.pm\z/ },
no_chdir => 1 }, @INC'
```
(The -T is here to prevent @INC from being populated by `PERL5LIB`, `PERLLIB`, and `PERL_USE_UNSAFE_INC`.) They should all have their own documentation installed and accessible via your system man(1) command. If you do not have a **find** program, you can use the Perl **find2perl** program instead, which generates Perl code as output you can run through perl. If you have a **man** program but it doesn't find your modules, you'll have to fix your manpath. See <perl> for details. If you have no system **man** command, you might try the **perldoc** program.
Note also that the command `perldoc perllocal` gives you a (possibly incomplete) list of the modules that have been further installed on your system. (The perllocal.pod file is updated by the standard MakeMaker install process.)
###
Extension Modules
Extension modules are written in C (or a mix of Perl and C). They are usually dynamically loaded into Perl if and when you need them, but may also be linked in statically. Supported extension modules include Socket, Fcntl, and POSIX.
Many popular C extension modules do not come bundled (at least, not completely) due to their sizes, volatility, or simply lack of time for adequate testing and configuration across the multitude of platforms on which Perl was beta-tested. You are encouraged to look for them on CPAN (described below), or using web search engines like Google or DuckDuckGo.
CPAN
----
CPAN stands for Comprehensive Perl Archive Network; it's a globally replicated trove of Perl materials, including documentation, style guides, tricks and traps, alternate ports to non-Unix systems and occasional binary distributions for these. Search engines for CPAN can be found at https://www.cpan.org/
Most importantly, CPAN includes around a thousand unbundled modules, some of which require a C compiler to build. Major categories of modules are:
* Language Extensions and Documentation Tools
* Development Support
* Operating System Interfaces
* Networking, Device Control (modems) and InterProcess Communication
* Data Types and Data Type Utilities
* Database Interfaces
* User Interfaces
* Interfaces to / Emulations of Other Programming Languages
* File Names, File Systems and File Locking (see also File Handles)
* String Processing, Language Text Processing, Parsing, and Searching
* Option, Argument, Parameter, and Configuration File Processing
* Internationalization and Locale
* Authentication, Security, and Encryption
* World Wide Web, HTML, HTTP, CGI, MIME
* Server and Daemon Utilities
* Archiving and Compression
* Images, Pixmap and Bitmap Manipulation, Drawing, and Graphing
* Mail and Usenet News
* Control Flow Utilities (callbacks and exceptions etc)
* File Handle and Input/Output Stream Utilities
* Miscellaneous Modules
You can find the CPAN online at <https://www.cpan.org/>
Modules: Creation, Use, and Abuse
----------------------------------
(The following section is borrowed directly from Tim Bunce's modules file, available at your nearest CPAN site.)
Perl implements a class using a package, but the presence of a package doesn't imply the presence of a class. A package is just a namespace. A class is a package that provides subroutines that can be used as methods. A method is just a subroutine that expects, as its first argument, either the name of a package (for "static" methods), or a reference to something (for "virtual" methods).
A module is a file that (by convention) provides a class of the same name (sans the .pm), plus an import method in that class that can be called to fetch exported symbols. This module may implement some of its methods by loading dynamic C or C++ objects, but that should be totally transparent to the user of the module. Likewise, the module might set up an AUTOLOAD function to slurp in subroutine definitions on demand, but this is also transparent. Only the *.pm* file is required to exist. See <perlsub>, <perlobj>, and [AutoLoader](autoloader) for details about the AUTOLOAD mechanism.
###
Guidelines for Module Creation
* Do similar modules already exist in some form?
If so, please try to reuse the existing modules either in whole or by inheriting useful features into a new class. If this is not practical try to get together with the module authors to work on extending or enhancing the functionality of the existing modules. A perfect example is the plethora of packages in perl4 for dealing with command line options.
If you are writing a module to expand an already existing set of modules, please coordinate with the author of the package. It helps if you follow the same naming scheme and module interaction scheme as the original author.
* Try to design the new module to be easy to extend and reuse.
Try to `use warnings;` (or `use warnings qw(...);`). Remember that you can add `no warnings qw(...);` to individual blocks of code that need less warnings.
Use blessed references. Use the two argument form of bless to bless into the class name given as the first parameter of the constructor, e.g.,:
```
sub new {
my $class = shift;
return bless {}, $class;
}
```
or even this if you'd like it to be used as either a static or a virtual method.
```
sub new {
my $self = shift;
my $class = ref($self) || $self;
return bless {}, $class;
}
```
Pass arrays as references so more parameters can be added later (it's also faster). Convert functions into methods where appropriate. Split large methods into smaller more flexible ones. Inherit methods from other modules if appropriate.
Avoid class name tests like: `die "Invalid" unless ref $ref eq 'FOO'`. Generally you can delete the `eq 'FOO'` part with no harm at all. Let the objects look after themselves! Generally, avoid hard-wired class names as far as possible.
Avoid `$r->Class::func()` where using `@ISA=qw(... Class ...)` and `$r->func()` would work.
Use autosplit so little used or newly added functions won't be a burden to programs that don't use them. Add test functions to the module after \_\_END\_\_ either using AutoSplit or by saying:
```
eval join('',<main::DATA>) || die $@ unless caller();
```
Does your module pass the 'empty subclass' test? If you say `@SUBCLASS::ISA = qw(YOURCLASS);` your applications should be able to use SUBCLASS in exactly the same way as YOURCLASS. For example, does your application still work if you change: `$obj = YOURCLASS->new();` into: `$obj = SUBCLASS->new();` ?
Avoid keeping any state information in your packages. It makes it difficult for multiple other packages to use yours. Keep state information in objects.
Always use **-w**.
Try to `use strict;` (or `use strict qw(...);`). Remember that you can add `no strict qw(...);` to individual blocks of code that need less strictness.
Always use **-w**.
Follow the guidelines in <perlstyle>.
Always use **-w**.
* Some simple style guidelines
The perlstyle manual supplied with Perl has many helpful points.
Coding style is a matter of personal taste. Many people evolve their style over several years as they learn what helps them write and maintain good code. Here's one set of assorted suggestions that seem to be widely used by experienced developers:
Use underscores to separate words. It is generally easier to read $var\_names\_like\_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR\_NAMES\_LIKE\_THIS.
Package/Module names are an exception to this rule. Perl informally reserves lowercase module names for 'pragma' modules like integer and strict. Other modules normally begin with a capital letter and use mixed case with no underscores (need to be short and portable).
You may find it helpful to use letter case to indicate the scope or nature of a variable. For example:
```
$ALL_CAPS_HERE constants only (beware clashes with Perl vars)
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my() or local() variables
```
Function and method names seem to work best as all lowercase. e.g., `$obj->as_string()`.
You can use a leading underscore to indicate that a variable or function should not be used outside the package that defined it.
* Select what to export.
Do NOT export method names!
Do NOT export anything else by default without a good reason!
Exports pollute the namespace of the module user. If you must export try to use @EXPORT\_OK in preference to @EXPORT and avoid short or common names to reduce the risk of name clashes.
Generally anything not exported is still accessible from outside the module using the ModuleName::item\_name (or `$blessed_ref->method`) syntax. By convention you can use a leading underscore on names to indicate informally that they are 'internal' and not for public use.
(It is actually possible to get private functions by saying: `my $subref = sub { ... }; &$subref;`. But there's no way to call that directly as a method, because a method must have a name in the symbol table.)
As a general rule, if the module is trying to be object oriented then export nothing. If it's just a collection of functions then @EXPORT\_OK anything but use @EXPORT with caution.
* Select a name for the module.
This name should be as descriptive, accurate, and complete as possible. Avoid any risk of ambiguity. Always try to use two or more whole words. Generally the name should reflect what is special about what the module does rather than how it does it. Please use nested module names to group informally or categorize a module. There should be a very good reason for a module not to have a nested name. Module names should begin with a capital letter.
Having 57 modules all called Sort will not make life easy for anyone (though having 23 called Sort::Quick is only marginally better :-). Imagine someone trying to install your module alongside many others.
If you are developing a suite of related modules/classes it's good practice to use nested classes with a common prefix as this will avoid namespace clashes. For example: Xyz::Control, Xyz::View, Xyz::Model etc. Use the modules in this list as a naming guide.
If adding a new module to a set, follow the original author's standards for naming modules and the interface to methods in those modules.
If developing modules for private internal or project specific use, that will never be released to the public, then you should ensure that their names will not clash with any future public module. You can do this either by using the reserved Local::\* category or by using a category name that includes an underscore like Foo\_Corp::\*.
To be portable each component of a module name should be limited to 11 characters. If it might be used on MS-DOS then try to ensure each is unique in the first 8 characters. Nested modules make this easier.
For additional guidance on the naming of modules, please consult:
```
https://pause.perl.org/pause/query?ACTION=pause_namingmodules
```
or send mail to the <[email protected]> mailing list.
* Have you got it right?
How do you know that you've made the right decisions? Have you picked an interface design that will cause problems later? Have you picked the most appropriate name? Do you have any questions?
The best way to know for sure, and pick up many helpful suggestions, is to ask someone who knows. The <[email protected]> mailing list is useful for this purpose; it's also accessible via news interface as perl.module-authors at nntp.perl.org.
All you need to do is post a short summary of the module, its purpose and interfaces. A few lines on each of the main methods is probably enough. (If you post the whole module it might be ignored by busy people - generally the very people you want to read it!)
Don't worry about posting if you can't say when the module will be ready - just say so in the message. It might be worth inviting others to help you, they may be able to complete it for you!
* README and other Additional Files.
It's well known that software developers usually fully document the software they write. If, however, the world is in urgent need of your software and there is not enough time to write the full documentation please at least provide a README file containing:
+ A description of the module/package/extension etc.
+ A copyright notice - see below.
+ Prerequisites - what else you may need to have.
+ How to build it - possible changes to Makefile.PL etc.
+ How to install it.
+ Recent changes in this release, especially incompatibilities
+ Changes / enhancements you plan to make in the future.If the README file seems to be getting too large you may wish to split out some of the sections into separate files: INSTALL, Copying, ToDo etc.
+ Adding a Copyright Notice.
How you choose to license your work is a personal decision. The general mechanism is to assert your Copyright and then make a declaration of how others may copy/use/modify your work.
Perl, for example, is supplied with two types of licence: The GNU GPL and The Artistic Licence (see the files README, Copying, and Artistic, or [perlgpl](https://perldoc.perl.org/5.36.0/perlgpl) and [perlartistic](https://perldoc.perl.org/5.36.0/perlartistic)). Larry has good reasons for NOT just using the GNU GPL.
My personal recommendation, out of respect for Larry, Perl, and the Perl community at large is to state something simply like:
```
Copyright (c) 1995 Your Name. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
```
This statement should at least appear in the README file. You may also wish to include it in a Copying file and your source files. Remember to include the other words in addition to the Copyright.
+ Give the module a version/issue/release number.
To be fully compatible with the Exporter and MakeMaker modules you should store your module's version number in a non-my package variable called $VERSION. This should be a positive floating point number with at least two digits after the decimal (i.e., hundredths, e.g, `$VERSION = "0.01"`). Don't use a "1.3.2" style version. See [Exporter](exporter) for details.
It may be handy to add a function or method to retrieve the number. Use the number in announcements and archive file names when releasing the module (ModuleName-1.02.tar.Z). See perldoc ExtUtils::MakeMaker.pm for details.
+ How to release and distribute a module.
If possible, register the module with CPAN. Follow the instructions and links on:
```
https://www.cpan.org/modules/04pause.html
```
and upload to:
```
https://pause.perl.org/
```
and notify <[email protected]>. This will allow anyone to install your module using the `cpan` tool distributed with Perl.
By using the WWW interface you can ask the Upload Server to mirror your modules from your ftp or WWW site into your own directory on CPAN!
+ Take care when changing a released module.
Always strive to remain compatible with previous released versions. Otherwise try to add a mechanism to revert to the old behavior if people rely on it. Document incompatible changes.
###
Guidelines for Converting Perl 4 Library Scripts into Modules
* There is no requirement to convert anything.
If it ain't broke, don't fix it! Perl 4 library scripts should continue to work with no problems. You may need to make some minor changes (like escaping non-array @'s in double quoted strings) but there is no need to convert a .pl file into a Module for just that.
* Consider the implications.
All Perl applications that make use of the script will need to be changed (slightly) if the script is converted into a module. Is it worth it unless you plan to make other changes at the same time?
* Make the most of the opportunity.
If you are going to convert the script to a module you can use the opportunity to redesign the interface. The guidelines for module creation above include many of the issues you should consider.
* The pl2pm utility will get you started.
This utility will read \*.pl files (given as parameters) and write corresponding \*.pm files. The pl2pm utilities does the following:
+ Adds the standard Module prologue lines
+ Converts package specifiers from ' to ::
+ Converts die(...) to croak(...)
+ Several other minor changesBeing a mechanical process pl2pm is not bullet proof. The converted code will need careful checking, especially any package statements. Don't delete the original .pl file till the new .pm one works!
###
Guidelines for Reusing Application Code
* Complete applications rarely belong in the Perl Module Library.
* Many applications contain some Perl code that could be reused.
Help save the world! Share your code in a form that makes it easy to reuse.
* Break-out the reusable code into one or more separate module files.
* Take the opportunity to reconsider and redesign the interfaces.
* In some cases the 'application' can then be reduced to a small
fragment of code built on top of the reusable modules. In these cases the application could invoked as:
```
% perl -e 'use Module::Name; method(@ARGV)' ...
or
% perl -mModule::Name ... (in perl5.002 or higher)
```
NOTE
----
Perl does not enforce private and public parts of its modules as you may have been used to in other languages like C++, Ada, or Modula-17. Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun.
The module and its user have a contract, part of which is common law, and part of which is "written". Part of the common law contract is that a module doesn't pollute any namespace it wasn't asked to. The written contract for the module (A.K.A. documentation) may make other provisions. But then you know when you `use RedefineTheWorld` that you're redefining the world and willing to take the consequences.
| programming_docs |
perl perldebguts perldebguts
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Debugger Internals](#Debugger-Internals)
+ [Writing Your Own Debugger](#Writing-Your-Own-Debugger)
- [Environment Variables](#Environment-Variables)
- [Debugger Internal Variables](#Debugger-Internal-Variables)
- [Debugger Customization Functions](#Debugger-Customization-Functions)
* [Frame Listing Output Examples](#Frame-Listing-Output-Examples)
* [Debugging Regular Expressions](#Debugging-Regular-Expressions)
+ [Compile-time Output](#Compile-time-Output)
+ [Types of Nodes](#Types-of-Nodes)
+ [Run-time Output](#Run-time-Output)
* [Debugging Perl Memory Usage](#Debugging-Perl-Memory-Usage)
+ [Using $ENV{PERL\_DEBUG\_MSTATS}](#Using-%24ENV%7BPERL_DEBUG_MSTATS%7D)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perldebguts - Guts of Perl debugging
DESCRIPTION
-----------
This is not <perldebug>, which tells you how to use the debugger. This manpage describes low-level details concerning the debugger's internals, which range from difficult to impossible to understand for anyone who isn't incredibly intimate with Perl's guts. Caveat lector.
Debugger Internals
-------------------
Perl has special debugging hooks at compile-time and run-time used to create debugging environments. These hooks are not to be confused with the *perl -Dxxx* command described in [perlrun](perlrun#-Dletters), which is usable only if a special Perl is built per the instructions in the *INSTALL* file in the Perl source tree.
For example, whenever you call Perl's built-in `caller` function from the package `DB`, the arguments that the corresponding stack frame was called with are copied to the `@DB::args` array. These mechanisms are enabled by calling Perl with the **-d** switch. Specifically, the following additional features are enabled (cf. ["$^P" in perlvar](perlvar#%24%5EP)):
* Perl inserts the contents of `$ENV{PERL5DB}` (or `BEGIN {require 'perl5db.pl'}` if not present) before the first line of your program.
* Each array `@{"_<$filename"}` holds the lines of $filename for a file compiled by Perl. The same is also true for `eval`ed strings that contain subroutines, or which are currently being executed. The $filename for `eval`ed strings looks like `(eval 34)`.
Values in this array are magical in numeric context: they compare equal to zero only if the line is not breakable.
* Each hash `%{"_<$filename"}` contains breakpoints and actions keyed by line number. Individual entries (as opposed to the whole hash) are settable. Perl only cares about Boolean true here, although the values used by *perl5db.pl* have the form `"$break_condition\0$action"`.
The same holds for evaluated strings that contain subroutines, or which are currently being executed. The $filename for `eval`ed strings looks like `(eval 34)`.
* Each scalar `${"_<$filename"}` contains `$filename`. This is also the case for evaluated strings that contain subroutines, or which are currently being executed. The `$filename` for `eval`ed strings looks like `(eval 34)`.
* After each `require`d file is compiled, but before it is executed, `DB::postponed(*{"_<$filename"})` is called if the subroutine `DB::postponed` exists. Here, the $filename is the expanded name of the `require`d file, as found in the values of %INC.
* After each subroutine `subname` is compiled, the existence of `$DB::postponed{subname}` is checked. If this key exists, `DB::postponed(subname)` is called if the `DB::postponed` subroutine also exists.
* A hash `%DB::sub` is maintained, whose keys are subroutine names and whose values have the form `filename:startline-endline`. `filename` has the form `(eval 34)` for subroutines defined inside `eval`s.
* When the execution of your program reaches a point that can hold a breakpoint, the `DB::DB()` subroutine is called if any of the variables `$DB::trace`, `$DB::single`, or `$DB::signal` is true. These variables are not `local`izable. This feature is disabled when executing inside `DB::DB()`, including functions called from it unless `$^D & (1<<30)` is true.
* When execution of the program reaches a subroutine call, a call to `&DB::sub`(*args*) is made instead, with `$DB::sub` set to identify the called subroutine. (This doesn't happen if the calling subroutine was compiled in the `DB` package.) `$DB::sub` normally holds the name of the called subroutine, if it has a name by which it can be looked up. Failing that, `$DB::sub` will hold a reference to the called subroutine. Either way, the `&DB::sub` subroutine can use `$DB::sub` as a reference by which to call the called subroutine, which it will normally want to do.
If the call is to an lvalue subroutine, and `&DB::lsub` is defined `&DB::lsub`(*args*) is called instead, otherwise falling back to `&DB::sub`(*args*).
* When execution of the program uses `goto` to enter a non-XS subroutine and the 0x80 bit is set in `$^P`, a call to `&DB::goto` is made, with `$DB::sub` set to identify the subroutine being entered. The call to `&DB::goto` does not replace the `goto`; the requested subroutine will still be entered once `&DB::goto` has returned. `$DB::sub` normally holds the name of the subroutine being entered, if it has one. Failing that, `$DB::sub` will hold a reference to the subroutine being entered. Unlike when `&DB::sub` is called, it is not guaranteed that `$DB::sub` can be used as a reference to operate on the subroutine being entered.
Note that if `&DB::sub` needs external data for it to work, no subroutine call is possible without it. As an example, the standard debugger's `&DB::sub` depends on the `$DB::deep` variable (it defines how many levels of recursion deep into the debugger you can go before a mandatory break). If `$DB::deep` is not defined, subroutine calls are not possible, even though `&DB::sub` exists.
###
Writing Your Own Debugger
####
Environment Variables
The `PERL5DB` environment variable can be used to define a debugger. For example, the minimal "working" debugger (it actually doesn't do anything) consists of one line:
```
sub DB::DB {}
```
It can easily be defined like this:
```
$ PERL5DB="sub DB::DB {}" perl -d your-script
```
Another brief debugger, slightly more useful, can be created with only the line:
```
sub DB::DB {print ++$i; scalar <STDIN>}
```
This debugger prints a number which increments for each statement encountered and waits for you to hit a newline before continuing to the next statement.
The following debugger is actually useful:
```
{
package DB;
sub DB {}
sub sub {print ++$i, " $sub\n"; &$sub}
}
```
It prints the sequence number of each subroutine call and the name of the called subroutine. Note that `&DB::sub` is being compiled into the package `DB` through the use of the `package` directive.
When it starts, the debugger reads your rc file (*./.perldb* or *~/.perldb* under Unix), which can set important options. (A subroutine (`&afterinit`) can be defined here as well; it is executed after the debugger completes its own initialization.)
After the rc file is read, the debugger reads the PERLDB\_OPTS environment variable and uses it to set debugger options. The contents of this variable are treated as if they were the argument of an `o ...` debugger command (q.v. in ["Configurable Options" in perldebug](perldebug#Configurable-Options)).
####
Debugger Internal Variables
In addition to the file and subroutine-related variables mentioned above, the debugger also maintains various magical internal variables.
* `@DB::dbline` is an alias for `@{"::_<current_file"}`, which holds the lines of the currently-selected file (compiled by Perl), either explicitly chosen with the debugger's `f` command, or implicitly by flow of execution.
Values in this array are magical in numeric context: they compare equal to zero only if the line is not breakable.
* `%DB::dbline` is an alias for `%{"::_<current_file"}`, which contains breakpoints and actions keyed by line number in the currently-selected file, either explicitly chosen with the debugger's `f` command, or implicitly by flow of execution.
As previously noted, individual entries (as opposed to the whole hash) are settable. Perl only cares about Boolean true here, although the values used by *perl5db.pl* have the form `"$break_condition\0$action"`.
####
Debugger Customization Functions
Some functions are provided to simplify customization.
* See ["Configurable Options" in perldebug](perldebug#Configurable-Options) for a description of options parsed by `DB::parse_options(string)`.
* `DB::dump_trace(skip[,count])` skips the specified number of frames and returns a list containing information about the calling frames (all of them, if `count` is missing). Each entry is reference to a hash with keys `context` (either `.`, `$`, or `@`), `sub` (subroutine name, or info about `eval`), `args` (`undef` or a reference to an array), `file`, and `line`.
* `DB::print_trace(FH, skip[, count[, short]])` prints formatted info about caller frames. The last two functions may be convenient as arguments to `<`, `<<` commands.
Note that any variables and functions that are not documented in this manpages (or in <perldebug>) are considered for internal use only, and as such are subject to change without notice.
Frame Listing Output Examples
------------------------------
The `frame` option can be used to control the output of frame information. For example, contrast this expression trace:
```
$ perl -de 42
Stack dump during die enabled outside of evals.
Loading DB routines from perl5db.pl patch level 0.94
Emacs support available.
Enter h or 'h h' for help.
main::(-e:1): 0
DB<1> sub foo { 14 }
DB<2> sub bar { 3 }
DB<3> t print foo() * bar()
main::((eval 172):3): print foo() + bar();
main::foo((eval 168):2):
main::bar((eval 170):2):
42
```
with this one, once the `o`ption `frame=2` has been set:
```
DB<4> o f=2
frame = '2'
DB<5> t print foo() * bar()
3: foo() * bar()
entering main::foo
2: sub foo { 14 };
exited main::foo
entering main::bar
2: sub bar { 3 };
exited main::bar
42
```
By way of demonstration, we present below a laborious listing resulting from setting your `PERLDB_OPTS` environment variable to the value `f=n N`, and running *perl -d -V* from the command line. Examples using various values of `n` are shown to give you a feel for the difference between settings. Long though it may be, this is not a complete listing, but only excerpts.
1. ```
entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
entering Config::TIEHASH
entering Exporter::import
entering Exporter::export
entering Config::myconfig
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
```
2. ```
entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
exited Config::BEGIN
Package lib/Config.pm.
entering Config::TIEHASH
exited Config::TIEHASH
entering Exporter::import
entering Exporter::export
exited Exporter::export
exited Exporter::import
exited main::BEGIN
entering Config::myconfig
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
```
3. ```
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574
```
4. ```
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
out $=main::BEGIN() from /dev/null:0
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
```
5. ```
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
out $=main::BEGIN() from /dev/null:0
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
in $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
```
6. ```
in $=CODE(0x15eca4)() from /dev/null:0
in $=CODE(0x182528)() from lib/Config.pm:2
Package lib/Exporter.pm.
out $=CODE(0x182528)() from lib/Config.pm:0
scalar context return from CODE(0x182528): undef
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:628
out $=Config::TIEHASH('Config') from lib/Config.pm:628
scalar context return from Config::TIEHASH: empty hash
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
scalar context return from Exporter::export: ''
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
scalar context return from Exporter::import: ''
```
In all cases shown above, the line indentation shows the call tree. If bit 2 of `frame` is set, a line is printed on exit from a subroutine as well. If bit 4 is set, the arguments are printed along with the caller info. If bit 8 is set, the arguments are printed even if they are tied or references. If bit 16 is set, the return value is printed, too.
When a package is compiled, a line like this
```
Package lib/Carp.pm.
```
is printed with proper indentation.
Debugging Regular Expressions
------------------------------
There are two ways to enable debugging output for regular expressions.
If your perl is compiled with `-DDEBUGGING`, you may use the **-Dr** flag on the command line, and `-Drv` for more verbose information.
Otherwise, one can `use re 'debug'`, which has effects at both compile time and run time. Since Perl 5.9.5, this pragma is lexically scoped.
###
Compile-time Output
The debugging output at compile time looks like this:
```
Compiling REx '[bc]d(ef*g)+h[ij]k$'
size 45 Got 364 bytes for offset annotations.
first at 1
rarest char g at 0
rarest char d at 0
1: ANYOF[bc](12)
12: EXACT <d>(14)
14: CURLYX[0] {1,32767}(28)
16: OPEN1(18)
18: EXACT <e>(20)
20: STAR(23)
21: EXACT <f>(0)
23: EXACT <g>(25)
25: CLOSE1(27)
27: WHILEM[1/1](0)
28: NOTHING(29)
29: EXACT <h>(31)
31: ANYOF[ij](42)
42: EXACT <k>(44)
44: EOL(45)
45: END(0)
anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating)
stclass 'ANYOF[bc]' minlen 7
Offsets: [45]
1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]
Omitting $` $& $' support.
```
The first line shows the pre-compiled form of the regex. The second shows the size of the compiled form (in arbitrary units, usually 4-byte words) and the total number of bytes allocated for the offset/length table, usually 4+`size`\*8. The next line shows the label *id* of the first node that does a match.
The
```
anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating)
stclass 'ANYOF[bc]' minlen 7
```
line (split into two lines above) contains optimizer information. In the example shown, the optimizer found that the match should contain a substring `de` at offset 1, plus substring `gh` at some offset between 3 and infinity. Moreover, when checking for these substrings (to abandon impossible matches quickly), Perl will check for the substring `gh` before checking for the substring `de`. The optimizer may also use the knowledge that the match starts (at the `first` *id*) with a character class, and no string shorter than 7 characters can possibly match.
The fields of interest which may appear in this line are
`anchored` *STRING* `at` *POS*
`floating` *STRING* `at` *POS1..POS2*
See above.
`matching floating/anchored`
Which substring to check first.
`minlen` The minimal length of the match.
`stclass` *TYPE*
Type of first matching node.
`noscan` Don't scan for the found substrings.
`isall` Means that the optimizer information is all that the regular expression contains, and thus one does not need to enter the regex engine at all.
`GPOS` Set if the pattern contains `\G`.
`plus` Set if the pattern starts with a repeated char (as in `x+y`).
`implicit` Set if the pattern starts with `.*`.
`with eval`
Set if the pattern contain eval-groups, such as `(?{ code })` and `(??{ code })`.
`anchored(TYPE)`
If the pattern may match only at a handful of places, with `TYPE` being `SBOL`, `MBOL`, or `GPOS`. See the table below.
If a substring is known to match at end-of-line only, it may be followed by `$`, as in `floating 'k'$`.
The optimizer-specific information is used to avoid entering (a slow) regex engine on strings that will not definitely match. If the `isall` flag is set, a call to the regex engine may be avoided even when the optimizer found an appropriate place for the match.
Above the optimizer section is the list of *nodes* of the compiled form of the regex. Each line has format
*id*: *TYPE* *OPTIONAL-INFO* (*next-id*)
###
Types of Nodes
Here are the current possible types, with short descriptions:
```
# TYPE arg-description [regnode-struct-suffix] [longjump-len] DESCRIPTION
# Exit points
END no End of program.
SUCCEED no Return from a subroutine, basically.
# Line Start Anchors:
SBOL no Match "" at beginning of line: /^/, /\A/
MBOL no Same, assuming multiline: /^/m
# Line End Anchors:
SEOL no Match "" at end of line: /$/
MEOL no Same, assuming multiline: /$/m
EOS no Match "" at end of string: /\z/
# Match Start Anchors:
GPOS no Matches where last m//g left off.
# Word Boundary Opcodes:
BOUND no Like BOUNDA for non-utf8, otherwise like
BOUNDU
BOUNDL no Like BOUND/BOUNDU, but \w and \W are
defined by current locale
BOUNDU no Match "" at any boundary of a given type
using /u rules.
BOUNDA no Match "" at any boundary between \w\W or
\W\w, where \w is [_a-zA-Z0-9]
NBOUND no Like NBOUNDA for non-utf8, otherwise like
BOUNDU
NBOUNDL no Like NBOUND/NBOUNDU, but \w and \W are
defined by current locale
NBOUNDU no Match "" at any non-boundary of a given
type using using /u rules.
NBOUNDA no Match "" betweeen any \w\w or \W\W, where
\w is [_a-zA-Z0-9]
# [Special] alternatives:
REG_ANY no Match any one character (except newline).
SANY no Match any one character.
ANYOF sv Match character in (or not in) this class,
charclass single char match only
ANYOFD sv Like ANYOF, but /d is in effect
charclass
ANYOFL sv Like ANYOF, but /l is in effect
charclass
ANYOFPOSIXL sv Like ANYOFL, but matches [[:posix:]]
charclass_ classes
posixl
ANYOFH sv 1 Like ANYOF, but only has "High" matches,
none in the bitmap; the flags field
contains the lowest matchable UTF-8 start
byte
ANYOFHb sv 1 Like ANYOFH, but all matches share the same
UTF-8 start byte, given in the flags field
ANYOFHr sv 1 Like ANYOFH, but the flags field contains
packed bounds for all matchable UTF-8 start
bytes.
ANYOFHs sv 1 Like ANYOFHb, but has a string field that
gives the leading matchable UTF-8 bytes;
flags field is len
ANYOFR packed 1 Matches any character in the range given by
its packed args: upper 12 bits is the max
delta from the base lower 20; the flags
field contains the lowest matchable UTF-8
start byte
ANYOFRb packed 1 Like ANYOFR, but all matches share the same
UTF-8 start byte, given in the flags field
ANYOFM byte 1 Like ANYOF, but matches an invariant byte
as determined by the mask and arg
NANYOFM byte 1 complement of ANYOFM
# POSIX Character Classes:
POSIXD none Some [[:class:]] under /d; the FLAGS field
gives which one
POSIXL none Some [[:class:]] under /l; the FLAGS field
gives which one
POSIXU none Some [[:class:]] under /u; the FLAGS field
gives which one
POSIXA none Some [[:class:]] under /a; the FLAGS field
gives which one
NPOSIXD none complement of POSIXD, [[:^class:]]
NPOSIXL none complement of POSIXL, [[:^class:]]
NPOSIXU none complement of POSIXU, [[:^class:]]
NPOSIXA none complement of POSIXA, [[:^class:]]
CLUMP no Match any extended grapheme cluster
sequence
# Alternation
# BRANCH The set of branches constituting a single choice are
# hooked together with their "next" pointers, since
# precedence prevents anything being concatenated to
# any individual branch. The "next" pointer of the last
# BRANCH in a choice points to the thing following the
# whole choice. This is also where the final "next"
# pointer of each individual branch points; each branch
# starts with the operand node of a BRANCH node.
#
BRANCH node Match this alternative, or the next...
# Literals
EXACT str Match this string (flags field is the
length).
# In a long string node, the U32 argument is the length, and is
# immediately followed by the string.
LEXACT len:str 1 Match this long string (preceded by length;
flags unused).
EXACTL str Like EXACT, but /l is in effect (used so
locale-related warnings can be checked for)
EXACTF str Like EXACT, but match using /id rules;
(string not UTF-8, ASCII folded; non-ASCII
not)
EXACTFL str Like EXACT, but match using /il rules;
(string not likely to be folded)
EXACTFU str Like EXACT, but match using /iu rules;
(string folded)
EXACTFAA str Like EXACT, but match using /iaa rules;
(string folded except MICRO in non-UTF8
patterns; doesn't contain SHARP S unless
UTF-8; folded length <= unfolded)
EXACTFAA_NO_TRIE str Like EXACTFAA, (string not UTF-8, folded
except: MICRO, SHARP S; folded length <=
unfolded, not currently trie-able)
EXACTFUP str Like EXACT, but match using /iu rules;
(string not UTF-8, folded except MICRO:
hence Problematic)
EXACTFLU8 str Like EXACTFU, but use /il, UTF-8, (string
is folded, and everything in it is above
255
EXACT_REQ8 str Like EXACT, but only UTF-8 encoded targets
can match
LEXACT_REQ8 len:str 1 Like LEXACT, but only UTF-8 encoded targets
can match
EXACTFU_REQ8 str Like EXACTFU, but only UTF-8 encoded
targets can match
EXACTFU_S_EDGE str /di rules, but nothing in it precludes /ui,
except begins and/or ends with [Ss];
(string not UTF-8; compile-time only)
# New charclass like patterns
LNBREAK none generic newline pattern
# Trie Related
# Behave the same as A|LIST|OF|WORDS would. The '..C' variants
# have inline charclass data (ascii only), the 'C' store it in the
# structure.
TRIE trie 1 Match many EXACT(F[ALU]?)? at once.
flags==type
TRIEC trie Same as TRIE, but with embedded charclass
charclass data
AHOCORASICK trie 1 Aho Corasick stclass. flags==type
AHOCORASICKC trie Same as AHOCORASICK, but with embedded
charclass charclass data
# Do nothing types
NOTHING no Match empty string.
# A variant of above which delimits a group, thus stops optimizations
TAIL no Match empty string. Can jump here from
outside.
# Loops
# STAR,PLUS '?', and complex '*' and '+', are implemented as
# circular BRANCH structures. Simple cases
# (one character per match) are implemented with STAR
# and PLUS for speed and to minimize recursive plunges.
#
STAR node Match this (simple) thing 0 or more times.
PLUS node Match this (simple) thing 1 or more times.
CURLY sv 2 Match this simple thing {n,m} times.
CURLYN no 2 Capture next-after-this simple thing
CURLYM no 2 Capture this medium-complex thing {n,m}
times.
CURLYX sv 2 Match this complex thing {n,m} times.
# This terminator creates a loop structure for CURLYX
WHILEM no Do curly processing and see if rest
matches.
# Buffer related
# OPEN,CLOSE,GROUPP ...are numbered at compile time.
OPEN num 1 Mark this point in input as start of #n.
CLOSE num 1 Close corresponding OPEN of #n.
SROPEN none Same as OPEN, but for script run
SRCLOSE none Close preceding SROPEN
REF num 1 Match some already matched string
REFF num 1 Match already matched string, using /di
rules.
REFFL num 1 Match already matched string, using /li
rules.
REFFU num 1 Match already matched string, usng /ui.
REFFA num 1 Match already matched string, using /aai
rules.
# Named references. Code in regcomp.c assumes that these all are after
# the numbered references
REFN no-sv 1 Match some already matched string
REFFN no-sv 1 Match already matched string, using /di
rules.
REFFLN no-sv 1 Match already matched string, using /li
rules.
REFFUN num 1 Match already matched string, using /ui
rules.
REFFAN num 1 Match already matched string, using /aai
rules.
# Support for long RE
LONGJMP off 1 1 Jump far away.
BRANCHJ off 1 1 BRANCH with long offset.
# Special Case Regops
IFMATCH off 1 1 Succeeds if the following matches; non-zero
flags "f", next_off "o" means lookbehind
assertion starting "f..(f-o)" characters
before current
UNLESSM off 1 1 Fails if the following matches; non-zero
flags "f", next_off "o" means lookbehind
assertion starting "f..(f-o)" characters
before current
SUSPEND off 1 1 "Independent" sub-RE.
IFTHEN off 1 1 Switch, should be preceded by switcher.
GROUPP num 1 Whether the group matched.
# The heavy worker
EVAL evl/flags Execute some Perl code.
2L
# Modifiers
MINMOD no Next operator is not greedy.
LOGICAL no Next opcode should set the flag only.
# This is not used yet
RENUM off 1 1 Group with independently numbered parens.
# Regex Subroutines
GOSUB num/ofs 2L recurse to paren arg1 at (signed) ofs arg2
# Special conditionals
GROUPPN no-sv 1 Whether the group matched.
INSUBP num 1 Whether we are in a specific recurse.
DEFINEP none 1 Never execute directly.
# Backtracking Verbs
ENDLIKE none Used only for the type field of verbs
OPFAIL no-sv 1 Same as (?!), but with verb arg
ACCEPT no-sv/num Accepts the current matched string, with
2L verbar
# Verbs With Arguments
VERB no-sv 1 Used only for the type field of verbs
PRUNE no-sv 1 Pattern fails at this startpoint if no-
backtracking through this
MARKPOINT no-sv 1 Push the current location for rollback by
cut.
SKIP no-sv 1 On failure skip forward (to the mark)
before retrying
COMMIT no-sv 1 Pattern fails outright if backtracking
through this
CUTGROUP no-sv 1 On failure go to the next alternation in
the group
# Control what to keep in $&.
KEEPS no $& begins here.
# Validate that lookbehind IFMATCH and UNLESSM end at the right place
LOOKBEHIND_END no Return from lookbehind (IFMATCH/UNLESSM)
and validate position
# SPECIAL REGOPS
# This is not really a node, but an optimized away piece of a "long"
# node. To simplify debugging output, we mark it as if it were a node
OPTIMIZED off Placeholder for dump.
# Special opcode with the property that no opcode in a compiled program
# will ever be of this type. Thus it can be used as a flag value that
# no other opcode has been seen. END is used similarly, in that an END
# node cant be optimized. So END implies "unoptimizable" and PSEUDO
# mean "not seen anything to optimize yet".
PSEUDO off Pseudo opcode for internal use.
REGEX_SET depth p Regex set, temporary node used in pre-
optimization compilation
```
Following the optimizer information is a dump of the offset/length table, here split across several lines:
```
Offsets: [45]
1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]
```
The first line here indicates that the offset/length table contains 45 entries. Each entry is a pair of integers, denoted by `offset[length]`. Entries are numbered starting with 1, so entry #1 here is `1[4]` and entry #12 is `5[1]`. `1[4]` indicates that the node labeled `1:` (the `1: ANYOF[bc]`) begins at character position 1 in the pre-compiled form of the regex, and has a length of 4 characters. `5[1]` in position 12 indicates that the node labeled `12:` (the `12: EXACT <d>`) begins at character position 5 in the pre-compiled form of the regex, and has a length of 1 character. `12[1]` in position 14 indicates that the node labeled `14:` (the `14: CURLYX[0] {1,32767}`) begins at character position 12 in the pre-compiled form of the regex, and has a length of 1 character---that is, it corresponds to the `+` symbol in the precompiled regex.
`0[0]` items indicate that there is no corresponding node.
###
Run-time Output
First of all, when doing a match, one may get no run-time output even if debugging is enabled. This means that the regex engine was never entered and that all of the job was therefore done by the optimizer.
If the regex engine was entered, the output may look like this:
```
Matching '[bc]d(ef*g)+h[ij]k$' against 'abcdefg__gh__'
Setting an EVAL scope, savestack=3
2 <ab> <cdefg__gh_> | 1: ANYOF
3 <abc> <defg__gh_> | 11: EXACT <d>
4 <abcd> <efg__gh_> | 13: CURLYX {1,32767}
4 <abcd> <efg__gh_> | 26: WHILEM
0 out of 1..32767 cc=effff31c
4 <abcd> <efg__gh_> | 15: OPEN1
4 <abcd> <efg__gh_> | 17: EXACT <e>
5 <abcde> <fg__gh_> | 19: STAR
EXACT <f> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
6 <bcdef> <g__gh__> | 22: EXACT <g>
7 <bcdefg> <__gh__> | 24: CLOSE1
7 <bcdefg> <__gh__> | 26: WHILEM
1 out of 1..32767 cc=effff31c
Setting an EVAL scope, savestack=12
7 <bcdefg> <__gh__> | 15: OPEN1
7 <bcdefg> <__gh__> | 17: EXACT <e>
restoring \1 to 4(4)..7
failed, try continuation...
7 <bcdefg> <__gh__> | 27: NOTHING
7 <bcdefg> <__gh__> | 28: EXACT <h>
failed...
failed...
```
The most significant information in the output is about the particular *node* of the compiled regex that is currently being tested against the target string. The format of these lines is
*STRING-OFFSET* <*PRE-STRING*> <*POST-STRING*> |*ID*: *TYPE*
The *TYPE* info is indented with respect to the backtracking level. Other incidental information appears interspersed within.
Debugging Perl Memory Usage
----------------------------
Perl is a profligate wastrel when it comes to memory use. There is a saying that to estimate memory usage of Perl, assume a reasonable algorithm for memory allocation, multiply that estimate by 10, and while you still may miss the mark, at least you won't be quite so astonished. This is not absolutely true, but may provide a good grasp of what happens.
Assume that an integer cannot take less than 20 bytes of memory, a float cannot take less than 24 bytes, a string cannot take less than 32 bytes (all these examples assume 32-bit architectures, the result are quite a bit worse on 64-bit architectures). If a variable is accessed in two of three different ways (which require an integer, a float, or a string), the memory footprint may increase yet another 20 bytes. A sloppy malloc(3) implementation can inflate these numbers dramatically.
On the opposite end of the scale, a declaration like
```
sub foo;
```
may take up to 500 bytes of memory, depending on which release of Perl you're running.
Anecdotal estimates of source-to-compiled code bloat suggest an eightfold increase. This means that the compiled form of reasonable (normally commented, properly indented etc.) code will take about eight times more space in memory than the code took on disk.
The **-DL** command-line switch is obsolete since circa Perl 5.6.0 (it was available only if Perl was built with `-DDEBUGGING`). The switch was used to track Perl's memory allocations and possible memory leaks. These days the use of malloc debugging tools like *Purify* or *valgrind* is suggested instead. See also ["PERL\_MEM\_LOG" in perlhacktips](perlhacktips#PERL_MEM_LOG).
One way to find out how much memory is being used by Perl data structures is to install the Devel::Size module from CPAN: it gives you the minimum number of bytes required to store a particular data structure. Please be mindful of the difference between the size() and total\_size().
If Perl has been compiled using Perl's malloc you can analyze Perl memory usage by setting $ENV{PERL\_DEBUG\_MSTATS}.
###
Using `$ENV{PERL_DEBUG_MSTATS}`
If your perl is using Perl's malloc() and was compiled with the necessary switches (this is the default), then it will print memory usage statistics after compiling your code when `$ENV{PERL_DEBUG_MSTATS} > 1`, and before termination of the program when `$ENV{PERL_DEBUG_MSTATS} >= 1`. The report format is similar to the following example:
```
$ PERL_DEBUG_MSTATS=2 perl -e "require Carp"
Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
14216 free: 130 117 28 7 9 0 2 2 1 0 0
437 61 36 0 5
60924 used: 125 137 161 55 7 8 6 16 2 0 1
74 109 304 84 20
Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
Memory allocation statistics after execution: (buckets 4(4)..8188(8192)
30888 free: 245 78 85 13 6 2 1 3 2 0 1
315 162 39 42 11
175816 used: 265 176 1112 111 26 22 11 27 2 1 1
196 178 1066 798 39
Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.
```
It is possible to ask for such a statistic at arbitrary points in your execution using the mstat() function out of the standard Devel::Peek module.
Here is some explanation of that format:
`buckets SMALLEST(APPROX)..GREATEST(APPROX)`
Perl's malloc() uses bucketed allocations. Every request is rounded up to the closest bucket size available, and a bucket is taken from the pool of buckets of that size.
The line above describes the limits of buckets currently in use. Each bucket has two sizes: memory footprint and the maximal size of user data that can fit into this bucket. Suppose in the above example that the smallest bucket were size 4. The biggest bucket would have usable size 8188, and the memory footprint would be 8192.
In a Perl built for debugging, some buckets may have negative usable size. This means that these buckets cannot (and will not) be used. For larger buckets, the memory footprint may be one page greater than a power of 2. If so, the corresponding power of two is printed in the `APPROX` field above.
Free/Used The 1 or 2 rows of numbers following that correspond to the number of buckets of each size between `SMALLEST` and `GREATEST`. In the first row, the sizes (memory footprints) of buckets are powers of two--or possibly one page greater. In the second row, if present, the memory footprints of the buckets are between the memory footprints of two buckets "above".
For example, suppose under the previous example, the memory footprints were
```
free: 8 16 32 64 128 256 512 1024 2048 4096 8192
4 12 24 48 80
```
With a non-`DEBUGGING` perl, the buckets starting from `128` have a 4-byte overhead, and thus an 8192-long bucket may take up to 8188-byte allocations.
`Total sbrk(): SBRKed/SBRKs:CONTINUOUS`
The first two fields give the total amount of memory perl sbrk(2)ed (ess-broken? :-) and number of sbrk(2)s used. The third number is what perl thinks about continuity of returned chunks. So long as this number is positive, malloc() will assume that it is probable that sbrk(2) will provide continuous memory.
Memory allocated by external libraries is not counted.
`pad: 0`
The amount of sbrk(2)ed memory needed to keep buckets aligned.
`heads: 2192`
Although memory overhead of bigger buckets is kept inside the bucket, for smaller buckets, it is kept in separate areas. This field gives the total size of these areas.
`chain: 0`
malloc() may want to subdivide a bigger bucket into smaller buckets. If only a part of the deceased bucket is left unsubdivided, the rest is kept as an element of a linked list. This field gives the total size of these chunks.
`tail: 6144`
To minimize the number of sbrk(2)s, malloc() asks for more memory. This field gives the size of the yet unused part, which is sbrk(2)ed, but never touched.
SEE ALSO
---------
<perldebug>, <perl5db.pl>, <perlguts>, <perlrun>, <re>, and <Devel::DProf>.
| programming_docs |
perl English English
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [PERFORMANCE](#PERFORMANCE)
NAME
----
English - use nice English (or awk) names for ugly punctuation variables
SYNOPSIS
--------
```
use English;
use English qw( -no_match_vars ) ; # Avoids regex performance
# penalty in perl 5.18 and
# earlier
...
if ($ERRNO =~ /denied/) { ... }
```
DESCRIPTION
-----------
This module provides aliases for the built-in variables whose names no one seems to like to read. Variables with side-effects which get triggered just by accessing them (like $0) will still be affected.
For those variables that have an **awk** version, both long and short English alternatives are provided. For example, the `$/` variable can be referred to either $RS or $INPUT\_RECORD\_SEPARATOR if you are using the English module.
See <perlvar> for a complete list of these.
PERFORMANCE
-----------
NOTE: This was fixed in perl 5.20. Mentioning these three variables no longer makes a speed difference. This section still applies if your code is to run on perl 5.18 or earlier.
This module can provoke sizeable inefficiencies for regular expressions, due to unfortunate implementation details. If performance matters in your application and you don't need $PREMATCH, $MATCH, or $POSTMATCH, try doing
```
use English qw( -no_match_vars ) ;
```
. **It is especially important to do this in modules to avoid penalizing all applications which use them.**
perl File::Glob File::Glob
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [META CHARACTERS](#META-CHARACTERS)
+ [EXPORTS](#EXPORTS)
- [:bsd\_glob](#:bsd_glob)
- [:glob](#:glob)
- [bsd\_glob](#bsd_glob1)
- [:nocase and :case](#:nocase-and-:case)
- [csh\_glob](#csh_glob)
+ [POSIX FLAGS](#POSIX-FLAGS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [NOTES](#NOTES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
File::Glob - Perl extension for BSD glob routine
SYNOPSIS
--------
```
use File::Glob ':bsd_glob';
@list = bsd_glob('*.[ch]');
$homedir = bsd_glob('~gnat', GLOB_TILDE | GLOB_ERR);
if (GLOB_ERROR) {
# an error occurred reading $homedir
}
## override the core glob (CORE::glob() does this automatically
## by default anyway, since v5.6.0)
use File::Glob ':globally';
my @sources = <*.{c,h,y}>;
## override the core glob, forcing case sensitivity
use File::Glob qw(:globally :case);
my @sources = <*.{c,h,y}>;
## override the core glob forcing case insensitivity
use File::Glob qw(:globally :nocase);
my @sources = <*.{c,h,y}>;
## glob on all files in home directory
use File::Glob ':globally';
my @sources = <~gnat/*>;
```
DESCRIPTION
-----------
The glob angle-bracket operator `<>` is a pathname generator that implements the rules for file name pattern matching used by Unix-like shells such as the Bourne shell or C shell.
File::Glob::bsd\_glob() implements the FreeBSD glob(3) routine, which is a superset of the POSIX glob() (described in IEEE Std 1003.2 "POSIX.2"). bsd\_glob() takes a mandatory `pattern` argument, and an optional `flags` argument, and returns a list of filenames matching the pattern, with interpretation of the pattern modified by the `flags` variable.
Since v5.6.0, Perl's CORE::glob() is implemented in terms of bsd\_glob(). Note that they don't share the same prototype--CORE::glob() only accepts a single argument. Due to historical reasons, CORE::glob() will also split its argument on whitespace, treating it as multiple patterns, whereas bsd\_glob() considers them as one pattern. But see `:bsd_glob` under ["EXPORTS"](#EXPORTS), below.
###
META CHARACTERS
```
\ Quote the next metacharacter
[] Character class
{} Multiple pattern
* Match any string of characters
? Match any single character
~ User name home directory
```
The metanotation `a{b,c,d}e` is a shorthand for `abe ace ade`. Left to right order is preserved, with results of matches being sorted separately at a low level to preserve this order. As a special case `{`, `}`, and `{}` are passed undisturbed.
### EXPORTS
See also the ["POSIX FLAGS"](#POSIX-FLAGS) below, which can be exported individually.
####
`:bsd_glob`
The `:bsd_glob` export tag exports bsd\_glob() and the constants listed below. It also overrides glob() in the calling package with one that behaves like bsd\_glob() with regard to spaces (the space is treated as part of a file name), but supports iteration in scalar context; i.e., it preserves the core function's feature of returning the next item each time it is called.
####
`:glob`
The `:glob` tag, now discouraged, is the old version of `:bsd_glob`. It exports the same constants and functions, but its glob() override does not support iteration; it returns the last file name in scalar context. That means this will loop forever:
```
use File::Glob ':glob';
while (my $file = <* copy.txt>) {
...
}
```
#### `bsd_glob`
This function, which is included in the two export tags listed above, takes one or two arguments. The first is the glob pattern. The second, if given, is a set of flags ORed together. The available flags and the default set of flags are listed below under ["POSIX FLAGS"](#POSIX-FLAGS).
Remember that to use the named constants for flags you must import them, for example with `:bsd_glob` described above. If not imported, and `use strict` is not in effect, then the constants will be treated as bareword strings, which won't do what you what.
####
`:nocase` and `:case`
These two export tags globally modify the default flags that bsd\_glob() and, except on VMS, Perl's built-in `glob` operator use. `GLOB_NOCASE` is turned on or off, respectively.
#### `csh_glob`
The csh\_glob() function can also be exported, but you should not use it directly unless you really know what you are doing. It splits the pattern into words and feeds each one to bsd\_glob(). Perl's own glob() function uses this internally.
###
POSIX FLAGS
If no flags argument is give then `GLOB_CSH` is set, and on VMS and Windows systems, `GLOB_NOCASE` too. Otherwise the flags to use are determined solely by the flags argument. The POSIX defined flags are:
`GLOB_ERR` Force bsd\_glob() to return an error when it encounters a directory it cannot open or read. Ordinarily bsd\_glob() continues to find matches.
`GLOB_LIMIT` Make bsd\_glob() return an error (GLOB\_NOSPACE) when the pattern expands to a size bigger than the system constant `ARG_MAX` (usually found in limits.h). If your system does not define this constant, bsd\_glob() uses `sysconf(_SC_ARG_MAX)` or `_POSIX_ARG_MAX` where available (in that order). You can inspect these values using the standard `POSIX` extension.
`GLOB_MARK` Each pathname that is a directory that matches the pattern has a slash appended.
`GLOB_NOCASE` By default, file names are assumed to be case sensitive; this flag makes bsd\_glob() treat case differences as not significant.
`GLOB_NOCHECK` If the pattern does not match any pathname, then bsd\_glob() returns a list consisting of only the pattern. If `GLOB_QUOTE` is set, its effect is present in the pattern returned.
`GLOB_NOSORT` By default, the pathnames are sorted in ascending ASCII order; this flag prevents that sorting (speeding up bsd\_glob()).
The FreeBSD extensions to the POSIX standard are the following flags:
`GLOB_BRACE` Pre-process the string to expand `{pat,pat,...}` strings like csh(1). The pattern '{}' is left unexpanded for historical reasons (and csh(1) does the same thing to ease typing of find(1) patterns).
`GLOB_NOMAGIC` Same as `GLOB_NOCHECK` but it only returns the pattern if it does not contain any of the special characters "\*", "?" or "[". `NOMAGIC` is provided to simplify implementing the historic csh(1) globbing behaviour and should probably not be used anywhere else.
`GLOB_QUOTE` Use the backslash ('\') character for quoting: every occurrence of a backslash followed by a character in the pattern is replaced by that character, avoiding any special interpretation of the character. (But see below for exceptions on DOSISH systems).
`GLOB_TILDE` Expand patterns that start with '~' to user name home directories.
`GLOB_CSH` For convenience, `GLOB_CSH` is a synonym for `GLOB_BRACE | GLOB_NOMAGIC | GLOB_QUOTE | GLOB_TILDE | GLOB_ALPHASORT`.
The POSIX provided `GLOB_APPEND`, `GLOB_DOOFFS`, and the FreeBSD extensions `GLOB_ALTDIRFUNC`, and `GLOB_MAGCHAR` flags have not been implemented in the Perl version because they involve more complex interaction with the underlying C structures.
The following flag has been added in the Perl implementation for csh compatibility:
`GLOB_ALPHASORT` If `GLOB_NOSORT` is not in effect, sort filenames is alphabetical order (case does not matter) rather than in ASCII order.
DIAGNOSTICS
-----------
bsd\_glob() returns a list of matching paths, possibly zero length. If an error occurred, &File::Glob::GLOB\_ERROR will be non-zero and `$!` will be set. &File::Glob::GLOB\_ERROR is guaranteed to be zero if no error occurred, or one of the following values otherwise:
`GLOB_NOSPACE` An attempt to allocate memory failed.
`GLOB_ABEND` The glob was stopped because an error was encountered.
In the case where bsd\_glob() has found some matching paths, but is interrupted by an error, it will return a list of filenames **and** set &File::Glob::ERROR.
Note that bsd\_glob() deviates from POSIX and FreeBSD glob(3) behaviour by not considering `ENOENT` and `ENOTDIR` as errors - bsd\_glob() will continue processing despite those errors, unless the `GLOB_ERR` flag is set.
Be aware that all filenames returned from File::Glob are tainted.
NOTES
-----
* If you want to use multiple patterns, e.g. `bsd_glob("a* b*")`, you should probably throw them in a set as in `bsd_glob("{a*,b*}")`. This is because the argument to bsd\_glob() isn't subjected to parsing by the C shell. Remember that you can use a backslash to escape things.
* On DOSISH systems, backslash is a valid directory separator character. In this case, use of backslash as a quoting character (via GLOB\_QUOTE) interferes with the use of backslash as a directory separator. The best (simplest, most portable) solution is to use forward slashes for directory separators, and backslashes for quoting. However, this does not match "normal practice" on these systems. As a concession to user expectation, therefore, backslashes (under GLOB\_QUOTE) only quote the glob metacharacters '[', ']', '{', '}', '-', '~', and backslash itself. All other backslashes are passed through unchanged.
* Win32 users should use the real slash. If you really want to use backslashes, consider using Sarathy's File::DosGlob, which comes with the standard Perl distribution.
SEE ALSO
---------
["glob" in perlfunc](perlfunc#glob), glob(3)
AUTHOR
------
The Perl interface was written by Nathan Torkington <[email protected]>, and is released under the artistic license. Further modifications were made by Greg Bacon <[email protected]>, Gurusamy Sarathy <[email protected]>, and Thomas Wegner <wegner\[email protected]>. The C glob code has the following copyright:
Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
This code is derived from software contributed to Berkeley by Guido van Rossum.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
perl Memoize::ExpireTest Memoize::ExpireTest
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Memoize::ExpireTest - test for Memoize expiration semantics
DESCRIPTION
-----------
This module is just for testing expiration semantics. It's not a very good example of how to write an expiration module.
If you are looking for an example, I recommend that you look at the simple example in the Memoize::Expire documentation, or at the code for Memoize::Expire itself.
If you have questions, I will be happy to answer them if you send them to [email protected].
perl ExtUtils::Installed ExtUtils::Installed
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [METHODS](#METHODS)
* [EXAMPLE](#EXAMPLE)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Installed - Inventory management of installed modules
SYNOPSIS
--------
```
use ExtUtils::Installed;
my ($inst) = ExtUtils::Installed->new( skip_cwd => 1 );
my (@modules) = $inst->modules();
my (@missing) = $inst->validate("DBI");
my $all_files = $inst->files("DBI");
my $files_below_usr_local = $inst->files("DBI", "all", "/usr/local");
my $all_dirs = $inst->directories("DBI");
my $dirs_below_usr_local = $inst->directory_tree("DBI", "prog");
my $packlist = $inst->packlist("DBI");
```
DESCRIPTION
-----------
ExtUtils::Installed provides a standard way to find out what core and module files have been installed. It uses the information stored in .packlist files created during installation to provide this information. In addition it provides facilities to classify the installed files and to extract directory information from the .packlist files.
USAGE
-----
The new() function searches for all the installed .packlists on the system, and stores their contents. The .packlists can be queried with the functions described below. Where it searches by default is determined by the settings found in `%Config::Config`, and what the value is of the PERL5LIB environment variable.
METHODS
-------
Unless specified otherwise all method can be called as class methods, or as object methods. If called as class methods then the "default" object will be used, and if necessary created using the current processes %Config and @INC. See the 'default' option to new() for details.
new() This takes optional named parameters. Without parameters, this searches for all the installed .packlists on the system using information from `%Config::Config` and the default module search paths `@INC`. The packlists are read using the <ExtUtils::Packlist> module.
If the named parameter `skip_cwd` is true, the current directory `.` will be stripped from `@INC` before searching for .packlists. This keeps ExtUtils::Installed from finding modules installed in other perls that happen to be located below the current directory.
If the named parameter `config_override` is specified, it should be a reference to a hash which contains all information usually found in `%Config::Config`. For example, you can obtain the configuration information for a separate perl installation and pass that in.
```
my $yoda_cfg = get_fake_config('yoda');
my $yoda_inst =
ExtUtils::Installed->new(config_override=>$yoda_cfg);
```
Similarly, the parameter `inc_override` may be a reference to an array which is used in place of the default module search paths from `@INC`.
```
use Config;
my @dirs = split(/\Q$Config{path_sep}\E/, $ENV{PERL5LIB});
my $p5libs = ExtUtils::Installed->new(inc_override=>\@dirs);
```
**Note**: You probably do not want to use these options alone, almost always you will want to set both together.
The parameter `extra_libs` can be used to specify **additional** paths to search for installed modules. For instance
```
my $installed =
ExtUtils::Installed->new(extra_libs=>["/my/lib/path"]);
```
This should only be necessary if */my/lib/path* is not in PERL5LIB.
Finally there is the 'default', and the related 'default\_get' and 'default\_set' options. These options control the "default" object which is provided by the class interface to the methods. Setting `default_get` to true tells the constructor to return the default object if it is defined. Setting `default_set` to true tells the constructor to make the default object the constructed object. Setting the `default` option is like setting both to true. This is used primarily internally and probably isn't interesting to any real user.
modules() This returns a list of the names of all the installed modules. The perl 'core' is given the special name 'Perl'.
files() This takes one mandatory parameter, the name of a module. It returns a list of all the filenames from the package. To obtain a list of core perl files, use the module name 'Perl'. Additional parameters are allowed. The first is one of the strings "prog", "doc" or "all", to select either just program files, just manual files or all files. The remaining parameters are a list of directories. The filenames returned will be restricted to those under the specified directories.
directories() This takes one mandatory parameter, the name of a module. It returns a list of all the directories from the package. Additional parameters are allowed. The first is one of the strings "prog", "doc" or "all", to select either just program directories, just manual directories or all directories. The remaining parameters are a list of directories. The directories returned will be restricted to those under the specified directories. This method returns only the leaf directories that contain files from the specified module.
directory\_tree() This is identical in operation to directories(), except that it includes all the intermediate directories back up to the specified directories.
validate() This takes one mandatory parameter, the name of a module. It checks that all the files listed in the modules .packlist actually exist, and returns a list of any missing files. If an optional second argument which evaluates to true is given any missing files will be removed from the .packlist
packlist() This returns the ExtUtils::Packlist object for the specified module.
version() This returns the version number for the specified module.
EXAMPLE
-------
See the example in <ExtUtils::Packlist>.
AUTHOR
------
Alan Burlison <[email protected]>
perl Digest::base Digest::base
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Digest::base - Digest base class
SYNOPSIS
--------
```
package Digest::Foo;
use base 'Digest::base';
```
DESCRIPTION
-----------
The `Digest::base` class provide implementations of the methods `addfile` and `add_bits` in terms of `add`, and of the methods `hexdigest` and `b64digest` in terms of `digest`.
Digest implementations might want to inherit from this class to get this implementations of the alternative *add* and *digest* methods. A minimal subclass needs to implement the following methods by itself:
```
new
clone
add
digest
```
The arguments and expected behaviour of these methods are described in [Digest](digest).
SEE ALSO
---------
[Digest](digest)
| programming_docs |
perl perldocstyle perldocstyle
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Purpose of this guide](#Purpose-of-this-guide)
+ [Intended audience](#Intended-audience)
+ [Status of this document](#Status-of-this-document)
* [FUNDAMENTALS](#FUNDAMENTALS)
+ [Choice of markup: Pod](#Choice-of-markup:-Pod)
+ [Choice of language: American English](#Choice-of-language:-American-English)
- [Other languages and translations](#Other-languages-and-translations)
+ [Choice of encoding: UTF-8](#Choice-of-encoding:-UTF-8)
+ [Choice of underlying style guide: CMOS](#Choice-of-underlying-style-guide:-CMOS)
+ [Contributing to Perl's documentation](#Contributing-to-Perl's-documentation)
* [FORMATTING AND STRUCTURE](#FORMATTING-AND-STRUCTURE)
+ [Document structure](#Document-structure)
- [Name](#Name)
- [Description and synopsis](#Description-and-synopsis)
- [Other sections and subsections](#Other-sections-and-subsections)
- [Author and copyright](#Author-and-copyright)
+ [Formatting rules](#Formatting-rules)
- [Line length and line wrap](#Line-length-and-line-wrap)
- [Code blocks](#Code-blocks)
- [Inline code and literals](#Inline-code-and-literals)
- [Function names](#Function-names)
- [Function arguments](#Function-arguments)
- [Apostrophes, quotes, and dashes](#Apostrophes,-quotes,-and-dashes)
- [Unix programs and C functions](#Unix-programs-and-C-functions)
- [Cross-references and hyperlinks](#Cross-references-and-hyperlinks)
- [Tables and diagrams](#Tables-and-diagrams)
+ [Adding comments](#Adding-comments)
+ [Perlfunc has special rules](#Perlfunc-has-special-rules)
* [TONE AND STYLE](#TONE-AND-STYLE)
+ [Apply one of the four documentation modes](#Apply-one-of-the-four-documentation-modes)
- [Tutorial](#Tutorial)
- [Cookbook](#Cookbook)
- [Reference](#Reference)
- [Explainer](#Explainer)
- [Further notes on documentation modes](#Further-notes-on-documentation-modes)
+ [Assume readers' intelligence, but not their knowledge](#Assume-readers'-intelligence,-but-not-their-knowledge)
- [Keep Perl's documentation about Perl](#Keep-Perl's-documentation-about-Perl)
- [Deploy jargon when needed, but define it as well](#Deploy-jargon-when-needed,-but-define-it-as-well)
+ [Use meaningful variable and symbol names in examples](#Use-meaningful-variable-and-symbol-names-in-examples)
+ [Write in English, but not just for English-speakers](#Write-in-English,-but-not-just-for-English-speakers)
+ [Omit placeholder text or commentary](#Omit-placeholder-text-or-commentary)
+ [Apply section-breaks and examples generously](#Apply-section-breaks-and-examples-generously)
+ [Lead with common cases and best practices](#Lead-with-common-cases-and-best-practices)
- [Show the better ways first](#Show-the-better-ways-first)
- [Show the lesser ways when needed](#Show-the-lesser-ways-when-needed)
+ [Document Perl's present](#Document-Perl's-present)
- [Recount the past only when necessary](#Recount-the-past-only-when-necessary)
- [Describe the uncertain future with care](#Describe-the-uncertain-future-with-care)
+ [The documentation speaks with one voice](#The-documentation-speaks-with-one-voice)
* [INDEX OF PREFERRED TERMS](#INDEX-OF-PREFERRED-TERMS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perldocstyle - A style guide for writing Perl's documentation
DESCRIPTION
-----------
This document is a guide for the authorship and maintenance of the documentation that ships with Perl. This includes the following:
* The several dozen manual sections whose filenames begin with "`perl`", such as `perlobj`, `perlre`, and `perlintro`. (And, yes, `perl`.)
* The documentation for all the modules included with Perl (as listed by [`perlmodlib`](perlmodlib)).
* The hundreds of individually presented reference sections derived from the [`perlfunc`](perlfunc) file.
This guide will hereafter refer to user-manual section files as *man pages*, per Unix convention.
###
Purpose of this guide
This style guide aims to establish standards, procedures, and philosophies applicable to Perl's core documentation.
Adherence to these standards will help ensure that any one part of Perl's manual has a tone and style consistent with that of any other. As with the rest of the Perl project, the language's documentation collection is an open-source project authored over a long period of time by many people. Maintaining consistency across such a wide swath of work presents a challenge; this guide provides a foundation to help mitigate this difficulty.
This will help its readers--especially those new to Perl--to feel more welcome and engaged with Perl's documentation, and this in turn will help the Perl project itself grow stronger through having a larger, more diverse, and more confident population of knowledgeable users.
###
Intended audience
Anyone interested in contributing to Perl's core documentation should familiarize themselves with the standards outlined by this guide.
Programmers documenting their own work apart from the Perl project itself may also find this guide worthwhile, especially if they wish their work to extend the tone and style of Perl's own manual.
###
Status of this document
This guide was initially drafted in late 2020, drawing from the documentation style guides of several open-source technologies contemporary with Perl. This has included Python, Raku, Rust, and the Linux kernel.
The author intends to see this guide used as starting place from which to launch a review of Perl's reams of extant documentation, with the expectation that those conducting this review should grow and modify this guide as needed to account for the requirements and quirks particular to Perl's programming manual.
FUNDAMENTALS
------------
###
Choice of markup: Pod
All of Perl's core documentation uses Pod ("Plain Old Documentation"), a simple markup language, to format its source text. Pod is similar in spirit to other contemporary lightweight markup technologies, such as Markdown and reStructuredText, and has a decades-long shared history with Perl itself.
For a comprehensive reference to Pod syntax, see [`perlpod`](perlpod). For the sake of reading this guide, familiarity with the Pod syntax for section headers (`=head2`, et cetera) and for inline text formatting (`C<like this>`) should suffice.
Perl programmers also use Pod to document their own scripts, libraries, and modules. This use of Pod has its own style guide, outlined by [`perlpodstyle`](perlpodstyle).
###
Choice of language: American English
Perl's core documentation is written in English, with a preference for American spelling of words and expression of phrases. That means "color" over "colour", "math" versus "maths", "the team has decided" and not "the team have decided", and so on.
We name one style of English for the sake of consistency across Perl's documentation, much as a software project might declare a four-space indentation standard--even when that doesn't affect how well the code compiles. Both efforts result in an easier read by avoiding jarring, mid-document changes in format or style.
Contributors to Perl's documentation should note that this rule describes the ultimate, published output of the project, and does not prescribe the dialect used within community contributions. The documentation team enthusiastically welcomes any English-language contributions, and will actively assist in Americanizing spelling and style when warranted.
####
Other languages and translations
Community-authored translations of Perl's documentation do exist, covering a variety of languages. While the Perl project appreciates these translation efforts and promotes them when applicable, it does not officially support or maintain any of them.
That said, keeping Perl's documentation clear, simple, and short has a welcome side effect of aiding any such translation project.
(Note that the Chinese, Japanese, and Korean-language README files included with Perl's source distributions provide an exception to this choice of language--but these documents fall outside the scope of this guide.)
###
Choice of encoding: UTF-8
Perl's core documentation files are encoded in UTF-8, and can make use of the full range of characters this encoding allows.
As such, every core doc file (or the Pod section of every core module) should commence with an `=encoding utf8` declaration.
###
Choice of underlying style guide: CMOS
Perl's documentation uses the [Chicago Manual of Style](https://www.chicagomanualofstyle.org) (CMOS), 17th Edition, as its baseline guide for style and grammar. While the document you are currently reading endeavors to serve as an adequate stand-alone style guide for the purposes of documenting Perl, authors should consider CMOS the fallback authority for any pertinent topics not covered here.
Because CMOS is not a free resource, access to it is not a prerequisite for contributing to Perl's documentation; the doc team will help contributors learn about and apply its guidelines as needed. However, we do encourage anyone interested in significant doc contributions to obtain or at least read through CMOS. (Copies are likely available through most public libraries, and CMOS-derived fundamentals can be found online as well.)
###
Contributing to Perl's documentation
Perl, like any programming language, is only as good as its documentation. Perl depends upon clear, friendly, and thorough documentation in order to welcome brand-new users, teach and explain the language's various concepts and components, and serve as a lifelong reference for experienced Perl programmers. As such, the Perl project welcomes and values all community efforts to improve the language's documentation.
Perl accepts documentation contributions through the same open-source project pipeline as code contributions. See [`perlhack`](perlhack) for more information.
FORMATTING AND STRUCTURE
-------------------------
This section details specific Pod syntax and style that all core Perl documentation should adhere to, in the interest of consistency and readability.
###
Document structure
Each individual work of core Perl documentation, whether contained within a `.pod` file or in the Pod section of a standard code module, patterns its structure after a number of long-time Unix man page conventions. (Hence this guide's use of "man page" to refer to any one self-contained part of Perl's documentation.)
Adhering to these conventions helps Pod formatters present a Perl man page's content in different contexts--whether a terminal, the web, or even print. Many of the following requirements originate with [`perlpodstyle`](perlpodstyle), which derives its recommendations in turn from these well-established practices.
#### Name
After its [`=encoding utf8` declaration](#Choice-of-encoding%3A-UTF-8), a Perl man page *must* present a level-one header named "NAME" (literally), followed by a paragraph containing the page's name and a very brief description.
The first few lines of a notional page named `perlpodexample`:
```
=encoding utf8
=head1 NAME
perlpodexample - An example of formatting a manual page's title line
```
####
Description and synopsis
Most Perl man pages also contain a DESCRIPTION section featuring a summary of, or introduction to, the document's content and purpose.
This section should also, one way or another, clearly identify the audience that the page addresses, especially if it has expectations about the reader's prior knowledge. For example, a man page that dives deep into the inner workings of Perl's regular expression engine should state its assumptions up front--and quickly redirect readers who are instead looking for a more basic reference or tutorial.
Reference pages, when appropriate, can precede the DESCRIPTION with a SYNOPSIS section that lists, within one or more code blocks, some very brief examples of the referenced feature's use. This section should show a handful of common-case and best-practice examples, rather than an exhaustive list of every obscure method or alternate syntax available.
####
Other sections and subsections
Pages should conclude, when appropriate, with a SEE ALSO section containing hyperlinks to relevant sections of Perl's manual, other Unix man pages, or appropriate web pages. Hyperlink each such cross-reference via `L<...>`.
What other sections to include depends entirely upon the topic at hand. Authors should feel free to include further `=head1`-level sections, whether other standard ones listed by `perlpodstyle`, or ones specific to the page's topic; in either case, render these top-level headings in all-capital letters.
You may then include as many subsections beneath them as needed to meet the standards of clarity, accessibility, and cross-reference affinity [suggested elsewhere in this guide](#Apply-one-of-the-four-documentation-modes).
####
Author and copyright
In most circumstances, Perl's stand-alone man pages--those contained within `.pod` files--do not need to include any copyright or license information about themselves. Their source Pod files are part of Perl's own core software repository, and that already covers them under the same copyright and license terms as Perl itself. You do not need to include additional "LICENSE" or "COPYRIGHT" sections of your own.
These man pages may optionally credit their primary author, or include a list of significant contributors, under "AUTHOR" or "CONTRIBUTORS" headings. Note that the presence of authors' names does not preclude a given page from [writing in a voice consistent with the rest of Perl's documentation](#The-documentation-speaks-with-one-voice).
Note that these guidelines do not apply to the core software modules that ship with Perl. These have their own standards for authorship and copyright statements, as found in `perlpodstyle`.
###
Formatting rules
####
Line length and line wrap
Each line within a Perl man page's Pod source file should measure 72 characters or fewer in length.
Please break paragraphs up into blocks of short lines, rather than "soft wrapping" paragraphs across hundreds of characters with no line breaks.
####
Code blocks
Just like the text around them, all code examples should be as short and readable as possible, displaying no more complexity than absolutely necessary to illustrate the concept at hand.
For the sake of consistency within and across Perl's man pages, all examples must adhere to the code-layout principles set out by [`perlstyle`](perlstyle).
Sample code should deviate from these standards only when necessary: during a demonstration of how Perl disregards whitespace, for example, or to temporarily switch to two-column indentation for an unavoidably verbose illustration.
You may include comments within example code to further clarify or label the code's behavior in-line. You may also use comments as placeholder for code normally present but not relevant to the current topic, like so:
```
while (my $line = <$fh>) {
#
# (Do something interesting with $line here.)
#
}
```
Even the simplest code blocks often require the use of example variables and subroutines, [whose names you should choose with care](#Use-meaningful-variable-and-symbol-names-in-examples).
####
Inline code and literals
Within a paragraph of text, use `C<...>` when quoting or referring to any bit of Perl code--even if it is only one character long.
For instance, when referring within an explanatory paragraph to Perl's operator for adding two numbers together, you'd write "`C<+>`".
####
Function names
Use `C<...>` to render all Perl function names in monospace, whenever they appear in text.
Unless you need to specifically quote a function call with a list of arguments, do not follow a function's name in text with a pair of empty parentheses. That is, when referring in general to Perl's `print` function, write it as "`print`", not "`print()`".
####
Function arguments
Represent functions' expected arguments in all-caps, with no sigils, and using `C<...>` to render them in monospace. These arguments should have short names making their nature and purpose clear. Convention specifies a few ones commonly seen throughout Perl's documentation:
* EXPR
The "generic" argument: any scalar value, or a Perl expression that evaluates to one.
* ARRAY
An array, stored in a named variable.
* HASH
A hash, stored in a named variable.
* BLOCK
A curly-braced code block, or a subroutine reference.
* LIST
Any number of values, stored across any number of variables or expressions, which the function will "flatten" and treat as a single list. (And because it can contain any number of variables, it must be the *last* argument, when present.)
When possible, give scalar arguments names that suggest their purpose among the arguments. See, for example, [`substr`'s documentation](perlfunc#substr), whose listed arguments include `EXPR`, `OFFSET`, `LENGTH`, and `REPLACEMENT`.
####
Apostrophes, quotes, and dashes
In Pod source, use straight quotes, and not "curly quotes": "Like this", not โlike thisโ. The same goes for apostrophes: Here's a positive example, and hereโs a negative one.
Render em dashes as two hyphens--like this:
```
Render em dashes as two hyphens--like this.
```
Leave it up to formatters to reformat and reshape these punctuation marks as best fits their respective target media.
####
Unix programs and C functions
When referring to a Unix program or C function with its own man page (outside of Perl's documentation), include its manual section number in parentheses. For example: `malloc(3)`, or `mkdir(1)`.
If mentioning this program for the first time within a man page or section, make it a cross reference, e.g. `L<malloc(3)>`.
Do not otherwise style this text.
####
Cross-references and hyperlinks
Make generous use of Pod's `L<...>` syntax to create hyperlinks to other parts of the current man page, or to other documents entirely -- whether elsewhere on the reader's computer, or somewhere on the internet, via URL.
Use `L<...>` to link to another section of the current man page when mentioning it, and make use of its page-and-section syntax to link to the most specific section of a separate page within Perl's documentation. Generally, the first time you refer to a specific function, program, or concept within a certain page or section, consider linking to its full documentation.
Hyperlinks do not supersede other formatting required by this guide; Pod allows nested text formats, and you should use this feature as needed.
Here is an example sentence that mentions Perl's `say` function, with a link to its documentation section within the `perlfunc` man page:
```
In version 5.10, Perl added support for the
L<C<say>|perlfunc/say FILEHANDLE LIST> function.
```
Note the use of the vertical pipe ("`|`") to separate how the link will appear to readers ("`C<say>`") from the full page-and-section specifier that the formatter links to.
####
Tables and diagrams
Pod does not officially support tables. To best present tabular data, include the table as both HTML and plain-text representations--the latter as an indented code block. Use `=begin` / `=end` directives to target these tables at `html` and `text` Pod formatters, respectively. For example:
```
=head2 Table of fruits
=begin text
Name Shape Color
=====================================
Apple Round Red
Banana Long Yellow
Pear Pear-shaped Green
=end text
=begin html
<table>
<tr><th>Name</th><th>Shape</th><th>Color</th></tr>
<tr><td>Apple</td><td>Round</td><td>Red</td></tr>
<tr><td>Banana</td><td>Long</td><td>Yellow</td></tr>
<tr><td>Pear</td><td>Pear-shaped</td><td>Green</td></tr>
</table>
=end html
```
The same holds true for figures and graphical illustrations. Pod does not natively support inline graphics, but you can mix HTML `<img>` tags with monospaced text-art representations of those images' content.
Due in part to these limitations, most Perl man pages use neither tables nor diagrams. Like any other tool in your documentation toolkit, however, you may consider their inclusion when they would improve an explanation's clarity without adding to its complexity.
###
Adding comments
Like any other kind of source code, Pod lets you insert comments visible only to other people reading the source directly, and ignored by the formatting programs that transform Pod into various human-friendly output formats (such as HTML or PDF).
To comment Pod text, use the `=for` and `=begin` / `=end` Pod directives, aiming them at a (notional) formatter called "`comment`". A couple of examples:
```
=for comment Using "=for comment" like this is good for short,
single-paragraph comments.
=begin comment
If you need to comment out more than one paragraph, use a
=begin/=end block, like this.
None of the text or markup in this whole example would be visible to
someone reading the documentation through normal means, so it's
great for leaving notes, explanations, or suggestions for your
fellow documentation writers.
=end comment
```
In the tradition of any good open-source project, you should make free but judicious use of comments to leave in-line "meta-documentation" as needed for other Perl documentation writers (including your future self).
###
Perlfunc has special rules
The [`perlfunc` man page](perlfunc), an exhaustive reference of every Perl built-in function, has a handful of formatting rules not seen elsewhere in Perl's documentation.
Software used during Perl's build process (<Pod::Functions>) parses this page according to certain rules, in order to build separate man pages for each of Perl's functions, as well as achieve other indexing effects. As such, contributors to perlfunc must know about and adhere to its particular rules.
Most of the perfunc man page comprises a single list, found under the header ["Alphabetical Listing of Perl Functions"](perlfunc#Alphabetical-Listing-of-Perl-Functions). Each function reference is an entry on that list, made of three parts, in order:
1. A list of `=item` lines which each demonstrate, in template format, a way to call this function. One line should exist for every combination of arguments that the function accepts (including no arguments at all, if applicable).
If modern best practices prefer certain ways to invoke the function over others, then those ways should lead the list.
The first item of the list should be immediately followed by one or more `X<...>` terms listing index-worthy topics; if nothing else, then the name of the function, with no arguments.
2. A `=for` line, directed at `Pod::Functions`, containing a one-line description of what the function does. This is written as a phrase, led with an imperative verb, with neither leading capitalization nor ending punctuation. Examples include "quote a list of words" and "change a filename".
3. The function's definition and reference material, including all explanatory text and code examples.
Complex functions that need their text divided into subsections (under the principles of ["Apply section-breaks and examples generously"](#Apply-section-breaks-and-examples-generously)) may do so by using sublists, with `=item` elements as header text.
A fictional function "`myfunc`", which takes a list as an optional argument, might have an entry in perlfunc shaped like this:
```
=item myfunc LIST
X<myfunc>
=item myfunc
=for Pod::Functions demonstrate a function's perlfunc section
[ Main part of function definition goes here, with examples ]
=over
=item Legacy uses
[ Examples of deprecated syntax still worth documenting ]
=item Security considerations
[ And so on... ]
=back
```
TONE AND STYLE
---------------
###
Apply one of the four documentation modes
Aside from "meta" documentation such as `perlhist` or `perlartistic`, each of Perl's man pages should conform to one of the four documentation "modes" suggested by [*The Documentation System* by Daniele Procida](https://documentation.divio.com). These include tutorials, cookbooks, explainers, and references--terms that we define in further detail below.
Each mode of documentation speaks to a different audience--not just people of different backgrounds and skill levels, but individual readers whose needs from language documentation can shift depending upon context. For example, a programmer with plenty of time to learn a new concept about Perl can ease into a tutorial about it, and later expand their knowledge further by studying an explainer. Later, that same programmer, wading knee-deep in live code and needing only to look up some function's exact syntax, will want to reach for a reference page instead.
Perl's documentation must strive to meet these different situational expectations by limiting each man page to a single mode. This helps writers ensure they provide readers with the documentation needed or expected, despite ever-evolving situations.
#### Tutorial
A tutorial man page focuses on **learning**, ideally by *doing*. It presents the reader with small, interesting examples that allow them to follow along themselves using their own Perl interpreter. The tutorial inspires comprehension by letting its readers immediately experience (and experiment on) the concept in question. Examples include `perlxstut`, `perlpacktut`, and `perlretut`.
Tutorial man pages must strive for a welcoming and reassuring tone from their outset; they may very well be the first things that a newcomer to Perl reads, playing a significant role in whether they choose to stick around. Even an experienced programmer can benefit from the sense of courage imparted by a strong tutorial about a more advanced topic. After completing a tutorial, a reader should feel like they've been led from zero knowledge of its topic to having an invigorating spark of basic understanding, excited to learn more and experiment further.
Tutorials can certainly use real-world examples when that helps make for clear, relatable demonstrations, so long as they keep the focus on teaching--more practical problem-solving should be left to the realm of cookbooks (as described below). Tutorials also needn't concern themselves with explanations into why or how things work beneath the surface, or explorations of alternate syntaxes and solutions; these are better handled by explainers and reference pages.
#### Cookbook
A cookbook man page focuses on **results**. Just like its name suggests, it presents succinct, step-by-step solutions to a variety of real-world problems around some topic. A cookbook's code examples serve less to enlighten and more to provide quick, paste-ready solutions that the reader can apply immediately to the situation facing them.
A Perl cookbook demonstrates ways that all the tools and techniques explained elsewhere can work together in order to achieve practical results. Any explanation deeper than that belongs in explainers and reference pages, instead. (Certainly, a cookbook can cross-reference other man pages in order to satisfy the curiosity of readers who, with their immediate problems solved, wish to learn more.)
The most prominent cookbook pages that ship with Perl itself are its many FAQ pages, in particular `perlfaq4` and up, which provide short solutions to practical questions in question-and-answer style. `perlunicook` shows another example, containing a bevy of practical code snippets for a variety of internationally minded text manipulations.
(An aside: *The Documentation System* calls this mode "how-to", but Perl's history of creative cuisine prefers the more kitchen-ready term that we employ here.)
#### Reference
A reference page focuses on **description**. Austere, uniform, and succinct, reference pages--often arranged into a whole section of mutually similar subpages--lend themselves well to "random access" by a reader who knows precisely what knowledge they need, requiring only the minimum amount of information before returning to the task at hand.
Perl's own best example of a reference work is `perlfunc`, the sprawling man page that details the operation of every function built into Perl, with each function's documentation presenting the same kinds of information in the same order as every other. For an example of a shorter reference on a single topic, look at `perlreref`.
Module documentation--including that of all the modules listed in [`perlmodlib`](perlmodlib)--also counts as reference. They follow precepts similar to those laid down by the `perlpodstyle` man page, such as opening with an example-laden "SYNOPSIS" section, or featuring a "METHODS" section that succinctly lists and defines an object-oriented module's public interface.
#### Explainer
Explainer pages focus on **discussion**. Each explainer dives as deep as needed into some Perl-relevant topic, taking all the time and space needed to give the reader a thorough understanding of it. Explainers mean to impart knowledge through study. They don't assume that the student has a Perl interpreter fired up and hungry for immediate examples (as with a tutorial), or specific Perl problems that they need quick answers for (which cookbooks and reference pages can help with).
Outside of its reference pages, most of Perl's manual belongs to this mode. This includes the majority of the man pages whose names start with "`perl`". A fine example is `perlsyn`, the Perl Syntax page, which explores the whys and wherefores of Perl's unique syntax in a wide-ranging discussion laden with many references to the language's history, culture, and driving philosophies.
Perl's explainer pages give authors a chance to explore Perl's penchant for [TMTOWTDI](perlglossary#TMTOWTDI), illustrating alternate and even obscure ways to use the language feature under discussion. However, as the remainder of this guide discusses, the ideal Perl documentation manages to deliver its message clearly and concisely, and not confuse mere wordiness for completeness.
####
Further notes on documentation modes
Keep in mind that the purpose of this categorization is not to dictate content--a very thorough explainer might contain short reference sections of its own, for example, or a reference page about a very complex function might resemble an explainer in places (e.g. [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR)). Rather, it makes sure that the authors and contributors of any given man page agree on what sort of audience that page addresses.
If a new or otherwise uncategorized man page presents itself as resistant to fitting into only one of the four modes, consider breaking it up into separate pages. That may mean creating a new "`perl[...]`" man page, or (in the case of module documentation) making new packages underneath that module's namespace that serve only to hold additional documentation. For instance, `Example::Module`'s reference documentation might include a see-also link to `Example::Module::Cookbook`.
Perl's several man pages about Unicode--comprising a short tutorial, a thorough explainer, a cookbook, and a FAQ--provide a fine example of spreading a complicated topic across several man pages with different and clearly indicated purposes.
###
Assume readers' intelligence, but not their knowledge
Perl has grown a great deal from its humble beginnings as a tool for people already well versed in C programming and various Unix utilities. Today, a person learning Perl might come from any social or technological background, with a range of possible motivations stretching far beyond system administration.
Perl's core documentation must recognize this by making as few assumptions as possible about the reader's prior knowledge. While you should assume that readers of Perl's documentation are smart, curious, and eager to learn, you should not confuse this for pre-existing knowledge about any other technology, or even programming in general--especially in tutorial or introductory material.
####
Keep Perl's documentation about Perl
Outside of pages tasked specifically with exploring Perl's relationship with other programming languages, the documentation should keep the focus on Perl. Avoid drawing analogies to other technologies that the reader may not have familiarity with.
For example, when documenting one of Perl's built-in functions, write as if the reader is now learning about that function for the first time, in any programming language.
Choosing to instead compare it to an equivalent or underlying C function will probably not illuminate much understanding in a contemporary reader. Worse, this can risk leaving readers unfamiliar with C feeling locked out from fully understanding of the topic--to say nothing of readers new to computer programming altogether.
If, however, that function's ties to its C roots can lead to deeper understanding with practical applications for a Perl programmer, you may mention that link after its more immediately useful documentation. Otherwise, omit this information entirely, leaving it for other documentation or external articles more concerned with examining Perl's underlying implementation details.
####
Deploy jargon when needed, but define it as well
Domain-specific jargon has its place, especially within documentation. However, if a man page makes use of jargon that a typical reader might not already know, then that page should make an effort to define the term in question early-on--either explicitly, or via cross reference.
For example, Perl loves working with filehandles, and as such that word appears throughout its documentation. A new Perl programmer arriving at a man page for the first time is quite likely to have no idea what a "filehandle" is, though. Any Perl man page mentioning filehandles should, at the very least, hyperlink that term to an explanation elsewhere in Perl's documentation. If appropriate--for example, in the lead-in to [`open` function's detailed reference](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR)--it can also include a very short in-place definition of the concept for the reader's convenience.
###
Use meaningful variable and symbol names in examples
When quickly sketching out examples, English-speaking programmers have a long tradition of using short nonsense words as placeholders for variables and other symbols--such as the venerable `foo`, `bar`, and `baz`. Example code found in a programming language's official, permanent documentation, however, can and should make an effort to provide a little more clarity through specificity.
Whenever possible, code examples should give variables, classes, and other programmer-defined symbols names that clearly demonstrate their function and their relationship to one another. For example, if an example requires that one class show an "is-a" relationship with another, consider naming them something like `Apple` and `Fruit`, rather than `Foo` and `Bar`. Similarly, sample code creating an instance of that class would do better to name it `$apple`, rather than `$baz`.
Even the simplest examples benefit from clear language using concrete words. Prefer a construct like `for my $item (@items) { ... }` over `for my $blah (@blah) { ... }`.
###
Write in English, but not just for English-speakers
While this style guide does specify American English as the documentation's language for the sake of internal consistency, authors should avoid cultural or idiomatic references available only to English-speaking Americans (or any other specific culture or society). As much as possible, the language employed by Perl's core documentation should strive towards cultural universality, if not neutrality. Regional turns of phrase, examples drawing on popular-culture knowledge, and other rhetorical techniques of that nature should appear sparingly, if at all.
Authors should feel free to let more freewheeling language flourish in "second-order" documentation about Perl, like books, blog entries, and magazine articles, published elsewhere and with a narrower readership in mind. But Perl's own docs should use language as accessible and welcoming to as wide an audience as possible.
###
Omit placeholder text or commentary
Placeholder text does not belong in the documentation that ships with Perl. No section header should be followed by text reading only "Watch this space", "To be included later", or the like. While Perl's source files may shift and alter as much as any other actively maintained technology, each released iteration of its technology should feel complete and self-contained, with no such future promises or other loose ends visible.
Take advantage of Perl's regular release cycle. Instead of cluttering the docs with flags promising more information later--the presence of which do not help readers at all today--the documentation's maintenance team should treat any known documentation absences as an issue to address like any other in the Perl project. Let Perl's contributors, testers, and release engineers address that need, and resist the temptation to insert apologies, which have all the utility in documentation as undeleted debug messages do in production code.
###
Apply section-breaks and examples generously
No matter how accessible their tone, the sight of monolithic blocks of text in technical documentation can present a will-weakening challenge for the reader. Authors can improve this situation through breaking long passages up into subsections with short, meaningful headers.
Since every section-header in Pod also acts as a potential end-point for a cross-reference (made via Pod's `L<...>` syntax), putting plenty of subsections in your documentation lets other man pages more precisely link to a particular topic. This creates hyperlinks directly to the most appropriate section rather than to the whole page in general, and helps create a more cohesive sense of a rich, consistent, and interrelated manual for readers.
Among the four documentation modes, sections belong more naturally in tutorials and explainers. The step-by-step instructions of cookbooks, or the austere definitions of reference pages, usually have no room for them. But authors can always make exceptions for unusually complex concepts that require further breakdown for clarity's sake.
Example code, on the other hand, can be a welcome addition to any mode of documentation. Code blocks help break up a man page visually, reassuring the reader that no matter how deep the textual explanation gets, they are never far from another practical example showing how it all comes together using a small, easy-to-read snippet of tested Perl code.
###
Lead with common cases and best practices
Perl famously gives programmers more than one way to do things. Like any other long-lived programming language, Perl has also built up a large, community-held notion of best practices, blessing some ways to do things as better than others, usually for the sake of more maintainable code.
####
Show the better ways first
Whenever it needs to show the rules for a technique which Perl provides many avenues for, the documentation should always lead with best practices. And when discussing some part of the Perl toolkit with many applications, the docs should begin with a demonstration of its application to the most common cases.
The `open` function, for example, has myriad potential uses within Perl programs, but *most of the time* programmers--and especially those new to Perl--turn to this reference because they simply wish to open a file for reading or writing. For this reason, `open`'s documentation begins there, and only descends into the function's more obscure uses after thoroughly documenting and demonstrating how it works in the common case. Furthermore, while engaging in this demonstration, the `open` documentation does not burden the reader right away with detailed explanations about calling `open` via any route other than the best-practice, three-argument style.
####
Show the lesser ways when needed
Sometimes, thoroughness demands documentation of deprecated techniques. For example, a certain Perl function might have an alternate syntax now considered outmoded and no longer best-practice, but which a maintainer of a legacy project might quite reasonably encounter when exploring old code. In this case, these features deserve documentation, but couched in clarity that modern Perl avoids such structures, and does not recommend their use in new projects.
Another way to look at this philosophy (and one [borrowed from our friends](https://devguide.python.org/documenting/#affirmative-tone) on Python's documentation team) involves writing while sympathizing with a programmer new to Perl, who may feel uncertain about learning a complex concept. By leading that concept's main documentation with clear, positive examples, we can immediately give these readers a simple and true picture of how it works in Perl, and boost their own confidence to start making use of this new knowledge. Certainly we should include alternate routes and admonitions as reasonably required, but we needn't emphasize them. Trust the reader to understand the basics quickly, and to keep reading for a deeper understanding if they feel so driven.
###
Document Perl's present
Perl's documentation should stay focused on Perl's present behavior, with a nod to future directions.
####
Recount the past only when necessary
When some Perl feature changes its behavior, documentation about that feature should change too, and just as definitively. The docs have no obligation to keep descriptions of past behavior hanging around, even if attaching clauses like "Prior to version 5.10, [...]".
Since Perl's core documentation is part of Perl's source distribution, it enjoys the same benefits of versioning and version-control as the source code of Perl itself. Take advantage of this, and update the text boldly when needed. Perl's history remains safe, even when you delete or replace outdated information from the current version's docs.
Perl's docs can acknowledge or discuss former behavior when warranted, including notes that some feature appeared in the language as of some specific version number. Authors should consider applying principles similar to those for deprecated techniques, [as described above](#Show-the-lesser-ways-when-needed): make the information present, but not prominent.
Otherwise, keep the past in the past. A manual uncluttered with outdated instruction stays more succinct and relevant.
####
Describe the uncertain future with care
Perl features marked as "experimental"--those that generate warnings when used in code not invoking the [`experimental`](experimental) pragma--deserve documentation, but only in certain contexts, and even then with caveats. These features represent possible new directions for Perl, but they have unstable interfaces and uncertain future presence.
The documentation should take both implications of "experimental" literally. It should not discourage these features' use by programmers who wish to try out new features in projects that can risk their inherent instability; this experimentation can help Perl grow and improve. By the same token, the docs should downplay these features' use in just about every other context.
Introductory or overview material should omit coverage of experimental features altogether.
More thorough reference materials or explanatory articles can include experimental features, but needs to clearly mark them as such, and not treat them with the same prominence as Perl's stable features. Using unstable features seldom coincides with best practices, and documentation that [puts best practices first](#Lead-with-common-cases-and-best-practices) should reflect this.
###
The documentation speaks with one voice
Even though it comes from many hands and minds, criss-crossing through the many years of Perl's lifetime, the language's documentation should speak with a single, consistent voice. With few exceptions, the docs should avoid explicit first-person-singular statements, or similar self-reference to any individual's contributor's philosophies or experiences.
Perl did begin life as a deeply personal expression by a single individual, and this famously carried through the first revisions of its documentation as well. Today, Perl's community understands that the language's continued development and support comes from many people working in concert, rather than any one person's vision or effort. Its documentation should not pretend otherwise.
The documentation should, however, carry forward the best tradition that Larry Wall set forth in the language's earliest days: Write both economically and with a humble, subtle wit, resulting in a technical manual that mixes concision with a friendly approachability. It avoids the dryness that one might expect from technical documentation, while not leaning so hard into overt comedy as to distract and confuse from the nonetheless-technical topics at hand.
Like the best written works, Perl's documentation has a soul. Get familiar with it as a reader to internalize its voice, and then find your own way to express it in your own contributions. Writing clearly, succinctly, and with knowledge of your audience's expectations will get you most of the way there, in the meantime.
Every line in the docs--whether English sentence or Perl statement--should serve the purpose of bringing understanding to the reader. Should a sentence exist mainly to make a wry joke that doesn't further the reader's knowledge of Perl, set it aside, and consider recasting it into a personal blog post or other article instead.
Write with a light heart, and a miserly hand.
INDEX OF PREFERRED TERMS
-------------------------
[As noted above](#Choice-of-underlying-style-guide%3A-CMOS), this guide "inherits" all the preferred terms listed in the Chicago Manual of Style, 17th edition, and adds the following terms of particular interest to Perl documentation.
built-in function Not "builtin".
Darwin See [macOS](#macOS).
macOS Use this term for Apple's operating system instead of "Mac OS X" or variants thereof.
This term is also preferable to "Darwin", unless one needs to refer to macOS's Unix layer specifically.
man page One unit of Unix-style documentation. Not "manpage". Preferable to "manual page".
Perl; perl The name of the programming language is Perl, with a leading capital "P", and the remainder in lowercase. (Never "PERL".)
The interpreter program that reads and executes Perl code is named "`perl`", in lowercase and in monospace (as with any other command name).
Generally, unless you are specifically writing about the command-line `perl` program (as, for example, [`perlrun`](perlrun) does), use "Perl" instead.
Perl 5 Documentation need not follow Perl's name with a "5", or any other number, except during discussions of Perl's history, future plans, or explicit comparisons between major Perl versions.
Before 2019, specifying "Perl 5" was sometimes needed to distinguish the language from Perl 6. With the latter's renaming to "Raku", this practice became unnecessary.
Perl 6 See [Raku](#Raku).
Perl 5 Porters, the; porters, the; p5p The full name of the team responsible for Perl's ongoing maintenance and development is "the Perl 5 Porters", and this sobriquet should be spelled out in the first mention within any one document. It may thereafter call the team "the porters" or "p5p".
Not "Perl5 Porters".
program The most general descriptor for a stand-alone work made out of executable Perl code. Synonymous with, and preferable to, "script".
Raku Perl's "sister language", whose homepage is <https://raku.org>.
Previously known as "Perl 6". In 2019, its design team renamed the language to better reflect its identity as a project independent from Perl. As such, Perl's documentation should always refer to this language as "Raku" and not "Perl 6".
script See [program](#program).
semicolon Perl code's frequently overlooked punctuation mark. Not "semi-colon".
Unix Not "UNIX", "\*nix", or "Un\*x". Applicable to both the original operating system from the 1970s as well as all its conceptual descendants. You may simply write "Unix" and not "a Unix-like operating system" when referring to a Unix-like operating system.
SEE ALSO
---------
* <perlpod>
* <perlpodstyle>
AUTHOR
------
This guide was initially drafted by Jason McIntosh ([email protected]), under a grant from The Perl Foundation.
| programming_docs |
perl threads threads
=======
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [WARNING](#WARNING)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXITING A THREAD](#EXITING-A-THREAD)
* [THREAD STATE](#THREAD-STATE)
* [THREAD CONTEXT](#THREAD-CONTEXT)
+ [Explicit context](#Explicit-context)
+ [Implicit context](#Implicit-context)
+ [$thr->wantarray()](#%24thr-%3Ewantarray())
+ [threads->wantarray()](#threads-%3Ewantarray())
* [THREAD STACK SIZE](#THREAD-STACK-SIZE)
* [THREAD SIGNALLING](#THREAD-SIGNALLING)
* [WARNINGS](#WARNINGS)
* [ERRORS](#ERRORS)
* [BUGS AND LIMITATIONS](#BUGS-AND-LIMITATIONS)
* [REQUIREMENTS](#REQUIREMENTS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
NAME
----
threads - Perl interpreter-based threads
VERSION
-------
This document describes threads version 2.27
WARNING
-------
The "interpreter-based threads" provided by Perl are not the fast, lightweight system for multitasking that one might expect or hope for. Threads are implemented in a way that makes them easy to misuse. Few people know how to use them correctly or will be able to provide help.
The use of interpreter-based threads in perl is officially [discouraged](perlpolicy#discouraged).
SYNOPSIS
--------
```
use threads ('yield',
'stack_size' => 64*4096,
'exit' => 'threads_only',
'stringify');
sub start_thread {
my @args = @_;
print('Thread started: ', join(' ', @args), "\n");
}
my $thr = threads->create('start_thread', 'argument');
$thr->join();
threads->create(sub { print("I am a thread\n"); })->join();
my $thr2 = async { foreach (@files) { ... } };
$thr2->join();
if (my $err = $thr2->error()) {
warn("Thread error: $err\n");
}
# Invoke thread in list context (implicit) so it can return a list
my ($thr) = threads->create(sub { return (qw/a b c/); });
# or specify list context explicitly
my $thr = threads->create({'context' => 'list'},
sub { return (qw/a b c/); });
my @results = $thr->join();
$thr->detach();
# Get a thread's object
$thr = threads->self();
$thr = threads->object($tid);
# Get a thread's ID
$tid = threads->tid();
$tid = $thr->tid();
$tid = "$thr";
# Give other threads a chance to run
threads->yield();
yield();
# Lists of non-detached threads
my @threads = threads->list();
my $thread_count = threads->list();
my @running = threads->list(threads::running);
my @joinable = threads->list(threads::joinable);
# Test thread objects
if ($thr1 == $thr2) {
...
}
# Manage thread stack size
$stack_size = threads->get_stack_size();
$old_size = threads->set_stack_size(32*4096);
# Create a thread with a specific context and stack size
my $thr = threads->create({ 'context' => 'list',
'stack_size' => 32*4096,
'exit' => 'thread_only' },
\&foo);
# Get thread's context
my $wantarray = $thr->wantarray();
# Check thread's state
if ($thr->is_running()) {
sleep(1);
}
if ($thr->is_joinable()) {
$thr->join();
}
# Send a signal to a thread
$thr->kill('SIGUSR1');
# Exit a thread
threads->exit();
```
DESCRIPTION
-----------
Since Perl 5.8, thread programming has been available using a model called *interpreter threads* which provides a new Perl interpreter for each thread, and, by default, results in no data or state information being shared between threads.
(Prior to Perl 5.8, *5005threads* was available through the `Thread.pm` API. This threading model has been deprecated, and was removed as of Perl 5.10.0.)
As just mentioned, all variables are, by default, thread local. To use shared variables, you need to also load <threads::shared>:
```
use threads;
use threads::shared;
```
When loading <threads::shared>, you must `use threads` before you `use threads::shared`. (`threads` will emit a warning if you do it the other way around.)
It is strongly recommended that you enable threads via `use threads` as early as possible in your script.
If needed, scripts can be written so as to run on both threaded and non-threaded Perls:
```
my $can_use_threads = eval 'use threads; 1';
if ($can_use_threads) {
# Do processing using threads
...
} else {
# Do it without using threads
...
}
```
$thr = threads->create(FUNCTION, ARGS) This will create a new thread that will begin execution with the specified entry point function, and give it the *ARGS* list as parameters. It will return the corresponding threads object, or `undef` if thread creation failed.
*FUNCTION* may either be the name of a function, an anonymous subroutine, or a code ref.
```
my $thr = threads->create('func_name', ...);
# or
my $thr = threads->create(sub { ... }, ...);
# or
my $thr = threads->create(\&func, ...);
```
The `->new()` method is an alias for `->create()`.
$thr->join() This will wait for the corresponding thread to complete its execution. When the thread finishes, `->join()` will return the return value(s) of the entry point function.
The context (void, scalar or list) for the return value(s) for `->join()` is determined at the time of thread creation.
```
# Create thread in list context (implicit)
my ($thr1) = threads->create(sub {
my @results = qw(a b c);
return (@results);
});
# or (explicit)
my $thr1 = threads->create({'context' => 'list'},
sub {
my @results = qw(a b c);
return (@results);
});
# Retrieve list results from thread
my @res1 = $thr1->join();
# Create thread in scalar context (implicit)
my $thr2 = threads->create(sub {
my $result = 42;
return ($result);
});
# Retrieve scalar result from thread
my $res2 = $thr2->join();
# Create a thread in void context (explicit)
my $thr3 = threads->create({'void' => 1},
sub { print("Hello, world\n"); });
# Join the thread in void context (i.e., no return value)
$thr3->join();
```
See ["THREAD CONTEXT"](#THREAD-CONTEXT) for more details.
If the program exits without all threads having either been joined or detached, then a warning will be issued.
Calling `->join()` or `->detach()` on an already joined thread will cause an error to be thrown.
$thr->detach() Makes the thread unjoinable, and causes any eventual return value to be discarded. When the program exits, any detached threads that are still running are silently terminated.
If the program exits without all threads having either been joined or detached, then a warning will be issued.
Calling `->join()` or `->detach()` on an already detached thread will cause an error to be thrown.
threads->detach() Class method that allows a thread to detach itself.
threads->self() Class method that allows a thread to obtain its own *threads* object.
$thr->tid() Returns the ID of the thread. Thread IDs are unique integers with the main thread in a program being 0, and incrementing by 1 for every thread created.
threads->tid() Class method that allows a thread to obtain its own ID.
"$thr" If you add the `stringify` import option to your `use threads` declaration, then using a threads object in a string or a string context (e.g., as a hash key) will cause its ID to be used as the value:
```
use threads qw(stringify);
my $thr = threads->create(...);
print("Thread $thr started\n"); # Prints: Thread 1 started
```
threads->object($tid) This will return the *threads* object for the *active* thread associated with the specified thread ID. If `$tid` is the value for the current thread, then this call works the same as `->self()`. Otherwise, returns `undef` if there is no thread associated with the TID, if the thread is joined or detached, if no TID is specified or if the specified TID is undef.
threads->yield() This is a suggestion to the OS to let this thread yield CPU time to other threads. What actually happens is highly dependent upon the underlying thread implementation.
You may do `use threads qw(yield)`, and then just use `yield()` in your code.
threads->list()
threads->list(threads::all)
threads->list(threads::running)
threads->list(threads::joinable) With no arguments (or using `threads::all`) and in a list context, returns a list of all non-joined, non-detached *threads* objects. In a scalar context, returns a count of the same.
With a *true* argument (using `threads::running`), returns a list of all non-joined, non-detached *threads* objects that are still running.
With a *false* argument (using `threads::joinable`), returns a list of all non-joined, non-detached *threads* objects that have finished running (i.e., for which `->join()` will not *block*).
$thr1->equal($thr2) Tests if two threads objects are the same thread or not. This is overloaded to the more natural forms:
```
if ($thr1 == $thr2) {
print("Threads are the same\n");
}
# or
if ($thr1 != $thr2) {
print("Threads differ\n");
}
```
(Thread comparison is based on thread IDs.)
async BLOCK; `async` creates a thread to execute the block immediately following it. This block is treated as an anonymous subroutine, and so must have a semicolon after the closing brace. Like `threads->create()`, `async` returns a *threads* object.
$thr->error() Threads are executed in an `eval` context. This method will return `undef` if the thread terminates *normally*. Otherwise, it returns the value of `$@` associated with the thread's execution status in its `eval` context.
$thr->\_handle() This *private* method returns a pointer (i.e., the memory location expressed as an unsigned integer) to the internal thread structure associated with a threads object. For Win32, this is a pointer to the `HANDLE` value returned by `CreateThread` (i.e., `HANDLE *`); for other platforms, it is a pointer to the `pthread_t` structure used in the `pthread_create` call (i.e., `pthread_t *`).
This method is of no use for general Perl threads programming. Its intent is to provide other (XS-based) thread modules with the capability to access, and possibly manipulate, the underlying thread structure associated with a Perl thread.
threads->\_handle() Class method that allows a thread to obtain its own *handle*.
EXITING A THREAD
-----------------
The usual method for terminating a thread is to [return()](perlfunc#return-EXPR) from the entry point function with the appropriate return value(s).
threads->exit() If needed, a thread can be exited at any time by calling `threads->exit()`. This will cause the thread to return `undef` in a scalar context, or the empty list in a list context.
When called from the *main* thread, this behaves the same as `exit(0)`.
threads->exit(status) When called from a thread, this behaves like `threads->exit()` (i.e., the exit status code is ignored).
When called from the *main* thread, this behaves the same as `exit(status)`.
die() Calling `die()` in a thread indicates an abnormal exit for the thread. Any `$SIG{__DIE__}` handler in the thread will be called first, and then the thread will exit with a warning message that will contain any arguments passed in the `die()` call.
exit(status) Calling [exit()](perlfunc#exit-EXPR) inside a thread causes the whole application to terminate. Because of this, the use of `exit()` inside threaded code, or in modules that might be used in threaded applications, is strongly discouraged.
If `exit()` really is needed, then consider using the following:
```
threads->exit() if threads->can('exit'); # Thread friendly
exit(status);
```
use threads 'exit' => 'threads\_only' This globally overrides the default behavior of calling `exit()` inside a thread, and effectively causes such calls to behave the same as `threads->exit()`. In other words, with this setting, calling `exit()` causes only the thread to terminate.
Because of its global effect, this setting should not be used inside modules or the like.
The *main* thread is unaffected by this setting.
threads->create({'exit' => 'thread\_only'}, ...) This overrides the default behavior of `exit()` inside the newly created thread only.
$thr->set\_thread\_exit\_only(boolean) This can be used to change the *exit thread only* behavior for a thread after it has been created. With a *true* argument, `exit()` will cause only the thread to exit. With a *false* argument, `exit()` will terminate the application.
The *main* thread is unaffected by this call.
threads->set\_thread\_exit\_only(boolean) Class method for use inside a thread to change its own behavior for `exit()`.
The *main* thread is unaffected by this call.
THREAD STATE
-------------
The following boolean methods are useful in determining the *state* of a thread.
$thr->is\_running() Returns true if a thread is still running (i.e., if its entry point function has not yet finished or exited).
$thr->is\_joinable() Returns true if the thread has finished running, is not detached and has not yet been joined. In other words, the thread is ready to be joined, and a call to `$thr->join()` will not *block*.
$thr->is\_detached() Returns true if the thread has been detached.
threads->is\_detached() Class method that allows a thread to determine whether or not it is detached.
THREAD CONTEXT
---------------
As with subroutines, the type of value returned from a thread's entry point function may be determined by the thread's *context*: list, scalar or void. The thread's context is determined at thread creation. This is necessary so that the context is available to the entry point function via [wantarray()](perlfunc#wantarray). The thread may then specify a value of the appropriate type to be returned from `->join()`.
###
Explicit context
Because thread creation and thread joining may occur in different contexts, it may be desirable to state the context explicitly to the thread's entry point function. This may be done by calling `->create()` with a hash reference as the first argument:
```
my $thr = threads->create({'context' => 'list'}, \&foo);
...
my @results = $thr->join();
```
In the above, the threads object is returned to the parent thread in scalar context, and the thread's entry point function `foo` will be called in list (array) context such that the parent thread can receive a list (array) from the `->join()` call. (`'array'` is synonymous with `'list'`.)
Similarly, if you need the threads object, but your thread will not be returning a value (i.e., *void* context), you would do the following:
```
my $thr = threads->create({'context' => 'void'}, \&foo);
...
$thr->join();
```
The context type may also be used as the *key* in the hash reference followed by a *true* value:
```
threads->create({'scalar' => 1}, \&foo);
...
my ($thr) = threads->list();
my $result = $thr->join();
```
###
Implicit context
If not explicitly stated, the thread's context is implied from the context of the `->create()` call:
```
# Create thread in list context
my ($thr) = threads->create(...);
# Create thread in scalar context
my $thr = threads->create(...);
# Create thread in void context
threads->create(...);
```
###
$thr->wantarray()
This returns the thread's context in the same manner as [wantarray()](perlfunc#wantarray).
###
threads->wantarray()
Class method to return the current thread's context. This returns the same value as running [wantarray()](perlfunc#wantarray) inside the current thread's entry point function.
THREAD STACK SIZE
------------------
The default per-thread stack size for different platforms varies significantly, and is almost always far more than is needed for most applications. On Win32, Perl's makefile explicitly sets the default stack to 16 MB; on most other platforms, the system default is used, which again may be much larger than is needed.
By tuning the stack size to more accurately reflect your application's needs, you may significantly reduce your application's memory usage, and increase the number of simultaneously running threads.
Note that on Windows, address space allocation granularity is 64 KB, therefore, setting the stack smaller than that on Win32 Perl will not save any more memory.
threads->get\_stack\_size(); Returns the current default per-thread stack size. The default is zero, which means the system default stack size is currently in use.
$size = $thr->get\_stack\_size(); Returns the stack size for a particular thread. A return value of zero indicates the system default stack size was used for the thread.
$old\_size = threads->set\_stack\_size($new\_size); Sets a new default per-thread stack size, and returns the previous setting.
Some platforms have a minimum thread stack size. Trying to set the stack size below this value will result in a warning, and the minimum stack size will be used.
Some Linux platforms have a maximum stack size. Setting too large of a stack size will cause thread creation to fail.
If needed, `$new_size` will be rounded up to the next multiple of the memory page size (usually 4096 or 8192).
Threads created after the stack size is set will then either call `pthread_attr_setstacksize()` *(for pthreads platforms)*, or supply the stack size to `CreateThread()` *(for Win32 Perl)*.
(Obviously, this call does not affect any currently extant threads.)
use threads ('stack\_size' => VALUE); This sets the default per-thread stack size at the start of the application.
$ENV{'PERL5\_ITHREADS\_STACK\_SIZE'} The default per-thread stack size may be set at the start of the application through the use of the environment variable `PERL5_ITHREADS_STACK_SIZE`:
```
PERL5_ITHREADS_STACK_SIZE=1048576
export PERL5_ITHREADS_STACK_SIZE
perl -e'use threads; print(threads->get_stack_size(), "\n")'
```
This value overrides any `stack_size` parameter given to `use threads`. Its primary purpose is to permit setting the per-thread stack size for legacy threaded applications.
threads->create({'stack\_size' => VALUE}, FUNCTION, ARGS) To specify a particular stack size for any individual thread, call `->create()` with a hash reference as the first argument:
```
my $thr = threads->create({'stack_size' => 32*4096},
\&foo, @args);
```
$thr2 = $thr1->create(FUNCTION, ARGS) This creates a new thread (`$thr2`) that inherits the stack size from an existing thread (`$thr1`). This is shorthand for the following:
```
my $stack_size = $thr1->get_stack_size();
my $thr2 = threads->create({'stack_size' => $stack_size},
FUNCTION, ARGS);
```
THREAD SIGNALLING
------------------
When safe signals is in effect (the default behavior - see ["Unsafe signals"](#Unsafe-signals) for more details), then signals may be sent and acted upon by individual threads.
$thr->kill('SIG...'); Sends the specified signal to the thread. Signal names and (positive) signal numbers are the same as those supported by [kill()](perlfunc#kill-SIGNAL%2C-LIST). For example, 'SIGTERM', 'TERM' and (depending on the OS) 15 are all valid arguments to `->kill()`.
Returns the thread object to allow for method chaining:
```
$thr->kill('SIG...')->join();
```
Signal handlers need to be set up in the threads for the signals they are expected to act upon. Here's an example for *cancelling* a thread:
```
use threads;
sub thr_func
{
# Thread 'cancellation' signal handler
$SIG{'KILL'} = sub { threads->exit(); };
...
}
# Create a thread
my $thr = threads->create('thr_func');
...
# Signal the thread to terminate, and then detach
# it so that it will get cleaned up automatically
$thr->kill('KILL')->detach();
```
Here's another simplistic example that illustrates the use of thread signalling in conjunction with a semaphore to provide rudimentary *suspend* and *resume* capabilities:
```
use threads;
use Thread::Semaphore;
sub thr_func
{
my $sema = shift;
# Thread 'suspend/resume' signal handler
$SIG{'STOP'} = sub {
$sema->down(); # Thread suspended
$sema->up(); # Thread resumes
};
...
}
# Create a semaphore and pass it to a thread
my $sema = Thread::Semaphore->new();
my $thr = threads->create('thr_func', $sema);
# Suspend the thread
$sema->down();
$thr->kill('STOP');
...
# Allow the thread to continue
$sema->up();
```
CAVEAT: The thread signalling capability provided by this module does not actually send signals via the OS. It *emulates* signals at the Perl-level such that signal handlers are called in the appropriate thread. For example, sending `$thr->kill('STOP')` does not actually suspend a thread (or the whole process), but does cause a `$SIG{'STOP'}` handler to be called in that thread (as illustrated above).
As such, signals that would normally not be appropriate to use in the `kill()` command (e.g., `kill('KILL', $$)`) are okay to use with the `->kill()` method (again, as illustrated above).
Correspondingly, sending a signal to a thread does not disrupt the operation the thread is currently working on: The signal will be acted upon after the current operation has completed. For instance, if the thread is *stuck* on an I/O call, sending it a signal will not cause the I/O call to be interrupted such that the signal is acted up immediately.
Sending a signal to a terminated/finished thread is ignored.
WARNINGS
--------
Perl exited with active threads: If the program exits without all threads having either been joined or detached, then this warning will be issued.
NOTE: If the *main* thread exits, then this warning cannot be suppressed using `no warnings 'threads';` as suggested below.
Thread creation failed: pthread\_create returned # See the appropriate *man* page for `pthread_create` to determine the actual cause for the failure.
Thread # terminated abnormally: ... A thread terminated in some manner other than just returning from its entry point function, or by using `threads->exit()`. For example, the thread may have terminated because of an error, or by using `die`.
Using minimum thread stack size of # Some platforms have a minimum thread stack size. Trying to set the stack size below this value will result in the above warning, and the stack size will be set to the minimum.
Thread creation failed: pthread\_attr\_setstacksize(*SIZE*) returned 22 The specified *SIZE* exceeds the system's maximum stack size. Use a smaller value for the stack size.
If needed, thread warnings can be suppressed by using:
```
no warnings 'threads';
```
in the appropriate scope.
ERRORS
------
This Perl not built to support threads The particular copy of Perl that you're trying to use was not built using the `useithreads` configuration option.
Having threads support requires all of Perl and all of the XS modules in the Perl installation to be rebuilt; it is not just a question of adding the <threads> module (i.e., threaded and non-threaded Perls are binary incompatible).
Cannot change stack size of an existing thread The stack size of currently extant threads cannot be changed, therefore, the following results in the above error:
```
$thr->set_stack_size($size);
```
Cannot signal threads without safe signals Safe signals must be in effect to use the `->kill()` signalling method. See ["Unsafe signals"](#Unsafe-signals) for more details.
Unrecognized signal name: ... The particular copy of Perl that you're trying to use does not support the specified signal being used in a `->kill()` call.
BUGS AND LIMITATIONS
---------------------
Before you consider posting a bug report, please consult, and possibly post a message to the discussion forum to see if what you've encountered is a known problem.
Thread-safe modules See ["Making your module threadsafe" in perlmod](perlmod#Making-your-module-threadsafe) when creating modules that may be used in threaded applications, especially if those modules use non-Perl data, or XS code.
Using non-thread-safe modules Unfortunately, you may encounter Perl modules that are not *thread-safe*. For example, they may crash the Perl interpreter during execution, or may dump core on termination. Depending on the module and the requirements of your application, it may be possible to work around such difficulties.
If the module will only be used inside a thread, you can try loading the module from inside the thread entry point function using `require` (and `import` if needed):
```
sub thr_func
{
require Unsafe::Module
# Unsafe::Module->import(...);
....
}
```
If the module is needed inside the *main* thread, try modifying your application so that the module is loaded (again using `require` and `->import()`) after any threads are started, and in such a way that no other threads are started afterwards.
If the above does not work, or is not adequate for your application, then file a bug report on <https://rt.cpan.org/Public/> against the problematic module.
Memory consumption On most systems, frequent and continual creation and destruction of threads can lead to ever-increasing growth in the memory footprint of the Perl interpreter. While it is simple to just launch threads and then `->join()` or `->detach()` them, for long-lived applications, it is better to maintain a pool of threads, and to reuse them for the work needed, using [queues](Thread::Queue) to notify threads of pending work. The CPAN distribution of this module contains a simple example (*examples/pool\_reuse.pl*) illustrating the creation, use and monitoring of a pool of *reusable* threads.
Current working directory On all platforms except MSWin32, the setting for the current working directory is shared among all threads such that changing it in one thread (e.g., using `chdir()`) will affect all the threads in the application.
On MSWin32, each thread maintains its own the current working directory setting.
Locales Prior to Perl 5.28, locales could not be used with threads, due to various race conditions. Starting in that release, on systems that implement thread-safe locale functions, threads can be used, with some caveats. This includes Windows starting with Visual Studio 2005, and systems compatible with POSIX 2008. See ["Multi-threaded operation" in perllocale](perllocale#Multi-threaded-operation).
Each thread (except the main thread) is started using the C locale. The main thread is started like all other Perl programs; see ["ENVIRONMENT" in perllocale](perllocale#ENVIRONMENT). You can switch locales in any thread as often as you like.
If you want to inherit the parent thread's locale, you can, in the parent, set a variable like so:
```
$foo = POSIX::setlocale(LC_ALL, NULL);
```
and then pass to threads->create() a sub that closes over `$foo`. Then, in the child, you say
```
POSIX::setlocale(LC_ALL, $foo);
```
Or you can use the facilities in <threads::shared> to pass `$foo`; or if the environment hasn't changed, in the child, do
```
POSIX::setlocale(LC_ALL, "");
```
Environment variables Currently, on all platforms except MSWin32, all *system* calls (e.g., using `system()` or back-ticks) made from threads use the environment variable settings from the *main* thread. In other words, changes made to `%ENV` in a thread will not be visible in *system* calls made by that thread.
To work around this, set environment variables as part of the *system* call. For example:
```
my $msg = 'hello';
system("FOO=$msg; echo \$FOO"); # Outputs 'hello' to STDOUT
```
On MSWin32, each thread maintains its own set of environment variables.
Catching signals Signals are *caught* by the main thread (thread ID = 0) of a script. Therefore, setting up signal handlers in threads for purposes other than ["THREAD SIGNALLING"](#THREAD-SIGNALLING) as documented above will not accomplish what is intended.
This is especially true if trying to catch `SIGALRM` in a thread. To handle alarms in threads, set up a signal handler in the main thread, and then use ["THREAD SIGNALLING"](#THREAD-SIGNALLING) to relay the signal to the thread:
```
# Create thread with a task that may time out
my $thr = threads->create(sub {
threads->yield();
eval {
$SIG{ALRM} = sub { die("Timeout\n"); };
alarm(10);
... # Do work here
alarm(0);
};
if ($@ =~ /Timeout/) {
warn("Task in thread timed out\n");
}
};
# Set signal handler to relay SIGALRM to thread
$SIG{ALRM} = sub { $thr->kill('ALRM') };
... # Main thread continues working
```
Parent-child threads On some platforms, it might not be possible to destroy *parent* threads while there are still existing *child* threads.
Unsafe signals Since Perl 5.8.0, signals have been made safer in Perl by postponing their handling until the interpreter is in a *safe* state. See ["Safe Signals" in perl58delta](https://perldoc.perl.org/5.36.0/perl58delta#Safe-Signals) and ["Deferred Signals (Safe Signals)" in perlipc](perlipc#Deferred-Signals-%28Safe-Signals%29) for more details.
Safe signals is the default behavior, and the old, immediate, unsafe signalling behavior is only in effect in the following situations:
* Perl has been built with `PERL_OLD_SIGNALS` (see `perl -V`).
* The environment variable `PERL_SIGNALS` is set to `unsafe` (see ["PERL\_SIGNALS" in perlrun](perlrun#PERL_SIGNALS)).
* The module <Perl::Unsafe::Signals> is used.
If unsafe signals is in effect, then signal handling is not thread-safe, and the `->kill()` signalling method cannot be used.
Identity of objects returned from threads When a value is returned from a thread through a `join` operation, the value and everything that it references is copied across to the joining thread, in much the same way that values are copied upon thread creation. This works fine for most kinds of value, including arrays, hashes, and subroutines. The copying recurses through array elements, reference scalars, variables closed over by subroutines, and other kinds of reference.
However, everything referenced by the returned value is a fresh copy in the joining thread, even if a returned object had in the child thread been a copy of something that previously existed in the parent thread. After joining, the parent will therefore have a duplicate of each such object. This sometimes matters, especially if the object gets mutated; this can especially matter for private data to which a returned subroutine provides access.
Returning blessed objects from threads Returning blessed objects from threads does not work. Depending on the classes involved, you may be able to work around this by returning a serialized version of the object (e.g., using <Data::Dumper> or [Storable](storable)), and then reconstituting it in the joining thread. If you're using Perl 5.10.0 or later, and if the class supports [shared objects](threads::shared#OBJECTS), you can pass them via [shared queues](Thread::Queue).
END blocks in threads It is possible to add [END blocks](perlmod#BEGIN%2C-UNITCHECK%2C-CHECK%2C-INIT-and-END) to threads by using [require](perlfunc#require-VERSION) or [eval](perlfunc#eval-EXPR) with the appropriate code. These `END` blocks will then be executed when the thread's interpreter is destroyed (i.e., either during a `->join()` call, or at program termination).
However, calling any <threads> methods in such an `END` block will most likely *fail* (e.g., the application may hang, or generate an error) due to mutexes that are needed to control functionality within the <threads> module.
For this reason, the use of `END` blocks in threads is **strongly** discouraged.
Open directory handles In perl 5.14 and higher, on systems other than Windows that do not support the `fchdir` C function, directory handles (see [opendir](perlfunc#opendir-DIRHANDLE%2CEXPR)) will not be copied to new threads. You can use the `d_fchdir` variable in [Config.pm](config) to determine whether your system supports it.
In prior perl versions, spawning threads with open directory handles would crash the interpreter. [[perl #75154]](https://rt.perl.org/rt3/Public/Bug/Display.html?id=75154)
Detached threads and global destruction If the main thread exits while there are detached threads which are still running, then Perl's global destruction phase is not executed because otherwise certain global structures that control the operation of threads and that are allocated in the main thread's memory may get destroyed before the detached thread is destroyed.
If you are using any code that requires the execution of the global destruction phase for clean up (e.g., removing temp files), then do not use detached threads, but rather join all threads before exiting the program.
Perl Bugs and the CPAN Version of <threads>
Support for threads extends beyond the code in this module (i.e., *threads.pm* and *threads.xs*), and into the Perl interpreter itself. Older versions of Perl contain bugs that may manifest themselves despite using the latest version of <threads> from CPAN. There is no workaround for this other than upgrading to the latest version of Perl.
Even with the latest version of Perl, it is known that certain constructs with threads may result in warning messages concerning leaked scalars or unreferenced scalars. However, such warnings are harmless, and may safely be ignored.
You can search for <threads> related bug reports at <https://rt.cpan.org/Public/>. If needed submit any new bugs, problems, patches, etc. to: <https://rt.cpan.org/Public/Dist/Display.html?Name=threads>
REQUIREMENTS
------------
Perl 5.8.0 or later
SEE ALSO
---------
threads on MetaCPAN: <https://metacpan.org/release/threads>
Code repository for CPAN distribution: <https://github.com/Dual-Life/threads>
<threads::shared>, <perlthrtut>
<https://www.perl.com/pub/a/2002/06/11/threads.html> and <https://www.perl.com/pub/a/2002/09/04/threads.html>
Perl threads mailing list: <https://lists.perl.org/list/ithreads.html>
Stack size discussion: <https://www.perlmonks.org/?node_id=532956>
Sample code in the *examples* directory of this distribution on CPAN.
AUTHOR
------
Artur Bergman <sky AT crucially DOT net>
CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
LICENSE
-------
threads is released under the same license as Perl.
ACKNOWLEDGEMENTS
----------------
Richard Soderberg <perl AT crystalflame DOT net> - Helping me out tons, trying to find reasons for races and other weird bugs!
Simon Cozens <simon AT brecon DOT co DOT uk> - Being there to answer zillions of annoying questions
Rocco Caputo <troc AT netrus DOT net>
Vipul Ved Prakash <mail AT vipul DOT net> - Helping with debugging
Dean Arnold <darnold AT presicient DOT com> - Stack size API
| programming_docs |
perl perlmroapi perlmroapi
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Callbacks](#Callbacks)
* [Caching](#Caching)
* [Examples](#Examples)
* [AUTHORS](#AUTHORS)
NAME
----
perlmroapi - Perl method resolution plugin interface
DESCRIPTION
-----------
As of Perl 5.10.1 there is a new interface for plugging and using method resolution orders other than the default (linear depth first search). The C3 method resolution order added in 5.10.0 has been re-implemented as a plugin, without changing its Perl-space interface.
Each plugin should register itself by providing the following structure
```
struct mro_alg {
AV *(*resolve)(pTHX_ HV *stash, U32 level);
const char *name;
U16 length;
U16 kflags;
U32 hash;
};
```
and calling `Perl_mro_register`:
```
Perl_mro_register(aTHX_ &my_mro_alg);
```
resolve Pointer to the linearisation function, described below.
name Name of the MRO, either in ISO-8859-1 or UTF-8.
length Length of the name.
kflags If the name is given in UTF-8, set this to `HVhek_UTF8`. The value is passed direct as the parameter *kflags* to `hv_common()`.
hash A precomputed hash value for the MRO's name, or 0.
Callbacks
---------
The `resolve` function is called to generate a linearised ISA for the given stash, using this MRO. It is called with a pointer to the stash, and a *level* of 0. The core always sets *level* to 0 when it calls your function - the parameter is provided to allow your implementation to track depth if it needs to recurse.
The function should return a reference to an array containing the parent classes in order. The names of the classes should be the result of calling `HvENAME()` on the stash. In those cases where `HvENAME()` returns null, `HvNAME()` should be used instead.
The caller is responsible for incrementing the reference count of the array returned if it wants to keep the structure. Hence, if you have created a temporary value that you keep no pointer to, `sv_2mortal()` to ensure that it is disposed of correctly. If you have cached your return value, then return a pointer to it without changing the reference count.
Caching
-------
Computing MROs can be expensive. The implementation provides a cache, in which you can store a single `SV *`, or anything that can be cast to `SV *`, such as `AV *`. To read your private value, use the macro `MRO_GET_PRIVATE_DATA()`, passing it the `mro_meta` structure from the stash, and a pointer to your `mro_alg` structure:
```
meta = HvMROMETA(stash);
private_sv = MRO_GET_PRIVATE_DATA(meta, &my_mro_alg);
```
To set your private value, call `Perl_mro_set_private_data()`:
```
Perl_mro_set_private_data(aTHX_ meta, &c3_alg, private_sv);
```
The private data cache will take ownership of a reference to private\_sv, much the same way that `hv_store()` takes ownership of a reference to the value that you pass it.
Examples
--------
For examples of MRO implementations, see `S_mro_get_linear_isa_c3()` and the `BOOT:` section of *ext/mro/mro.xs*, and `S_mro_get_linear_isa_dfs()` in *mro\_core.c*
AUTHORS
-------
The implementation of the C3 MRO and switchable MROs within the perl core was written by Brandon L Black. Nicholas Clark created the pluggable interface, refactored Brandon's implementation to work with it, and wrote this document.
perl autodie::Scope::Guard autodie::Scope::Guard
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods](#Methods)
- [new](#new)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
autodie::Scope::Guard - Wrapper class for calling subs at end of scope
SYNOPSIS
--------
```
use autodie::Scope::Guard;
$^H{'my-key'} = autodie::Scope::Guard->new(sub {
print "Hallo world\n";
});
```
DESCRIPTION
-----------
This class is used to bless perl subs so that they are invoked when they are destroyed. This is mostly useful for ensuring the code is invoked at end of scope. This module is not a part of autodie's public API.
This module is directly inspired by chocolateboy's excellent Scope::Guard module.
### Methods
#### new
```
my $hook = autodie::Scope::Guard->new(sub {});
```
Creates a new `autodie::Scope::Guard`, which will invoke the given sub once it goes out of scope (i.e. its DESTROY handler is called).
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.
perl XSLoader XSLoader
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Migration from DynaLoader](#Migration-from-DynaLoader)
+ [Backward compatible boilerplate](#Backward-compatible-boilerplate)
* [Order of initialization: early load()](#Order-of-initialization:-early-load())
+ [The most hairy case](#The-most-hairy-case)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [LIMITATIONS](#LIMITATIONS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
XSLoader - Dynamically load C libraries into Perl code
VERSION
-------
Version 0.31
SYNOPSIS
--------
```
package YourPackage;
require XSLoader;
XSLoader::load(__PACKAGE__, $VERSION);
```
DESCRIPTION
-----------
This module defines a standard *simplified* interface to the dynamic linking mechanisms available on many platforms. Its primary purpose is to implement cheap automatic dynamic loading of Perl modules.
For a more complicated interface, see [DynaLoader](dynaloader). Many (most) features of `DynaLoader` are not implemented in `XSLoader`, like for example the `dl_load_flags`, not honored by `XSLoader`.
###
Migration from `DynaLoader`
A typical module using [DynaLoader](dynaloader) starts like this:
```
package YourPackage;
require DynaLoader;
our @ISA = qw( OnePackage OtherPackage DynaLoader );
our $VERSION = '0.01';
__PACKAGE__->bootstrap($VERSION);
```
Change this to
```
package YourPackage;
use XSLoader;
our @ISA = qw( OnePackage OtherPackage );
our $VERSION = '0.01';
XSLoader::load(__PACKAGE__, $VERSION);
```
In other words: replace `require DynaLoader` by `use XSLoader`, remove `DynaLoader` from `@ISA`, change `bootstrap` by `XSLoader::load`. Do not forget to quote the name of your package on the `XSLoader::load` line, and add comma (`,`) before the arguments (`$VERSION` above).
Of course, if `@ISA` contained only `DynaLoader`, there is no need to have the `@ISA` assignment at all; moreover, if instead of `our` one uses the more backward-compatible
```
use vars qw($VERSION @ISA);
```
one can remove this reference to `@ISA` together with the `@ISA` assignment.
If no `$VERSION` was specified on the `bootstrap` line, the last line becomes
```
XSLoader::load(__PACKAGE__);
```
in which case it can be further simplified to
```
XSLoader::load();
```
as `load` will use `caller` to determine the package.
###
Backward compatible boilerplate
If you want to have your cake and eat it too, you need a more complicated boilerplate.
```
package YourPackage;
our @ISA = qw( OnePackage OtherPackage );
our $VERSION = '0.01';
eval {
require XSLoader;
XSLoader::load(__PACKAGE__, $VERSION);
1;
} or do {
require DynaLoader;
push @ISA, 'DynaLoader';
__PACKAGE__->bootstrap($VERSION);
};
```
The parentheses about `XSLoader::load()` arguments are needed since we replaced `use XSLoader` by `require`, so the compiler does not know that a function `XSLoader::load()` is present.
This boilerplate uses the low-overhead `XSLoader` if present; if used with an antique Perl which has no `XSLoader`, it falls back to using `DynaLoader`.
Order of initialization: early load()
--------------------------------------
*Skip this section if the XSUB functions are supposed to be called from other modules only; read it only if you call your XSUBs from the code in your module, or have a `BOOT:` section in your XS file (see ["The BOOT: Keyword" in perlxs](perlxs#The-BOOT%3A-Keyword)). What is described here is equally applicable to the [DynaLoader](dynaloader) interface.*
A sufficiently complicated module using XS would have both Perl code (defined in *YourPackage.pm*) and XS code (defined in *YourPackage.xs*). If this Perl code makes calls into this XS code, and/or this XS code makes calls to the Perl code, one should be careful with the order of initialization.
The call to `XSLoader::load()` (or `bootstrap()`) calls the module's bootstrap code. For modules build by *xsubpp* (nearly all modules) this has three side effects:
* A sanity check is done to ensure that the versions of the *.pm* and the (compiled) *.xs* parts are compatible. If `$VERSION` was specified, this is used for the check. If not specified, it defaults to `$XS_VERSION // $VERSION` (in the module's namespace)
* the XSUBs are made accessible from Perl
* if a `BOOT:` section was present in the *.xs* file, the code there is called.
Consequently, if the code in the *.pm* file makes calls to these XSUBs, it is convenient to have XSUBs installed before the Perl code is defined; for example, this makes prototypes for XSUBs visible to this Perl code. Alternatively, if the `BOOT:` section makes calls to Perl functions (or uses Perl variables) defined in the *.pm* file, they must be defined prior to the call to `XSLoader::load()` (or `bootstrap()`).
The first situation being much more frequent, it makes sense to rewrite the boilerplate as
```
package YourPackage;
use XSLoader;
our ($VERSION, @ISA);
BEGIN {
@ISA = qw( OnePackage OtherPackage );
$VERSION = '0.01';
# Put Perl code used in the BOOT: section here
XSLoader::load(__PACKAGE__, $VERSION);
}
# Put Perl code making calls into XSUBs here
```
###
The most hairy case
If the interdependence of your `BOOT:` section and Perl code is more complicated than this (e.g., the `BOOT:` section makes calls to Perl functions which make calls to XSUBs with prototypes), get rid of the `BOOT:` section altogether. Replace it with a function `onBOOT()`, and call it like this:
```
package YourPackage;
use XSLoader;
our ($VERSION, @ISA);
BEGIN {
@ISA = qw( OnePackage OtherPackage );
$VERSION = '0.01';
XSLoader::load(__PACKAGE__, $VERSION);
}
# Put Perl code used in onBOOT() function here; calls to XSUBs are
# prototype-checked.
onBOOT;
# Put Perl initialization code assuming that XS is initialized here
```
DIAGNOSTICS
-----------
`Can't find '%s' symbol in %s`
**(F)** The bootstrap symbol could not be found in the extension module.
`Can't load '%s' for module %s: %s`
**(F)** The loading or initialisation of the extension module failed. The detailed error follows.
`Undefined symbols present after loading %s: %s`
**(W)** As the message says, some symbols stay undefined although the extension module was correctly loaded and initialised. The list of undefined symbols follows.
LIMITATIONS
-----------
To reduce the overhead as much as possible, only one possible location is checked to find the extension DLL (this location is where `make install` would put the DLL). If not found, the search for the DLL is transparently delegated to `DynaLoader`, which looks for the DLL along the `@INC` list.
In particular, this is applicable to the structure of `@INC` used for testing not-yet-installed extensions. This means that running uninstalled extensions may have much more overhead than running the same extensions after `make install`.
KNOWN BUGS
-----------
The new simpler way to call `XSLoader::load()` with no arguments at all does not work on Perl 5.8.4 and 5.8.5.
BUGS
----
Please report any bugs or feature requests via the perlbug(1) utility.
SEE ALSO
---------
[DynaLoader](dynaloader)
AUTHORS
-------
Ilya Zakharevich originally extracted `XSLoader` from `DynaLoader`.
CPAN version is currently maintained by Sรฉbastien Aperghis-Tramoni <[email protected]>.
Previous maintainer was Michael G Schwern <[email protected]>.
COPYRIGHT & LICENSE
--------------------
Copyright (C) 1990-2011 by Larry Wall and others.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlbs2000 perlbs2000
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [gzip on BS2000](#gzip-on-BS2000)
+ [bison on BS2000](#bison-on-BS2000)
+ [Unpacking Perl Distribution on BS2000](#Unpacking-Perl-Distribution-on-BS2000)
+ [Compiling Perl on BS2000](#Compiling-Perl-on-BS2000)
+ [Testing Perl on BS2000](#Testing-Perl-on-BS2000)
+ [Installing Perl on BS2000](#Installing-Perl-on-BS2000)
+ [Using Perl in the Posix-Shell of BS2000](#Using-Perl-in-the-Posix-Shell-of-BS2000)
+ [Using Perl in "native" BS2000](#Using-Perl-in-%22native%22-BS2000)
+ [Floating point anomalies on BS2000](#Floating-point-anomalies-on-BS2000)
+ [Using PerlIO and different encodings on ASCII and EBCDIC partitions](#Using-PerlIO-and-different-encodings-on-ASCII-and-EBCDIC-partitions)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
+ [Mailing list](#Mailing-list)
* [HISTORY](#HISTORY)
NAME
----
perlbs2000 - building and installing Perl for BS2000.
**This document needs to be updated, but we don't know what it should say. Please submit comments to <https://github.com/Perl/perl5/issues>.**
SYNOPSIS
--------
This document will help you Configure, build, test and install Perl on BS2000 in the POSIX subsystem.
DESCRIPTION
-----------
This is a ported perl for the POSIX subsystem in BS2000 VERSION OSD V3.1A or later. It may work on other versions, but we started porting and testing it with 3.1A and are currently using Version V4.0A.
You may need the following GNU programs in order to install perl:
###
gzip on BS2000
We used version 1.2.4, which could be installed out of the box with one failure during 'make check'.
###
bison on BS2000
The yacc coming with BS2000 POSIX didn't work for us. So we had to use bison. We had to make a few changes to perl in order to use the pure (reentrant) parser of bison. We used version 1.25, but we had to add a few changes due to EBCDIC. See below for more details concerning yacc.
###
Unpacking Perl Distribution on BS2000
To extract an ASCII tar archive on BS2000 POSIX you need an ASCII filesystem (we used the mountpoint /usr/local/ascii for this). Now you extract the archive in the ASCII filesystem without I/O-conversion:
cd /usr/local/ascii export IO\_CONVERSION=NO gunzip < /usr/local/src/perl.tar.gz | pax -r
You may ignore the error message for the first element of the archive (this doesn't look like a tar archive / skipping to next file...), it's only the directory which will be created automatically anyway.
After extracting the archive you copy the whole directory tree to your EBCDIC filesystem. **This time you use I/O-conversion**:
cd /usr/local/src IO\_CONVERSION=YES cp -r /usr/local/ascii/perl5.005\_02 ./
###
Compiling Perl on BS2000
There is a "hints" file for BS2000 called hints.posix-bc (because posix-bc is the OS name given by `uname`) that specifies the correct values for most things. The major problem is (of course) the EBCDIC character set. We have german EBCDIC version.
Because of our problems with the native yacc we used GNU bison to generate a pure (=reentrant) parser for perly.y. So our yacc is really the following script:
-----8<-----/usr/local/bin/yacc-----8<----- #! /usr/bin/sh
# Bison as a reentrant yacc:
# save parameters: params="" while [[ $# -gt 1 ]]; do params="$params $1" shift done
# add flag %pure\_parser:
tmpfile=/tmp/bison.$$.y echo %pure\_parser > $tmpfile cat $1 >> $tmpfile
# call bison:
echo "/usr/local/bin/bison --yacc $params $1\t\t\t(Pure Parser)" /usr/local/bin/bison --yacc $params $tmpfile
# cleanup:
rm -f $tmpfile -----8<----------8<-----
We still use the normal yacc for a2p.y though!!! We made a softlink called byacc to distinguish between the two versions:
ln -s /usr/bin/yacc /usr/local/bin/byacc
We build perl using GNU make. We tried the native make once and it worked too.
###
Testing Perl on BS2000
We still got a few errors during `make test`. Some of them are the result of using bison. Bison prints *parser error* instead of *syntax error*, so we may ignore them. The following list shows our errors, your results may differ:
op/numconvert.......FAILED tests 1409-1440 op/regexp...........FAILED tests 483, 496 op/regexp\_noamp.....FAILED tests 483, 496 pragma/overload.....FAILED tests 152-153, 170-171 pragma/warnings.....FAILED tests 14, 82, 129, 155, 192, 205, 207 lib/bigfloat........FAILED tests 351-352, 355 lib/bigfltpm........FAILED tests 354-355, 358 lib/complex.........FAILED tests 267, 487 lib/dumper..........FAILED tests 43, 45 Failed 11/231 test scripts, 95.24% okay. 57/10595 subtests failed, 99.46% okay.
###
Installing Perl on BS2000
We have no nroff on BS2000 POSIX (yet), so we ignored any errors while installing the documentation.
###
Using Perl in the Posix-Shell of BS2000
BS2000 POSIX doesn't support the shebang notation (`#!/usr/local/bin/perl`), so you have to use the following lines instead:
: # use perl eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}' if 0; # ^ Run only under a shell
###
Using Perl in "native" BS2000
We don't have much experience with this yet, but try the following:
Copy your Perl executable to a BS2000 LLM using bs2cp:
`bs2cp /usr/local/bin/perl 'bs2:perl(perl,l)'`
Now you can start it with the following (SDF) command:
`/START-PROG FROM-FILE=*MODULE(PERL,PERL),PROG-MODE=*ANY,RUN-MODE=*ADV`
First you get the BS2000 commandline prompt ('\*'). Here you may enter your parameters, e.g. `-e 'print "Hello World!\\n";'` (note the double backslash!) or `-w` and the name of your Perl script. Filenames starting with `/` are searched in the Posix filesystem, others are searched in the BS2000 filesystem. You may even use wildcards if you put a `%` in front of your filename (e.g. `-w checkfiles.pl %*.c`). Read your C/C++ manual for additional possibilities of the commandline prompt (look for PARAMETER-PROMPTING).
###
Floating point anomalies on BS2000
There appears to be a bug in the floating point implementation on BS2000 POSIX systems such that calling int() on the product of a number and a small magnitude number is not the same as calling int() on the quotient of that number and a large magnitude number. For example, in the following Perl code:
```
my $x = 100000.0;
my $y = int($x * 1e-5) * 1e5; # '0'
my $z = int($x / 1e+5) * 1e5; # '100000'
print "\$y is $y and \$z is $z\n"; # $y is 0 and $z is 100000
```
Although one would expect the quantities $y and $z to be the same and equal to 100000 they will differ and instead will be 0 and 100000 respectively.
###
Using PerlIO and different encodings on ASCII and EBCDIC partitions
Since version 5.8 Perl uses the new PerlIO on BS2000. This enables you using different encodings per IO channel. For example you may use
```
use Encode;
open($f, ">:encoding(ascii)", "test.ascii");
print $f "Hello World!\n";
open($f, ">:encoding(posix-bc)", "test.ebcdic");
print $f "Hello World!\n";
open($f, ">:encoding(latin1)", "test.latin1");
print $f "Hello World!\n";
open($f, ">:encoding(utf8)", "test.utf8");
print $f "Hello World!\n";
```
to get two files containing "Hello World!\n" in ASCII, EBCDIC, ISO Latin-1 (in this example identical to ASCII) respective UTF-EBCDIC (in this example identical to normal EBCDIC). See the documentation of Encode::PerlIO for details.
As the PerlIO layer uses raw IO internally, all this totally ignores the type of your filesystem (ASCII or EBCDIC) and the IO\_CONVERSION environment variable. If you want to get the old behavior, that the BS2000 IO functions determine conversion depending on the filesystem PerlIO still is your friend. You use IO\_CONVERSION as usual and tell Perl, that it should use the native IO layer:
```
export IO_CONVERSION=YES
export PERLIO=stdio
```
Now your IO would be ASCII on ASCII partitions and EBCDIC on EBCDIC partitions. See the documentation of PerlIO (without `Encode::`!) for further possibilities.
AUTHORS
-------
Thomas Dorner
SEE ALSO
---------
[INSTALL](install), <perlport>.
###
Mailing list
If you are interested in the z/OS (formerly known as OS/390) and POSIX-BC (BS2000) ports of Perl then see the perl-mvs mailing list. To subscribe, send an empty message to [email protected].
See also:
```
https://lists.perl.org/list/perl-mvs.html
```
There are web archives of the mailing list at:
```
https://www.nntp.perl.org/group/perl.mvs/
```
HISTORY
-------
This document was originally written by Thomas Dorner for the 5.005 release of Perl.
This document was podified for the 5.6 release of perl 11 July 2000.
| programming_docs |
perl strict strict
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [HISTORY](#HISTORY)
NAME
----
strict - Perl pragma to restrict unsafe constructs
SYNOPSIS
--------
```
use strict;
use strict "vars";
use strict "refs";
use strict "subs";
use strict;
no strict "vars";
```
DESCRIPTION
-----------
The `strict` pragma disables certain Perl expressions that could behave unexpectedly or are difficult to debug, turning them into errors. The effect of this pragma is limited to the current file or scope block.
If no import list is supplied, all possible restrictions are assumed. (This is the safest mode to operate in, but is sometimes too strict for casual programming.) Currently, there are three possible things to be strict about: "subs", "vars", and "refs".
`strict refs`
This generates a runtime error if you use symbolic references (see <perlref>).
```
use strict 'refs';
$ref = \$foo;
print $$ref; # ok
$ref = "foo";
print $$ref; # runtime error; normally ok
$file = "STDOUT";
print $file "Hi!"; # error; note: no comma after $file
```
There is one exception to this rule:
```
$bar = \&{'foo'};
&$bar;
```
is allowed so that `goto &$AUTOLOAD` would not break under stricture.
`strict vars`
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of `my`, `our`, `state`, or `use vars`) nor fully qualified. (Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely `local` variable isn't good enough.) See ["my" in perlfunc](perlfunc#my), ["our" in perlfunc](perlfunc#our), ["state" in perlfunc](perlfunc#state), ["local" in perlfunc](perlfunc#local), and <vars>.
```
use strict 'vars';
$X::foo = 1; # ok, fully qualified
my $foo = 10; # ok, my() var
local $baz = 9; # blows up, $baz not declared before
package Cinna;
our $bar; # Declares $bar in current package
$bar = 'HgS'; # ok, global declared via pragma
```
The local() generated a compile-time error because you just touched a global name without fully qualifying it.
Because of their special use by sort(), the variables $a and $b are exempted from this check.
`strict subs`
This disables the poetry optimization, generating a compile-time error if you try to use a bareword identifier that's not a subroutine, unless it is a simple identifier (no colons) and that it appears in curly braces, on the left hand side of the `=>` symbol, or has the unary minus operator applied to it.
```
use strict 'subs';
$SIG{PIPE} = Plumber; # blows up
$SIG{PIPE} = "Plumber"; # fine: quoted string is always ok
$SIG{PIPE} = \&Plumber; # preferred form
```
See ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules).
HISTORY
-------
`strict 'subs'`, with Perl 5.6.1, erroneously permitted to use an unquoted compound identifier (e.g. `Foo::Bar`) as a hash key (before `=>` or inside curlies), but without forcing it always to a literal string.
Starting with Perl 5.8.1 strict is strict about its restrictions: if unknown restrictions are used, the strict pragma will abort with
```
Unknown 'strict' tag(s) '...'
```
As of version 1.04 (Perl 5.10), strict verifies that it is used as "strict" to avoid the dreaded Strict trap on case insensitive file systems.
perl TAP::Object TAP::Object
===========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [\_initialize](#_initialize)
- [\_croak](#_croak)
- [\_confess](#_confess)
- [\_construct](#_construct)
- [mk\_methods](#mk_methods)
NAME
----
TAP::Object - Base class that provides common functionality to all `TAP::*` modules
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
package TAP::Whatever;
use strict;
use base 'TAP::Object';
# new() implementation by TAP::Object
sub _initialize {
my ( $self, @args) = @_;
# initialize your object
return $self;
}
# ... later ...
my $obj = TAP::Whatever->new(@args);
```
DESCRIPTION
-----------
`TAP::Object` provides a default constructor and exception model for all `TAP::*` classes. Exceptions are raised using [Carp](carp).
METHODS
-------
###
Class Methods
#### `new`
Create a new object. Any arguments passed to `new` will be passed on to the ["\_initialize"](#_initialize) method. Returns a new object.
###
Instance Methods
####
`_initialize`
Initializes a new object. This method is a stub by default, you should override it as appropriate.
*Note:* ["new"](#new) expects you to return `$self` or raise an exception. See ["\_croak"](#_croak), and [Carp](carp).
####
`_croak`
Raise an exception using `croak` from [Carp](carp), eg:
```
$self->_croak( 'why me?', 'aaarrgh!' );
```
May also be called as a *class* method.
```
$class->_croak( 'this works too' );
```
####
`_confess`
Raise an exception using `confess` from [Carp](carp), eg:
```
$self->_confess( 'why me?', 'aaarrgh!' );
```
May also be called as a *class* method.
```
$class->_confess( 'this works too' );
```
####
`_construct`
Create a new instance of the specified class.
#### `mk_methods`
Create simple getter/setters.
```
__PACKAGE__->mk_methods(@method_names);
```
perl Tie::Memoize Tie::Memoize
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Inheriting from Tie::Memoize](#Inheriting-from-Tie::Memoize)
* [EXAMPLE](#EXAMPLE)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
Tie::Memoize - add data to hash when needed
SYNOPSIS
--------
```
require Tie::Memoize;
tie %hash, 'Tie::Memoize',
\&fetch, # The rest is optional
$DATA, \&exists,
{%ini_value}, {%ini_existence};
```
DESCRIPTION
-----------
This package allows a tied hash to autoload its values on the first access, and to use the cached value on the following accesses.
Only read-accesses (via fetching the value or `exists`) result in calls to the functions; the modify-accesses are performed as on a normal hash.
The required arguments during `tie` are the hash, the package, and the reference to the `FETCH`ing function. The optional arguments are an arbitrary scalar $data, the reference to the `EXISTS` function, and initial values of the hash and of the existence cache.
Both the `FETCH`ing function and the `EXISTS` functions have the same signature: the arguments are `$key, $data`; $data is the same value as given as argument during tie()ing. Both functions should return an empty list if the value does not exist. If `EXISTS` function is different from the `FETCH`ing function, it should return a TRUE value on success. The `FETCH`ing function should return the intended value if the key is valid.
Inheriting from **Tie::Memoize**
---------------------------------
The structure of the tied() data is an array reference with elements
```
0: cache of known values
1: cache of known existence of keys
2: FETCH function
3: EXISTS function
4: $data
```
The rest is for internal usage of this package. In particular, if TIEHASH is overwritten, it should call SUPER::TIEHASH.
EXAMPLE
-------
```
sub slurp {
my ($key, $dir) = shift;
open my $h, '<', "$dir/$key" or return;
local $/; <$h> # slurp it all
}
sub exists { my ($key, $dir) = shift; return -f "$dir/$key" }
tie %hash, 'Tie::Memoize', \&slurp, $directory, \&exists,
{ fake_file1 => $content1, fake_file2 => $content2 },
{ pretend_does_not_exists => 0, known_to_exist => 1 };
```
This example treats the slightly modified contents of $directory as a hash. The modifications are that the keys *fake\_file1* and *fake\_file2* fetch values $content1 and $content2, and *pretend\_does\_not\_exists* will never be accessed. Additionally, the existence of *known\_to\_exist* is never checked (so if it does not exists when its content is needed, the user of %hash may be confused).
BUGS
----
FIRSTKEY and NEXTKEY methods go through the keys which were already read, not all the possible keys of the hash.
AUTHOR
------
Ilya Zakharevich <mailto:[email protected]>.
perl ExtUtils::ParseXS ExtUtils::ParseXS
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORT](#EXPORT)
* [METHODS](#METHODS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::ParseXS - converts Perl XS code into C code
SYNOPSIS
--------
```
use ExtUtils::ParseXS;
my $pxs = ExtUtils::ParseXS->new;
$pxs->process_file( filename => 'foo.xs' );
$pxs->process_file( filename => 'foo.xs',
output => 'bar.c',
'C++' => 1,
typemap => 'path/to/typemap',
hiertype => 1,
except => 1,
versioncheck => 1,
linenumbers => 1,
optimize => 1,
prototypes => 1,
);
# Legacy non-OO interface using a singleton:
use ExtUtils::ParseXS qw(process_file);
process_file( filename => 'foo.xs' );
```
DESCRIPTION
-----------
`ExtUtils::ParseXS` 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. The compiler uses typemaps to determine how to map C function parameters and variables to Perl values.
The compiler will search for typemap files called *typemap*. It will use the following search path to find default typemaps, with the rightmost typemap taking precedence.
```
../../../typemap:../../typemap:../typemap:typemap
```
EXPORT
------
None by default. `process_file()` and/or `report_error_count()` may be exported upon request. Using the functional interface is discouraged.
METHODS
-------
$pxs->new() Returns a new, empty XS parser/compiler object.
$pxs->process\_file() This method processes an XS file and sends output to a C file. The method may be called as a function (this is the legacy interface) and will then use a singleton as invocant.
Named parameters control how the processing is done. The following parameters are accepted:
**C++**
Adds `extern "C"` to the C code. Default is false.
**hiertype** Retains `::` in type names so that C++ hierarchical types can be mapped. Default is false.
**except** Adds exception handling stubs to the C code. Default is false.
**typemap** Indicates that a user-supplied typemap should take precedence over the default typemaps. A single typemap may be specified as a string, or multiple typemaps can be specified in an array reference, with the last typemap having the highest precedence.
**prototypes** Generates prototype code for all xsubs. Default is false.
**versioncheck** Makes sure at run time that the object file (derived from the `.xs` file) and the `.pm` files have the same version number. Default is true.
**linenumbers** Adds `#line` directives to the C output so error messages will look like they came from the original XS file. Default is true.
**optimize** Enables certain optimizations. The only optimization that is currently affected is the use of *target*s by the output C code (see <perlguts>). Not optimizing may significantly slow down the generated code, but this is the way **xsubpp** of 5.005 and earlier operated. Default is to optimize.
**inout** Enable recognition of `IN`, `OUT_LIST` and `INOUT_LIST` declarations. Default is true.
**argtypes** Enable recognition of ANSI-like descriptions of function signature. Default is true.
**s** *Maintainer note:* I have no clue what this does. Strips function prefixes?
$pxs->report\_error\_count() This method returns the number of [a certain kind of] errors encountered during processing of the XS file.
The method may be called as a function (this is the legacy interface) and will then use a singleton as invocant.
AUTHOR
------
Based on xsubpp code, written by Larry Wall.
Maintained by:
* Ken Williams, <[email protected]>
* David Golden, <[email protected]>
* James Keenan, <[email protected]>
* Steffen Mueller, <[email protected]>
COPYRIGHT
---------
Copyright 2002-2014 by Ken Williams, David Golden and other contributors. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Based on the `ExtUtils::xsubpp` code by Larry Wall and the Perl 5 Porters, which was released under the same license terms.
SEE ALSO
---------
<perl>, ExtUtils::xsubpp, ExtUtils::MakeMaker, <perlxs>, <perlxstut>.
perl Fcntl Fcntl
=====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [EXPORTED SYMBOLS](#EXPORTED-SYMBOLS)
NAME
----
Fcntl - load the C Fcntl.h defines
SYNOPSIS
--------
```
use Fcntl;
use Fcntl qw(:DEFAULT :flock);
```
DESCRIPTION
-----------
This module is just a translation of the C *fcntl.h* file. Unlike the old mechanism of requiring a translated *fcntl.ph* file, this uses the **h2xs** program (see the Perl source distribution) and your native C compiler. This means that it has a far more likely chance of getting the numbers right.
NOTE
----
Only `#define` symbols get translated; you must still correctly pack up your own arguments to pass as args for locking functions, etc.
EXPORTED SYMBOLS
-----------------
By default your system's F\_\* and O\_\* constants (eg, F\_DUPFD and O\_CREAT) and the FD\_CLOEXEC constant are exported into your namespace.
You can request that the flock() constants (LOCK\_SH, LOCK\_EX, LOCK\_NB and LOCK\_UN) be provided by using the tag `:flock`. See [Exporter](exporter).
You can request that the old constants (FAPPEND, FASYNC, FCREAT, FDEFER, FEXCL, FNDELAY, FNONBLOCK, FSYNC, FTRUNC) be provided for compatibility reasons by using the tag `:Fcompat`. For new applications the newer versions of these constants are suggested (O\_APPEND, O\_ASYNC, O\_CREAT, O\_DEFER, O\_EXCL, O\_NDELAY, O\_NONBLOCK, O\_SYNC, O\_TRUNC).
For ease of use also the SEEK\_\* constants (for seek() and sysseek(), e.g. SEEK\_END) and the S\_I\* constants (for chmod() and stat()) are available for import. They can be imported either separately or using the tags `:seek` and `:mode`.
Please refer to your native fcntl(2), open(2), fseek(3), lseek(2) (equal to Perl's seek() and sysseek(), respectively), and chmod(2) documentation to see what constants are implemented in your system.
See <perlopentut> to learn about the uses of the O\_\* constants with sysopen().
See ["seek" in perlfunc](perlfunc#seek) and ["sysseek" in perlfunc](perlfunc#sysseek) about the SEEK\_\* constants.
See ["stat" in perlfunc](perlfunc#stat) about the S\_I\* constants.
perl CPAN::Plugin::Specfile CPAN::Plugin::Specfile
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [OPTIONS](#OPTIONS)
* [AUTHOR](#AUTHOR)
NAME
----
CPAN::Plugin::Specfile - Proof of concept implementation of a trivial CPAN::Plugin
SYNOPSIS
--------
```
# once in the cpan shell
o conf plugin_list push CPAN::Plugin::Specfile
# make permanent
o conf commit
# any time in the cpan shell to write a spec file
test Acme::Meta
# disable
# if it is the last in plugin_list:
o conf plugin_list pop
# otherwise, determine the index to splice:
o conf plugin_list
# and then use splice, e.g. to splice position 3:
o conf plugin_list splice 3 1
```
DESCRIPTION
-----------
Implemented as a post-test hook, this plugin writes a specfile after every successful test run. The content is also written to the terminal.
As a side effect, the timestamps of the written specfiles reflect the linear order of all dependencies.
**WARNING:** This code is just a small demo how to use the plugin system of the CPAN shell, not a full fledged spec file writer. Do not expect new features in this plugin.
### OPTIONS
The target directory to store the spec files in can be set using `dir` as in
```
o conf plugin_list push CPAN::Plugin::Specfile=dir,/tmp/specfiles-000042
```
The default directory for this is the `plugins/CPAN::Plugin::Specfile` directory in the *cpan\_home* directory.
AUTHOR
------
Andreas Koenig <[email protected]>, Branislav Zahradnik <[email protected]>
perl Encode::Encoding Encode::Encoding
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods you should implement](#Methods-you-should-implement)
+ [Other methods defined in Encode::Encodings](#Other-methods-defined-in-Encode::Encodings)
+ [Example: Encode::ROT13](#Example:-Encode::ROT13)
* [Why the heck Encode API is different?](#Why-the-heck-Encode-API-is-different?)
+ [Compiled Encodings](#Compiled-Encodings)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Encoding - Encode Implementation Base Class
SYNOPSIS
--------
```
package Encode::MyEncoding;
use parent qw(Encode::Encoding);
__PACKAGE__->Define(qw(myCanonical myAlias));
```
DESCRIPTION
-----------
As mentioned in [Encode](encode), encodings are (in the current implementation at least) defined as objects. The mapping of encoding name to object is via the `%Encode::Encoding` hash. Though you can directly manipulate this hash, it is strongly encouraged to use this base class module and add encode() and decode() methods.
###
Methods you should implement
You are strongly encouraged to implement methods below, at least either encode() or decode().
->encode($string [,$check]) MUST return the octet sequence representing *$string*.
* If *$check* is true, it SHOULD modify *$string* in place to remove the converted part (i.e. the whole string unless there is an error). If perlio\_ok() is true, SHOULD becomes MUST.
* If an error occurs, it SHOULD return the octet sequence for the fragment of string that has been converted and modify $string in-place to remove the converted part leaving it starting with the problem fragment. If perlio\_ok() is true, SHOULD becomes MUST.
* If *$check* is false then `encode` MUST make a "best effort" to convert the string - for example, by using a replacement character.
->decode($octets [,$check]) MUST return the string that *$octets* represents.
* If *$check* is true, it SHOULD modify *$octets* in place to remove the converted part (i.e. the whole sequence unless there is an error). If perlio\_ok() is true, SHOULD becomes MUST.
* If an error occurs, it SHOULD return the fragment of string that has been converted and modify $octets in-place to remove the converted part leaving it starting with the problem fragment. If perlio\_ok() is true, SHOULD becomes MUST.
* If *$check* is false then `decode` should make a "best effort" to convert the string - for example by using Unicode's "\x{FFFD}" as a replacement character.
If you want your encoding to work with <encoding> pragma, you should also implement the method below.
->cat\_decode($destination, $octets, $offset, $terminator [,$check]) MUST decode *$octets* with *$offset* and concatenate it to *$destination*. Decoding will terminate when $terminator (a string) appears in output. *$offset* will be modified to the last $octets position at end of decode. Returns true if $terminator appears output, else returns false.
###
Other methods defined in Encode::Encodings
You do not have to override methods shown below unless you have to.
->name Predefined As:
```
sub name { return shift->{'Name'} }
```
MUST return the string representing the canonical name of the encoding.
->mime\_name Predefined As:
```
sub mime_name{
return Encode::MIME::Name::get_mime_name(shift->name);
}
```
MUST return the string representing the IANA charset name of the encoding.
->renew Predefined As:
```
sub renew {
my $self = shift;
my $clone = bless { %$self } => ref($self);
$clone->{renewed}++;
return $clone;
}
```
This method reconstructs the encoding object if necessary. If you need to store the state during encoding, this is where you clone your object.
PerlIO ALWAYS calls this method to make sure it has its own private encoding object.
->renewed Predefined As:
```
sub renewed { $_[0]->{renewed} || 0 }
```
Tells whether the object is renewed (and how many times). Some modules emit `Use of uninitialized value in null operation` warning unless the value is numeric so return 0 for false.
->perlio\_ok() Predefined As:
```
sub perlio_ok {
return eval { require PerlIO::encoding } ? 1 : 0;
}
```
If your encoding does not support PerlIO for some reasons, just;
```
sub perlio_ok { 0 }
```
->needs\_lines() Predefined As:
```
sub needs_lines { 0 };
```
If your encoding can work with PerlIO but needs line buffering, you MUST define this method so it returns true. 7bit ISO-2022 encodings are one example that needs this. When this method is missing, false is assumed.
###
Example: Encode::ROT13
```
package Encode::ROT13;
use strict;
use parent qw(Encode::Encoding);
__PACKAGE__->Define('rot13');
sub encode($$;$){
my ($obj, $str, $chk) = @_;
$str =~ tr/A-Za-z/N-ZA-Mn-za-m/;
$_[1] = '' if $chk; # this is what in-place edit means
return $str;
}
# Jr pna or ynml yvxr guvf;
*decode = \&encode;
1;
```
Why the heck Encode API is different?
--------------------------------------
It should be noted that the *$check* behaviour is different from the outer public API. The logic is that the "unchecked" case is useful when the encoding is part of a stream which may be reporting errors (e.g. STDERR). In such cases, it is desirable to get everything through somehow without causing additional errors which obscure the original one. Also, the encoding is best placed to know what the correct replacement character is, so if that is the desired behaviour then letting low level code do it is the most efficient.
By contrast, if *$check* is true, the scheme above allows the encoding to do as much as it can and tell the layer above how much that was. What is lacking at present is a mechanism to report what went wrong. The most likely interface will be an additional method call to the object, or perhaps (to avoid forcing per-stream objects on otherwise stateless encodings) an additional parameter.
It is also highly desirable that encoding classes inherit from `Encode::Encoding` as a base class. This allows that class to define additional behaviour for all encoding objects.
```
package Encode::MyEncoding;
use parent qw(Encode::Encoding);
__PACKAGE__->Define(qw(myCanonical myAlias));
```
to create an object with `bless {Name => ...}, $class`, and call define\_encoding. They inherit their `name` method from `Encode::Encoding`.
###
Compiled Encodings
For the sake of speed and efficiency, most of the encodings are now supported via a *compiled form*: XS modules generated from UCM files. Encode provides the enc2xs tool to achieve that. Please see <enc2xs> for more details.
SEE ALSO
---------
<perlmod>, <enc2xs>
| programming_docs |
perl Test2::Hub::Interceptor::Terminator Test2::Hub::Interceptor::Terminator
===================================
CONTENTS
--------
* [NAME](#NAME)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Hub::Interceptor::Terminator - Exception class used by Test2::Hub::Interceptor
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::Perldoc::ToNroff Pod::Perldoc::ToNroff
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToNroff - let Perldoc convert Pod to nroff
SYNOPSIS
--------
```
perldoc -o nroff -d something.3 Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Man as a formatter class.
The following options are supported: center, date, fixed, fixedbold, fixeditalic, fixedbolditalic, quotes, release, section
Those options are explained in <Pod::Man>.
For example:
```
perldoc -o nroff -w center:Pod -d something.3 Some::Modulename
```
CAVEAT
------
This module may change to use a different pod-to-nroff formatter class in the future, and this may change what options are supported.
SEE ALSO
---------
<Pod::Man>, <Pod::Perldoc>, <Pod::Perldoc::ToMan>
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 Time::Seconds Time::Seconds
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [Bugs](#Bugs)
NAME
----
Time::Seconds - a simple API to convert seconds to other date values
SYNOPSIS
--------
```
use Time::Piece;
use Time::Seconds;
my $t = localtime;
$t += ONE_DAY;
my $t2 = localtime;
my $s = $t - $t2;
print "Difference is: ", $s->days, "\n";
```
DESCRIPTION
-----------
This module is part of the Time::Piece distribution. It allows the user to find out the number of minutes, hours, days, weeks or years in a given number of seconds. It is returned by Time::Piece when you delta two Time::Piece objects.
Time::Seconds also exports the following constants:
```
ONE_DAY
ONE_WEEK
ONE_HOUR
ONE_MINUTE
ONE_MONTH
ONE_YEAR
ONE_FINANCIAL_MONTH
LEAP_YEAR
NON_LEAP_YEAR
```
Since perl does not (yet?) support constant objects, these constants are in seconds only, so you cannot, for example, do this: `print ONE_WEEK->minutes;`
METHODS
-------
The following methods are available:
```
my $val = Time::Seconds->new(SECONDS)
$val->seconds;
$val->minutes;
$val->hours;
$val->days;
$val->weeks;
$val->months;
$val->financial_months; # 30 days
$val->years;
$val->pretty; # gives English representation of the delta
```
The usual arithmetic (+,-,+=,-=) is also available on the objects.
The methods make the assumption that there are 24 hours in a day, 7 days in a week, 365.24225 days in a year and 12 months in a year. (from The Calendar FAQ at http://www.tondering.dk/claus/calendar.html)
AUTHOR
------
Matt Sergeant, [email protected]
Tobias Brox, [email protected]
Balรกzs Szabรณ (dLux), [email protected]
COPYRIGHT AND LICENSE
----------------------
Copyright 2001, Larry Wall.
This module is free software, you may distribute it under the same terms as Perl.
Bugs
----
Currently the methods aren't as efficient as they could be, for reasons of clarity. This is probably a bad idea.
perl h2xs h2xs
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [EXAMPLES](#EXAMPLES)
+ [Extension based on .h and .c files](#Extension-based-on-.h-and-.c-files)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [LIMITATIONS of -x](#LIMITATIONS-of-x)
NAME
----
h2xs - convert .h C header files to Perl extensions
SYNOPSIS
--------
**h2xs** [**OPTIONS** ...] [headerfile ... [extra\_libraries]]
**h2xs** **-h**|**-?**|**--help**
DESCRIPTION
-----------
*h2xs* builds a Perl extension from C header files. The extension will include functions which can be used to retrieve the value of any #define statement which was in the C header files.
The *module\_name* will be used for the name of the extension. If module\_name is not supplied then the name of the first header file will be used, with the first character capitalized.
If the extension might need extra libraries, they should be included here. The extension Makefile.PL will take care of checking whether the libraries actually exist and how they should be loaded. The extra libraries should be specified in the form -lm -lposix, etc, just as on the cc command line. By default, the Makefile.PL will search through the library path determined by Configure. That path can be augmented by including arguments of the form **-L/another/library/path** in the extra-libraries argument.
In spite of its name, *h2xs* may also be used to create a skeleton pure Perl module. See the **-X** option.
OPTIONS
-------
**-A**, **--omit-autoload**
Omit all autoload facilities. This is the same as **-c** but also removes the `use AutoLoader` statement from the .pm file.
**-B**, **--beta-version**
Use an alpha/beta style version number. Causes version number to be "0.00\_01" unless **-v** is specified.
**-C**, **--omit-changes**
Omits creation of the *Changes* file, and adds a HISTORY section to the POD template.
**-F**, **--cpp-flags**=*addflags*
Additional flags to specify to C preprocessor when scanning header for function declarations. Writes these options in the generated *Makefile.PL* too.
**-M**, **--func-mask**=*regular expression*
selects functions/macros to process.
**-O**, **--overwrite-ok**
Allows a pre-existing extension directory to be overwritten.
**-P**, **--omit-pod**
Omit the autogenerated stub POD section.
**-X**, **--omit-XS**
Omit the XS portion. Used to generate a skeleton pure Perl module. `-c` and `-f` are implicitly enabled.
**-a**, **--gen-accessors**
Generate an accessor method for each element of structs and unions. The generated methods are named after the element name; will return the current value of the element if called without additional arguments; and will set the element to the supplied value (and return the new value) if called with an additional argument. Embedded structures and unions are returned as a pointer rather than the complete structure, to facilitate chained calls.
These methods all apply to the Ptr type for the structure; additionally two methods are constructed for the structure type itself, `_to_ptr` which returns a Ptr type pointing to the same structure, and a `new` method to construct and return a new structure, initialised to zeroes.
**-b**, **--compat-version**=*version*
Generates a .pm file which is backwards compatible with the specified perl version.
For versions < 5.6.0, the changes are. - no use of 'our' (uses 'use vars' instead) - no 'use warnings'
Specifying a compatibility version higher than the version of perl you are using to run h2xs will have no effect. If unspecified h2xs will default to compatibility with the version of perl you are using to run h2xs.
**-c**, **--omit-constant**
Omit `constant()` from the .xs file and corresponding specialised `AUTOLOAD` from the .pm file.
**-d**, **--debugging**
Turn on debugging messages.
**-e**, **--omit-enums**=[*regular expression*] If *regular expression* is not given, skip all constants that are defined in a C enumeration. Otherwise skip only those constants that are defined in an enum whose name matches *regular expression*.
Since *regular expression* is optional, make sure that this switch is followed by at least one other switch if you omit *regular expression* and have some pending arguments such as header-file names. This is ok:
```
h2xs -e -n Module::Foo foo.h
```
This is not ok:
```
h2xs -n Module::Foo -e foo.h
```
In the latter, foo.h is taken as *regular expression*.
**-f**, **--force**
Allows an extension to be created for a header even if that header is not found in standard include directories.
**-g**, **--global**
Include code for safely storing static data in the .xs file. Extensions that do no make use of static data can ignore this option.
**-h**, **-?**, **--help**
Print the usage, help and version for this h2xs and exit.
**-k**, **--omit-const-func**
For function arguments declared as `const`, omit the const attribute in the generated XS code.
**-m**, **--gen-tied-var**
**Experimental**: for each variable declared in the header file(s), declare a perl variable of the same name magically tied to the C variable.
**-n**, **--name**=*module\_name*
Specifies a name to be used for the extension, e.g., -n RPC::DCE
**-o**, **--opaque-re**=*regular expression*
Use "opaque" data type for the C types matched by the regular expression, even if these types are `typedef`-equivalent to types from typemaps. Should not be used without **-x**.
This may be useful since, say, types which are `typedef`-equivalent to integers may represent OS-related handles, and one may want to work with these handles in OO-way, as in `$handle->do_something()`. Use `-o .` if you want to handle all the `typedef`ed types as opaque types.
The type-to-match is whitewashed (except for commas, which have no whitespace before them, and multiple `*` which have no whitespace between them).
**-p**, **--remove-prefix**=*prefix*
Specify a prefix which should be removed from the Perl function names, e.g., -p sec\_rgy\_ This sets up the XS **PREFIX** keyword and removes the prefix from functions that are autoloaded via the `constant()` mechanism.
**-s**, **--const-subs**=*sub1,sub2*
Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine. These macros are assumed to have a return type of **char \***, e.g., -s sec\_rgy\_wildcard\_name,sec\_rgy\_wildcard\_sid.
**-t**, **--default-type**=*type*
Specify the internal type that the constant() mechanism uses for macros. The default is IV (signed integer). Currently all macros found during the header scanning process will be assumed to have this type. Future versions of `h2xs` may gain the ability to make educated guesses.
**--use-new-tests**
When **--compat-version** (**-b**) is present the generated tests will use `Test::More` rather than `Test` which is the default for versions before 5.6.2. `Test::More` will be added to PREREQ\_PM in the generated `Makefile.PL`.
**--use-old-tests**
Will force the generation of test code that uses the older `Test` module.
**--skip-exporter**
Do not use `Exporter` and/or export any symbol.
**--skip-ppport**
Do not use `Devel::PPPort`: no portability to older version.
**--skip-autoloader**
Do not use the module `AutoLoader`; but keep the constant() function and `sub AUTOLOAD` for constants.
**--skip-strict**
Do not use the pragma `strict`.
**--skip-warnings**
Do not use the pragma `warnings`.
**-v**, **--version**=*version*
Specify a version number for this extension. This version number is added to the templates. The default is 0.01, or 0.00\_01 if `-B` is specified. The version specified should be numeric.
**-x**, **--autogen-xsubs**
Automatically generate XSUBs basing on function declarations in the header file. The package `C::Scan` should be installed. If this option is specified, the name of the header file may look like `NAME1,NAME2`. In this case NAME1 is used instead of the specified string, but XSUBs are emitted only for the declarations included from file NAME2.
Note that some types of arguments/return-values for functions may result in XSUB-declarations/typemap-entries which need hand-editing. Such may be objects which cannot be converted from/to a pointer (like `long long`), pointers to functions, or arrays. See also the section on ["LIMITATIONS of **-x**"](#LIMITATIONS-of-x).
EXAMPLES
--------
```
# Default behavior, extension is Rusers
h2xs rpcsvc/rusers
# Same, but extension is RUSERS
h2xs -n RUSERS rpcsvc/rusers
# Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
h2xs rpcsvc::rusers
# Extension is ONC::RPC. Still finds <rpcsvc/rusers.h>
h2xs -n ONC::RPC rpcsvc/rusers
# Without constant() or AUTOLOAD
h2xs -c rpcsvc/rusers
# Creates templates for an extension named RPC
h2xs -cfn RPC
# Extension is ONC::RPC.
h2xs -cfn ONC::RPC
# Extension is a pure Perl module with no XS code.
h2xs -X My::Module
# Extension is Lib::Foo which works at least with Perl5.005_03.
# Constants are created for all #defines and enums h2xs can find
# in foo.h.
h2xs -b 5.5.3 -n Lib::Foo foo.h
# Extension is Lib::Foo which works at least with Perl5.005_03.
# Constants are created for all #defines but only for enums
# whose names do not start with 'bar_'.
h2xs -b 5.5.3 -e '^bar_' -n Lib::Foo foo.h
# Makefile.PL will look for library -lrpc in
# additional directory /opt/net/lib
h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
# Extension is DCE::rgynbase
# prefix "sec_rgy_" is dropped from perl function names
h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
# Extension is DCE::rgynbase
# prefix "sec_rgy_" is dropped from perl function names
# subroutines are created for sec_rgy_wildcard_name and
# sec_rgy_wildcard_sid
h2xs -n DCE::rgynbase -p sec_rgy_ \
-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
# Make XS without defines in perl.h, but with function declarations
# visible from perl.h. Name of the extension is perl1.
# When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
# Extra backslashes below because the string is passed to shell.
# Note that a directory with perl header files would
# be added automatically to include path.
h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
# Same with function declaration in proto.h as visible from perl.h.
h2xs -xAn perl2 perl.h,proto.h
# Same but select only functions which match /^av_/
h2xs -M '^av_' -xAn perl2 perl.h,proto.h
# Same but treat SV* etc as "opaque" types
h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
```
###
Extension based on *.h* and *.c* files
Suppose that you have some C files implementing some functionality, and the corresponding header files. How to create an extension which makes this functionality accessible in Perl? The example below assumes that the header files are *interface\_simple.h* and *interface\_hairy.h*, and you want the perl module be named as `Ext::Ension`. If you need some preprocessor directives and/or linking with external libraries, see the flags `-F`, `-L` and `-l` in ["OPTIONS"](#OPTIONS).
Find the directory name Start with a dummy run of h2xs:
```
h2xs -Afn Ext::Ension
```
The only purpose of this step is to create the needed directories, and let you know the names of these directories. From the output you can see that the directory for the extension is *Ext/Ension*.
Copy C files Copy your header files and C files to this directory *Ext/Ension*.
Create the extension Run h2xs, overwriting older autogenerated files:
```
h2xs -Oxan Ext::Ension interface_simple.h interface_hairy.h
```
h2xs looks for header files *after* changing to the extension directory, so it will find your header files OK.
Archive and test As usual, run
```
cd Ext/Ension
perl Makefile.PL
make dist
make
make test
```
Hints It is important to do `make dist` as early as possible. This way you can easily merge(1) your changes to autogenerated files if you decide to edit your `.h` files and rerun h2xs.
Do not forget to edit the documentation in the generated *.pm* file.
Consider the autogenerated files as skeletons only, you may invent better interfaces than what h2xs could guess.
Consider this section as a guideline only, some other options of h2xs may better suit your needs.
ENVIRONMENT
-----------
No environment variables are used.
AUTHOR
------
Larry Wall and others
SEE ALSO
---------
<perl>, <perlxstut>, <ExtUtils::MakeMaker>, and [AutoLoader](autoloader).
DIAGNOSTICS
-----------
The usual warnings if it cannot read or write the files involved.
LIMITATIONS of **-x**
----------------------
*h2xs* would not distinguish whether an argument to a C function which is of the form, say, `int *`, is an input, output, or input/output parameter. In particular, argument declarations of the form
```
int
foo(n)
int *n
```
should be better rewritten as
```
int
foo(n)
int &n
```
if `n` is an input parameter.
Additionally, *h2xs* has no facilities to intuit that a function
```
int
foo(addr,l)
char *addr
int l
```
takes a pair of address and length of data at this address, so it is better to rewrite this function as
```
int
foo(sv)
SV *addr
PREINIT:
STRLEN len;
char *s;
CODE:
s = SvPV(sv,len);
RETVAL = foo(s, len);
OUTPUT:
RETVAL
```
or alternately
```
static int
my_foo(SV *sv)
{
STRLEN len;
char *s = SvPV(sv,len);
return foo(s, len);
}
MODULE = foo PACKAGE = foo PREFIX = my_
int
foo(sv)
SV *sv
```
See <perlxs> and <perlxstut> for additional details.
perl Devel::SelfStubber Devel::SelfStubber
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Devel::SelfStubber - generate stubs for a SelfLoading module
SYNOPSIS
--------
To generate just the stubs:
```
use Devel::SelfStubber;
Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR');
```
or to generate the whole module with stubs inserted correctly
```
use Devel::SelfStubber;
$Devel::SelfStubber::JUST_STUBS=0;
Devel::SelfStubber->stub('MODULENAME','MY_LIB_DIR');
```
MODULENAME is the Perl module name, e.g. Devel::SelfStubber, NOT 'Devel/SelfStubber' or 'Devel/SelfStubber.pm'.
MY\_LIB\_DIR defaults to '.' if not present.
DESCRIPTION
-----------
Devel::SelfStubber prints the stubs you need to put in the module before the \_\_DATA\_\_ token (or you can get it to print the entire module with stubs correctly placed). The stubs ensure that if a method is called, it will get loaded. They are needed specifically for inherited autoloaded methods.
This is best explained using the following example:
Assume four classes, A,B,C & D.
A is the root class, B is a subclass of A, C is a subclass of B, and D is another subclass of A.
```
A
/ \
B D
/
C
```
If D calls an autoloaded method 'foo' which is defined in class A, then the method is loaded into class A, then executed. If C then calls method 'foo', and that method was reimplemented in class B, but set to be autoloaded, then the lookup mechanism never gets to the AUTOLOAD mechanism in B because it first finds the method already loaded in A, and so erroneously uses that. If the method foo had been stubbed in B, then the lookup mechanism would have found the stub, and correctly loaded and used the sub from B.
So, for classes and subclasses to have inheritance correctly work with autoloading, you need to ensure stubs are loaded.
The SelfLoader can load stubs automatically at module initialization with the statement 'SelfLoader->load\_stubs()';, but you may wish to avoid having the stub loading overhead associated with your initialization (though note that the SelfLoader::load\_stubs method will be called sooner or later - at latest when the first sub is being autoloaded). In this case, you can put the sub stubs before the \_\_DATA\_\_ token. This can be done manually, but this module allows automatic generation of the stubs.
By default it just prints the stubs, but you can set the global $Devel::SelfStubber::JUST\_STUBS to 0 and it will print out the entire module with the stubs positioned correctly.
At the very least, this is useful to see what the SelfLoader thinks are stubs - in order to ensure future versions of the SelfStubber remain in step with the SelfLoader, the SelfStubber actually uses the SelfLoader to determine which stubs are needed.
| programming_docs |
perl charnames charnames
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LOOSE MATCHES](#LOOSE-MATCHES)
* [ALIASES](#ALIASES)
* [CUSTOM ALIASES](#CUSTOM-ALIASES)
* [charnames::string\_vianame(name)](#charnames::string_vianame(name))
* [charnames::vianame(name)](#charnames::vianame(name))
* [charnames::viacode(code)](#charnames::viacode(code))
* [CUSTOM TRANSLATORS](#CUSTOM-TRANSLATORS)
* [BUGS](#BUGS)
NAME
----
charnames - access to Unicode character names and named character sequences; also define character names
SYNOPSIS
--------
```
use charnames ':full';
print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
print "\N{LATIN CAPITAL LETTER E WITH VERTICAL LINE BELOW}",
" is an officially named sequence of two Unicode characters\n";
use charnames ':loose';
print "\N{Greek small-letter sigma}",
"can be used to ignore case, underscores, most blanks,"
"and when you aren't sure if the official name has hyphens\n";
use charnames ':short';
print "\N{greek:Sigma} is an upper-case sigma.\n";
use charnames qw(cyrillic greek);
print "\N{sigma} is Greek sigma, and \N{be} is Cyrillic b.\n";
use utf8;
use charnames ":full", ":alias" => {
e_ACUTE => "LATIN SMALL LETTER E WITH ACUTE",
mychar => 0xE8000, # Private use area
"่ช่ปข่ปใซไนใไบบ" => "BICYCLIST"
};
print "\N{e_ACUTE} is a small letter e with an acute.\n";
print "\N{mychar} allows me to name private use characters.\n";
print "And I can create synonyms in other languages,",
" such as \N{่ช่ปข่ปใซไนใไบบ} for "BICYCLIST (U+1F6B4)\n";
use charnames ();
print charnames::viacode(0x1234); # prints "ETHIOPIC SYLLABLE SEE"
printf "%04X", charnames::vianame("GOTHIC LETTER AHSA"); # prints
# "10330"
print charnames::vianame("LATIN CAPITAL LETTER A"); # prints 65 on
# ASCII platforms;
# 193 on EBCDIC
print charnames::string_vianame("LATIN CAPITAL LETTER A"); # prints "A"
```
DESCRIPTION
-----------
Pragma `use charnames` is used to gain access to the names of the Unicode characters and named character sequences, and to allow you to define your own character and character sequence names.
All forms of the pragma enable use of the following 3 functions:
* ["charnames::string\_vianame(*name*)"](#charnames%3A%3Astring_vianame%28name%29) for run-time lookup of a either a character name or a named character sequence, returning its string representation
* ["charnames::vianame(*name*)"](#charnames%3A%3Avianame%28name%29) for run-time lookup of a character name (but not a named character sequence) to get its ordinal value (code point)
* ["charnames::viacode(*code*)"](#charnames%3A%3Aviacode%28code%29) for run-time lookup of a code point to get its Unicode name.
Starting in Perl v5.16, any occurrence of `\N{*CHARNAME*}` sequences in a double-quotish string automatically loads this module with arguments `:full` and `:short` (described below) if it hasn't already been loaded with different arguments, in order to compile the named Unicode character into position in the string. Prior to v5.16, an explicit `use charnames` was required to enable this usage. (However, prior to v5.16, the form `"use charnames ();"` did not enable `\N{*CHARNAME*}`.)
Note that `\N{U+*...*}`, where the *...* is a hexadecimal number, also inserts a character into a string. The character it inserts is the one whose Unicode code point (ordinal value) is equal to the number. For example, `"\N{U+263a}"` is the Unicode (white background, black foreground) smiley face equivalent to `"\N{WHITE SMILING FACE}"`. Also note, `\N{*...*}` can mean a regex quantifier instead of a character name, when the *...* is a number (or comma separated pair of numbers (see ["QUANTIFIERS" in perlreref](perlreref#QUANTIFIERS)), and is not related to this pragma.
The `charnames` pragma supports arguments `:full`, `:loose`, `:short`, script names and [customized aliases](#CUSTOM-ALIASES).
If `:full` is present, for expansion of `\N{*CHARNAME*}`, the string *CHARNAME* is first looked up in the list of standard Unicode character names.
`:loose` is a variant of `:full` which allows *CHARNAME* to be less precisely specified. Details are in ["LOOSE MATCHES"](#LOOSE-MATCHES).
If `:short` is present, and *CHARNAME* has the form `*SCRIPT*:*CNAME*`, then *CNAME* is looked up as a letter in script *SCRIPT*, as described in the next paragraph. Or, if `use charnames` is used with script name arguments, then for `\N{*CHARNAME*}` the name *CHARNAME* is looked up as a letter in the given scripts (in the specified order). Customized aliases can override these, and are explained in ["CUSTOM ALIASES"](#CUSTOM-ALIASES).
For lookup of *CHARNAME* inside a given script *SCRIPTNAME*, this pragma looks in the table of standard Unicode names for the names
```
SCRIPTNAME CAPITAL LETTER CHARNAME
SCRIPTNAME SMALL LETTER CHARNAME
SCRIPTNAME LETTER CHARNAME
```
If *CHARNAME* is all lowercase, then the `CAPITAL` variant is ignored, otherwise the `SMALL` variant is ignored, and both *CHARNAME* and *SCRIPTNAME* are converted to all uppercase for look-up. Other than that, both of them follow [loose](#LOOSE-MATCHES) rules if `:loose` is also specified; strict otherwise.
Note that `\N{...}` is compile-time; it's a special form of string constant used inside double-quotish strings; this means that you cannot use variables inside the `\N{...}`. If you want similar run-time functionality, use [charnames::string\_vianame()](#charnames%3A%3Astring_vianame%28name%29).
Note, starting in Perl 5.18, the name `BELL` refers to the Unicode character U+1F514, instead of the traditional U+0007. For the latter, use `ALERT` or `BEL`.
It is a syntax error to use `\N{NAME}` where `NAME` is unknown.
For `\N{NAME}`, it is a fatal error if `use bytes` is in effect and the input name is that of a character that won't fit into a byte (i.e., whose ordinal is above 255).
Otherwise, any string that includes a `\N{*charname*}` or `\N{U+*code point*}` will automatically have Unicode rules (see ["Byte and Character Semantics" in perlunicode](perlunicode#Byte-and-Character-Semantics)).
LOOSE MATCHES
--------------
By specifying `:loose`, Unicode's [loose character name matching](http://www.unicode.org/reports/tr44#Matching_Rules) rules are selected instead of the strict exact match used otherwise. That means that *CHARNAME* doesn't have to be so precisely specified. Upper/lower case doesn't matter (except with scripts as mentioned above), nor do any underscores, and the only hyphens that matter are those at the beginning or end of a word in the name (with one exception: the hyphen in U+1180 `HANGUL JUNGSEONG O-E` does matter). Also, blanks not adjacent to hyphens don't matter. The official Unicode names are quite variable as to where they use hyphens versus spaces to separate word-like units, and this option allows you to not have to care as much. The reason non-medial hyphens matter is because of cases like U+0F60 `TIBETAN LETTER -A` versus U+0F68 `TIBETAN LETTER A`. The hyphen here is significant, as is the space before it, and so both must be included.
`:loose` slows down look-ups by a factor of 2 to 3 versus `:full`, but the trade-off may be worth it to you. Each individual look-up takes very little time, and the results are cached, so the speed difference would become a factor only in programs that do look-ups of many different spellings, and probably only when those look-ups are through `vianame()` and `string_vianame()`, since `\N{...}` look-ups are done at compile time.
ALIASES
-------
Starting in Unicode 6.1 and Perl v5.16, Unicode defines many abbreviations and names that were formerly Perl extensions, and some additional ones that Perl did not previously accept. The list is getting too long to reproduce here, but you can get the complete list from the Unicode web site: <http://www.unicode.org/Public/UNIDATA/NameAliases.txt>.
Earlier versions of Perl accepted almost all the 6.1 names. These were most extensively documented in the v5.14 version of this pod: <http://perldoc.perl.org/5.14.0/charnames.html#ALIASES>.
CUSTOM ALIASES
---------------
You can add customized aliases to standard (`:full`) Unicode naming conventions. The aliases override any standard definitions, so, if you're twisted enough, you can change `"\N{LATIN CAPITAL LETTER A}"` to mean `"B"`, etc.
Aliases must begin with a character that is alphabetic. After that, each may contain any combination of word (`\w`) characters, SPACE (U+0020), HYPHEN-MINUS (U+002D), LEFT PARENTHESIS (U+0028), and RIGHT PARENTHESIS (U+0029). These last two should never have been allowed in names, and are retained for backwards compatibility only, and may be deprecated and removed in future releases of Perl, so don't use them for new names. (More precisely, the first character of a name you specify must be something that matches all of `\p{ID_Start}`, `\p{Alphabetic}`, and `\p{Gc=Letter}`. This makes sure it is what any reasonable person would view as an alphabetic character. And, the continuation characters that match `\w` must also match `\p{ID_Continue}`.) Starting with Perl v5.18, any Unicode characters meeting the above criteria may be used; prior to that only Latin1-range characters were acceptable.
An alias can map to either an official Unicode character name (not a loose matched name) or to a numeric code point (ordinal). The latter is useful for assigning names to code points in Unicode private use areas such as U+E800 through U+F8FF. A numeric code point must be a non-negative integer, or a string beginning with `"U+"` or `"0x"` with the remainder considered to be a hexadecimal integer. A literal numeric constant must be unsigned; it will be interpreted as hex if it has a leading zero or contains non-decimal hex digits; otherwise it will be interpreted as decimal. If it begins with `"U+"`, it is interpreted as the Unicode code point; otherwise it is interpreted as native. (Only code points below 256 can differ between Unicode and native.) Thus `U+41` is always the Latin letter "A"; but `0x41` can be "NO-BREAK SPACE" on EBCDIC platforms.
Aliases are added either by the use of anonymous hashes:
```
use charnames ":alias" => {
e_ACUTE => "LATIN SMALL LETTER E WITH ACUTE",
mychar1 => 0xE8000,
};
my $str = "\N{e_ACUTE}";
```
or by using a file containing aliases:
```
use charnames ":alias" => "pro";
```
This will try to read `"unicore/pro_alias.pl"` from the `@INC` path. This file should return a list in plain perl:
```
(
A_GRAVE => "LATIN CAPITAL LETTER A WITH GRAVE",
A_CIRCUM => "LATIN CAPITAL LETTER A WITH CIRCUMFLEX",
A_DIAERES => "LATIN CAPITAL LETTER A WITH DIAERESIS",
A_TILDE => "LATIN CAPITAL LETTER A WITH TILDE",
A_BREVE => "LATIN CAPITAL LETTER A WITH BREVE",
A_RING => "LATIN CAPITAL LETTER A WITH RING ABOVE",
A_MACRON => "LATIN CAPITAL LETTER A WITH MACRON",
mychar2 => "U+E8001",
);
```
Both these methods insert `":full"` automatically as the first argument (if no other argument is given), and you can give the `":full"` explicitly as well, like
```
use charnames ":full", ":alias" => "pro";
```
`":loose"` has no effect with these. Input names must match exactly, using `":full"` rules.
Also, both these methods currently allow only single characters to be named. To name a sequence of characters, use a [custom translator](#CUSTOM-TRANSLATORS) (described below).
charnames::string\_vianame(*name*)
-----------------------------------
This is a runtime equivalent to `\N{...}`. *name* can be any expression that evaluates to a name accepted by `\N{...}` under the [`:full` option](#DESCRIPTION) to `charnames`. In addition, any other options for the controlling `"use charnames"` in the same scope apply, like `:loose` or any [script list, `:short` option](#DESCRIPTION), or [custom aliases](#CUSTOM-ALIASES) you may have defined.
The only differences are due to the fact that `string_vianame` is run-time and `\N{}` is compile time. You can't interpolate inside a `\N{}`, (so `\N{$variable}` doesn't work); and if the input name is unknown, `string_vianame` returns `undef` instead of it being a syntax error.
charnames::vianame(*name*)
---------------------------
This is similar to `string_vianame`. The main difference is that under most circumstances, `vianame` returns an ordinal code point, whereas `string_vianame` returns a string. For example,
```
printf "U+%04X", charnames::vianame("FOUR TEARDROP-SPOKED ASTERISK");
```
prints "U+2722".
This leads to the other two differences. Since a single code point is returned, the function can't handle named character sequences, as these are composed of multiple characters (it returns `undef` for these. And, the code point can be that of any character, even ones that aren't legal under the `use bytes` pragma,
See ["BUGS"](#BUGS) for the circumstances in which the behavior differs from that described above.
charnames::viacode(*code*)
---------------------------
Returns the full name of the character indicated by the numeric code. For example,
```
print charnames::viacode(0x2722);
```
prints "FOUR TEARDROP-SPOKED ASTERISK".
The name returned is the "best" (defined below) official name or alias for the code point, if available; otherwise your custom alias for it, if defined; otherwise `undef`. This means that your alias will only be returned for code points that don't have an official Unicode name (nor alias) such as private use code points.
If you define more than one name for the code point, it is indeterminate which one will be returned.
As mentioned, the function returns `undef` if no name is known for the code point. In Unicode the proper name for these is the empty string, which `undef` stringifies to. (If you ask for a code point past the legal Unicode maximum of U+10FFFF that you haven't assigned an alias to, you get `undef` plus a warning.)
The input number must be a non-negative integer, or a string beginning with `"U+"` or `"0x"` with the remainder considered to be a hexadecimal integer. A literal numeric constant must be unsigned; it will be interpreted as hex if it has a leading zero or contains non-decimal hex digits; otherwise it will be interpreted as decimal. If it begins with `"U+"`, it is interpreted as the Unicode code point; otherwise it is interpreted as native. (Only code points below 256 can differ between Unicode and native.) Thus `U+41` is always the Latin letter "A"; but `0x41` can be "NO-BREAK SPACE" on EBCDIC platforms.
As mentioned above under ["ALIASES"](#ALIASES), Unicode 6.1 defines extra names (synonyms or aliases) for some code points, most of which were already available as Perl extensions. All these are accepted by `\N{...}` and the other functions in this module, but `viacode` has to choose which one name to return for a given input code point, so it returns the "best" name. To understand how this works, it is helpful to know more about the Unicode name properties. All code points actually have only a single name, which (starting in Unicode 2.0) can never change once a character has been assigned to the code point. But mistakes have been made in assigning names, for example sometimes a clerical error was made during the publishing of the Standard which caused words to be misspelled, and there was no way to correct those. The Name\_Alias property was eventually created to handle these situations. If a name was wrong, a corrected synonym would be published for it, using Name\_Alias. `viacode` will return that corrected synonym as the "best" name for a code point. (It is even possible, though it hasn't happened yet, that the correction itself will need to be corrected, and so another Name\_Alias can be created for that code point; `viacode` will return the most recent correction.)
The Unicode name for each of the control characters (such as LINE FEED) is the empty string. However almost all had names assigned by other standards, such as the ASCII Standard, or were in common use. `viacode` returns these names as the "best" ones available. Unicode 6.1 has created Name\_Aliases for each of them, including alternate names, like NEW LINE. `viacode` uses the original name, "LINE FEED" in preference to the alternate. Similarly the name returned for U+FEFF is "ZERO WIDTH NO-BREAK SPACE", not "BYTE ORDER MARK".
Until Unicode 6.1, the 4 control characters U+0080, U+0081, U+0084, and U+0099 did not have names nor aliases. To preserve backwards compatibility, any alias you define for these code points will be returned by this function, in preference to the official name.
Some code points also have abbreviated names, such as "LF" or "NL". `viacode` never returns these.
Because a name correction may be added in future Unicode releases, the name that `viacode` returns may change as a result. This is a rare event, but it does happen.
CUSTOM TRANSLATORS
-------------------
The mechanism of translation of `\N{...}` escapes is general and not hardwired into *charnames.pm*. A module can install custom translations (inside the scope which `use`s the module) with the following magic incantation:
```
sub import {
shift;
$^H{charnames} = \&translator;
}
```
Here translator() is a subroutine which takes *CHARNAME* as an argument, and returns text to insert into the string instead of the `\N{*CHARNAME*}` escape.
This is the only way you can create a custom named sequence of code points.
Since the text to insert should be different in `bytes` mode and out of it, the function should check the current state of `bytes`-flag as in:
```
use bytes (); # for $bytes::hint_bits
sub translator {
if ($^H & $bytes::hint_bits) {
return bytes_translator(@_);
}
else {
return utf8_translator(@_);
}
}
```
See ["CUSTOM ALIASES"](#CUSTOM-ALIASES) above for restrictions on *CHARNAME*.
Of course, `vianame`, `viacode`, and `string_vianame` would need to be overridden as well.
BUGS
----
vianame() normally returns an ordinal code point, but when the input name is of the form `U+...`, it returns a chr instead. In this case, if `use bytes` is in effect and the character won't fit into a byte, it returns `undef` and raises a warning.
Since evaluation of the translation function (see ["CUSTOM TRANSLATORS"](#CUSTOM-TRANSLATORS)) happens in the middle of compilation (of a string literal), the translation function should not do any `eval`s or `require`s. This restriction should be lifted (but is low priority) in a future version of Perl.
perl Amiga::ARexx Amiga::ARexx
============
CONTENTS
--------
* [NAME](#NAME)
* [ABSTRACT](#ABSTRACT)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Amiga::ARexx METHODS](#Amiga::ARexx-METHODS)
+ [new](#new)
- [HostName](#HostName)
+ [wait](#wait)
- [TimeOut](#TimeOut)
+ [getmsg](#getmsg)
+ [signal](#signal)
+ [DoRexx](#DoRexx)
* [Amiga::ARexx::Msg METHODS](#Amiga::ARexx::Msg-METHODS)
+ [message](#message)
+ [reply](#reply)
+ [setvar](#setvar)
+ [getvar](#getvar)
+ [EXPORT](#EXPORT)
+ [Exportable constants](#Exportable-constants)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Amiga::ARexx - Perl extension for ARexx support
ABSTRACT
--------
This a perl class / module to enable you to use ARexx with your perlscript. Creating a function host or executing scripts in other hosts. The API is loosley modeled on the python arexx module supplied by with AmigaOS4.1
SYNOPSIS
--------
```
# Create a new host
use Amiga::ARexx;
my $host = Amiga::ARexx->new('HostName' => "PERLREXX" );
# Wait for and process rexxcommands
my $alive = 1;
while ($alive)
{
$host->wait();
my $msg = $host->getmsg();
while($msg)
{
my $rc = 0;
my $rc2 = 0;
my $result = "";
print $msg->message . "\n";
given($msg->message)
{
when ("QUIT")
{
$alive = 0;
$result = "quitting!";
}
default {
$rc = 10;
$rc2 = 22;
}
}
$msg->reply($rc,$rc2,$result);
$msg = $host->getmsg();
}
}
# Send a command to a host
my $port = "SOMEHOST";
my $command = "SOMECOMMAND";
my ($rc,$rc2,$result) = Amiga::ARexx->DoRexx($port,$command);
```
DESCRIPTION
-----------
The interface to the arexx.class in entirely encapsulated within the perl class, there is no need to access the low level methods directly and they are not exported by default.
Amiga::ARexx METHODS
---------------------
### new
```
my $host = Amiga::ARexx->new( HostName => "PERLREXX");
```
Create an ARexx host for your script / program.
#### HostName
The HostName for the hosts command port. This is madatory, the program will fail if not provided.
### wait
```
$host->wait('TimeOut' => $timeoutinusecs );
```
Wait for a message to arive at the port.
#### TimeOut
optional time out in microseconds.
### getmsg
```
$msg = $host->getmsg();
```
Fetch an ARexx message from the host port. Returns an objrct of class Amiga::ARexx::Msg
### signal
```
$signal = $host->signal()
```
Retrieve the signal mask for the host port for use with Amiga::Exec Wait()
### DoRexx
```
($rc,$rc2,$result) = DoRexx("desthost","commandstring");
```
Send the "commandstring" to host "desthost" for execution. Commandstring might be a specific command or scriptname.
Amiga::ARexx::Msg METHODS
--------------------------
### message
```
$m = $msg->message();
```
Retrieve the message "command" as a string;
### reply
```
$msg->reply($rc,$rc2,$result)
```
Reply the message returning the results of any command. Set $rc = 0 for success and $result to the result string if appropriate.
Set $rc to non zero for error and $rc2 for an additional error code if appropriate.
### setvar
```
$msg->setvar($varname,$value)
```
Set a variable in the language context sending this message.
### getvar
```
$value = $msg->getvar($varname)
```
Get the value of a variable in the language context sending this message.
### EXPORT
None by default.
###
Exportable constants
None
AUTHOR
------
Andy Broad <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2013 by Andy Broad.
| programming_docs |
perl Encode::CN::HZ Encode::CN::HZ
==============
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::CN::HZ -- internally used by Encode::CN
perl perlfaq2 perlfaq2
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [What machines support Perl? Where do I get it?](#What-machines-support-Perl?-Where-do-I-get-it?)
+ [How can I get a binary version of Perl?](#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-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-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?](#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?](#What-modules-and-extensions-are-available-for-Perl?-What-is-CPAN?)
+ [Where can I get information on Perl?](#Where-can-I-get-information-on-Perl?)
+ [What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org?](#What-is-perl.com?-Perl-Mongers?-pm.org?-perl.org?-cpan.org?)
+ [Where can I post questions?](#Where-can-I-post-questions?)
+ [Perl Books](#Perl-Books)
+ [Which magazines have Perl content?](#Which-magazines-have-Perl-content?)
+ [Which Perl blogs should I read?](#Which-Perl-blogs-should-I-read?)
+ [What mailing lists are there for Perl?](#What-mailing-lists-are-there-for-Perl?)
+ [Where can I buy a commercial version of Perl?](#Where-can-I-buy-a-commercial-version-of-Perl?)
+ [Where do I send bug reports?](#Where-do-I-send-bug-reports?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq2 - Obtaining and Learning about Perl
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
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?
The standard release of Perl (the one maintained by the Perl development team) is distributed only in source code form. You can find the latest releases at <http://www.cpan.org/src/>.
Perl builds and runs on a bewildering number of platforms. Virtually all known and current Unix derivatives are supported (perl's native platform), as are other systems like VMS, DOS, OS/2, Windows, QNX, BeOS, OS X, MPE/iX and the Amiga.
Binary distributions for some proprietary platforms can be found <http://www.cpan.org/ports/> directory. Because these are not part of the standard distribution, they may and in fact do differ from the base perl port in a variety of ways. You'll have to check their respective release notes to see just what the differences are. These differences can be either positive (e.g. extensions for the features of the particular platform that are not supported in the source release of perl) or negative (e.g. might be based upon a less current source release of perl).
###
How can I get a binary version of Perl?
See [CPAN Ports](http://www.cpan.org/ports/)
###
I don't have a C compiler. How can I build my own Perl interpreter?
For Windows, use a binary version of Perl, [Strawberry Perl](http://strawberryperl.com/) and [ActivePerl](http://www.activestate.com/activeperl) come with a bundled C compiler.
Otherwise if you really do want to build Perl, you need to get a binary version of `gcc` for your system first. Use a search engine to find out how to do this for your operating system.
###
I copied the Perl binary from one machine to another, but scripts don't work.
That's probably because you forgot libraries, or library paths differ. You really should build the whole distribution on the machine it will eventually live on, and then type `make install`. Most other approaches are doomed to failure.
One simple way to check that things are in the right place is to print out the hard-coded `@INC` that perl looks through for libraries:
```
% perl -le 'print for @INC'
```
If this command lists any paths that don't exist on your system, then you may need to move the appropriate libraries to these locations, or create symbolic links, aliases, or shortcuts appropriately. `@INC` is also printed as part of the output of
```
% perl -V
```
You might also want to check out ["How do I keep my own module/library directory?" in perlfaq8](perlfaq8#How-do-I-keep-my-own-module%2Flibrary-directory%3F).
###
I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work?
Read the *INSTALL* file, which is part of the source distribution. It describes in detail how to cope with most idiosyncrasies that the `Configure` script can't work around for any given system or architecture.
###
What modules and extensions are available for Perl? What is CPAN?
CPAN stands for Comprehensive Perl Archive Network, a multi-gigabyte archive replicated on hundreds of machines all over the world. CPAN contains tens of thousands of modules and extensions, source code and documentation, designed for *everything* from commercial database interfaces to keyboard/screen control and running large web sites.
You can search CPAN on <http://metacpan.org>.
The master web site for CPAN is <http://www.cpan.org/>, <http://www.cpan.org/SITES.html> lists all mirrors.
See the CPAN FAQ at <http://www.cpan.org/misc/cpan-faq.html> for answers to the most frequently asked questions about CPAN.
The <Task::Kensho> module has a list of recommended modules which you should review as a good starting point.
###
Where can I get information on Perl?
* <http://www.perl.org/>
* <http://perldoc.perl.org/>
* <http://learn.perl.org/>
The complete Perl documentation is available with the Perl distribution. If you have Perl installed locally, you probably have the documentation installed as well: type `perldoc perl` in a terminal or [view online](http://perldoc.perl.org/perl.html).
(Some operating system distributions may ship the documentation in a different package; for instance, on Debian, you need to install the `perl-doc` package.)
Many good books have been written about Perl--see the section later in <perlfaq2> for more details.
###
What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org?
[Perl.com](http://www.perl.com/) used to be part of the O'Reilly Network, a subsidiary of O'Reilly Media. Although it retains most of the original content from its O'Reilly Network, it is now hosted by [The Perl Foundation](http://www.perlfoundation.org/).
The Perl Foundation is an advocacy organization for the Perl language which maintains the web site <http://www.perl.org/> as a general advocacy site for the Perl language. It uses the domain to provide general support services to the Perl community, including the hosting of mailing lists, web sites, and other services. There are also many other sub-domains for special topics like learning Perl and jobs in Perl, such as:
* <http://www.perl.org/>
* <http://learn.perl.org/>
* <http://jobs.perl.org/>
* <http://lists.perl.org/>
[Perl Mongers](http://www.pm.org/) uses the pm.org domain for services related to local Perl user groups, including the hosting of mailing lists and web sites. See the [Perl Mongers web site](http://www.pm.org/) for more information about joining, starting, or requesting services for a Perl user group.
CPAN, or the Comprehensive Perl Archive Network <http://www.cpan.org/>, is a replicated, worldwide repository of Perl software. See [What is CPAN?](#What-modules-and-extensions-are-available-for-Perl%3F-What-is-CPAN%3F).
###
Where can I post questions?
There are many Perl [mailing lists](lists.perl.org) for various topics, specifically the [beginners list](http://lists.perl.org/list/beginners.html) may be of use.
Other places to ask questions are on the [PerlMonks site](http://www.perlmonks.org/) or [stackoverflow](http://stackoverflow.com/questions/tagged/perl).
###
Perl Books
There are many good [books on Perl](http://www.perl.org/books/library.html).
###
Which magazines have Perl content?
There's also *$foo Magazin*, a German magazine dedicated to Perl, at ( <http://www.foo-magazin.de> ). The *Perl-Zeitung* is another German-speaking magazine for Perl beginners (see <http://perl-zeitung.at.tf> ).
Several Unix/Linux related magazines frequently include articles on Perl.
###
Which Perl blogs should I read?
[Perl News](http://perlnews.org/) covers some of the major events in the Perl world, [Perl Weekly](http://perlweekly.com/) is a weekly e-mail (and RSS feed) of hand-picked Perl articles.
<http://blogs.perl.org/> hosts many Perl blogs, there are also several blog aggregators: [Perlsphere](http://perlsphere.net/) and [IronMan](http://ironman.enlightenedperl.org/) are two of them.
###
What mailing lists are there for Perl?
A comprehensive list of Perl-related mailing lists can be found at <http://lists.perl.org/>
###
Where can I buy a commercial version of Perl?
Perl already *is* commercial software: it has a license that you can grab and carefully read to your manager. It is distributed in releases and comes in well-defined packages. There is a very large and supportive user community and an extensive literature.
If you still need commercial support [ActiveState](http://www.activestate.com/activeperl) offers this.
###
Where do I send bug reports?
(contributed by brian d foy)
First, ensure that you've found an actual bug. Second, ensure you've found an actual bug.
If you've found a bug with the perl interpreter or one of the modules in the standard library (those that come with Perl), you can submit a bug report to the GitHub issue tracker at <https://github.com/Perl/perl5/issues>.
To determine if a module came with your version of Perl, you can install and use the <Module::CoreList> module. It has the information about the modules (with their versions) included with each release of Perl.
Every CPAN module has a bug tracker set up in RT, <http://rt.cpan.org>. You can submit bugs to RT either through its web interface or by email. To email a bug report, send it to bug-<distribution-name>@rt.cpan.org . For example, if you wanted to report a bug in <Business::ISBN>, you could send a message to [email protected] .
Some modules might have special reporting requirements, such as a GitHub or Google Code tracking system, so you should check the module documentation too.
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.
perl perlgit perlgit
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [CLONING THE REPOSITORY](#CLONING-THE-REPOSITORY)
* [WORKING WITH THE REPOSITORY](#WORKING-WITH-THE-REPOSITORY)
+ [Finding out your status](#Finding-out-your-status)
+ [Patch workflow](#Patch-workflow)
+ [A note on derived files](#A-note-on-derived-files)
+ [Cleaning a working directory](#Cleaning-a-working-directory)
+ [Bisecting](#Bisecting)
+ [Topic branches and rewriting history](#Topic-branches-and-rewriting-history)
+ [Grafts](#Grafts)
* [WRITE ACCESS TO THE GIT REPOSITORY](#WRITE-ACCESS-TO-THE-GIT-REPOSITORY)
+ [Working with Github pull requests](#Working-with-Github-pull-requests)
+ [Accepting a patch](#Accepting-a-patch)
+ [Committing to blead](#Committing-to-blead)
+ [On merging and rebasing](#On-merging-and-rebasing)
+ [Committing to maintenance versions](#Committing-to-maintenance-versions)
+ [Using a smoke-me branch to test changes](#Using-a-smoke-me-branch-to-test-changes)
NAME
----
perlgit - Detailed information about git and the Perl repository
DESCRIPTION
-----------
This document provides details on using git to develop Perl. If you are just interested in working on a quick patch, see <perlhack> first. This document is intended for people who are regular contributors to Perl, including those with write access to the git repository.
CLONING THE REPOSITORY
-----------------------
All of Perl's source code is kept centrally in a Git repository at *github.com*.
You can make a read-only clone of the repository by running:
```
% git clone [email protected]:Perl/perl5.git perl
```
If you cannot use that for firewall reasons, you can also clone via http:
```
% git clone https://github.com/Perl/perl5.git perl
```
WORKING WITH THE REPOSITORY
----------------------------
Once you have changed into the repository directory, you can inspect it. After a clone the repository will contain a single local branch, which will be the current branch as well, as indicated by the asterisk.
```
% git branch
* blead
```
Using the -a switch to `branch` will also show the remote tracking branches in the repository:
```
% git branch -a
* blead
origin/HEAD
origin/blead
...
```
The branches that begin with "origin" correspond to the "git remote" that you cloned from (which is named "origin"). Each branch on the remote will be exactly tracked by these branches. You should NEVER do work on these remote tracking branches. You only ever do work in a local branch. Local branches can be configured to automerge (on pull) from a designated remote tracking branch. This is the case with the default branch `blead` which will be configured to merge from the remote tracking branch `origin/blead`.
You can see recent commits:
```
% git log
```
And pull new changes from the repository, and update your local repository (must be clean first)
```
% git pull
```
Assuming we are on the branch `blead` immediately after a pull, this command would be more or less equivalent to:
```
% git fetch
% git merge origin/blead
```
In fact if you want to update your local repository without touching your working directory you do:
```
% git fetch
```
And if you want to update your remote-tracking branches for all defined remotes simultaneously you can do
```
% git remote update
```
Neither of these last two commands will update your working directory, however both will update the remote-tracking branches in your repository.
To make a local branch of a remote branch:
```
% git checkout -b maint-5.10 origin/maint-5.10
```
To switch back to blead:
```
% git checkout blead
```
###
Finding out your status
The most common git command you will use will probably be
```
% git status
```
This command will produce as output a description of the current state of the repository, including modified files and unignored untracked files, and in addition it will show things like what files have been staged for the next commit, and usually some useful information about how to change things. For instance the following:
```
% git status
On branch blead
Your branch is ahead of 'origin/blead' by 1 commit.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: pod/perlgit.pod
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working
directory)
modified: pod/perlgit.pod
Untracked files:
(use "git add <file>..." to include in what will be committed)
deliberate.untracked
```
This shows that there were changes to this document staged for commit, and that there were further changes in the working directory not yet staged. It also shows that there was an untracked file in the working directory, and as you can see shows how to change all of this. It also shows that there is one commit on the working branch `blead` which has not been pushed to the `origin` remote yet. **NOTE**: This output is also what you see as a template if you do not provide a message to `git commit`.
###
Patch workflow
First, please read <perlhack> for details on hacking the Perl core. That document covers many details on how to create a good patch.
If you already have a Perl repository, you should ensure that you're on the *blead* branch, and your repository is up to date:
```
% git checkout blead
% git pull
```
It's preferable to patch against the latest blead version, since this is where new development occurs for all changes other than critical bug fixes. Critical bug fix patches should be made against the relevant maint branches, or should be submitted with a note indicating all the branches where the fix should be applied.
Now that we have everything up to date, we need to create a temporary new branch for these changes and switch into it:
```
% git checkout -b orange
```
which is the short form of
```
% git branch orange
% git checkout orange
```
Creating a topic branch makes it easier for the maintainers to rebase or merge back into the master blead for a more linear history. If you don't work on a topic branch the maintainer has to manually cherry pick your changes onto blead before they can be applied.
That'll get you scolded on perl5-porters, so don't do that. Be Awesome.
Then make your changes. For example, if Leon Brocard changes his name to Orange Brocard, we should change his name in the AUTHORS file:
```
% perl -pi -e 's{Leon Brocard}{Orange Brocard}' AUTHORS
```
You can see what files are changed:
```
% git status
On branch orange
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: AUTHORS
```
And you can see the changes:
```
% git diff
diff --git a/AUTHORS b/AUTHORS
index 293dd70..722c93e 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -541,7 +541,7 @@ Lars Hecking <[email protected]>
Laszlo Molnar <[email protected]>
Leif Huhn <[email protected]>
Len Johnson <[email protected]>
-Leon Brocard <[email protected]>
+Orange Brocard <[email protected]>
Les Peters <[email protected]>
Lesley Binks <[email protected]>
Lincoln D. Stein <[email protected]>
```
Now commit your change locally:
```
% git commit -a -m 'Rename Leon Brocard to Orange Brocard'
Created commit 6196c1d: Rename Leon Brocard to Orange Brocard
1 files changed, 1 insertions(+), 1 deletions(-)
```
The `-a` option is used to include all files that git tracks that you have changed. If at this time, you only want to commit some of the files you have worked on, you can omit the `-a` and use the command `git add *FILE ...*` before doing the commit. `git add --interactive` allows you to even just commit portions of files instead of all the changes in them.
The `-m` option is used to specify the commit message. If you omit it, git will open a text editor for you to compose the message interactively. This is useful when the changes are more complex than the sample given here, and, depending on the editor, to know that the first line of the commit message doesn't exceed the 50 character legal maximum. See ["Commit message" in perlhack](perlhack#Commit-message) for more information about what makes a good commit message.
Once you've finished writing your commit message and exited your editor, git will write your change to disk and tell you something like this:
```
Created commit daf8e63: explain git status and stuff about remotes
1 files changed, 83 insertions(+), 3 deletions(-)
```
If you re-run `git status`, you should see something like this:
```
% git status
On branch orange
Untracked files:
(use "git add <file>..." to include in what will be committed)
deliberate.untracked
nothing added to commit but untracked files present (use "git add" to
track)
```
When in doubt, before you do anything else, check your status and read it carefully, many questions are answered directly by the git status output.
You can examine your last commit with:
```
% git show HEAD
```
and if you are not happy with either the description or the patch itself you can fix it up by editing the files once more and then issue:
```
% git commit -a --amend
```
Now, create a fork on GitHub to push your branch to, 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
```
And push the branch to your fork:
```
% git push -u fork orange
```
You should now submit a Pull Request (PR) on GitHub from the new branch to blead. For more information, see the GitHub documentation at <https://help.github.com/en/articles/creating-a-pull-request-from-a-fork>.
You can also send patch files to [[email protected]](mailto:[email protected]) directly if the patch is not ready to be applied, but intended for discussion.
To create a patch file for all your local changes:
```
% git format-patch -M blead..
0001-Rename-Leon-Brocard-to-Orange-Brocard.patch
```
Or for a lot of changes, e.g. from a topic branch:
```
% git format-patch --stdout -M blead.. > topic-branch-changes.patch
```
If you want to delete your temporary branch, you may do so with:
```
% git checkout blead
% git branch -d orange
error: The branch 'orange' is not an ancestor of your current HEAD.
If you are sure you want to delete it, run 'git branch -D orange'.
% git branch -D orange
Deleted branch orange.
```
###
A note on derived files
Be aware that many files in the distribution are derivative--avoid patching them, because git won't see the changes to them, and the build process will overwrite them. Patch the originals instead. Most utilities (like perldoc) are in this category, i.e. patch *utils/perldoc.PL* rather than *utils/perldoc*. Similarly, don't create patches for files under *$src\_root/ext* from their copies found in *$install\_root/lib*. If you are unsure about the proper location of a file that may have gotten copied while building the source distribution, consult the *MANIFEST*.
###
Cleaning a working directory
The command `git clean` can with varying arguments be used as a replacement for `make clean`.
To reset your working directory to a pristine condition you can do:
```
% git clean -dxf
```
However, be aware this will delete ALL untracked content. You can use
```
% git clean -Xf
```
to remove all ignored untracked files, such as build and test byproduct, but leave any manually created files alone.
If you only want to cancel some uncommitted edits, you can use `git checkout` and give it a list of files to be reverted, or `git checkout -f` to revert them all.
If you want to cancel one or several commits, you can use `git reset`.
### Bisecting
`git` provides a built-in way to determine which commit should be blamed for introducing a given bug. `git bisect` performs a binary search of history to locate the first failing commit. It is fast, powerful and flexible, but requires some setup and to automate the process an auxiliary shell script is needed.
The core provides a wrapper program, *Porting/bisect.pl*, which attempts to simplify as much as possible, making bisecting as simple as running a Perl one-liner. For example, if you want to know when this became an error:
```
perl -e 'my $a := 2'
```
you simply run this:
```
.../Porting/bisect.pl -e 'my $a := 2;'
```
Using *Porting/bisect.pl*, with one command (and no other files) it's easy to find out
* Which commit caused this example code to break?
* Which commit caused this example code to start working?
* Which commit added the first file to match this regex?
* Which commit removed the last file to match this regex?
usually without needing to know which versions of perl to use as start and end revisions, as *Porting/bisect.pl* automatically searches to find the earliest stable version for which the test case passes. Run `Porting/bisect.pl --help` for the full documentation, including how to set the `Configure` and build time options.
If you require more flexibility than *Porting/bisect.pl* has to offer, you'll need to run `git bisect` yourself. It's most useful to use `git bisect run` to automate the building and testing of perl revisions. For this you'll need a shell script for `git` to call to test a particular revision. An example script is *Porting/bisect-example.sh*, which you should copy **outside** of the repository, as the bisect process will reset the state to a clean checkout as it runs. The instructions below assume that you copied it as *~/run* and then edited it as appropriate.
You first enter in bisect mode with:
```
% git bisect start
```
For example, if the bug is present on `HEAD` but wasn't in 5.10.0, `git` will learn about this when you enter:
```
% git bisect bad
% git bisect good perl-5.10.0
Bisecting: 853 revisions left to test after this
```
This results in checking out the median commit between `HEAD` and `perl-5.10.0`. You can then run the bisecting process with:
```
% git bisect run ~/run
```
When the first bad commit is isolated, `git bisect` will tell you so:
```
ca4cfd28534303b82a216cfe83a1c80cbc3b9dc5 is first bad commit
commit ca4cfd28534303b82a216cfe83a1c80cbc3b9dc5
Author: Dave Mitchell <[email protected]>
Date: Sat Feb 9 14:56:23 2008 +0000
[perl #49472] Attributes + Unknown Error
...
bisect run success
```
You can peek into the bisecting process with `git bisect log` and `git bisect visualize`. `git bisect reset` will get you out of bisect mode.
Please note that the first `good` state must be an ancestor of the first `bad` state. If you want to search for the commit that *solved* some bug, you have to negate your test case (i.e. exit with `1` if OK and `0` if not) and still mark the lower bound as `good` and the upper as `bad`. The "first bad commit" has then to be understood as the "first commit where the bug is solved".
`git help bisect` has much more information on how you can tweak your binary searches.
Following bisection you may wish to configure, build and test perl at commits identified by the bisection process. Sometimes, particularly with older perls, `make` may fail during this process. In this case you may be able to patch the source code at the older commit point. To do so, please follow the suggestions provided in ["Building perl at older commits" in perlhack](perlhack#Building-perl-at-older-commits).
###
Topic branches and rewriting history
Individual committers should create topic branches under **yourname**/**some\_descriptive\_name**:
```
% branch="$yourname/$some_descriptive_name"
% git checkout -b $branch
... do local edits, commits etc ...
% git push origin -u $branch
```
Should you be stuck with an ancient version of git (prior to 1.7), then `git push` will not have the `-u` switch, and you have to replace the last step with the following sequence:
```
% git push origin $branch:refs/heads/$branch
% git config branch.$branch.remote origin
% git config branch.$branch.merge refs/heads/$branch
```
If you want to make changes to someone else's topic branch, you should check with its creator before making any change to it.
You might sometimes find that the original author has edited the branch's history. There are lots of good reasons for this. Sometimes, an author might simply be rebasing the branch onto a newer source point. Sometimes, an author might have found an error in an early commit which they wanted to fix before merging the branch to blead.
Currently the master repository is configured to forbid non-fast-forward merges. This means that the branches within can not be rebased and pushed as a single step.
The only way you will ever be allowed to rebase or modify the history of a pushed branch is to delete it and push it as a new branch under the same name. Please think carefully about doing this. It may be better to sequentially rename your branches so that it is easier for others working with you to cherry-pick their local changes onto the new version. (XXX: needs explanation).
If you want to rebase a personal topic branch, you will have to delete your existing topic branch and push as a new version of it. You can do this via the following formula (see the explanation about `refspec`'s in the git push documentation for details) after you have rebased your branch:
```
# first rebase
% git checkout $user/$topic
% git fetch
% git rebase origin/blead
# then "delete-and-push"
% git push origin :$user/$topic
% git push origin $user/$topic
```
**NOTE:** it is forbidden at the repository level to delete any of the "primary" branches. That is any branch matching `m!^(blead|maint|perl)!`. Any attempt to do so will result in git producing an error like this:
```
% git push origin :blead
*** It is forbidden to delete blead/maint branches in this repository
error: hooks/update exited with error code 1
error: hook declined to update refs/heads/blead
To ssh://perl5.git.perl.org/perl
! [remote rejected] blead (hook declined)
error: failed to push some refs to 'ssh://perl5.git.perl.org/perl'
```
As a matter of policy we do **not** edit the history of the blead and maint-\* branches. If a typo (or worse) sneaks into a commit to blead or maint-\*, we'll fix it in another commit. The only types of updates allowed on these branches are "fast-forwards", where all history is preserved.
Annotated tags in the canonical perl.git repository will never be deleted or modified. Think long and hard about whether you want to push a local tag to perl.git before doing so. (Pushing simple tags is not allowed.)
### Grafts
The perl history contains one mistake which was not caught in the conversion: a merge was recorded in the history between blead and maint-5.10 where no merge actually occurred. Due to the nature of git, this is now impossible to fix in the public repository. You can remove this mis-merge locally by adding the following line to your `.git/info/grafts` file:
```
296f12bbbbaa06de9be9d09d3dcf8f4528898a49 434946e0cb7a32589ed92d18008aaa1d88515930
```
It is particularly important to have this graft line if any bisecting is done in the area of the "merge" in question.
WRITE ACCESS TO THE GIT REPOSITORY
-----------------------------------
Once you have write access, you will need to modify the URL for the origin remote to enable pushing. Edit *.git/config* with the git-config(1) command:
```
% git config remote.origin.url [email protected]:Perl/perl5.git
```
You can also set up your user name and e-mail address. Most people do this once globally in their *~/.gitconfig* by doing something like:
```
% git config --global user.name "รvar Arnfjรถrรฐ Bjarmason"
% git config --global user.email [email protected]
```
However, if you'd like to override that just for perl, execute something like the following in *perl*:
```
% git config user.email [email protected]
```
It is also possible to keep `origin` as a git remote, and add a new remote for ssh access:
```
% git remote add camel [email protected]:Perl/perl5.git
```
This allows you to update your local repository by pulling from `origin`, which is faster and doesn't require you to authenticate, and to push your changes back with the `camel` remote:
```
% git fetch camel
% git push camel
```
The `fetch` command just updates the `camel` refs, as the objects themselves should have been fetched when pulling from `origin`.
###
Working with Github pull requests
Pull requests typically originate from outside of the `Perl/perl.git` repository, so if you want to test or work with it locally a vanilla `git fetch` from the `Perl/perl5.git` repository won't fetch it.
However Github does provide a mechanism to fetch a pull request to a local branch. They are available on Github remotes under `pull/`, so you can use `git fetch pull/*PRID*/head:*localname*` to make a local copy. eg. to fetch pull request 9999 to the local branch `local-branch-name` run:
```
git fetch origin pull/9999/head:local-branch-name
```
and then:
```
git checkout local-branch-name
```
Note: this branch is not rebased on `blead`, so instead of the checkout above, you might want:
```
git rebase origin/blead local-branch-name
```
which rebases `local-branch-name` on `blead`, and checks it out.
Alternatively you can configure the remote to fetch all pull requests as remote-tracking branches. To do this edit the remote in *.git/config*, for example if your github remote is `origin` you'd have:
```
[remote "origin"]
url = [email protected]:/Perl/perl5.git
fetch = +refs/heads/*:refs/remotes/origin/*
```
Add a line to map the remote pull request branches to remote-tracking branches:
```
[remote "origin"]
url = [email protected]:/Perl/perl5.git
fetch = +refs/heads/*:refs/remotes/origin/*
fetch = +refs/pull/*/head:refs/remotes/origin/pull/*
```
and then do a fetch as normal:
```
git fetch origin
```
This will create a remote-tracking branch for every pull request, including closed requests.
To remove those remote-tracking branches, remove the line added above and prune:
```
git fetch -p origin # or git remote prune origin
```
###
Accepting a patch
If you have received a patch file generated using the above section, you should try out the patch.
First we need to create a temporary new branch for these changes and switch into it:
```
% git checkout -b experimental
```
Patches that were formatted by `git format-patch` are applied with `git am`:
```
% git am 0001-Rename-Leon-Brocard-to-Orange-Brocard.patch
Applying Rename Leon Brocard to Orange Brocard
```
Note that some UNIX mail systems can mess with text attachments containing 'From '. This will fix them up:
```
% perl -pi -e's/^>From /From /' \
0001-Rename-Leon-Brocard-to-Orange-Brocard.patch
```
If just a raw diff is provided, it is also possible use this two-step process:
```
% git apply bugfix.diff
% git commit -a -m "Some fixing" \
--author="That Guy <[email protected]>"
```
Now we can inspect the change:
```
% git show HEAD
commit b1b3dab48344cff6de4087efca3dbd63548ab5e2
Author: Leon Brocard <[email protected]>
Date: Fri Dec 19 17:02:59 2008 +0000
Rename Leon Brocard to Orange Brocard
diff --git a/AUTHORS b/AUTHORS
index 293dd70..722c93e 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -541,7 +541,7 @@ Lars Hecking <[email protected]>
Laszlo Molnar <[email protected]>
Leif Huhn <[email protected]>
Len Johnson <[email protected]>
-Leon Brocard <[email protected]>
+Orange Brocard <[email protected]>
Les Peters <[email protected]>
Lesley Binks <[email protected]>
Lincoln D. Stein <[email protected]>
```
If you are a committer to Perl and you think the patch is good, you can then merge it into blead then push it out to the main repository:
```
% git checkout blead
% git merge experimental
% git push origin blead
```
If you want to delete your temporary branch, you may do so with:
```
% git checkout blead
% git branch -d experimental
error: The branch 'experimental' is not an ancestor of your current
HEAD. If you are sure you want to delete it, run 'git branch -D
experimental'.
% git branch -D experimental
Deleted branch experimental.
```
###
Committing to blead
The 'blead' branch will become the next production release of Perl.
Before pushing *any* local change to blead, it's incredibly important that you do a few things, lest other committers come after you with pitchforks and torches:
* Make sure you have a good commit message. See ["Commit message" in perlhack](perlhack#Commit-message) for details.
* Run the test suite. You might not think that one typo fix would break a test file. You'd be wrong. Here's an example of where not running the suite caused problems. A patch was submitted that added a couple of tests to an existing *.t*. It couldn't possibly affect anything else, so no need to test beyond the single affected *.t*, right? But, the submitter's email address had changed since the last of their submissions, and this caused other tests to fail. Running the test target given in the next item would have caught this problem.
* If you don't run the full test suite, at least `make test_porting`. This will run basic sanity checks. To see which sanity checks, have a look in *t/porting*.
* If you make any changes that affect miniperl or core routines that have different code paths for miniperl, be sure to run `make minitest`. This will catch problems that even the full test suite will not catch because it runs a subset of tests under miniperl rather than perl.
###
On merging and rebasing
Simple, one-off commits pushed to the 'blead' branch should be simple commits that apply cleanly. In other words, you should make sure your work is committed against the current position of blead, so that you can push back to the master repository without merging.
Sometimes, blead will move while you're building or testing your changes. When this happens, your push will be rejected with a message like this:
```
To ssh://perl5.git.perl.org/perl.git
! [rejected] blead -> blead (non-fast-forward)
error: failed to push some refs to 'ssh://perl5.git.perl.org/perl.git'
To prevent you from losing history, non-fast-forward updates were
rejected Merge the remote changes (e.g. 'git pull') before pushing
again. See the 'Note about fast-forwards' section of 'git push --help'
for details.
```
When this happens, you can just *rebase* your work against the new position of blead, like this (assuming your remote for the master repository is "p5p"):
```
% git fetch p5p
% git rebase p5p/blead
```
You will see your commits being re-applied, and you will then be able to push safely. More information about rebasing can be found in the documentation for the git-rebase(1) command.
For larger sets of commits that only make sense together, or that would benefit from a summary of the set's purpose, you should use a merge commit. You should perform your work on a [topic branch](#Topic-branches-and-rewriting-history), which you should regularly rebase against blead to ensure that your code is not broken by blead moving. When you have finished your work, please perform a final rebase and test. Linear history is something that gets lost with every commit on blead, but a final rebase makes the history linear again, making it easier for future maintainers to see what has happened. Rebase as follows (assuming your work was on the branch `committer/somework`):
```
% git checkout committer/somework
% git rebase blead
```
Then you can merge it into master like this:
```
% git checkout blead
% git merge --no-ff --no-commit committer/somework
% git commit -a
```
The switches above deserve explanation. `--no-ff` indicates that even if all your work can be applied linearly against blead, a merge commit should still be prepared. This ensures that all your work will be shown as a side branch, with all its commits merged into the mainstream blead by the merge commit.
`--no-commit` means that the merge commit will be *prepared* but not *committed*. The commit is then actually performed when you run the next command, which will bring up your editor to describe the commit. Without `--no-commit`, the commit would be made with nearly no useful message, which would greatly diminish the value of the merge commit as a placeholder for the work's description.
When describing the merge commit, explain the purpose of the branch, and keep in mind that this description will probably be used by the eventual release engineer when reviewing the next perldelta document.
###
Committing to maintenance versions
Maintenance versions should only be altered to add critical bug fixes, see <perlpolicy>.
To commit to a maintenance version of perl, you need to create a local tracking branch:
```
% git checkout --track -b maint-5.005 origin/maint-5.005
```
This creates a local branch named `maint-5.005`, which tracks the remote branch `origin/maint-5.005`. Then you can pull, commit, merge and push as before.
You can also cherry-pick commits from blead and another branch, by using the `git cherry-pick` command. It is recommended to use the **-x** option to `git cherry-pick` in order to record the SHA1 of the original commit in the new commit message.
Before pushing any change to a maint version, make sure you've satisfied the steps in ["Committing to blead"](#Committing-to-blead) above.
###
Using a smoke-me branch to test changes
Sometimes a change affects code paths which you cannot test on the OSes which are directly available to you and it would be wise to have users on other OSes test the change before you commit it to blead.
Fortunately, there is a way to get your change smoke-tested on various OSes: push it to a "smoke-me" branch and wait for certain automated smoke-testers to report the results from their OSes. A "smoke-me" branch is identified by the branch name: specifically, as seen on github.com it must be a local branch whose first name component is precisely `smoke-me`.
The procedure for doing this is roughly as follows (using the example of tonyc's smoke-me branch called win32stat):
First, make a local branch and switch to it:
```
% git checkout -b win32stat
```
Make some changes, build perl and test your changes, then commit them to your local branch. Then push your local branch to a remote smoke-me branch:
```
% git push origin win32stat:smoke-me/tonyc/win32stat
```
Now you can switch back to blead locally:
```
% git checkout blead
```
and continue working on other things while you wait a day or two, keeping an eye on the results reported for your smoke-me branch at <http://perl.develop-help.com/?b=smoke-me/tonyc/win32state>.
If all is well then update your blead branch:
```
% git pull
```
then checkout your smoke-me branch once more and rebase it on blead:
```
% git rebase blead win32stat
```
Now switch back to blead and merge your smoke-me branch into it:
```
% git checkout blead
% git merge win32stat
```
As described earlier, if there are many changes on your smoke-me branch then you should prepare a merge commit in which to give an overview of those changes by using the following command instead of the last command above:
```
% git merge win32stat --no-ff --no-commit
```
You should now build perl and test your (merged) changes one last time (ideally run the whole test suite, but failing that at least run the *t/porting/\*.t* tests) before pushing your changes as usual:
```
% git push origin blead
```
Finally, you should then delete the remote smoke-me branch:
```
% git push origin :smoke-me/tonyc/win32stat
```
(which is likely to produce a warning like this, which can be ignored:
```
remote: fatal: ambiguous argument
'refs/heads/smoke-me/tonyc/win32stat':
unknown revision or path not in the working tree.
remote: Use '--' to separate paths from revisions
```
) and then delete your local branch:
```
% git branch -d win32stat
```
| programming_docs |
perl CPAN::API::HOWTO CPAN::API::HOWTO
================
CONTENTS
--------
* [NAME](#NAME)
* [RECIPES](#RECIPES)
+ [What distribution contains a particular module?](#What-distribution-contains-a-particular-module?)
+ [What modules does a particular distribution contain?](#What-modules-does-a-particular-distribution-contain?)
* [SEE ALSO](#SEE-ALSO)
* [LICENSE](#LICENSE)
* [AUTHOR](#AUTHOR)
NAME
----
CPAN::API::HOWTO - a recipe book for programming with CPAN.pm
RECIPES
-------
All of these recipes assume that you have put "use CPAN" at the top of your program.
###
What distribution contains a particular module?
```
my $distribution = CPAN::Shell->expand(
"Module", "Data::UUID"
)->distribution()->pretty_id();
```
This returns a string of the form "AUTHORID/TARBALL". If you want the full path and filename to this distribution on a CPAN mirror, then it is `.../authors/id/A/AU/AUTHORID/TARBALL`.
###
What modules does a particular distribution contain?
```
CPAN::Index->reload();
my @modules = CPAN::Shell->expand(
"Distribution", "JHI/Graph-0.83.tar.gz"
)->containsmods();
```
You may also refer to a distribution in the form A/AU/AUTHORID/TARBALL.
SEE ALSO
---------
the main CPAN.pm documentation
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>
AUTHOR
------
David Cantrell
perl TAP::Parser::SourceHandler::Executable TAP::Parser::SourceHandler::Executable
======================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [can\_handle](#can_handle)
- [make\_iterator](#make_iterator)
- [iterator\_class](#iterator_class)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::SourceHandler::Executable - Stream output from an executable TAP source
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Source;
use TAP::Parser::SourceHandler::Executable;
my $source = TAP::Parser::Source->new->raw(['/usr/bin/ruby', 'mytest.rb']);
$source->assemble_meta;
my $class = 'TAP::Parser::SourceHandler::Executable';
my $vote = $class->can_handle( $source );
my $iter = $class->make_iterator( $source );
```
DESCRIPTION
-----------
This is an *executable* <TAP::Parser::SourceHandler> - it has 2 jobs:
1. Figure out if the <TAP::Parser::Source> it's given is an executable command (["can\_handle"](#can_handle)).
2. Creates an iterator for executable commands (["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 an executable file. Casts the following votes:
```
0.9 if it's a hash with an 'exec' key
0.8 if it's a .bat file
0.75 if it's got an execute bit set
```
#### `make_iterator`
```
my $iterator = $class->make_iterator( $source );
```
Returns a new <TAP::Parser::Iterator::Process> for the source. `$source->raw` must be in one of the following forms:
```
{ exec => [ @exec ] }
[ @exec ]
$file
```
`croak`s on error.
#### `iterator_class`
The class of iterator to use, override if you're sub-classing. Defaults to <TAP::Parser::Iterator::Process>.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
### Example
```
package MyRubySourceHandler;
use strict;
use Carp qw( croak );
use TAP::Parser::SourceHandler::Executable;
use base 'TAP::Parser::SourceHandler::Executable';
# expect $handler->(['mytest.rb', 'cmdline', 'args']);
sub make_iterator {
my ($self, $source) = @_;
my @test_args = @{ $source->test_args };
my $rb_file = $test_args[0];
croak("error: Ruby file '$rb_file' not found!") unless (-f $rb_file);
return $self->SUPER::raw_source(['/usr/bin/ruby', @test_args]);
}
```
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler>, <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::File>, <TAP::Parser::SourceHandler::Handle>, <TAP::Parser::SourceHandler::RawTAP>
perl Hash::Util::FieldHash Hash::Util::FieldHash
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [FUNCTIONS](#FUNCTIONS)
* [DESCRIPTION](#DESCRIPTION)
+ [The Inside-out Technique](#The-Inside-out-Technique)
+ [Problems of Inside-out](#Problems-of-Inside-out)
+ [Solutions](#Solutions)
+ [More Problems](#More-Problems)
+ [The Generic Object](#The-Generic-Object)
+ [How to use Field Hashes](#How-to-use-Field-Hashes)
+ [Garbage-Collected Hashes](#Garbage-Collected-Hashes)
* [EXAMPLES](#EXAMPLES)
+ [Example 1](#Example-1)
+ [Example 2](#Example-2)
* [GUTS](#GUTS)
+ [The PERL\_MAGIC\_uvar interface for hashes](#The-PERL_MAGIC_uvar-interface-for-hashes)
+ [Weakrefs call uvar magic](#Weakrefs-call-uvar-magic)
+ [How field hashes work](#How-field-hashes-work)
+ [Internal function Hash::Util::FieldHash::\_fieldhash](#Internal-function-Hash::Util::FieldHash::_fieldhash)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Hash::Util::FieldHash - Support for Inside-Out Classes
SYNOPSIS
--------
```
### Create fieldhashes
use Hash::Util qw(fieldhash fieldhashes);
# Create a single field hash
fieldhash my %foo;
# Create three at once...
fieldhashes \ my(%foo, %bar, %baz);
# ...or any number
fieldhashes @hashrefs;
### Create an idhash and register it for garbage collection
use Hash::Util::FieldHash qw(idhash register);
idhash my %name;
my $object = \ do { my $o };
# register the idhash for garbage collection with $object
register($object, \ %name);
# the following entry will be deleted when $object goes out of scope
$name{$object} = 'John Doe';
### Register an ordinary hash for garbage collection
use Hash::Util::FieldHash qw(id register);
my %name;
my $object = \ do { my $o };
# register the hash %name for garbage collection of $object's id
register $object, \ %name;
# the following entry will be deleted when $object goes out of scope
$name{id $object} = 'John Doe';
```
FUNCTIONS
---------
`Hash::Util::FieldHash` offers a number of functions in support of ["The Inside-out Technique"](#The-Inside-out-Technique) of class construction.
id
```
id($obj)
```
Returns the reference address of a reference $obj. If $obj is not a reference, returns $obj.
This function is a stand-in replacement for [Scalar::Util::refaddr](Scalar::Util#refaddr), that is, it returns the reference address of its argument as a numeric value. The only difference is that `refaddr()` returns `undef` when given a non-reference while `id()` returns its argument unchanged.
`id()` also uses a caching technique that makes it faster when the id of an object is requested often, but slower if it is needed only once or twice.
id\_2obj
```
$obj = id_2obj($id)
```
If `$id` is the id of a registered object (see ["register"](#register)), returns the object, otherwise an undefined value. For registered objects this is the inverse function of `id()`.
register
```
register($obj)
register($obj, @hashrefs)
```
In the first form, registers an object to work with for the function `id_2obj()`. In the second form, it additionally marks the given hashrefs down for garbage collection. This means that when the object goes out of scope, any entries in the given hashes under the key of `id($obj)` will be deleted from the hashes.
It is a fatal error to register a non-reference $obj. Any non-hashrefs among the following arguments are silently ignored.
It is *not* an error to register the same object multiple times with varying sets of hashrefs. Any hashrefs that are not registered yet will be added, others ignored.
Registry also implies thread support. When a new thread is created, all references are replaced with new ones, including all objects. If a hash uses the reference address of an object as a key, that connection would be broken. With a registered object, its id will be updated in all hashes registered with it.
idhash
```
idhash my %hash
```
Makes an idhash from the argument, which must be a hash.
An *idhash* works like a normal hash, except that it stringifies a *reference used as a key* differently. A reference is stringified as if the `id()` function had been invoked on it, that is, its reference address in decimal is used as the key.
idhashes
```
idhashes \ my(%hash, %gnash, %trash)
idhashes \ @hashrefs
```
Creates many idhashes from its hashref arguments. Returns those arguments that could be converted or their number in scalar context.
fieldhash
```
fieldhash %hash;
```
Creates a single fieldhash. The argument must be a hash. Returns a reference to the given hash if successful, otherwise nothing.
A *fieldhash* is, in short, an idhash with auto-registry. When an object (or, indeed, any reference) is used as a fieldhash key, the fieldhash is automatically registered for garbage collection with the object, as if `register $obj, \ %fieldhash` had been called.
fieldhashes
```
fieldhashes @hashrefs;
```
Creates any number of field hashes. Arguments must be hash references. Returns the converted hashrefs in list context, their number in scalar context.
DESCRIPTION
-----------
A word on terminology: I shall use the term *field* for a scalar piece of data that a class associates with an object. Other terms that have been used for this concept are "object variable", "(object) property", "(object) attribute" and more. Especially "attribute" has some currency among Perl programmer, but that clashes with the `attributes` pragma. The term "field" also has some currency in this sense and doesn't seem to conflict with other Perl terminology.
In Perl, an object is a blessed reference. The standard way of associating data with an object is to store the data inside the object's body, that is, the piece of data pointed to by the reference.
In consequence, if two or more classes want to access an object they *must* agree on the type of reference and also on the organization of data within the object body. Failure to agree on the type results in immediate death when the wrong method tries to access an object. Failure to agree on data organization may lead to one class trampling over the data of another.
This object model leads to a tight coupling between subclasses. If one class wants to inherit from another (and both classes access object data), the classes must agree about implementation details. Inheritance can only be used among classes that are maintained together, in a single source or not.
In particular, it is not possible to write general-purpose classes in this technique, classes that can advertise themselves as "Put me on your @ISA list and use my methods". If the other class has different ideas about how the object body is used, there is trouble.
For reference `Name_hash` in ["Example 1"](#Example-1) shows the standard implementation of a simple class `Name` in the well-known hash based way. It also demonstrates the predictable failure to construct a common subclass `NamedFile` of `Name` and the class `IO::File` (whose objects *must* be globrefs).
Thus, techniques are of interest that store object data *not* in the object body but some other place.
###
The Inside-out Technique
With *inside-out* classes, each class declares a (typically lexical) hash for each field it wants to use. The reference address of an object is used as the hash key. By definition, the reference address is unique to each object so this guarantees a place for each field that is private to the class and unique to each object. See `Name_id` in ["Example 1"](#Example-1) for a simple example.
In comparison to the standard implementation where the object is a hash and the fields correspond to hash keys, here the fields correspond to hashes, and the object determines the hash key. Thus the hashes appear to be turned *inside out*.
The body of an object is never examined by an inside-out class, only its reference address is used. This allows for the body of an actual object to be *anything at all* while the object methods of the class still work as designed. This is a key feature of inside-out classes.
###
Problems of Inside-out
Inside-out classes give us freedom of inheritance, but as usual there is a price.
Most obviously, there is the necessity of retrieving the reference address of an object for each data access. It's a minor inconvenience, but it does clutter the code.
More important (and less obvious) is the necessity of garbage collection. When a normal object dies, anything stored in the object body is garbage-collected by perl. With inside-out objects, Perl knows nothing about the data stored in field hashes by a class, but these must be deleted when the object goes out of scope. Thus the class must provide a `DESTROY` method to take care of that.
In the presence of multiple classes it can be non-trivial to make sure that every relevant destructor is called for every object. Perl calls the first one it finds on the inheritance tree (if any) and that's it.
A related issue is thread-safety. When a new thread is created, the Perl interpreter is cloned, which implies that all reference addresses in use will be replaced with new ones. Thus, if a class tries to access a field of a cloned object its (cloned) data will still be stored under the now invalid reference address of the original in the parent thread. A general `CLONE` method must be provided to re-establish the association.
### Solutions
`Hash::Util::FieldHash` addresses these issues on several levels.
The `id()` function is provided in addition to the existing `Scalar::Util::refaddr()`. Besides its short name it can be a little faster under some circumstances (and a bit slower under others). Benchmark if it matters. The working of `id()` also allows the use of the class name as a *generic object* as described [further down](#The-Generic-Object).
The `id()` function is incorporated in *id hashes* in the sense that it is called automatically on every key that is used with the hash. No explicit call is necessary.
The problems of garbage collection and thread safety are both addressed by the function `register()`. It registers an object together with any number of hashes. Registry means that when the object dies, an entry in any of the hashes under the reference address of this object will be deleted. This guarantees garbage collection in these hashes. It also means that on thread cloning the object's entries in registered hashes will be replaced with updated entries whose key is the cloned object's reference address. Thus the object-data association becomes thread-safe.
Object registry is best done when the object is initialized for use with a class. That way, garbage collection and thread safety are established for every object and every field that is initialized.
Finally, *field hashes* incorporate all these functions in one package. Besides automatically calling the `id()` function on every object used as a key, the object is registered with the field hash on first use. Classes based on field hashes are fully garbage-collected and thread safe without further measures.
###
More Problems
Another problem that occurs with inside-out classes is serialization. Since the object data is not in its usual place, standard routines like `Storable::freeze()`, `Storable::thaw()` and `Data::Dumper::Dumper()` can't deal with it on their own. Both `Data::Dumper` and `Storable` provide the necessary hooks to make things work, but the functions or methods used by the hooks must be provided by each inside-out class.
A general solution to the serialization problem would require another level of registry, one that associates *classes* and fields. So far, the functions of `Hash::Util::FieldHash` are unaware of any classes, which I consider a feature. Therefore `Hash::Util::FieldHash` doesn't address the serialization problems.
###
The Generic Object
Classes based on the `id()` function (and hence classes based on `idhash()` and `fieldhash()`) show a peculiar behavior in that the class name can be used like an object. Specifically, methods that set or read data associated with an object continue to work as class methods, just as if the class name were an object, distinct from all other objects, with its own data. This object may be called the *generic object* of the class.
This works because field hashes respond to keys that are not references like a normal hash would and use the string offered as the hash key. Thus, if a method is called as a class method, the field hash is presented with the class name instead of an object and blithely uses it as a key. Since the keys of real objects are decimal numbers, there is no conflict and the slot in the field hash can be used like any other. The `id()` function behaves correspondingly with respect to non-reference arguments.
Two possible uses (besides ignoring the property) come to mind. A singleton class could be implemented this using the generic object. If necessary, an `init()` method could die or ignore calls with actual objects (references), so only the generic object will ever exist.
Another use of the generic object would be as a template. It is a convenient place to store class-specific defaults for various fields to be used in actual object initialization.
Usually, the feature can be entirely ignored. Calling *object methods* as *class methods* normally leads to an error and isn't used routinely anywhere. It may be a problem that this error isn't indicated by a class with a generic object.
###
How to use Field Hashes
Traditionally, the definition of an inside-out class contains a bare block inside which a number of lexical hashes are declared and the basic accessor methods defined, usually through `Scalar::Util::refaddr`. Further methods may be defined outside this block. There has to be a DESTROY method and, for thread support, a CLONE method.
When field hashes are used, the basic structure remains the same. Each lexical hash will be made a field hash. The call to `refaddr` can be omitted from the accessor methods. DESTROY and CLONE methods are not necessary.
If you have an existing inside-out class, simply making all hashes field hashes with no other change should make no difference. Through the calls to `refaddr` or equivalent, the field hashes never get to see a reference and work like normal hashes. Your DESTROY (and CLONE) methods are still needed.
To make the field hashes kick in, it is easiest to redefine `refaddr` as
```
sub refaddr { shift }
```
instead of importing it from `Scalar::Util`. It should now be possible to disable DESTROY and CLONE. Note that while it isn't disabled, DESTROY will be called before the garbage collection of field hashes, so it will be invoked with a functional object and will continue to function.
It is not desirable to import the functions `fieldhash` and/or `fieldhashes` into every class that is going to use them. They are only used once to set up the class. When the class is up and running, these functions serve no more purpose.
If there are only a few field hashes to declare, it is simplest to
```
use Hash::Util::FieldHash;
```
early and call the functions qualified:
```
Hash::Util::FieldHash::fieldhash my %foo;
```
Otherwise, import the functions into a convenient package like `HUF` or, more general, `Aux`
```
{
package Aux;
use Hash::Util::FieldHash ':all';
}
```
and call
```
Aux::fieldhash my %foo;
```
as needed.
###
Garbage-Collected Hashes
Garbage collection in a field hash means that entries will "spontaneously" disappear when the object that created them disappears. That must be borne in mind, especially when looping over a field hash. If anything you do inside the loop could cause an object to go out of scope, a random key may be deleted from the hash you are looping over. That can throw the loop iterator, so it's best to cache a consistent snapshot of the keys and/or values and loop over that. You will still have to check that a cached entry still exists when you get to it.
Garbage collection can be confusing when keys are created in a field hash from normal scalars as well as references. Once a reference is *used* with a field hash, the entry will be collected, even if it was later overwritten with a plain scalar key (every positive integer is a candidate). This is true even if the original entry was deleted in the meantime. In fact, deletion from a field hash, and also a test for existence constitute *use* in this sense and create a liability to delete the entry when the reference goes out of scope. If you happen to create an entry with an identical key from a string or integer, that will be collected instead. Thus, mixed use of references and plain scalars as field hash keys is not entirely supported.
EXAMPLES
--------
The examples show a very simple class that implements a *name*, consisting of a first and last name (no middle initial). The name class has four methods:
* `init()`
An object method that initializes the first and last name to its two arguments. If called as a class method, `init()` creates an object in the given class and initializes that.
* `first()`
Retrieve the first name
* `last()`
Retrieve the last name
* `name()`
Retrieve the full name, the first and last name joined by a blank.
The examples show this class implemented with different levels of support by `Hash::Util::FieldHash`. All supported combinations are shown. The difference between implementations is often quite small. The implementations are:
* `Name_hash`
A conventional (not inside-out) implementation where an object is a hash that stores the field values, without support by `Hash::Util::FieldHash`. This implementation doesn't allow arbitrary inheritance.
* `Name_id`
Inside-out implementation based on the `id()` function. It needs a `DESTROY` method. For thread support a `CLONE` method (not shown) would also be needed. Instead of `Hash::Util::FieldHash::id()` the function `Scalar::Util::refaddr` could be used with very little functional difference. This is the basic pattern of an inside-out class.
* `Name_idhash`
Idhash-based inside-out implementation. Like `Name_id` it needs a `DESTROY` method and would need `CLONE` for thread support.
* `Name_id_reg`
Inside-out implementation based on the `id()` function with explicit object registry. No destructor is needed and objects are thread safe.
* `Name_idhash_reg`
Idhash-based inside-out implementation with explicit object registry. No destructor is needed and objects are thread safe.
* `Name_fieldhash`
FieldHash-based inside-out implementation. Object registry happens automatically. No destructor is needed and objects are thread safe.
These examples are realized in the code below, which could be copied to a file *Example.pm*.
###
Example 1
```
use strict; use warnings;
{
package Name_hash; # standard implementation: the
# object is a hash
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless {}, $obj unless ref $obj;
$obj->{ first} = $first;
$obj->{ last} = $last;
$obj;
}
sub first { shift()->{ first} }
sub last { shift()->{ last} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
}
{
package Name_id;
use Hash::Util::FieldHash qw(id);
my (%first, %last);
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless \ my $o, $obj unless ref $obj;
$first{ id $obj} = $first;
$last{ id $obj} = $last;
$obj;
}
sub first { $first{ id shift()} }
sub last { $last{ id shift()} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
sub DESTROY {
my $id = id shift;
delete $first{ $id};
delete $last{ $id};
}
}
{
package Name_idhash;
use Hash::Util::FieldHash;
Hash::Util::FieldHash::idhashes( \ my (%first, %last) );
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless \ my $o, $obj unless ref $obj;
$first{ $obj} = $first;
$last{ $obj} = $last;
$obj;
}
sub first { $first{ shift()} }
sub last { $last{ shift()} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
sub DESTROY {
my $n = shift;
delete $first{ $n};
delete $last{ $n};
}
}
{
package Name_id_reg;
use Hash::Util::FieldHash qw(id register);
my (%first, %last);
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless \ my $o, $obj unless ref $obj;
register( $obj, \ (%first, %last) );
$first{ id $obj} = $first;
$last{ id $obj} = $last;
$obj;
}
sub first { $first{ id shift()} }
sub last { $last{ id shift()} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
}
{
package Name_idhash_reg;
use Hash::Util::FieldHash qw(register);
Hash::Util::FieldHash::idhashes \ my (%first, %last);
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless \ my $o, $obj unless ref $obj;
register( $obj, \ (%first, %last) );
$first{ $obj} = $first;
$last{ $obj} = $last;
$obj;
}
sub first { $first{ shift()} }
sub last { $last{ shift()} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
}
{
package Name_fieldhash;
use Hash::Util::FieldHash;
Hash::Util::FieldHash::fieldhashes \ my (%first, %last);
sub init {
my $obj = shift;
my ($first, $last) = @_;
# create an object if called as class method
$obj = bless \ my $o, $obj unless ref $obj;
$first{ $obj} = $first;
$last{ $obj} = $last;
$obj;
}
sub first { $first{ shift()} }
sub last { $last{ shift()} }
sub name {
my $n = shift;
join ' ' => $n->first, $n->last;
}
}
1;
```
To exercise the various implementations the script [below](#Example-2) can be used.
It sets up a class `Name` that is a mirror of one of the implementation classes `Name_hash`, `Name_id`, ..., `Name_fieldhash`. That determines which implementation is run.
The script first verifies the function of the `Name` class.
In the second step, the free inheritability of the implementation (or lack thereof) is demonstrated. For this purpose it constructs a class called `NamedFile` which is a common subclass of `Name` and the standard class `IO::File`. This puts inheritability to the test because objects of `IO::File` *must* be globrefs. Objects of `NamedFile` should behave like a file opened for reading and also support the `name()` method. This class juncture works with exception of the `Name_hash` implementation, where object initialization fails because of the incompatibility of object bodies.
###
Example 2
```
use strict; use warnings; $| = 1;
use Example;
{
package Name;
use parent 'Name_id'; # define here which implementation to run
}
# Verify that the base package works
my $n = Name->init(qw(Albert Einstein));
print $n->name, "\n";
print "\n";
# Create a named file handle (See definition below)
my $nf = NamedFile->init(qw(/tmp/x Filomena File));
# use as a file handle...
for ( 1 .. 3 ) {
my $l = <$nf>;
print "line $_: $l";
}
# ...and as a Name object
print "...brought to you by ", $nf->name, "\n";
exit;
# Definition of NamedFile
package NamedFile;
use parent 'Name';
use parent 'IO::File';
sub init {
my $obj = shift;
my ($file, $first, $last) = @_;
$obj = $obj->IO::File::new() unless ref $obj;
$obj->open($file) or die "Can't read '$file': $!";
$obj->Name::init($first, $last);
}
__END__
```
GUTS
----
To make `Hash::Util::FieldHash` work, there were two changes to *perl* itself. `PERL_MAGIC_uvar` was made available for hashes, and weak references now call uvar `get` magic after a weakref has been cleared. The first feature is used to make field hashes intercept their keys upon access. The second one triggers garbage collection.
###
The `PERL_MAGIC_uvar` interface for hashes
`PERL_MAGIC_uvar` *get* magic is called from `hv_fetch_common` and `hv_delete_common` through the function `hv_magic_uvar_xkey`, which defines the interface. The call happens for hashes with "uvar" magic if the `ufuncs` structure has equal values in the `uf_val` and `uf_set` fields. Hashes are unaffected if (and as long as) these fields hold different values.
Upon the call, the `mg_obj` field will hold the hash key to be accessed. Upon return, the `SV*` value in `mg_obj` will be used in place of the original key in the hash access. The integer index value in the first parameter will be the `action` value from `hv_fetch_common`, or -1 if the call is from `hv_delete_common`.
This is a template for a function suitable for the `uf_val` field in a `ufuncs` structure for this call. The `uf_set` and `uf_index` fields are irrelevant.
```
IV watch_key(pTHX_ IV action, SV* field) {
MAGIC* mg = mg_find(field, PERL_MAGIC_uvar);
SV* keysv = mg->mg_obj;
/* Do whatever you need to. If you decide to
supply a different key newkey, return it like this
*/
sv_2mortal(newkey);
mg->mg_obj = newkey;
return 0;
}
```
###
Weakrefs call uvar magic
When a weak reference is stored in an `SV` that has "uvar" magic, `set` magic is called after the reference has gone stale. This hook can be used to trigger further garbage-collection activities associated with the referenced object.
###
How field hashes work
The three features of key hashes, *key replacement*, *thread support*, and *garbage collection* are supported by a data structure called the *object registry*. This is a private hash where every object is stored. An "object" in this sense is any reference (blessed or unblessed) that has been used as a field hash key.
The object registry keeps track of references that have been used as field hash keys. The keys are generated from the reference address like in a field hash (though the registry isn't a field hash). Each value is a weak copy of the original reference, stored in an `SV` that is itself magical (`PERL_MAGIC_uvar` again). The magical structure holds a list (another hash, really) of field hashes that the reference has been used with. When the weakref becomes stale, the magic is activated and uses the list to delete the reference from all field hashes it has been used with. After that, the entry is removed from the object registry itself. Implicitly, that frees the magic structure and the storage it has been using.
Whenever a reference is used as a field hash key, the object registry is checked and a new entry is made if necessary. The field hash is then added to the list of fields this reference has used.
The object registry is also used to repair a field hash after thread cloning. Here, the entire object registry is processed. For every reference found there, the field hashes it has used are visited and the entry is updated.
###
Internal function Hash::Util::FieldHash::\_fieldhash
```
# test if %hash is a field hash
my $result = _fieldhash \ %hash, 0;
# make %hash a field hash
my $result = _fieldhash \ %hash, 1;
```
`_fieldhash` is the internal function used to create field hashes. It takes two arguments, a hashref and a mode. If the mode is boolean false, the hash is not changed but tested if it is a field hash. If the hash isn't a field hash the return value is boolean false. If it is, the return value indicates the mode of field hash. When called with a boolean true mode, it turns the given hash into a field hash of this mode, returning the mode of the created field hash. `_fieldhash` does not erase the given hash.
Currently there is only one type of field hash, and only the boolean value of the mode makes a difference, but that may change.
AUTHOR
------
Anno Siegel (ANNO) wrote the xs code and the changes in perl proper Jerry Hedden (JDHEDDEN) made it faster
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2006-2007 by (Anno Siegel)
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.7 or, at your option, any later version of Perl 5 you may have available.
| programming_docs |
perl IO::Compress::Zip IO::Compress::Zip
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [zip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#zip-%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)
- [File Naming Options](#File-Naming-Options)
- [Overall Zip Archive Structure](#Overall-Zip-Archive-Structure)
- [Deflate Compression Options](#Deflate-Compression-Options)
- [Bzip2 Compression Options](#Bzip2-Compression-Options)
- [Lzma and Xz Compression Options](#Lzma-and-Xz-Compression-Options)
- [Other Options](#Other-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::Zip - Write zip files/buffers
SYNOPSIS
--------
```
use IO::Compress::Zip qw(zip $ZipError) ;
my $status = zip $input => $output [,OPTS]
or die "zip failed: $ZipError\n";
my $z = IO::Compress::Zip->new( $output [,OPTS] )
or die "zip failed: $ZipError\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() ;
$ZipError ;
# 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 zip compressed data to files or buffer.
The primary purpose of this module is to provide streaming write access to zip files and buffers.
At present the following compression methods are supported by IO::Compress::Zip
Store (0)
Deflate (8)
Bzip2 (12) To write Bzip2 content, the module `IO::Uncompress::Bunzip2` must be installed.
Lzma (14) To write LZMA content, the module `IO::Uncompress::UnLzma` must be installed.
Zstandard (93) To write Zstandard content, the module `IO::Compress::Zstd` must be installed.
Xz (95) To write Xz content, the module `IO::Uncompress::UnXz` must be installed.
For reading zip files/buffers, see the companion module <IO::Uncompress::Unzip>.
Functional Interface
---------------------
A top-level function, `zip`, 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::Zip qw(zip $ZipError) ;
zip $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "zip failed: $ZipError\n";
```
The functional interface needs Perl5.005 or better.
###
zip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`zip` 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 ">" `zip` 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.
In addition, if `$input_filename_or_reference` is a simple filename, the default values for the `Name`, `Time`, `TextFlag`, `ExtAttr`, `exUnixN` and `exTime` options will be sourced from that file.
If you do not want to use these defaults they can be overridden by explicitly setting the `Name`, `Time`, `TextFlag`, `ExtAttr`, `exUnixN` and `exTime` options or by setting the `Minimal` parameter.
####
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 ">" `zip` 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 each be stored in `$output_filename_or_reference` as a distinct entry.
###
Optional Parameters
The optional parameters for the one-shot function `zip` 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 `zip` 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 `zip` 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::Zip=zip -e 'zip \*STDIN => \*STDOUT' >output.zip
```
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::Zip=zip -e 'zip "-" => "-"' >output.zip
```
One problem with creating a zip archive directly from STDIN can be demonstrated by looking at the contents of the zip file, output.zip, that we have just created.
```
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:21
--------- -------
12 1 file
```
The archive member (filename) used is the empty string.
If that doesn't suit your needs, you can explicitly set the filename used in the zip archive by specifying the [Name](#File-Naming-Options) option, like so
```
echo hello world | perl -MIO::Compress::Zip=zip -e 'zip "-" => "-", Name => "hello.txt"' >output.zip
```
Now the contents of the zip file looks like this
```
$ unzip -l output.zip
Archive: output.zip
Length Date Time Name
--------- ---------- ----- ----
12 2019-08-16 22:22 hello.txt
--------- -------
12 1 file
```
####
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.zip`.
```
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my $input = "file1.txt";
zip $input => "$input.zip"
or die "zip failed: $ZipError\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::Zip qw(zip $ZipError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt" )
or die "Cannot open 'file1.txt': $!\n" ;
my $buffer ;
zip $input => \$buffer
or die "zip failed: $ZipError\n";
```
####
Compressing multiple files
To create a zip file, `output.zip`, that contains the compressed contents of the files `alpha.txt` and `beta.txt`
```
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
zip [ 'alpha.txt', 'beta.txt' ] => 'output.zip'
or die "zip failed: $ZipError\n";
```
Alternatively, rather than having to explicitly name each of the files that you want to compress, you could use a fileglob to select all the `txt` files in the current directory, as follows
```
use strict ;
use warnings ;
use IO::Compress::Zip qw(zip $ZipError) ;
my @files = <*.txt>;
zip \@files => 'output.zip'
or die "zip failed: $ZipError\n";
```
or more succinctly
```
zip [ <*.txt> ] => 'output.zip'
or die "zip failed: $ZipError\n";
```
OO Interface
-------------
### Constructor
The format of the constructor for `IO::Compress::Zip` is shown below
```
my $z = IO::Compress::Zip->new( $output [,OPTS] )
or die "IO::Compress::Zip failed: $ZipError\n";
```
It returns an `IO::Compress::Zip` object on success and undef on failure. The variable `$ZipError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Compress::Zip 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::Zip`::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::Zip` 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.
####
File Naming Options
A quick bit of zip file terminology -- A zip archive consists of one or more *archive members*, where each member has an associated filename, known as the *archive member name*.
The options listed in this section control how the *archive member name* (or filename) is stored the zip archive.
`Name => $string`
This option is used to explicitly set the *archive member name* in the zip archive to `$string`. Most of the time you don't need to make use of this option. By default when adding a filename to the zip archive, the *archive member name* will match the filename.
You should only need to use this option if you want the *archive member name* to be different from the uncompressed filename or when the input is a filehandle or a buffer.
The default behaviour for what *archive member name* is used when the `Name` option is *not* specified depends on the form of the `$input` parameter:
* If the `$input` parameter is a filename, the value of `$input` will be used for the *archive member name* .
* If the `$input` parameter is not a filename, the *archive member name* will be an empty string.
Note that both the `CanonicalName` and `FilterName` options can modify the value used for the *archive member name*.
Also note that you should set the `Efs` option to true if you are working with UTF8 filenames.
`CanonicalName => 0|1`
This option controls whether the *archive member name* is *normalized* into Unix format before being written to the zip file.
It is recommended that you enable this option unless you really need to create a non-standard Zip file.
This is what APPNOTE.TXT has to say on what should be stored in the zip filename header field.
```
The name of the file, with optional relative path.
The path stored should not contain a drive or
device letter, or a leading slash. All slashes
should be forward slashes '/' as opposed to
backwards slashes '\' for compatibility with Amiga
and UNIX file systems etc.
```
This option defaults to **false**.
`FilterName => sub { ... }`
This option allow the *archive member* name to be modified before it is written to the zip file.
This option takes a parameter that must be a reference to a sub. On entry to the sub the `$_` variable will contain the name to be filtered. If no filename is available `$_` will contain an empty string.
The value of `$_` when the sub returns will be used as the *archive member name*.
Note that if `CanonicalName` is enabled, a normalized filename will be passed to the sub.
If you use `FilterName` to modify the filename, it is your responsibility to keep the filename in Unix format.
Although this option can be used with the OO interface, it is of most use with the one-shot interface. For example, the code below shows how `FilterName` can be used to remove the path component from a series of filenames before they are stored in `$zipfile`.
```
sub compressTxtFiles
{
my $zipfile = shift ;
my $dir = shift ;
zip [ <$dir/*.txt> ] => $zipfile,
FilterName => sub { s[^$dir/][] } ;
}
```
`Efs => 0|1`
This option controls setting of the "Language Encoding Flag" (EFS) in the zip archive. When set, the filename and comment fields for the zip archive MUST be valid UTF-8.
If the string used for the filename and/or comment is not valid UTF-8 when this option is true, the script will die with a "wide character" error.
Note that this option only works with Perl 5.8.4 or better.
This option defaults to **false**.
####
Overall Zip Archive Structure
`Minimal => 1|0`
If specified, this option will disable the creation of all extra fields in the zip local and central headers. So the `exTime`, `exUnix2`, `exUnixN`, `ExtraFieldLocal` and `ExtraFieldCentral` options will be ignored.
This parameter defaults to 0.
`Stream => 0|1`
This option controls whether the zip file/buffer output is created in streaming mode.
Note that when outputting to a file with streaming mode disabled (`Stream` is 0), the output file must be seekable.
The default is 1.
`Zip64 => 0|1`
Create a Zip64 zip file/buffer. This option is used if you want to store files larger than 4 Gig or store more than 64K files in a single zip archive.
`Zip64` will be automatically set, as needed, if working with the one-shot interface when the input is either a filename or a scalar reference.
If you intend to manipulate the Zip64 zip files created with this module 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.
The default is 0.
####
Deflate Compression Options
-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::Zip` by default.
```
use IO::Compress::Zip qw(:strategy);
use IO::Compress::Zip qw(:constants);
use IO::Compress::Zip 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.
####
Bzip2 Compression Options
`BlockSize100K => number`
Specify the number of 100K blocks bzip2 uses during compression.
Valid values are from 1 to 9, where 9 is best compression.
This option is only valid if the `Method` is ZIP\_CM\_BZIP2. It is ignored otherwise.
The default is 1.
`WorkFactor => number`
Specifies how much effort bzip2 should take before resorting to a slower fallback compression algorithm.
Valid values range from 0 to 250, where 0 means use the default value 30.
This option is only valid if the `Method` is ZIP\_CM\_BZIP2. It is ignored otherwise.
The default is 0.
####
Lzma and Xz Compression Options
`Preset => number`
Used to choose the LZMA compression preset.
Valid values are 0-9 and `LZMA_PRESET_DEFAULT`.
0 is the fastest compression with the lowest memory usage and the lowest compression.
9 is the slowest compression with the highest memory usage but with the best compression.
This option is only valid if the `Method` is ZIP\_CM\_LZMA. It is ignored otherwise.
Defaults to `LZMA_PRESET_DEFAULT` (6).
`Extreme => 0|1`
Makes LZMA compression a lot slower, but a small compression gain.
This option is only valid if the `Method` is ZIP\_CM\_LZMA. It is ignored otherwise.
Defaults to 0.
####
Other Options
`Time => $number`
Sets the last modified time field in the zip header to $number.
This field defaults to the time the `IO::Compress::Zip` object was created if this option is not specified and the `$input` parameter is not a filename.
`ExtAttr => $attr`
This option controls the "external file attributes" field in the central header of the zip file. This is a 4 byte field.
If you are running a Unix derivative this value defaults to
```
0100644 << 16
```
This should allow read/write access to any files that are extracted from the zip file/buffer`.
For all other systems it defaults to 0.
`exTime => [$atime, $mtime, $ctime]`
This option expects an array reference with exactly three elements: `$atime`, `mtime` and `$ctime`. These correspond to the last access time, last modification time and creation time respectively.
It uses these values to set the extended timestamp field (ID is "UT") in the local zip header using the three values, $atime, $mtime, $ctime. In addition it sets the extended timestamp field in the central zip header using `$mtime`.
If any of the three values is `undef` that time value will not be used. So, for example, to set only the `$mtime` you would use this
```
exTime => [undef, $mtime, undef]
```
If the `Minimal` option is set to true, this option will be ignored.
By default no extended time field is created.
`exUnix2 => [$uid, $gid]`
This option expects an array reference with exactly two elements: `$uid` and `$gid`. These values correspond to the numeric User ID (UID) and Group ID (GID) of the owner of the files respectively.
When the `exUnix2` option is present it will trigger the creation of a Unix2 extra field (ID is "Ux") in the local zip header. This will be populated with `$uid` and `$gid`. An empty Unix2 extra field will also be created in the central zip header.
Note - The UID & GID are stored as 16-bit integers in the "Ux" field. Use `exUnixN` if your UID or GID are 32-bit.
If the `Minimal` option is set to true, this option will be ignored.
By default no Unix2 extra field is created.
`exUnixN => [$uid, $gid]`
This option expects an array reference with exactly two elements: `$uid` and `$gid`. These values correspond to the numeric User ID (UID) and Group ID (GID) of the owner of the files respectively.
When the `exUnixN` option is present it will trigger the creation of a UnixN extra field (ID is "ux") in both the local and central zip headers. This will be populated with `$uid` and `$gid`. The UID & GID are stored as 32-bit integers.
If the `Minimal` option is set to true, this option will be ignored.
By default no UnixN extra field is created.
`Comment => $comment`
Stores the contents of `$comment` in the Central File Header of the zip file.
Set the `Efs` option to true if you want to store a UTF8 comment.
By default, no comment field is written to the zip file.
`ZipComment => $comment`
Stores the contents of `$comment` in the End of Central Directory record of the zip file.
By default, no comment field is written to the zip file.
`Method => $method`
Controls which compression method is used. At present the compression methods supported are: Store (no compression at all), Deflate, Bzip2, Zstd, Xz and Lzma.
The symbols ZIP\_CM\_STORE, ZIP\_CM\_DEFLATE, ZIP\_CM\_BZIP2, ZIP\_CM\_ZSTD, ZIP\_CM\_XZ and ZIP\_CM\_LZMA are used to select the compression method.
These constants are not imported by `IO::Compress::Zip` by default.
```
use IO::Compress::Zip qw(:zip_method);
use IO::Compress::Zip qw(:constants);
use IO::Compress::Zip qw(:all);
```
Note that to create Bzip2 content, the module `IO::Compress::Bzip2` must be installed. A fatal error will be thrown if you attempt to create Bzip2 content when `IO::Compress::Bzip2` is not available.
Note that to create Lzma content, the module `IO::Compress::Lzma` must be installed. A fatal error will be thrown if you attempt to create Lzma content when `IO::Compress::Lzma` is not available.
Note that to create Xz content, the module `IO::Compress::Xz` must be installed. A fatal error will be thrown if you attempt to create Xz content when `IO::Compress::Xz` is not available.
Note that to create Zstd content, the module `IO::Compress::Zstd` must be installed. A fatal error will be thrown if you attempt to create Zstd content when `IO::Compress::Zstd` is not available.
The default method is ZIP\_CM\_DEFLATE.
`TextFlag => 0|1`
This parameter controls the setting of a bit in the zip central header. It is used to signal that the data stored in the zip file/buffer is probably text.
In one-shot mode this flag will be set to true if the Perl `-T` operator thinks the file contains text.
The default is 0.
`ExtraFieldLocal => $data`
`ExtraFieldCentral => $data`
The `ExtraFieldLocal` option is used to store additional metadata in the local header for the zip file/buffer. The `ExtraFieldCentral` does the same for the matching central header.
An extra field consists of zero or more subfields. Each subfield consists of a two byte header followed by the subfield data.
The list of subfields can be supplied in any of the following formats
```
ExtraFieldLocal => [$id1, $data1,
$id2, $data2,
...
]
ExtraFieldLocal => [ [$id1 => $data1],
[$id2 => $data2],
...
]
ExtraFieldLocal => { $id1 => $data1,
$id2 => $data2,
...
}
```
Where `$id1`, `$id2` are two byte subfield ID's.
If you use the hash syntax, you have no control over the order in which the ExtraSubFields are stored, plus you cannot have SubFields with duplicate ID.
Alternatively the list of subfields can by supplied as a scalar, thus
```
ExtraField => $rawdata
```
In this case `IO::Compress::Zip` will check that `$rawdata` consists of zero or more conformant sub-fields.
The Extended Time field (ID "UT"), set using the `exTime` option, and the Unix2 extra field (ID "Ux), set using the `exUnix2` option, are examples of extra fields.
If the `Minimal` option is set to true, this option will be ignored.
The maximum size of an extra field 65535 bytes.
`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::Zip 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::Zip 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::Zip`. None are imported by default.
:all Imports `zip`, `$ZipError` and all symbolic constants that can be used by `IO::Compress::Zip`. Same as doing this
```
use IO::Compress::Zip qw(zip $ZipError :constants) ;
```
:constants Import all symbolic constants. Same as doing this
```
use IO::Compress::Zip qw(:flush :level :strategy :zip_method) ;
```
: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
```
:zip\_method These symbolic constants are used by the `Method` option in the constructor.
```
ZIP_CM_STORE
ZIP_CM_DEFLATE
ZIP_CM_BZIP2
```
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::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 autodie::Util autodie::Util
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods](#Methods)
- [on\_end\_of\_compile\_scope](#on_end_of_compile_scope)
- [fill\_protos](#fill_protos)
- [make\_core\_trampoline](#make_core_trampoline)
- [install\_subs](#install_subs)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
autodie::Util - Internal Utility subroutines for autodie and Fatal
SYNOPSIS
--------
```
# INTERNAL API for autodie and Fatal only!
use autodie::Util qw(on_end_of_compile_scope);
on_end_of_compile_scope(sub { print "Hallo world\n"; });
```
DESCRIPTION
-----------
Interal Utilities for autodie and Fatal! This module is not a part of autodie's public API.
This module contains utility subroutines for abstracting away the underlying magic of autodie and (ab)uses of `%^H` to call subs at the end of a (compile-time) scopes.
Note that due to how `%^H` works, some of these utilities are only useful during the compilation phase of a perl module and relies on the internals of how perl handles references in `%^H`.
### Methods
#### on\_end\_of\_compile\_scope
```
on_end_of_compile_scope(sub { print "Hallo world\n"; });
```
Will invoke a sub at the end of a (compile-time) scope. The sub is called once with no arguments. Can be called multiple times (even in the same "compile-time" scope) to install multiple subs. Subs are called in a "first-in-last-out"-order (FILO or "stack"-order).
#### fill\_protos
```
fill_protos('*$$;$@')
```
Given a Perl subroutine prototype, return a list of invocation specifications. Each specification is a listref, where the first member is the (minimum) number of arguments for this invocation specification. The remaining arguments are a string representation of how to pass the arguments correctly to a sub with the given prototype, when called with the given number of arguments.
The specifications are returned in increasing order of arguments starting at 0 (e.g. ';$') or 1 (e.g. '$@'). Note that if the prototype is "slurpy" (e.g. ends with a "@"), the number of arguments for the last specification is a "minimum" number rather than an exact number. This can be detected by the last member of the last specification matching m/[@#]\_/.
#### make\_core\_trampoline
```
make_core_trampoline('CORE::open', 'main', prototype('CORE::open'))
```
Creates a trampoline for calling a core sub. Essentially, a tiny sub that figures out how we should be calling our core sub, puts in the arguments in the right way, and bounces our control over to it.
If we could reliably use `goto &` on core builtins, we wouldn't need this subroutine.
#### install\_subs
```
install_subs('My::Module', { 'read' => sub { die("Hallo\n"), ... }})
```
Given a package name and a hashref mapping names to a subroutine reference (or `undef`), this subroutine will install said subroutines on their given name in that module. If a name mapes to `undef`, any subroutine with that name in the target module will be remove (possibly "unshadowing" a CORE sub of same name).
AUTHOR
------
Copyright 2013-2014, Niels Thykier <[email protected]>
LICENSE
-------
This module is free software. You may distribute it under the same terms as Perl itself.
perl Math::BigInt Math::BigInt
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Input](#Input)
+ [Output](#Output)
* [METHODS](#METHODS)
+ [Configuration methods](#Configuration-methods)
+ [Constructor methods](#Constructor-methods)
+ [Boolean methods](#Boolean-methods)
+ [Comparison methods](#Comparison-methods)
+ [Arithmetic methods](#Arithmetic-methods)
+ [Bitwise methods](#Bitwise-methods)
+ [Rounding methods](#Rounding-methods)
+ [Other mathematical methods](#Other-mathematical-methods)
+ [Object property methods](#Object-property-methods)
+ [String conversion methods](#String-conversion-methods)
+ [Other conversion methods](#Other-conversion-methods)
+ [Utility methods](#Utility-methods)
* [ACCURACY and PRECISION](#ACCURACY-and-PRECISION)
+ [Precision P](#Precision-P)
+ [Accuracy A](#Accuracy-A)
+ [Fallback F](#Fallback-F)
+ [Rounding mode R](#Rounding-mode-R)
- [Directed rounding](#Directed-rounding)
- [Rounding to nearest](#Rounding-to-nearest)
* [Infinity and Not a Number](#Infinity-and-Not-a-Number)
* [INTERNALS](#INTERNALS)
+ [MATH LIBRARY](#MATH-LIBRARY)
- [The default library](#The-default-library)
- [Specifying a library](#Specifying-a-library)
- [Which library to use?](#Which-library-to-use?)
- [Loading multiple libraries](#Loading-multiple-libraries)
+ [SIGN](#SIGN)
* [EXAMPLES](#EXAMPLES)
* [NUMERIC LITERALS](#NUMERIC-LITERALS)
+ [Hexadecimal, octal, and binary floating point literals](#Hexadecimal,-octal,-and-binary-floating-point-literals)
* [PERFORMANCE](#PERFORMANCE)
+ [Alternative math libraries](#Alternative-math-libraries)
* [SUBCLASSING](#SUBCLASSING)
+ [Subclassing Math::BigInt](#Subclassing-Math::BigInt)
* [UPGRADING](#UPGRADING)
+ [Auto-upgrade](#Auto-upgrade)
* [EXPORTS](#EXPORTS)
* [CAVEATS](#CAVEATS)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
Math::BigInt - arbitrary size integer math package
SYNOPSIS
--------
```
use Math::BigInt;
# or make it faster with huge numbers: install (optional)
# Math::BigInt::GMP and always use (it falls back to
# pure Perl if the GMP library is not installed):
# (See also the L<MATH LIBRARY> section!)
# to warn if Math::BigInt::GMP cannot be found, use
use Math::BigInt lib => 'GMP';
# to suppress the warning if Math::BigInt::GMP cannot be found, use
# use Math::BigInt try => 'GMP';
# to die if Math::BigInt::GMP cannot be found, use
# use Math::BigInt only => 'GMP';
my $str = '1234567890';
my @values = (64, 74, 18);
my $n = 1; my $sign = '-';
# Configuration methods (may be used as class methods and instance methods)
Math::BigInt->accuracy(); # get class accuracy
Math::BigInt->accuracy($n); # set class accuracy
Math::BigInt->precision(); # get class precision
Math::BigInt->precision($n); # set class precision
Math::BigInt->round_mode(); # get class rounding mode
Math::BigInt->round_mode($m); # set global round mode, must be one of
# 'even', 'odd', '+inf', '-inf', 'zero',
# 'trunc', or 'common'
Math::BigInt->config(); # return hash with configuration
# Constructor methods (when the class methods below are used as instance
# methods, the value is assigned the invocand)
$x = Math::BigInt->new($str); # defaults to 0
$x = Math::BigInt->new('0x123'); # from hexadecimal
$x = Math::BigInt->new('0b101'); # from binary
$x = Math::BigInt->from_hex('cafe'); # from hexadecimal
$x = Math::BigInt->from_oct('377'); # from octal
$x = Math::BigInt->from_bin('1101'); # from binary
$x = Math::BigInt->from_base('why', 36); # from any base
$x = Math::BigInt->from_base_num([1, 0], 2); # from any base
$x = Math::BigInt->bzero(); # create a +0
$x = Math::BigInt->bone(); # create a +1
$x = Math::BigInt->bone('-'); # create a -1
$x = Math::BigInt->binf(); # create a +inf
$x = Math::BigInt->binf('-'); # create a -inf
$x = Math::BigInt->bnan(); # create a Not-A-Number
$x = Math::BigInt->bpi(); # returns pi
$y = $x->copy(); # make a copy (unlike $y = $x)
$y = $x->as_int(); # return as a Math::BigInt
# Boolean methods (these don't modify the invocand)
$x->is_zero(); # if $x is 0
$x->is_one(); # if $x is +1
$x->is_one("+"); # ditto
$x->is_one("-"); # if $x is -1
$x->is_inf(); # if $x is +inf or -inf
$x->is_inf("+"); # if $x is +inf
$x->is_inf("-"); # if $x is -inf
$x->is_nan(); # if $x is NaN
$x->is_positive(); # if $x > 0
$x->is_pos(); # ditto
$x->is_negative(); # if $x < 0
$x->is_neg(); # ditto
$x->is_odd(); # if $x is odd
$x->is_even(); # if $x is even
$x->is_int(); # if $x is an integer
# Comparison methods
$x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0)
$x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0)
$x->beq($y); # true if and only if $x == $y
$x->bne($y); # true if and only if $x != $y
$x->blt($y); # true if and only if $x < $y
$x->ble($y); # true if and only if $x <= $y
$x->bgt($y); # true if and only if $x > $y
$x->bge($y); # true if and only if $x >= $y
# Arithmetic methods
$x->bneg(); # negation
$x->babs(); # absolute value
$x->bsgn(); # sign function (-1, 0, 1, or NaN)
$x->bnorm(); # normalize (no-op)
$x->binc(); # increment $x by 1
$x->bdec(); # decrement $x by 1
$x->badd($y); # addition (add $y to $x)
$x->bsub($y); # subtraction (subtract $y from $x)
$x->bmul($y); # multiplication (multiply $x by $y)
$x->bmuladd($y,$z); # $x = $x * $y + $z
$x->bdiv($y); # division (floored), set $x to quotient
# return (quo,rem) or quo if scalar
$x->btdiv($y); # division (truncated), set $x to quotient
# return (quo,rem) or quo if scalar
$x->bmod($y); # modulus (x % y)
$x->btmod($y); # modulus (truncated)
$x->bmodinv($mod); # modular multiplicative inverse
$x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod)
$x->bpow($y); # power of arguments (x ** y)
$x->blog(); # logarithm of $x to base e (Euler's number)
$x->blog($base); # logarithm of $x to base $base (e.g., base 2)
$x->bexp(); # calculate e ** $x where e is Euler's number
$x->bnok($y); # x over y (binomial coefficient n over k)
$x->buparrow($n, $y); # Knuth's up-arrow notation
$x->backermann($y); # the Ackermann function
$x->bsin(); # sine
$x->bcos(); # cosine
$x->batan(); # inverse tangent
$x->batan2($y); # two-argument inverse tangent
$x->bsqrt(); # calculate square root
$x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->bdfac(); # double factorial of $x ($x*($x-2)*($x-4)*...)
$x->btfac(); # triple factorial of $x ($x*($x-3)*($x-6)*...)
$x->bmfac($k); # $k'th multi-factorial of $x ($x*($x-$k)*...)
$x->blsft($n); # left shift $n places in base 2
$x->blsft($n,$b); # left shift $n places in base $b
# returns (quo,rem) or quo (scalar context)
$x->brsft($n); # right shift $n places in base 2
$x->brsft($n,$b); # right shift $n places in base $b
# returns (quo,rem) or quo (scalar context)
# Bitwise methods
$x->band($y); # bitwise and
$x->bior($y); # bitwise inclusive or
$x->bxor($y); # bitwise exclusive or
$x->bnot(); # bitwise not (two's complement)
# Rounding methods
$x->round($A,$P,$mode); # round to accuracy or precision using
# rounding mode $mode
$x->bround($n); # accuracy: preserve $n digits
$x->bfround($n); # $n > 0: round to $nth digit left of dec. point
# $n < 0: round to $nth digit right of dec. point
$x->bfloor(); # round towards minus infinity
$x->bceil(); # round towards plus infinity
$x->bint(); # round towards zero
# Other mathematical methods
$x->bgcd($y); # greatest common divisor
$x->blcm($y); # least common multiple
# Object property methods (do not modify the invocand)
$x->sign(); # the sign, either +, - or NaN
$x->digit($n); # the nth digit, counting from the right
$x->digit(-$n); # the nth digit, counting from the left
$x->length(); # return number of digits in number
($xl,$f) = $x->length(); # length of number and length of fraction
# part, latter is always 0 digits long
# for Math::BigInt objects
$x->mantissa(); # return (signed) mantissa as a Math::BigInt
$x->exponent(); # return exponent as a Math::BigInt
$x->parts(); # return (mantissa,exponent) as a Math::BigInt
$x->sparts(); # mantissa and exponent (as integers)
$x->nparts(); # mantissa and exponent (normalised)
$x->eparts(); # mantissa and exponent (engineering notation)
$x->dparts(); # integer and fraction part
$x->fparts(); # numerator and denominator
$x->numerator(); # numerator
$x->denominator(); # denominator
# Conversion methods (do not modify the invocand)
$x->bstr(); # decimal notation, possibly zero padded
$x->bsstr(); # string in scientific notation with integers
$x->bnstr(); # string in normalized notation
$x->bestr(); # string in engineering notation
$x->bdstr(); # string in decimal notation
$x->to_hex(); # as signed hexadecimal string
$x->to_bin(); # as signed binary string
$x->to_oct(); # as signed octal string
$x->to_bytes(); # as byte string
$x->to_base($b); # as string in any base
$x->to_base_num($b); # as array of integers in any base
$x->as_hex(); # as signed hexadecimal string with prefixed 0x
$x->as_bin(); # as signed binary string with prefixed 0b
$x->as_oct(); # as signed octal string with prefixed 0
# Other conversion methods
$x->numify(); # return as scalar (might overflow or underflow)
```
DESCRIPTION
-----------
Math::BigInt provides support for arbitrary precision integers. Overloading is also provided for Perl operators.
### Input
Input values to these routines may be any scalar number or string that looks like a number and represents an integer. Anything that is accepted by Perl as a literal numeric constant should be accepted by this module, except that finite non-integers return NaN.
* Leading and trailing whitespace is ignored.
* Leading zeros are ignored, except for floating point numbers with a binary exponent, in which case the number is interpreted as an octal floating point number. For example, "01.4p+0" gives 1.5, "00.4p+0" gives 0.5, but "0.4p+0" gives a NaN. And while "0377" gives 255, "0377p0" gives 255.
* If the string has a "0x" or "0X" prefix, it is interpreted as a hexadecimal number.
* If the string has a "0o" or "0O" prefix, it is interpreted as an octal number. A floating point literal with a "0" prefix is also interpreted as an octal number.
* If the string has a "0b" or "0B" prefix, it is interpreted as a binary number.
* Underline characters are allowed in the same way as they are allowed in literal numerical constants.
* If the string can not be interpreted, or does not represent a finite integer, NaN is returned.
* For hexadecimal, octal, and binary floating point numbers, the exponent must be separated from the significand (mantissa) by the letter "p" or "P", not "e" or "E" as with decimal numbers.
Some examples of valid string input
```
Input string Resulting value
123 123
1.23e2 123
12300e-2 123
67_538_754 67538754
-4_5_6.7_8_9e+0_1_0 -4567890000000
0x13a 314
0x13ap0 314
0x1.3ap+8 314
0x0.00013ap+24 314
0x13a000p-12 314
0o472 314
0o1.164p+8 314
0o0.0001164p+20 314
0o1164000p-10 314
0472 472 Note!
01.164p+8 314
00.0001164p+20 314
01164000p-10 314
0b100111010 314
0b1.0011101p+8 314
0b0.00010011101p+12 314
0b100111010000p-3 314
```
Input given as scalar numbers might lose precision. Quote your input to ensure that no digits are lost:
```
$x = Math::BigInt->new( 56789012345678901234 ); # bad
$x = Math::BigInt->new('56789012345678901234'); # good
```
Currently, `Math::BigInt-`new()> (no input argument) and `Math::BigInt-`new("")> return 0. This might change in the future, so always use the following explicit forms to get a zero:
```
$zero = Math::BigInt->bzero();
```
### Output
Output values are usually Math::BigInt objects.
Boolean operators `is_zero()`, `is_one()`, `is_inf()`, etc. return true or false.
Comparison operators `bcmp()` and `bacmp()`) return -1, 0, 1, or undef.
METHODS
-------
###
Configuration methods
Each of the methods below (except config(), accuracy() and precision()) accepts three additional parameters. These arguments `$A`, `$P` and `$R` are `accuracy`, `precision` and `round_mode`. Please see the section about ["ACCURACY and PRECISION"](#ACCURACY-and-PRECISION) for more information.
Setting a class variable effects all object instance that are created afterwards.
accuracy()
```
Math::BigInt->accuracy(5); # set class accuracy
$x->accuracy(5); # set instance accuracy
$A = Math::BigInt->accuracy(); # get class accuracy
$A = $x->accuracy(); # get instance accuracy
```
Set or get the accuracy, i.e., the number of significant digits. The accuracy must be an integer. If the accuracy is set to `undef`, no rounding is done.
Alternatively, one can round the results explicitly using one of ["round()"](#round%28%29), ["bround()"](#bround%28%29) or ["bfround()"](#bfround%28%29) or by passing the desired accuracy to the method as an additional parameter:
```
my $x = Math::BigInt->new(30000);
my $y = Math::BigInt->new(7);
print scalar $x->copy()->bdiv($y, 2); # prints 4300
print scalar $x->copy()->bdiv($y)->bround(2); # prints 4300
```
Please see the section about ["ACCURACY and PRECISION"](#ACCURACY-and-PRECISION) for further details.
```
$y = Math::BigInt->new(1234567); # $y is not rounded
Math::BigInt->accuracy(4); # set class accuracy to 4
$x = Math::BigInt->new(1234567); # $x is rounded automatically
print "$x $y"; # prints "1235000 1234567"
print $x->accuracy(); # prints "4"
print $y->accuracy(); # also prints "4", since
# class accuracy is 4
Math::BigInt->accuracy(5); # set class accuracy to 5
print $x->accuracy(); # prints "4", since instance
# accuracy is 4
print $y->accuracy(); # prints "5", since no instance
# accuracy, and class accuracy is 5
```
Note: Each class has it's own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt.
precision()
```
Math::BigInt->precision(-2); # set class precision
$x->precision(-2); # set instance precision
$P = Math::BigInt->precision(); # get class precision
$P = $x->precision(); # get instance precision
```
Set or get the precision, i.e., the place to round relative to the decimal point. The precision must be a integer. Setting the precision to $P means that each number is rounded up or down, depending on the rounding mode, to the nearest multiple of 10\*\*$P. If the precision is set to `undef`, no rounding is done.
You might want to use ["accuracy()"](#accuracy%28%29) instead. With ["accuracy()"](#accuracy%28%29) you set the number of digits each result should have, with ["precision()"](#precision%28%29) you set the place where to round.
Please see the section about ["ACCURACY and PRECISION"](#ACCURACY-and-PRECISION) for further details.
```
$y = Math::BigInt->new(1234567); # $y is not rounded
Math::BigInt->precision(4); # set class precision to 4
$x = Math::BigInt->new(1234567); # $x is rounded automatically
print $x; # prints "1230000"
```
Note: Each class has its own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt.
div\_scale() Set/get the fallback accuracy. This is the accuracy used when neither accuracy nor precision is set explicitly. It is used when a computation might otherwise attempt to return an infinite number of digits.
round\_mode() Set/get the rounding mode.
upgrade() Set/get the class for upgrading. When a computation might result in a non-integer, the operands are upgraded to this class. This is used for instance by <bignum>. The default is `undef`, i.e., no upgrading.
```
# with no upgrading
$x = Math::BigInt->new(12);
$y = Math::BigInt->new(5);
print $x / $y, "\n"; # 2 as a Math::BigInt
# with upgrading to Math::BigFloat
Math::BigInt -> upgrade("Math::BigFloat");
print $x / $y, "\n"; # 2.4 as a Math::BigFloat
# with upgrading to Math::BigRat (after loading Math::BigRat)
Math::BigInt -> upgrade("Math::BigRat");
print $x / $y, "\n"; # 12/5 as a Math::BigRat
```
downgrade() Set/get the class for downgrading. The default is `undef`, i.e., no downgrading. Downgrading is not done by Math::BigInt.
modify()
```
$x->modify('bpowd');
```
This method returns 0 if the object can be modified with the given operation, or 1 if not.
This is used for instance by <Math::BigInt::Constant>.
config()
```
Math::BigInt->config("trap_nan" => 1); # set
$accu = Math::BigInt->config("accuracy"); # get
```
Set or get class variables. Read-only parameters are marked as RO. Read-write parameters are marked as RW. The following parameters are supported.
```
Parameter RO/RW Description
Example
============================================================
lib RO Name of the math backend library
Math::BigInt::Calc
lib_version RO Version of the math backend library
0.30
class RO The class of config you just called
Math::BigRat
version RO version number of the class you used
0.10
upgrade RW To which class numbers are upgraded
undef
downgrade RW To which class numbers are downgraded
undef
precision RW Global precision
undef
accuracy RW Global accuracy
undef
round_mode RW Global round mode
even
div_scale RW Fallback accuracy for division etc.
40
trap_nan RW Trap NaNs
undef
trap_inf RW Trap +inf/-inf
undef
```
###
Constructor methods
new()
```
$x = Math::BigInt->new($str,$A,$P,$R);
```
Creates a new Math::BigInt object from a scalar or another Math::BigInt object. The input is accepted as decimal, hexadecimal (with leading '0x'), octal (with leading ('0o') or binary (with leading '0b').
See ["Input"](#Input) for more info on accepted input formats.
from\_dec()
```
$x = Math::BigInt->from_dec("314159"); # input is decimal
```
Interpret input as a decimal. It is equivalent to new(), but does not accept anything but strings representing finite, decimal numbers.
from\_hex()
```
$x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal
```
Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.
from\_oct()
```
$x = Math::BigInt->from_oct("0775"); # input is octal
```
Interpret the input as an octal string and return the corresponding value. A "0" (zero) prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.
from\_bin()
```
$x = Math::BigInt->from_bin("0b10011"); # input is binary
```
Interpret the input as a binary string. A "0b" or "b" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned.
from\_bytes()
```
$x = Math::BigInt->from_bytes("\xf3\x6b"); # $x = 62315
```
Interpret the input as a byte string, assuming big endian byte order. The output is always a non-negative, finite integer.
In some special cases, from\_bytes() matches the conversion done by unpack():
```
$b = "\x4e"; # one char byte string
$x = Math::BigInt->from_bytes($b); # = 78
$y = unpack "C", $b; # ditto, but scalar
$b = "\xf3\x6b"; # two char byte string
$x = Math::BigInt->from_bytes($b); # = 62315
$y = unpack "S>", $b; # ditto, but scalar
$b = "\x2d\xe0\x49\xad"; # four char byte string
$x = Math::BigInt->from_bytes($b); # = 769673645
$y = unpack "L>", $b; # ditto, but scalar
$b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string
$x = Math::BigInt->from_bytes($b); # = 3305723134637787565
$y = unpack "Q>", $b; # ditto, but scalar
```
from\_base() Given a string, a base, and an optional collation sequence, interpret the string as a number in the given base. The collation sequence describes the value of each character in the string.
If a collation sequence is not given, a default collation sequence is used. If the base is less than or equal to 36, the collation sequence is the string consisting of the 36 characters "0" to "9" and "A" to "Z". In this case, the letter case in the input is ignored. If the base is greater than 36, and smaller than or equal to 62, the collation sequence is the string consisting of the 62 characters "0" to "9", "A" to "Z", and "a" to "z". A base larger than 62 requires the collation sequence to be specified explicitly.
These examples show standard binary, octal, and hexadecimal conversion. All cases return 250.
```
$x = Math::BigInt->from_base("11111010", 2);
$x = Math::BigInt->from_base("372", 8);
$x = Math::BigInt->from_base("fa", 16);
```
When the base is less than or equal to 36, and no collation sequence is given, the letter case is ignored, so both of these also return 250:
```
$x = Math::BigInt->from_base("6Y", 16);
$x = Math::BigInt->from_base("6y", 16);
```
When the base greater than 36, and no collation sequence is given, the default collation sequence contains both uppercase and lowercase letters, so the letter case in the input is not ignored:
```
$x = Math::BigInt->from_base("6S", 37); # $x is 250
$x = Math::BigInt->from_base("6s", 37); # $x is 276
$x = Math::BigInt->from_base("121", 3); # $x is 16
$x = Math::BigInt->from_base("XYZ", 36); # $x is 44027
$x = Math::BigInt->from_base("Why", 42); # $x is 58314
```
The collation sequence can be any set of unique characters. These two cases are equivalent
```
$x = Math::BigInt->from_base("100", 2, "01"); # $x is 4
$x = Math::BigInt->from_base("|--", 2, "-|"); # $x is 4
```
from\_base\_num() Returns a new Math::BigInt 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 = Math::BigInt->from_base_num([1, 1, 0, 1], 2) # $x is 13
$x = Math::BigInt->from_base_num([3, 125, 39], 128) # $x is 65191
```
bzero()
```
$x = Math::BigInt->bzero();
$x->bzero();
```
Returns a new Math::BigInt object representing zero. If used as an instance method, assigns the value to the invocand.
bone()
```
$x = Math::BigInt->bone(); # +1
$x = Math::BigInt->bone("+"); # +1
$x = Math::BigInt->bone("-"); # -1
$x->bone(); # +1
$x->bone("+"); # +1
$x->bone('-'); # -1
```
Creates a new Math::BigInt object representing one. The optional argument is either '-' or '+', indicating whether you want plus one or minus one. If used as an instance method, assigns the value to the invocand.
binf()
```
$x = Math::BigInt->binf($sign);
```
Creates a new Math::BigInt object representing infinity. The optional argument is either '-' or '+', indicating whether you want infinity or minus infinity. If used as an instance method, assigns the value to the invocand.
```
$x->binf();
$x->binf('-');
```
bnan()
```
$x = Math::BigInt->bnan();
```
Creates a new Math::BigInt object representing NaN (Not A Number). If used as an instance method, assigns the value to the invocand.
```
$x->bnan();
```
bpi()
```
$x = Math::BigInt->bpi(100); # 3
$x->bpi(100); # 3
```
Creates a new Math::BigInt object representing PI. If used as an instance method, assigns the value to the invocand. With Math::BigInt this always returns 3.
If upgrading is in effect, returns PI, rounded to N digits with the current rounding mode:
```
use Math::BigFloat;
use Math::BigInt upgrade => "Math::BigFloat";
print Math::BigInt->bpi(3), "\n"; # 3.14
print Math::BigInt->bpi(100), "\n"; # 3.1415....
```
copy()
```
$x->copy(); # make a true copy of $x (unlike $y = $x)
```
as\_int()
as\_number() These methods are called when Math::BigInt encounters an object it doesn't know how to handle. For instance, assume $x is a Math::BigInt, or subclass thereof, and $y is defined, but not a Math::BigInt, or subclass thereof. If you do
```
$x -> badd($y);
```
$y needs to be converted into an object that $x can deal with. This is done by first checking if $y is something that $x might be upgraded to. If that is the case, no further attempts are made. The next is to see if $y supports the method `as_int()`. If it does, `as_int()` is called, but if it doesn't, the next thing is to see if $y supports the method `as_number()`. If it does, `as_number()` is called. The method `as_int()` (and `as_number()`) is expected to return either an object that has the same class as $x, a subclass thereof, or a string that `ref($x)->new()` can parse to create an object.
`as_number()` is an alias to `as_int()`. `as_number` was introduced in v1.22, while `as_int()` was introduced in v1.68.
In Math::BigInt, `as_int()` has the same effect as `copy()`.
###
Boolean methods
None of these methods modify the invocand object.
is\_zero()
```
$x->is_zero(); # true if $x is 0
```
Returns true if the invocand is zero and false otherwise.
is\_one( [ SIGN ])
```
$x->is_one(); # true if $x is +1
$x->is_one("+"); # ditto
$x->is_one("-"); # true if $x is -1
```
Returns true if the invocand is one and false otherwise.
is\_finite()
```
$x->is_finite(); # true if $x is not +inf, -inf or NaN
```
Returns true if the invocand is a finite number, i.e., it is neither +inf, -inf, nor NaN.
is\_inf( [ SIGN ] )
```
$x->is_inf(); # true if $x is +inf
$x->is_inf("+"); # ditto
$x->is_inf("-"); # true if $x is -inf
```
Returns true if the invocand is infinite and false otherwise.
is\_nan()
```
$x->is_nan(); # true if $x is NaN
```
is\_positive()
is\_pos()
```
$x->is_positive(); # true if > 0
$x->is_pos(); # ditto
```
Returns true if the invocand is positive and false otherwise. A `NaN` is neither positive nor negative.
is\_negative()
is\_neg()
```
$x->is_negative(); # true if < 0
$x->is_neg(); # ditto
```
Returns true if the invocand is negative and false otherwise. A `NaN` is neither positive nor negative.
is\_non\_positive()
```
$x->is_non_positive(); # true if <= 0
```
Returns true if the invocand is negative or zero.
is\_non\_negative()
```
$x->is_non_negative(); # true if >= 0
```
Returns true if the invocand is positive or zero.
is\_odd()
```
$x->is_odd(); # true if odd, false for even
```
Returns true if the invocand is odd and false otherwise. `NaN`, `+inf`, and `-inf` are neither odd nor even.
is\_even()
```
$x->is_even(); # true if $x is even
```
Returns true if the invocand is even and false otherwise. `NaN`, `+inf`, `-inf` are not integers and are neither odd nor even.
is\_int()
```
$x->is_int(); # true if $x is an integer
```
Returns true if the invocand is an integer and false otherwise. `NaN`, `+inf`, `-inf` are not integers.
###
Comparison methods
None of these methods modify the invocand object. Note that a `NaN` is neither less than, greater than, or equal to anything else, even a `NaN`.
bcmp()
```
$x->bcmp($y);
```
Returns -1, 0, 1 depending on whether $x is less than, equal to, or grater than $y. Returns undef if any operand is a NaN.
bacmp()
```
$x->bacmp($y);
```
Returns -1, 0, 1 depending on whether the absolute value of $x is less than, equal to, or grater than the absolute value of $y. Returns undef if any operand is a NaN.
beq()
```
$x -> beq($y);
```
Returns true if and only if $x is equal to $y, and false otherwise.
bne()
```
$x -> bne($y);
```
Returns true if and only if $x is not equal to $y, and false otherwise.
blt()
```
$x -> blt($y);
```
Returns true if and only if $x is equal to $y, and false otherwise.
ble()
```
$x -> ble($y);
```
Returns true if and only if $x is less than or equal to $y, and false otherwise.
bgt()
```
$x -> bgt($y);
```
Returns true if and only if $x is greater than $y, and false otherwise.
bge()
```
$x -> bge($y);
```
Returns true if and only if $x is greater than or equal to $y, and false otherwise.
###
Arithmetic methods
These methods modify the invocand object and returns it.
bneg()
```
$x->bneg();
```
Negate the number, e.g. change the sign between '+' and '-', or between '+inf' and '-inf', respectively. Does nothing for NaN or zero.
babs()
```
$x->babs();
```
Set the number to its absolute value, e.g. change the sign from '-' to '+' and from '-inf' to '+inf', respectively. Does nothing for NaN or positive numbers.
bsgn()
```
$x->bsgn();
```
Signum function. Set the number to -1, 0, or 1, depending on whether the number is negative, zero, or positive, respectively. Does not modify NaNs.
bnorm()
```
$x->bnorm(); # normalize (no-op)
```
Normalize the number. This is a no-op and is provided only for backwards compatibility.
binc()
```
$x->binc(); # increment x by 1
```
bdec()
```
$x->bdec(); # decrement x by 1
```
badd()
```
$x->badd($y); # addition (add $y to $x)
```
bsub()
```
$x->bsub($y); # subtraction (subtract $y from $x)
```
bmul()
```
$x->bmul($y); # multiplication (multiply $x by $y)
```
bmuladd()
```
$x->bmuladd($y,$z);
```
Multiply $x by $y, and then add $z to the result,
This method was added in v1.87 of Math::BigInt (June 2007).
bdiv()
```
$x->bdiv($y); # divide, set $x to quotient
```
Divides $x by $y by doing floored division (F-division), where the quotient is the floored (rounded towards negative infinity) quotient of the two operands. In list context, returns the quotient and the remainder. The remainder is either zero or has the same sign as the second operand. In scalar context, only the quotient is returned.
The quotient is always the greatest integer less than or equal to the real-valued quotient of the two operands, and the remainder (when it is non-zero) always has the same sign as the second operand; so, for example,
```
1 / 4 => ( 0, 1)
1 / -4 => (-1, -3)
-3 / 4 => (-1, 1)
-3 / -4 => ( 0, -3)
-11 / 2 => (-5, 1)
11 / -2 => (-5, -1)
```
The behavior of the overloaded operator % agrees with the behavior of Perl's built-in % operator (as documented in the perlop manpage), and the equation
```
$x == ($x / $y) * $y + ($x % $y)
```
holds true for any finite $x and finite, non-zero $y.
Perl's "use integer" might change the behaviour of % and / for scalars. This is because under 'use integer' Perl does what the underlying C library thinks is right, and this varies. However, "use integer" does not change the way things are done with Math::BigInt objects.
btdiv()
```
$x->btdiv($y); # divide, set $x to quotient
```
Divides $x by $y by doing truncated division (T-division), where quotient is the truncated (rouneded towards zero) quotient of the two operands. In list context, returns the quotient and the remainder. The remainder is either zero or has the same sign as the first operand. In scalar context, only the quotient is returned.
bmod()
```
$x->bmod($y); # modulus (x % y)
```
Returns $x modulo $y, i.e., the remainder after floored division (F-division). This method is like Perl's % operator. See ["bdiv()"](#bdiv%28%29).
btmod()
```
$x->btmod($y); # modulus
```
Returns the remainer after truncated division (T-division). See ["btdiv()"](#btdiv%28%29).
bmodinv()
```
$x->bmodinv($mod); # modular multiplicative inverse
```
Returns the multiplicative inverse of `$x` modulo `$mod`. If
```
$y = $x -> copy() -> bmodinv($mod)
```
then `$y` is the number closest to zero, and with the same sign as `$mod`, satisfying
```
($x * $y) % $mod = 1 % $mod
```
If `$x` and `$y` are non-zero, they must be relative primes, i.e., `bgcd($y, $mod)==1`. '`NaN`' is returned when no modular multiplicative inverse exists.
bmodpow()
```
$num->bmodpow($exp,$mod); # modular exponentiation
# ($num**$exp % $mod)
```
Returns the value of `$num` taken to the power `$exp` in the modulus `$mod` using binary exponentiation. `bmodpow` is far superior to writing
```
$num ** $exp % $mod
```
because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers.
`bmodpow` also supports negative exponents.
```
bmodpow($num, -1, $mod)
```
is exactly equivalent to
```
bmodinv($num, $mod)
```
bpow()
```
$x->bpow($y); # power of arguments (x ** y)
```
`bpow()` (and the rounding functions) now modifies the first argument and returns it, unlike the old code which left it alone and only returned the result. This is to be consistent with `badd()` etc. The first three modifies $x, the last one won't:
```
print bpow($x,$i),"\n"; # modify $x
print $x->bpow($i),"\n"; # ditto
print $x **= $i,"\n"; # the same
print $x ** $i,"\n"; # leave $x alone
```
The form `$x **= $y` is faster than `$x = $x ** $y;`, though.
blog()
```
$x->blog($base, $accuracy); # logarithm of x to the base $base
```
If `$base` is not defined, Euler's number (e) is used:
```
print $x->blog(undef, 100); # log(x) to 100 digits
```
bexp()
```
$x->bexp($accuracy); # calculate e ** X
```
Calculates the expression `e ** $x` where `e` is Euler's number.
This method was added in v1.82 of Math::BigInt (April 2007).
See also ["blog()"](#blog%28%29).
bnok()
```
$x->bnok($y); # x over y (binomial coefficient n over k)
```
Calculates the binomial coefficient n over k, also called the "choose" function, which is
```
( n ) n!
| | = --------
( k ) k!(n-k)!
```
when n and k are non-negative. This method implements the full Kronenburg extension (Kronenburg, M.J. "The Binomial Coefficient for Negative Arguments." 18 May 2011. http://arxiv.org/abs/1105.3689/) illustrated by the following pseudo-code:
```
if n >= 0 and k >= 0:
return binomial(n, k)
if k >= 0:
return (-1)^k*binomial(-n+k-1, k)
if k <= n:
return (-1)^(n-k)*binomial(-k-1, n-k)
else
return 0
```
The behaviour is identical to the behaviour of the Maple and Mathematica function for negative integers n, k.
buparrow()
uparrow()
```
$a -> buparrow($n, $b); # modifies $a
$x = $a -> uparrow($n, $b); # does not modify $a
```
This method implements Knuth's up-arrow notation, where $n is a non-negative integer representing the number of up-arrows. $n = 0 gives multiplication, $n = 1 gives exponentiation, $n = 2 gives tetration, $n = 3 gives hexation etc. The following illustrates the relation between the first values of $n.
See <https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>.
backermann()
ackermann()
```
$m -> backermann($n); # modifies $a
$x = $m -> ackermann($n); # does not modify $a
```
This method implements the Ackermann function:
```
/ n + 1 if m = 0
A(m, n) = | A(m-1, 1) if m > 0 and n = 0
\ A(m-1, A(m, n-1)) if m > 0 and n > 0
```
Its value grows rapidly, even for small inputs. For example, A(4, 2) is an integer of 19729 decimal digits.
See https://en.wikipedia.org/wiki/Ackermann\_function
bsin()
```
my $x = Math::BigInt->new(1);
print $x->bsin(100), "\n";
```
Calculate the sine of $x, modifying $x in place.
In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
bcos()
```
my $x = Math::BigInt->new(1);
print $x->bcos(100), "\n";
```
Calculate the cosine of $x, modifying $x in place.
In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
batan()
```
my $x = Math::BigFloat->new(0.5);
print $x->batan(100), "\n";
```
Calculate the arcus tangens of $x, modifying $x in place.
In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
batan2()
```
my $x = Math::BigInt->new(1);
my $y = Math::BigInt->new(1);
print $y->batan2($x), "\n";
```
Calculate the arcus tangens of `$y` divided by `$x`, modifying $y in place.
In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer.
This method was added in v1.87 of Math::BigInt (June 2007).
bsqrt()
```
$x->bsqrt(); # calculate square root
```
`bsqrt()` returns the square root truncated to an integer.
If you want a better approximation of the square root, then use:
```
$x = Math::BigFloat->new(12);
Math::BigFloat->precision(0);
Math::BigFloat->round_mode('even');
print $x->copy->bsqrt(),"\n"; # 4
Math::BigFloat->precision(2);
print $x->bsqrt(),"\n"; # 3.46
print $x->bsqrt(3),"\n"; # 3.464
```
broot()
```
$x->broot($N);
```
Calculates the N'th root of `$x`.
bfac()
```
$x->bfac(); # factorial of $x
```
Returns the factorial of `$x`, i.e., $x\*($x-1)\*($x-2)\*...\*2\*1, the product of all positive integers up to and including `$x`. `$x` must be > -1. The factorial of N is commonly written as N!, or N!1, when using the multifactorial notation.
bdfac()
```
$x->bdfac(); # double factorial of $x
```
Returns the double factorial of `$x`, i.e., $x\*($x-2)\*($x-4)\*... `$x` must be > -2. The double factorial of N is commonly written as N!!, or N!2, when using the multifactorial notation.
btfac()
```
$x->btfac(); # triple factorial of $x
```
Returns the triple factorial of `$x`, i.e., $x\*($x-3)\*($x-6)\*... `$x` must be > -3. The triple factorial of N is commonly written as N!!!, or N!3, when using the multifactorial notation.
bmfac()
```
$x->bmfac($k); # $k'th multifactorial of $x
```
Returns the multi-factorial of `$x`, i.e., $x\*($x-$k)\*($x-2\*$k)\*... `$x` must be > -$k. The multi-factorial of N is commonly written as N!K.
bfib()
```
$F = $n->bfib(); # a single Fibonacci number
@F = $n->bfib(); # a list of Fibonacci numbers
```
In scalar context, returns a single Fibonacci number. In list context, returns a list of Fibonacci numbers. The invocand is the last element in the output.
The Fibonacci sequence is defined by
```
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2)
```
In list context, F(0) and F(n) is the first and last number in the output, respectively. For example, if $n is 12, then `@F = $n->bfib()` returns the following values, F(0) to F(12):
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
```
The sequence can also be extended to negative index n using the re-arranged recurrence relation
```
F(n-2) = F(n) - F(n-1)
```
giving the bidirectional sequence
```
n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
F(n) 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13
```
If $n is -12, the following values, F(0) to F(12), are returned:
```
0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144
```
blucas()
```
$F = $n->blucas(); # a single Lucas number
@F = $n->blucas(); # a list of Lucas numbers
```
In scalar context, returns a single Lucas number. In list context, returns a list of Lucas numbers. The invocand is the last element in the output.
The Lucas sequence is defined by
```
L(0) = 2
L(1) = 1
L(n) = L(n-1) + L(n-2)
```
In list context, L(0) and L(n) is the first and last number in the output, respectively. For example, if $n is 12, then `@L = $n->blucas()` returns the following values, L(0) to L(12):
```
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322
```
The sequence can also be extended to negative index n using the re-arranged recurrence relation
```
L(n-2) = L(n) - L(n-1)
```
giving the bidirectional sequence
```
n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
L(n) 29 -18 11 -7 4 -3 1 2 1 3 4 7 11 18 29
```
If $n is -12, the following values, L(0) to L(-12), are returned:
```
2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322
```
brsft()
```
$x->brsft($n); # right shift $n places in base 2
$x->brsft($n, $b); # right shift $n places in base $b
```
The latter is equivalent to
```
$x -> bdiv($b -> copy() -> bpow($n))
```
blsft()
```
$x->blsft($n); # left shift $n places in base 2
$x->blsft($n, $b); # left shift $n places in base $b
```
The latter is equivalent to
```
$x -> bmul($b -> copy() -> bpow($n))
```
###
Bitwise methods
band()
```
$x->band($y); # bitwise and
```
bior()
```
$x->bior($y); # bitwise inclusive or
```
bxor()
```
$x->bxor($y); # bitwise exclusive or
```
bnot()
```
$x->bnot(); # bitwise not (two's complement)
```
Two's complement (bitwise not). This is equivalent to, but faster than,
```
$x->binc()->bneg();
```
###
Rounding methods
round()
```
$x->round($A,$P,$round_mode);
```
Round $x to accuracy `$A` or precision `$P` using the round mode `$round_mode`.
bround()
```
$x->bround($N); # accuracy: preserve $N digits
```
Rounds $x to an accuracy of $N digits.
bfround()
```
$x->bfround($N);
```
Rounds to a multiple of 10\*\*$N. Examples:
```
Input N Result
123456.123456 3 123500
123456.123456 2 123450
123456.123456 -2 123456.12
123456.123456 -3 123456.123
```
bfloor()
```
$x->bfloor();
```
Round $x towards minus infinity, i.e., set $x to the largest integer less than or equal to $x.
bceil()
```
$x->bceil();
```
Round $x towards plus infinity, i.e., set $x to the smallest integer greater than or equal to $x).
bint()
```
$x->bint();
```
Round $x towards zero.
###
Other mathematical methods
bgcd()
```
$x -> bgcd($y); # GCD of $x and $y
$x -> bgcd($y, $z, ...); # GCD of $x, $y, $z, ...
```
Returns the greatest common divisor (GCD).
blcm()
```
$x -> blcm($y); # LCM of $x and $y
$x -> blcm($y, $z, ...); # LCM of $x, $y, $z, ...
```
Returns the least common multiple (LCM).
###
Object property methods
sign()
```
$x->sign();
```
Return the sign, of $x, meaning either `+`, `-`, `-inf`, `+inf` or NaN.
If you want $x to have a certain sign, use one of the following methods:
```
$x->babs(); # '+'
$x->babs()->bneg(); # '-'
$x->bnan(); # 'NaN'
$x->binf(); # '+inf'
$x->binf('-'); # '-inf'
```
digit()
```
$x->digit($n); # return the nth digit, counting from right
```
If `$n` is negative, returns the digit counting from left.
digitsum()
```
$x->digitsum();
```
Computes the sum of the base 10 digits and returns it.
bdigitsum()
```
$x->bdigitsum();
```
Computes the sum of the base 10 digits and assigns the result to the invocand.
length()
```
$x->length();
($xl, $fl) = $x->length();
```
Returns the number of digits in the decimal representation of the number. In list context, returns the length of the integer and fraction part. For Math::BigInt objects, the length of the fraction part is always 0.
The following probably doesn't do what you expect:
```
$c = Math::BigInt->new(123);
print $c->length(),"\n"; # prints 30
```
It prints both the number of digits in the number and in the fraction part since print calls `length()` in list context. Use something like:
```
print scalar $c->length(),"\n"; # prints 3
```
mantissa()
```
$x->mantissa();
```
Return the signed mantissa of $x as a Math::BigInt.
exponent()
```
$x->exponent();
```
Return the exponent of $x as a Math::BigInt.
parts()
```
$x->parts();
```
Returns the significand (mantissa) and the exponent as integers. In Math::BigFloat, both are returned as Math::BigInt objects.
sparts() Returns the significand (mantissa) and the exponent as integers. In scalar context, only the significand is returned. The significand is the integer with the smallest absolute value. The output of `sparts()` corresponds to the output from `bsstr()`.
In Math::BigInt, this method is identical to `parts()`.
nparts() Returns the significand (mantissa) and exponent corresponding to normalized notation. In scalar context, only the significand is returned. For finite non-zero numbers, the significand's absolute value is greater than or equal to 1 and less than 10. The output of `nparts()` corresponds to the output from `bnstr()`. In Math::BigInt, if the significand can not be represented as an integer, upgrading is performed or NaN is returned.
eparts() Returns the significand (mantissa) and exponent corresponding to engineering notation. In scalar context, only the significand is returned. For finite non-zero numbers, the significand's absolute value is greater than or equal to 1 and less than 1000, and the exponent is a multiple of 3. The output of `eparts()` corresponds to the output from `bestr()`. In Math::BigInt, if the significand can not be represented as an integer, upgrading is performed or NaN is returned.
dparts() Returns the integer part and the fraction part. If the fraction part can not be represented as an integer, upgrading is performed or NaN is returned. The output of `dparts()` corresponds to the output from `bdstr()`.
fparts() Returns the smallest possible numerator and denominator so that the numerator divided by the denominator gives back the original value. For finite numbers, both values are integers. Mnemonic: fraction.
numerator() Together with ["denominator()"](#denominator%28%29), returns the smallest integers so that the numerator divided by the denominator reproduces the original value. With Math::BigInt, numerator() simply returns a copy of the invocand.
denominator() Together with ["numerator()"](#numerator%28%29), returns the smallest integers so that the numerator divided by the denominator reproduces the original value. With Math::BigInt, denominator() always returns either a 1 or a NaN.
###
String conversion methods
bstr() Returns a string representing the number using decimal notation. In Math::BigFloat, the output is zero padded according to the current accuracy or precision, if any of those are defined.
bsstr() Returns a string representing the number using scientific notation where both the significand (mantissa) and the exponent are integers. The output corresponds to the output from `sparts()`.
```
123 is returned as "123e+0"
1230 is returned as "123e+1"
12300 is returned as "123e+2"
12000 is returned as "12e+3"
10000 is returned as "1e+4"
```
bnstr() Returns a string representing the number using normalized notation, the most common variant of scientific notation. For finite non-zero numbers, the absolute value of the significand is greater than or equal to 1 and less than 10. The output corresponds to the output from `nparts()`.
```
123 is returned as "1.23e+2"
1230 is returned as "1.23e+3"
12300 is returned as "1.23e+4"
12000 is returned as "1.2e+4"
10000 is returned as "1e+4"
```
bestr() Returns a string representing the number using engineering notation. For finite non-zero numbers, the absolute value of the significand is greater than or equal to 1 and less than 1000, and the exponent is a multiple of 3. The output corresponds to the output from `eparts()`.
```
123 is returned as "123e+0"
1230 is returned as "1.23e+3"
12300 is returned as "12.3e+3"
12000 is returned as "12e+3"
10000 is returned as "10e+3"
```
bdstr() Returns a string representing the number using decimal notation. The output corresponds to the output from `dparts()`.
```
123 is returned as "123"
1230 is returned as "1230"
12300 is returned as "12300"
12000 is returned as "12000"
10000 is returned as "10000"
```
to\_hex()
```
$x->to_hex();
```
Returns a hexadecimal string representation of the number. See also from\_hex().
to\_bin()
```
$x->to_bin();
```
Returns a binary string representation of the number. See also from\_bin().
to\_oct()
```
$x->to_oct();
```
Returns an octal string representation of the number. See also from\_oct().
to\_bytes()
```
$x = Math::BigInt->new("1667327589");
$s = $x->to_bytes(); # $s = "cafe"
```
Returns a byte string representation of the number using big endian byte order. The invocand must be a non-negative, finite integer. See also from\_bytes().
to\_base()
```
$x = Math::BigInt->new("250");
$x->to_base(2); # returns "11111010"
$x->to_base(8); # returns "372"
$x->to_base(16); # returns "fa"
```
Returns a string representation of the number in the given base. If a collation sequence is given, the collation sequence determines which characters are used in the output.
Here are some more examples
```
$x = Math::BigInt->new("16")->to_base(3); # returns "121"
$x = Math::BigInt->new("44027")->to_base(36); # returns "XYZ"
$x = Math::BigInt->new("58314")->to_base(42); # returns "Why"
$x = Math::BigInt->new("4")->to_base(2, "-|"); # returns "|--"
```
See from\_base() for information and examples.
to\_base\_num() 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 = Math::BigInt->new(13);
$x->to_base_num(2); # returns [1, 1, 0, 1]
$x = Math::BigInt->new(65191);
$x->to_base_num(128); # returns [3, 125, 39]
```
as\_hex()
```
$x->as_hex();
```
As, `to_hex()`, but with a "0x" prefix.
as\_bin()
```
$x->as_bin();
```
As, `to_bin()`, but with a "0b" prefix.
as\_oct()
```
$x->as_oct();
```
As, `to_oct()`, but with a "0" prefix.
as\_bytes() This is just an alias for `to_bytes()`.
###
Other conversion methods
numify()
```
print $x->numify();
```
Returns a Perl scalar from $x. It is used automatically whenever a scalar is needed, for instance in array index operations.
###
Utility methods
These utility methods are made public
dec\_str\_to\_dec\_flt\_str() Takes a string representing any valid number using decimal notation and converts it to a string representing the same number using decimal floating point notation. The output consists of five parts joined together: the sign of the significand, the absolute value of the significand as the smallest possible integer, the letter "e", the sign of the exponent, and the absolute value of the exponent. If the input is invalid, nothing is returned.
```
$str2 = $class -> dec_str_to_dec_flt_str($str1);
```
Some examples
```
Input Output
31400.00e-4 +314e-2
-0.00012300e8 -123e+2
0 +0e+0
```
hex\_str\_to\_dec\_flt\_str() Takes a string representing any valid number using hexadecimal notation and converts it to a string representing the same number using decimal floating point notation. The output has the same format as that of ["dec\_str\_to\_dec\_flt\_str()"](#dec_str_to_dec_flt_str%28%29).
```
$str2 = $class -> hex_str_to_dec_flt_str($str1);
```
Some examples
```
Input Output
0xff +255e+0
```
Some examples
oct\_str\_to\_dec\_flt\_str() Takes a string representing any valid number using octal notation and converts it to a string representing the same number using decimal floating point notation. The output has the same format as that of ["dec\_str\_to\_dec\_flt\_str()"](#dec_str_to_dec_flt_str%28%29).
```
$str2 = $class -> oct_str_to_dec_flt_str($str1);
```
bin\_str\_to\_dec\_flt\_str() Takes a string representing any valid number using binary notation and converts it to a string representing the same number using decimal floating point notation. The output has the same format as that of ["dec\_str\_to\_dec\_flt\_str()"](#dec_str_to_dec_flt_str%28%29).
```
$str2 = $class -> bin_str_to_dec_flt_str($str1);
```
dec\_str\_to\_dec\_str() Takes a string representing any valid number using decimal notation and converts it to a string representing the same number using decimal notation. If the number represents an integer, the output consists of a sign and the absolute value. If the number represents a non-integer, the output consists of a sign, the integer part of the number, the decimal point ".", and the fraction part of the number without any trailing zeros. If the input is invalid, nothing is returned.
hex\_str\_to\_dec\_str() Takes a string representing any valid number using hexadecimal notation and converts it to a string representing the same number using decimal notation. The output has the same format as that of ["dec\_str\_to\_dec\_str()"](#dec_str_to_dec_str%28%29).
oct\_str\_to\_dec\_str() Takes a string representing any valid number using octal notation and converts it to a string representing the same number using decimal notation. The output has the same format as that of ["dec\_str\_to\_dec\_str()"](#dec_str_to_dec_str%28%29).
bin\_str\_to\_dec\_str() Takes a string representing any valid number using binary notation and converts it to a string representing the same number using decimal notation. The output has the same format as that of ["dec\_str\_to\_dec\_str()"](#dec_str_to_dec_str%28%29).
ACCURACY and PRECISION
-----------------------
Math::BigInt and Math::BigFloat have full support for accuracy and precision based rounding, both automatically after every operation, as well as manually.
This section describes the accuracy/precision handling in Math::BigInt and Math::BigFloat as it used to be and as it is now, complete with an explanation of all terms and abbreviations.
Not yet implemented things (but with correct description) are marked with '!', things that need to be answered are marked with '?'.
In the next paragraph follows a short description of terms used here (because these may differ from terms used by others people or documentation).
During the rest of this document, the shortcuts A (for accuracy), P (for precision), F (fallback) and R (rounding mode) are be used.
###
Precision P
Precision is a fixed number of digits before (positive) or after (negative) the decimal point. For example, 123.45 has a precision of -2. 0 means an integer like 123 (or 120). A precision of 2 means at least two digits to the left of the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers with zeros before the decimal point may have different precisions, because 1200 can have P = 0, 1 or 2 (depending on what the initial value was). It could also have p < 0, when the digits after the decimal point are zero.
The string output (of floating point numbers) is padded with zeros:
```
Initial value P A Result String
------------------------------------------------------------
1234.01 -3 1000 1000
1234 -2 1200 1200
1234.5 -1 1230 1230
1234.001 1 1234 1234.0
1234.01 0 1234 1234
1234.01 2 1234.01 1234.01
1234.01 5 1234.01 1234.01000
```
For Math::BigInt objects, no padding occurs.
###
Accuracy A
Number of significant digits. Leading zeros are not counted. A number may have an accuracy greater than the non-zero digits when there are zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7, 123.45000 has 8 and 0.000123 has 3.
The string output (of floating point numbers) is padded with zeros:
```
Initial value P A Result String
------------------------------------------------------------
1234.01 3 1230 1230
1234.01 6 1234.01 1234.01
1234.1 8 1234.1 1234.1000
```
For Math::BigInt objects, no padding occurs.
###
Fallback F
When both A and P are undefined, this is used as a fallback accuracy when dividing numbers.
###
Rounding mode R
When rounding a number, different 'styles' or 'kinds' of rounding are possible. (Note that random rounding, as in Math::Round, is not implemented.)
####
Directed rounding
These round modes always round in the same direction.
'trunc' Round towards zero. Remove all digits following the rounding place, i.e., replace them with zeros. Thus, 987.65 rounded to tens (P=1) becomes 980, and rounded to the fourth significant digit becomes 987.6 (A=4). 123.456 rounded to the second place after the decimal point (P=-2) becomes 123.46. This corresponds to the IEEE 754 rounding mode 'roundTowardZero'.
####
Rounding to nearest
These rounding modes round to the nearest digit. They differ in how they determine which way to round in the ambiguous case when there is a tie.
'even' Round towards the nearest even digit, e.g., when rounding to nearest integer, -5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode 'roundTiesToEven'.
'odd' Round towards the nearest odd digit, e.g., when rounding to nearest integer, 4.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This corresponds to the IEEE 754 rounding mode 'roundTiesToOdd'.
'+inf' Round towards plus infinity, i.e., always round up. E.g., when rounding to the nearest integer, 4.5 becomes 5, -5.5 becomes -5, and 4.501 also becomes 5. This corresponds to the IEEE 754 rounding mode 'roundTiesToPositive'.
'-inf' Round towards minus infinity, i.e., always round down. E.g., when rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -6, but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode 'roundTiesToNegative'.
'zero' Round towards zero, i.e., round positive numbers down and negative numbers up. E.g., when rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -5, but 4.501 becomes 5. This corresponds to the IEEE 754 rounding mode 'roundTiesToZero'.
'common' Round away from zero, i.e., round to the number with the largest absolute value. E.g., when rounding to the nearest integer, -1.5 becomes -2, 1.5 becomes 2 and 1.49 becomes 1. This corresponds to the IEEE 754 rounding mode 'roundTiesToAway'.
The handling of A & P in MBI/MBF (the old core code shipped with Perl versions <= 5.7.2) is like this:
Precision
```
* bfround($p) is able to round to $p number of digits after the decimal
point
* otherwise P is unused
```
Accuracy (significant digits)
```
* bround($a) rounds to $a significant digits
* only bdiv() and bsqrt() take A as (optional) parameter
+ other operations simply create the same number (bneg etc), or
more (bmul) of digits
+ rounding/truncating is only done when explicitly calling one
of bround or bfround, and never for Math::BigInt (not implemented)
* bsqrt() simply hands its accuracy argument over to bdiv.
* the documentation and the comment in the code indicate two
different ways on how bdiv() determines the maximum number
of digits it should calculate, and the actual code does yet
another thing
POD:
max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
Comment:
result has at most max(scale, length(dividend), length(divisor)) digits
Actual code:
scale = max(scale, length(dividend)-1,length(divisor)-1);
scale += length(divisor) - length(dividend);
So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10
So for lx = 3, ly = 9, scale = 10, scale will actually be 16
(10+9-3). Actually, the 'difference' added to the scale is cal-
culated from the number of "significant digits" in dividend and
divisor, which is derived by looking at the length of the man-
tissa. Which is wrong, since it includes the + sign (oops) and
actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus
124/3 with div_scale=1 will get you '41.3' based on the strange
assumption that 124 has 3 significant digits, while 120/7 will
get you '17', not '17.1' since 120 is thought to have 2 signif-
icant digits. The rounding after the division then uses the
remainder and $y to determine whether it must round up or down.
? I have no idea which is the right way. That's why I used a slightly more
? simple scheme and tweaked the few failing testcases to match it.
```
This is how it works now:
Setting/Accessing
```
* You can set the A global via Math::BigInt->accuracy() or
Math::BigFloat->accuracy() or whatever class you are using.
* You can also set P globally by using Math::SomeClass->precision()
likewise.
* Globals are classwide, and not inherited by subclasses.
* to undefine A, use Math::SomeClass->accuracy(undef);
* to undefine P, use Math::SomeClass->precision(undef);
* Setting Math::SomeClass->accuracy() clears automatically
Math::SomeClass->precision(), and vice versa.
* To be valid, A must be > 0, P can have any value.
* If P is negative, this means round to the P'th place to the right of the
decimal point; positive values mean to the left of the decimal point.
P of 0 means round to integer.
* to find out the current global A, use Math::SomeClass->accuracy()
* to find out the current global P, use Math::SomeClass->precision()
* use $x->accuracy() respective $x->precision() for the local
setting of $x.
* Please note that $x->accuracy() respective $x->precision()
return eventually defined global A or P, when $x's A or P is not
set.
```
Creating numbers
```
* When you create a number, you can give the desired A or P via:
$x = Math::BigInt->new($number,$A,$P);
* Only one of A or P can be defined, otherwise the result is NaN
* If no A or P is give ($x = Math::BigInt->new($number) form), then the
globals (if set) will be used. Thus changing the global defaults later on
will not change the A or P of previously created numbers (i.e., A and P of
$x will be what was in effect when $x was created)
* If given undef for A and P, NO rounding will occur, and the globals will
NOT be used. This is used by subclasses to create numbers without
suffering rounding in the parent. Thus a subclass is able to have its own
globals enforced upon creation of a number by using
$x = Math::BigInt->new($number,undef,undef):
use Math::BigInt::SomeSubclass;
use Math::BigInt;
Math::BigInt->accuracy(2);
Math::BigInt::SomeSubclass->accuracy(3);
$x = Math::BigInt::SomeSubclass->new(1234);
$x is now 1230, and not 1200. A subclass might choose to implement
this otherwise, e.g. falling back to the parent's A and P.
```
Usage
```
* If A or P are enabled/defined, they are used to round the result of each
operation according to the rules below
* Negative P is ignored in Math::BigInt, since Math::BigInt objects never
have digits after the decimal point
* Math::BigFloat uses Math::BigInt internally, but setting A or P inside
Math::BigInt as globals does not tamper with the parts of a Math::BigFloat.
A flag is used to mark all Math::BigFloat numbers as 'never round'.
```
Precedence
```
* It only makes sense that a number has only one of A or P at a time.
If you set either A or P on one object, or globally, the other one will
be automatically cleared.
* If two objects are involved in an operation, and one of them has A in
effect, and the other P, this results in an error (NaN).
* A takes precedence over P (Hint: A comes before P).
If neither of them is defined, nothing is used, i.e. the result will have
as many digits as it can (with an exception for bdiv/bsqrt) and will not
be rounded.
* There is another setting for bdiv() (and thus for bsqrt()). If neither of
A or P is defined, bdiv() will use a fallback (F) of $div_scale digits.
If either the dividend's or the divisor's mantissa has more digits than
the value of F, the higher value will be used instead of F.
This is to limit the digits (A) of the result (just consider what would
happen with unlimited A and P in the case of 1/3 :-)
* bdiv will calculate (at least) 4 more digits than required (determined by
A, P or F), and, if F is not used, round the result
(this will still fail in the case of a result like 0.12345000000001 with A
or P of 5, but this can not be helped - or can it?)
* Thus you can have the math done by on Math::Big* class in two modi:
+ never round (this is the default):
This is done by setting A and P to undef. No math operation
will round the result, with bdiv() and bsqrt() as exceptions to guard
against overflows. You must explicitly call bround(), bfround() or
round() (the latter with parameters).
Note: Once you have rounded a number, the settings will 'stick' on it
and 'infect' all other numbers engaged in math operations with it, since
local settings have the highest precedence. So, to get SaferRound[tm],
use a copy() before rounding like this:
$x = Math::BigFloat->new(12.34);
$y = Math::BigFloat->new(98.76);
$z = $x * $y; # 1218.6984
print $x->copy()->bround(3); # 12.3 (but A is now 3!)
$z = $x * $y; # still 1218.6984, without
# copy would have been 1210!
+ round after each op:
After each single operation (except for testing like is_zero()), the
method round() is called and the result is rounded appropriately. By
setting proper values for A and P, you can have all-the-same-A or
all-the-same-P modes. For example, Math::Currency might set A to undef,
and P to -2, globally.
?Maybe an extra option that forbids local A & P settings would be in order,
?so that intermediate rounding does not 'poison' further math?
```
Overriding globals
```
* you will be able to give A, P and R as an argument to all the calculation
routines; the second parameter is A, the third one is P, and the fourth is
R (shift right by one for binary operations like badd). P is used only if
the first parameter (A) is undefined. These three parameters override the
globals in the order detailed as follows, i.e. the first defined value
wins:
(local: per object, global: global default, parameter: argument to sub)
+ parameter A
+ parameter P
+ local A (if defined on both of the operands: smaller one is taken)
+ local P (if defined on both of the operands: bigger one is taken)
+ global A
+ global P
+ global F
* bsqrt() will hand its arguments to bdiv(), as it used to, only now for two
arguments (A and P) instead of one
```
Local settings
```
* You can set A or P locally by using $x->accuracy() or
$x->precision()
and thus force different A and P for different objects/numbers.
* Setting A or P this way immediately rounds $x to the new value.
* $x->accuracy() clears $x->precision(), and vice versa.
```
Rounding
```
* the rounding routines will use the respective global or local settings.
bround() is for accuracy rounding, while bfround() is for precision
* the two rounding functions take as the second parameter one of the
following rounding modes (R):
'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
* you can set/get the global R by using Math::SomeClass->round_mode()
or by setting $Math::SomeClass::round_mode
* after each operation, $result->round() is called, and the result may
eventually be rounded (that is, if A or P were set either locally,
globally or as parameter to the operation)
* to manually round a number, call $x->round($A,$P,$round_mode);
this will round the number by using the appropriate rounding function
and then normalize it.
* rounding modifies the local settings of the number:
$x = Math::BigFloat->new(123.456);
$x->accuracy(5);
$x->bround(4);
Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
will be 4 from now on.
```
Default values
```
* R: 'even'
* F: 40
* A: undef
* P: undef
```
Remarks
```
* The defaults are set up so that the new code gives the same results as
the old code (except in a few cases on bdiv):
+ Both A and P are undefined and thus will not be used for rounding
after each operation.
+ round() is thus a no-op, unless given extra parameters A and P
```
Infinity and Not a Number
--------------------------
While Math::BigInt has extensive handling of inf and NaN, certain quirks remain.
oct()/hex() These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf.
```
te@linux:~> perl -wle 'print 2 ** 3333'
Inf
te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1
te@linux:~> perl -wle 'print oct(2 ** 3333)'
0
te@linux:~> perl -wle 'print hex(2 ** 3333)'
Illegal hexadecimal digit 'I' ignored at -e line 1.
0
```
The same problems occur if you pass them Math::BigInt->binf() objects. Since overloading these routines is not possible, this cannot be fixed from Math::BigInt.
INTERNALS
---------
You should neither care about nor depend on the internal representation; it might change without notice. Use **ONLY** method calls like `$x->sign();` instead relying on the internal representation.
###
MATH LIBRARY
The mathematical computations are performed by a backend library. It is not required to specify which backend library to use, but some backend libraries are much faster than the default library.
####
The default library
The default library is <Math::BigInt::Calc>, which is implemented in pure Perl and hence does not require a compiler.
####
Specifying a library
The simple case
```
use Math::BigInt;
```
is equivalent to saying
```
use Math::BigInt try => 'Calc';
```
You can use a different backend library with, e.g.,
```
use Math::BigInt try => 'GMP';
```
which attempts to load the <Math::BigInt::GMP> library, and falls back to the default library if the specified library can't be loaded.
Multiple libraries can be specified by separating them by a comma, e.g.,
```
use Math::BigInt try => 'GMP,Pari';
```
If you request a specific set of libraries and do not allow fallback to the default library, specify them using "only",
```
use Math::BigInt only => 'GMP,Pari';
```
If you prefer a specific set of libraries, but want to see a warning if the fallback library is used, specify them using "lib",
```
use Math::BigInt lib => 'GMP,Pari';
```
The following first tries to find Math::BigInt::Foo, then Math::BigInt::Bar, and if this also fails, reverts to Math::BigInt::Calc:
```
use Math::BigInt try => 'Foo,Math::BigInt::Bar';
```
####
Which library to use?
**Note**: General purpose packages should not be explicit about the library to use; let the script author decide which is best.
<Math::BigInt::GMP>, <Math::BigInt::Pari>, and <Math::BigInt::GMPz> are in cases involving big numbers much faster than <Math::BigInt::Calc>. However these libraries are slower when dealing with very small numbers (less than about 20 digits) and when converting very large numbers to decimal (for instance for printing, rounding, calculating their length in decimal etc.).
So please select carefully what library you want to use.
Different low-level libraries use different formats to store the numbers, so mixing them won't work. You should not depend on the number having a specific internal format.
See the respective math library module documentation for further details.
####
Loading multiple libraries
The first library that is successfully loaded is the one that will be used. Any further attempts at loading a different module will be ignored. This is to avoid the situation where module A requires math library X, and module B requires math library Y, causing modules A and B to be incompatible. For example,
```
use Math::BigInt; # loads default "Calc"
use Math::BigFloat only => "GMP"; # ignores "GMP"
```
### SIGN
The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
A sign of 'NaN' is used to represent the result when input arguments are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively minus infinity. You get '+inf' when dividing a positive number by 0, and '-inf' when dividing any negative number by 0.
EXAMPLES
--------
```
use Math::BigInt;
sub bigint { Math::BigInt->new(shift); }
$x = Math::BigInt->bstr("1234") # string "1234"
$x = "$x"; # same as bstr()
$x = Math::BigInt->bneg("1234"); # Math::BigInt "-1234"
$x = Math::BigInt->babs("-12345"); # Math::BigInt "12345"
$x = Math::BigInt->bnorm("-0.00"); # Math::BigInt "0"
$x = bigint(1) + bigint(2); # Math::BigInt "3"
$x = bigint(1) + "2"; # ditto ("2" becomes a Math::BigInt)
$x = bigint(1); # Math::BigInt "1"
$x = $x + 5 / 2; # Math::BigInt "3"
$x = $x ** 3; # Math::BigInt "27"
$x *= 2; # Math::BigInt "54"
$x = Math::BigInt->new(0); # Math::BigInt "0"
$x--; # Math::BigInt "-1"
$x = Math::BigInt->badd(4,5) # Math::BigInt "9"
print $x->bsstr(); # 9e+0
```
Examples for rounding:
```
use Math::BigFloat;
use Test::More;
$x = Math::BigFloat->new(123.4567);
$y = Math::BigFloat->new(123.456789);
Math::BigFloat->accuracy(4); # no more A than 4
is ($x->copy()->bround(),123.4); # even rounding
print $x->copy()->bround(),"\n"; # 123.4
Math::BigFloat->round_mode('odd'); # round to odd
print $x->copy()->bround(),"\n"; # 123.5
Math::BigFloat->accuracy(5); # no more A than 5
Math::BigFloat->round_mode('odd'); # round to odd
print $x->copy()->bround(),"\n"; # 123.46
$y = $x->copy()->bround(4),"\n"; # A = 4: 123.4
print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
Math::BigFloat->accuracy(undef); # A not important now
Math::BigFloat->precision(2); # P important
print $x->copy()->bnorm(),"\n"; # 123.46
print $x->copy()->bround(),"\n"; # 123.46
```
Examples for converting:
```
my $x = Math::BigInt->new('0b1'.'01' x 123);
print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
```
NUMERIC LITERALS
-----------------
After `use Math::BigInt ':constant'` all numeric literals in the given scope are converted to `Math::BigInt` objects. This conversion happens at compile time. Every non-integer is convert to a NaN.
For example,
```
perl -MMath::BigInt=:constant -le 'print 2**150'
```
prints the exact value of `2**150`. Note that without conversion of constants to objects the expression `2**150` is calculated using Perl scalars, which leads to an inaccurate result.
Please note that strings are not affected, so that
```
use Math::BigInt qw/:constant/;
$x = "1234567890123456789012345678901234567890"
+ "123456789123456789";
```
does give you what you expect. You need an explicit Math::BigInt->new() around at least one of the operands. You should also quote large constants to prevent loss of precision:
```
use Math::BigInt;
$x = Math::BigInt->new("1234567889123456789123456789123456789");
```
Without the quotes Perl first converts the large number to a floating point constant at compile time, and then converts the result to a Math::BigInt object at run time, which results in an inaccurate result.
###
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. Below are some examples of different ways to write the number decimal 314.
Hexadecimal floating point literals:
```
0x1.3ap+8 0X1.3AP+8
0x1.3ap8 0X1.3AP8
0x13a0p-4 0X13A0P-4
```
Octal floating point literals (with "0" prefix):
```
01.164p+8 01.164P+8
01.164p8 01.164P8
011640p-4 011640P-4
```
Octal floating point literals (with "0o" prefix) (requires v5.34.0):
```
0o1.164p+8 0O1.164P+8
0o1.164p8 0O1.164P8
0o11640p-4 0O11640P-4
```
Binary floating point literals:
```
0b1.0011101p+8 0B1.0011101P+8
0b1.0011101p8 0B1.0011101P8
0b10011101000p-2 0B10011101000P-2
```
PERFORMANCE
-----------
Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x must be made in the second case. For long numbers, the copy can eat up to 20% of the work (in the case of addition/subtraction, less for multiplication/division). If $y is very small compared to $x, the form $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes more time then the actual addition.
With a technique called copy-on-write, the cost of copying with overload could be minimized or even completely avoided. A test implementation of COW did show performance gains for overloaded math, but introduced a performance loss due to a constant overhead for all other operations. So Math::BigInt does currently not COW.
The rewritten version of this module (vs. v0.01) is slower on certain operations, like `new()`, `bstr()` and `numify()`. The reason are that it does now more work and handles much more cases. The time spent in these operations is usually gained in the other math operations so that code on the average should get (much) faster. If they don't, please contact the author.
Some operations may be slower for small numbers, but are significantly faster for big numbers. Other operations are now constant (O(1), like `bneg()`, `babs()` etc), instead of O(N) and thus nearly always take much less time. These optimizations were done on purpose.
If you find the Calc module to slow, try to install any of the replacement modules and see if they help you.
###
Alternative math libraries
You can use an alternative library to drive Math::BigInt. See the section ["MATH LIBRARY"](#MATH-LIBRARY) for more information.
For more benchmark results see <http://bloodgate.com/perl/benchmarks.html>.
SUBCLASSING
-----------
###
Subclassing Math::BigInt
The basic design of Math::BigInt allows simple subclasses with very little work, as long as a few simple rules are followed:
* The public API must remain consistent, i.e. if a sub-class is overloading addition, the sub-class must use the same name, in this case badd(). The reason for this is that Math::BigInt is optimized to call the object methods directly.
* The private object hash keys like `$x->{sign}` may not be changed, but additional keys can be added, like `$x->{_custom}`.
* Accessor functions are available for all existing object hash keys and should be used instead of directly accessing the internal hash keys. The reason for this is that Math::BigInt itself has a pluggable interface which permits it to support different storage methods.
More complex sub-classes may have to replicate more of the logic internal of Math::BigInt if they need to change more basic behaviors. A subclass that needs to merely change the output only needs to overload `bstr()`.
All other object methods and overloaded functions can be directly inherited from the parent class.
At the very minimum, any subclass needs to provide its own `new()` and can store additional hash keys in the object. There are also some package globals that must be defined, e.g.:
```
# Globals
$accuracy = undef;
$precision = -2; # round to 2 decimal places
$round_mode = 'even';
$div_scale = 40;
```
Additionally, you might want to provide the following two globals to allow auto-upgrading and auto-downgrading to work correctly:
```
$upgrade = undef;
$downgrade = undef;
```
This allows Math::BigInt to correctly retrieve package globals from the subclass, like `$SubClass::precision`. See t/Math/BigInt/Subclass.pm or t/Math/BigFloat/SubClass.pm completely functional subclass examples.
Don't forget to
```
use overload;
```
in your subclass to automatically inherit the overloading from the parent. If you like, you can change part of the overloading, look at Math::String for an example.
UPGRADING
---------
When used like this:
```
use Math::BigInt upgrade => 'Foo::Bar';
```
certain operations 'upgrade' their calculation and thus the result to the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
```
use Math::BigInt upgrade => 'Math::BigFloat';
```
As a shortcut, you can use the module <bignum>:
```
use bignum;
```
Also good for one-liners:
```
perl -Mbignum -le 'print 2 ** 255'
```
This makes it possible to mix arguments of different classes (as in 2.5 + 2) as well es preserve accuracy (as in sqrt(3)).
Beware: This feature is not fully implemented yet.
###
Auto-upgrade
The following methods upgrade themselves unconditionally; that is if upgrade is in effect, they always hands up their work:
```
div bsqrt blog bexp bpi bsin bcos batan batan2
```
All other methods upgrade themselves only when one (or all) of their arguments are of the class mentioned in $upgrade.
EXPORTS
-------
`Math::BigInt` exports nothing by default, but can export the following methods:
```
bgcd
blcm
```
CAVEATS
-------
Some things might not work as you expect them. Below is documented what is known to be troublesome:
Comparing numbers as strings Both `bstr()` and `bsstr()` as well as stringify via overload drop the leading '+'. This is to be consistent with Perl and to make `cmp` (especially with overloading) to work as you expect. It also solves problems with `Test.pm` and <Test::More>, which stringify arguments before comparing them.
Mark Biggar said, when asked about to drop the '+' altogether, or make only `cmp` work:
```
I agree (with the first alternative), don't add the '+' on positive
numbers. It's not as important anymore with the new internal form
for numbers. It made doing things like abs and neg easier, but
those have to be done differently now anyway.
```
So, the following examples now works as expected:
```
use Test::More tests => 1;
use Math::BigInt;
my $x = Math::BigInt -> new(3*3);
my $y = Math::BigInt -> new(3*3);
is($x,3*3, 'multiplication');
print "$x eq 9" if $x eq $y;
print "$x eq 9" if $x eq '9';
print "$x eq 9" if $x eq 3*3;
```
Additionally, the following still works:
```
print "$x == 9" if $x == $y;
print "$x == 9" if $x == 9;
print "$x == 9" if $x == 3*3;
```
There is now a `bsstr()` method to get the string in scientific notation aka `1e+2` instead of `100`. Be advised that overloaded 'eq' always uses bstr() for comparison, but Perl represents some numbers as 100 and others as 1e+308. If in doubt, convert both arguments to Math::BigInt before comparing them as strings:
```
use Test::More tests => 3;
use Math::BigInt;
$x = Math::BigInt->new('1e56'); $y = 1e56;
is($x,$y); # fails
is($x->bsstr(),$y); # okay
$y = Math::BigInt->new($y);
is($x,$y); # okay
```
Alternatively, simply use `<=>` for comparisons, this always gets it right. There is not yet a way to get a number automatically represented as a string that matches exactly the way Perl represents it.
See also the section about ["Infinity and Not a Number"](#Infinity-and-Not-a-Number) for problems in comparing NaNs.
int() `int()` returns (at least for Perl v5.7.1 and up) another Math::BigInt, not a Perl scalar:
```
$x = Math::BigInt->new(123);
$y = int($x); # 123 as a Math::BigInt
$x = Math::BigFloat->new(123.45);
$y = int($x); # 123 as a Math::BigFloat
```
If you want a real Perl scalar, use `numify()`:
```
$y = $x->numify(); # 123 as a scalar
```
This is seldom necessary, though, because this is done automatically, like when you access an array:
```
$z = $array[$x]; # does work automatically
```
Modifying and = Beware of:
```
$x = Math::BigFloat->new(5);
$y = $x;
```
This makes a second reference to the **same** object and stores it in $y. Thus anything that modifies $x (except overloaded operators) also modifies $y, and vice versa. Or in other words, `=` is only safe if you modify your Math::BigInt objects only via overloaded math. As soon as you use a method call it breaks:
```
$x->bmul(2);
print "$x, $y\n"; # prints '10, 10'
```
If you want a true copy of $x, use:
```
$y = $x->copy();
```
You can also chain the calls like this, this first makes a copy and then multiply it by 2:
```
$y = $x->copy()->bmul(2);
```
See also the documentation for overload.pm regarding `=`.
Overloading -$x The following:
```
$x = -$x;
```
is slower than
```
$x->bneg();
```
since overload calls `sub($x,0,1);` instead of `neg($x)`. The first variant needs to preserve $x since it does not know that it later gets overwritten. This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
Mixing different object types With overloaded operators, it is the first (dominating) operand that determines which method is called. Here are some examples showing what actually gets called in various cases.
```
use Math::BigInt;
use Math::BigFloat;
$mbf = Math::BigFloat->new(5);
$mbi2 = Math::BigInt->new(5);
$mbi = Math::BigInt->new(2);
# what actually gets called:
$float = $mbf + $mbi; # $mbf->badd($mbi)
$float = $mbf / $mbi; # $mbf->bdiv($mbi)
$integer = $mbi + $mbf; # $mbi->badd($mbf)
$integer = $mbi2 / $mbi; # $mbi2->bdiv($mbi)
$integer = $mbi2 / $mbf; # $mbi2->bdiv($mbf)
```
For instance, Math::BigInt->bdiv() always returns a Math::BigInt, regardless of whether the second operant is a Math::BigFloat. To get a Math::BigFloat you either need to call the operation manually, make sure each operand already is a Math::BigFloat, or cast to that type via Math::BigFloat->new():
```
$float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
```
Beware of casting the entire expression, as this would cast the result, at which point it is too late:
```
$float = Math::BigFloat->new($mbi2 / $mbi); # = 2
```
Beware also of the order of more complicated expressions like:
```
$integer = ($mbi2 + $mbi) / $mbf; # int / float => int
$integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
```
If in doubt, break the expression into simpler terms, or cast all operands to the desired resulting type.
Scalar values are a bit different, since:
```
$float = 2 + $mbf;
$float = $mbf + 2;
```
both result in the proper type due to the way the overloaded math works.
This section also applies to other overloaded math packages, like Math::String.
One solution to you problem might be autoupgrading|upgrading. See the pragmas <bignum>, <bigint> and <bigrat> for an easy way to do this.
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
```
You can also look for information at:
* GitHub
<https://github.com/pjacklam/p5-Math-BigInt>
* RT: CPAN's request tracker
<https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
* MetaCPAN
<https://metacpan.org/release/Math-BigInt>
* CPAN Testers Matrix
<http://matrix.cpantesters.org/?dist=Math-BigInt>
* CPAN Ratings
<https://cpanratings.perl.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.
SEE ALSO
---------
<Math::BigFloat> and <Math::BigRat> as well as the backends <Math::BigInt::FastCalc>, <Math::BigInt::GMP>, and <Math::BigInt::Pari>.
The pragmas <bignum>, <bigint> and <bigrat> also might be of interest because they solve the autoupgrading/downgrading issue, at least partly.
AUTHORS
-------
* Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
* Completely rewritten by Tels <http://bloodgate.com>, 2001-2008.
* Florian Ragwitz <[email protected]>, 2010.
* Peter John Acklam <[email protected]>, 2011-.
Many people contributed in one or more ways to the final beast, see the file CREDITS for an (incomplete) list. If you miss your name, please drop me a mail. Thank you!
| programming_docs |
perl Test2::EventFacet::Amnesty Test2::EventFacet::Amnesty
==========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Amnesty - Facet for assertion amnesty.
DESCRIPTION
-----------
This package represents what is expected in units of amnesty.
NOTES
-----
This facet appears in a list instead of being a single item.
FIELDS
------
$string = $amnesty->{details}
$string = $amnesty->details() Human readable explanation of why amnesty was granted.
Example: *Not implemented yet, will fix*
$short\_string = $amnesty->{tag}
$short\_string = $amnesty->tag() Short string (usually 10 characters or less, not enforced, but may be truncated by renderers) categorizing the amnesty.
$bool = $amnesty->{inherited}
$bool = $amnesty->inherited() This will be true if the amnesty was granted to a parent event and inherited by this event, which is a child, such as an assertion within a subtest that is marked todo.
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 Archive::Tar::File Archive::Tar::File
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Accessors](#Accessors)
* [Methods](#Methods)
+ [Archive::Tar::File->new( file => $path )](#Archive::Tar::File-%3Enew(-file-=%3E-%24path-))
+ [Archive::Tar::File->new( data => $path, $data, $opt )](#Archive::Tar::File-%3Enew(-data-=%3E-%24path,-%24data,-%24opt-))
+ [Archive::Tar::File->new( chunk => $chunk )](#Archive::Tar::File-%3Enew(-chunk-=%3E-%24chunk-))
+ [$bool = $file->extract( [ $alternative\_name ] )](#%24bool-=-%24file-%3Eextract(-%5B-%24alternative_name-%5D-))
+ [$path = $file->full\_path](#%24path-=-%24file-%3Efull_path)
+ [$bool = $file->validate](#%24bool-=-%24file-%3Evalidate)
+ [$bool = $file->has\_content](#%24bool-=-%24file-%3Ehas_content)
+ [$content = $file->get\_content](#%24content-=-%24file-%3Eget_content)
+ [$cref = $file->get\_content\_by\_ref](#%24cref-=-%24file-%3Eget_content_by_ref)
+ [$bool = $file->replace\_content( $content )](#%24bool-=-%24file-%3Ereplace_content(-%24content-))
+ [$bool = $file->rename( $new\_name )](#%24bool-=-%24file-%3Erename(-%24new_name-))
+ [$bool = $file->chmod $mode)](#%24bool-=-%24file-%3Echmod-%24mode))
+ [$bool = $file->chown( $user [, $group])](#%24bool-=-%24file-%3Echown(-%24user-%5B,-%24group%5D))
* [Convenience methods](#Convenience-methods)
NAME
----
Archive::Tar::File - a subclass for in-memory extracted file from Archive::Tar
SYNOPSIS
--------
```
my @items = $tar->get_files;
print $_->name, ' ', $_->size, "\n" for @items;
print $object->get_content;
$object->replace_content('new content');
$object->rename( 'new/full/path/to/file.c' );
```
DESCRIPTION
-----------
Archive::Tar::Files provides a neat little object layer for in-memory extracted files. It's mostly used internally in Archive::Tar to tidy up the code, but there's no reason users shouldn't use this API as well.
### Accessors
A lot of the methods in this package are accessors to the various fields in the tar header:
name The file's name
mode The file's mode
uid The user id owning the file
gid The group id owning the file
size File size in bytes
mtime Modification time. Adjusted to mac-time on MacOS if required
chksum Checksum field for the tar header
type File type -- numeric, but comparable to exported constants -- see Archive::Tar's documentation
linkname If the file is a symlink, the file it's pointing to
magic Tar magic string -- not useful for most users
version Tar version string -- not useful for most users
uname The user name that owns the file
gname The group name that owns the file
devmajor Device major number in case of a special file
devminor Device minor number in case of a special file
prefix Any directory to prefix to the extraction path, if any
raw Raw tar header -- not useful for most users
Methods
-------
###
Archive::Tar::File->new( file => $path )
Returns a new Archive::Tar::File object from an existing file.
Returns undef on failure.
###
Archive::Tar::File->new( data => $path, $data, $opt )
Returns a new Archive::Tar::File object from data.
`$path` defines the file name (which need not exist), `$data` the file contents, and `$opt` is a reference to a hash of attributes which may be used to override the default attributes (fields in the tar header), which are described above in the Accessors section.
Returns undef on failure.
###
Archive::Tar::File->new( chunk => $chunk )
Returns a new Archive::Tar::File object from a raw 512-byte tar archive chunk.
Returns undef on failure.
###
$bool = $file->extract( [ $alternative\_name ] )
Extract this object, optionally to an alternative name.
See `Archive::Tar->extract_file` for details.
Returns true on success and false on failure.
###
$path = $file->full\_path
Returns the full path from the tar header; this is basically a concatenation of the `prefix` and `name` fields.
###
$bool = $file->validate
Done by Archive::Tar internally when reading the tar file: validate the header against the checksum to ensure integer tar file.
Returns true on success, false on failure
###
$bool = $file->has\_content
Returns a boolean to indicate whether the current object has content. Some special files like directories and so on never will have any content. This method is mainly to make sure you don't get warnings for using uninitialized values when looking at an object's content.
###
$content = $file->get\_content
Returns the current content for the in-memory file
###
$cref = $file->get\_content\_by\_ref
Returns the current content for the in-memory file as a scalar reference. Normal users won't need this, but it will save memory if you are dealing with very large data files in your tar archive, since it will pass the contents by reference, rather than make a copy of it first.
###
$bool = $file->replace\_content( $content )
Replace the current content of the file with the new content. This only affects the in-memory archive, not the on-disk version until you write it.
Returns true on success, false on failure.
###
$bool = $file->rename( $new\_name )
Rename the current file to $new\_name.
Note that you must specify a Unix path for $new\_name, since per tar standard, all files in the archive must be Unix paths.
Returns true on success and false on failure.
###
$bool = $file->chmod $mode)
Change mode of $file to $mode. The mode can be a string or a number which is interpreted as octal whether or not a leading 0 is given.
Returns true on success and false on failure.
###
$bool = $file->chown( $user [, $group])
Change owner of $file to $user. If a $group is given that is changed as well. You can also pass a single parameter with a colon separating the use and group as in 'root:wheel'.
Returns true on success and false on failure.
Convenience methods
--------------------
To quickly check the type of a `Archive::Tar::File` object, you can use the following methods:
$file->is\_file Returns true if the file is of type `file`
$file->is\_dir Returns true if the file is of type `dir`
$file->is\_hardlink Returns true if the file is of type `hardlink`
$file->is\_symlink Returns true if the file is of type `symlink`
$file->is\_chardev Returns true if the file is of type `chardev`
$file->is\_blockdev Returns true if the file is of type `blockdev`
$file->is\_fifo Returns true if the file is of type `fifo`
$file->is\_socket Returns true if the file is of type `socket`
$file->is\_longlink Returns true if the file is of type `LongLink`. Should not happen after a successful `read`.
$file->is\_label Returns true if the file is of type `Label`. Should not happen after a successful `read`.
$file->is\_unknown Returns true if the file type is `unknown`
perl Getopt::Std Getopt::Std
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [--help and --version](#-help-and-version)
NAME
----
Getopt::Std - Process single-character switches with switch clustering
SYNOPSIS
--------
```
use Getopt::Std;
getopts('oif:'); # -o & -i are boolean flags, -f takes an argument
# Sets $opt_* as a side effect.
getopts('oif:', \%opts); # options as above. Values in %opts
getopt('oDI'); # -o, -D & -I take arg.
# Sets $opt_* as a side effect.
getopt('oDI', \%opts); # -o, -D & -I take arg. Values in %opts
```
DESCRIPTION
-----------
The `getopts()` function processes single-character switches with switch clustering. Pass one argument which is a string containing all switches to be recognized. For each switch found, if an argument is expected and provided, `getopts()` sets `$opt_x` (where `x` is the switch name) to the value of the argument. If an argument is expected but none is provided, `$opt_x` is set to an undefined value. If a switch does not take an argument, `$opt_x` is set to `1`.
Switches which take an argument don't care whether there is a space between the switch and the argument. If unspecified switches are found on the command-line, the user will be warned that an unknown option was given.
The `getopts()` function returns true unless an invalid option was found.
The `getopt()` function is similar, but its argument is a string containing all switches that take an argument. If no argument is provided for a switch, say, `y`, the corresponding `$opt_y` will be set to an undefined value. Unspecified switches are silently accepted. Use of `getopt()` is not recommended.
Note that, if your code is running under the recommended `use strict vars` pragma, you will need to declare these package variables with `our`:
```
our($opt_x, $opt_y);
```
For those of you who don't like additional global variables being created, `getopt()` and `getopts()` will also accept a hash reference as an optional second argument. Hash keys will be `x` (where `x` is the switch name) with key values the value of the argument or `1` if no argument is specified.
To allow programs to process arguments that look like switches, but aren't, both functions will stop processing switches when they see the argument `--`. The `--` will be removed from @ARGV.
`--help` and `--version`
-------------------------
If `-` is not a recognized switch letter, getopts() supports arguments `--help` and `--version`. If `main::HELP_MESSAGE()` and/or `main::VERSION_MESSAGE()` are defined, they are called; the arguments are the output file handle, the name of option-processing package, its version, and the switches string. If the subroutines are not defined, an attempt is made to generate intelligent messages; for best results, define $main::VERSION.
If embedded documentation (in pod format, see <perlpod>) is detected in the script, `--help` will also show how to access the documentation.
Note that due to excessive paranoia, if $Getopt::Std::STANDARD\_HELP\_VERSION isn't true (the default is false), then the messages are printed on STDERR, and the processing continues after the messages are printed. This being the opposite of the standard-conforming behaviour, it is strongly recommended to set $Getopt::Std::STANDARD\_HELP\_VERSION to true.
One can change the output file handle of the messages by setting $Getopt::Std::OUTPUT\_HELP\_VERSION. One can print the messages of `--help` (without the `Usage:` line) and `--version` by calling functions help\_mess() and version\_mess() with the switches string as an argument.
perl File::GlobMapper File::GlobMapper
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Behind The Scenes](#Behind-The-Scenes)
+ [Limitations](#Limitations)
+ [Input File Glob](#Input-File-Glob)
+ [Output File Glob](#Output-File-Glob)
+ [Returned Data](#Returned-Data)
* [EXAMPLES](#EXAMPLES)
+ [A Rename script](#A-Rename-script)
+ [A few example globmaps](#A-few-example-globmaps)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
File::GlobMapper - Extend File Glob to Allow Input and Output Files
SYNOPSIS
--------
```
use File::GlobMapper qw( globmap );
my $aref = globmap $input => $output
or die $File::GlobMapper::Error ;
my $gm = File::GlobMapper->new( $input => $output )
or die $File::GlobMapper::Error ;
```
DESCRIPTION
-----------
This module needs Perl5.005 or better.
This module takes the existing `File::Glob` module as a starting point and extends it to allow new filenames to be derived from the files matched by `File::Glob`.
This can be useful when carrying out batch operations on multiple files that have both an input filename and output filename and the output file can be derived from the input filename. Examples of operations where this can be useful include, file renaming, file copying and file compression.
###
Behind The Scenes
To help explain what `File::GlobMapper` does, consider what code you would write if you wanted to rename all files in the current directory that ended in `.tar.gz` to `.tgz`. So say these files are in the current directory
```
alpha.tar.gz
beta.tar.gz
gamma.tar.gz
```
and they need renamed to this
```
alpha.tgz
beta.tgz
gamma.tgz
```
Below is a possible implementation of a script to carry out the rename (error cases have been omitted)
```
foreach my $old ( glob "*.tar.gz" )
{
my $new = $old;
$new =~ s#(.*)\.tar\.gz$#$1.tgz# ;
rename $old => $new
or die "Cannot rename '$old' to '$new': $!\n;
}
```
Notice that a file glob pattern `*.tar.gz` was used to match the `.tar.gz` files, then a fairly similar regular expression was used in the substitute to allow the new filename to be created.
Given that the file glob is just a cut-down regular expression and that it has already done a lot of the hard work in pattern matching the filenames, wouldn't it be handy to be able to use the patterns in the fileglob to drive the new filename?
Well, that's *exactly* what `File::GlobMapper` does.
Here is same snippet of code rewritten using `globmap`
```
for my $pair (globmap '<*.tar.gz>' => '<#1.tgz>' )
{
my ($from, $to) = @$pair;
rename $from => $to
or die "Cannot rename '$old' to '$new': $!\n;
}
```
So how does it work?
Behind the scenes the `globmap` function does a combination of a file glob to match existing filenames followed by a substitute to create the new filenames.
Notice how both parameters to `globmap` are strings that are delimited by <>. This is done to make them look more like file globs - it is just syntactic sugar, but it can be handy when you want the strings to be visually distinctive. The enclosing <> are optional, so you don't have to use them - in fact the first thing globmap will do is remove these delimiters if they are present.
The first parameter to `globmap`, `*.tar.gz`, is an *Input File Glob*. Once the enclosing "< ... >" is removed, this is passed (more or less) unchanged to `File::Glob` to carry out a file match.
Next the fileglob `*.tar.gz` is transformed behind the scenes into a full Perl regular expression, with the additional step of wrapping each transformed wildcard metacharacter sequence in parenthesis.
In this case the input fileglob `*.tar.gz` will be transformed into this Perl regular expression
```
([^/]*)\.tar\.gz
```
Wrapping with parenthesis allows the wildcard parts of the Input File Glob to be referenced by the second parameter to `globmap`, `#1.tgz`, the *Output File Glob*. This parameter operates just like the replacement part of a substitute command. The difference is that the `#1` syntax is used to reference sub-patterns matched in the input fileglob, rather than the `$1` syntax that is used with perl regular expressions. In this case `#1` is used to refer to the text matched by the `*` in the Input File Glob. This makes it easier to use this module where the parameters to `globmap` are typed at the command line.
The final step involves passing each filename matched by the `*.tar.gz` file glob through the derived Perl regular expression in turn and expanding the output fileglob using it.
The end result of all this is a list of pairs of filenames. By default that is what is returned by `globmap`. In this example the data structure returned will look like this
```
( ['alpha.tar.gz' => 'alpha.tgz'],
['beta.tar.gz' => 'beta.tgz' ],
['gamma.tar.gz' => 'gamma.tgz']
)
```
Each pair is an array reference with two elements - namely the *from* filename, that `File::Glob` has matched, and a *to* filename that is derived from the *from* filename.
### Limitations
`File::GlobMapper` has been kept simple deliberately, so it isn't intended to solve all filename mapping operations. Under the hood `File::Glob` (or for older versions of Perl, `File::BSDGlob`) is used to match the files, so you will never have the flexibility of full Perl regular expression.
###
Input File Glob
The syntax for an Input FileGlob is identical to `File::Glob`, except for the following
1. No nested {}
2. Whitespace does not delimit fileglobs.
3. The use of parenthesis can be used to capture parts of the input filename.
4. If an Input glob matches the same file more than once, only the first will be used.
The syntax
**~**
**~user**
**.**
Matches a literal '.'. Equivalent to the Perl regular expression
```
\.
```
**\***
Matches zero or more characters, except '/'. Equivalent to the Perl regular expression
```
[^/]*
```
**?**
Matches zero or one character, except '/'. Equivalent to the Perl regular expression
```
[^/]?
```
**\**
Backslash is used, as usual, to escape the next character.
**[]**
Character class.
**{,}**
Alternation
**()**
Capturing parenthesis that work just like perl
Any other character it taken literally.
###
Output File Glob
The Output File Glob is a normal string, with 2 glob-like features.
The first is the '\*' metacharacter. This will be replaced by the complete filename matched by the input file glob. So
```
*.c *.Z
```
The second is
Output FileGlobs take the
"\*" The "\*" character will be replaced with the complete input filename.
#1 Patterns of the form /#\d/ will be replaced with the
###
Returned Data
EXAMPLES
--------
###
A Rename script
Below is a simple "rename" script that uses `globmap` to determine the source and destination filenames.
```
use File::GlobMapper qw(globmap) ;
use File::Copy;
die "rename: Usage rename 'from' 'to'\n"
unless @ARGV == 2 ;
my $fromGlob = shift @ARGV;
my $toGlob = shift @ARGV;
my $pairs = globmap($fromGlob, $toGlob)
or die $File::GlobMapper::Error;
for my $pair (@$pairs)
{
my ($from, $to) = @$pair;
move $from => $to ;
}
```
Here is an example that renames all c files to cpp.
```
$ rename '*.c' '#1.cpp'
```
###
A few example globmaps
Below are a few examples of globmaps
To copy all your .c file to a backup directory
```
'</my/home/*.c>' '</my/backup/#1.c>'
```
If you want to compress all
```
'</my/home/*.[ch]>' '<*.gz>'
```
To uncompress
```
'</my/home/*.[ch].gz>' '</my/home/#1.#2>'
```
SEE ALSO
---------
<File::Glob>
AUTHOR
------
The *File::GlobMapper* module was written by Paul Marquess, *[email protected]*.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005 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 autouse autouse
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [WARNING](#WARNING)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
autouse - postpone load of modules until a function is used
SYNOPSIS
--------
```
use autouse 'Carp' => qw(carp croak);
carp "this carp was predeclared and autoused ";
```
DESCRIPTION
-----------
If the module `Module` is already loaded, then the declaration
```
use autouse 'Module' => qw(func1 func2($;$));
```
is equivalent to
```
use Module qw(func1 func2);
```
if `Module` defines func2() with prototype `($;$)`, and func1() has no prototypes. (At least if `Module` uses `Exporter`'s `import`, otherwise it is a fatal error.)
If the module `Module` is not loaded yet, then the above declaration declares functions func1() and func2() in the current package. When these functions are called, they load the package `Module` if needed, and substitute themselves with the correct definitions.
WARNING
-------
Using `autouse` will move important steps of your program's execution from compile time to runtime. This can
* Break the execution of your program if the module you `autouse`d has some initialization which it expects to be done early.
* hide bugs in your code since important checks (like correctness of prototypes) is moved from compile time to runtime. In particular, if the prototype you specified on `autouse` line is wrong, you will not find it out until the corresponding function is executed. This will be very unfortunate for functions which are not always called (note that for such functions `autouse`ing gives biggest win, for a workaround see below).
To alleviate the second problem (partially) it is advised to write your scripts like this:
```
use Module;
use autouse Module => qw(carp($) croak(&$));
carp "this carp was predeclared and autoused ";
```
The first line ensures that the errors in your argument specification are found early. When you ship your application you should comment out the first line, since it makes the second one useless.
AUTHOR
------
Ilya Zakharevich ([email protected])
SEE ALSO
---------
perl(1).
perl perlopentut perlopentut
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Opening Text Files](#Opening-Text-Files)
+ [Opening Text Files for Reading](#Opening-Text-Files-for-Reading)
+ [Opening Text Files for Writing](#Opening-Text-Files-for-Writing)
* [Opening Binary Files](#Opening-Binary-Files)
* [Opening Pipes](#Opening-Pipes)
+ [Opening a pipe for reading](#Opening-a-pipe-for-reading)
+ [Opening a pipe for writing](#Opening-a-pipe-for-writing)
+ [Expressing the command as a list](#Expressing-the-command-as-a-list)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR and COPYRIGHT](#AUTHOR-and-COPYRIGHT)
NAME
----
perlopentut - simple recipes for opening files and pipes in Perl
DESCRIPTION
-----------
Whenever you do I/O on a file in Perl, you do so through what in Perl is called a **filehandle**. A filehandle is an internal name for an external file. It is the job of the `open` function to make the association between the internal name and the external name, and it is the job of the `close` function to break that association.
For your convenience, Perl sets up a few special filehandles that are already open when you run. These include `STDIN`, `STDOUT`, `STDERR`, and `ARGV`. Since those are pre-opened, you can use them right away without having to go to the trouble of opening them yourself:
```
print STDERR "This is a debugging message.\n";
print STDOUT "Please enter something: ";
$response = <STDIN> // die "how come no input?";
print STDOUT "Thank you!\n";
while (<ARGV>) { ... }
```
As you see from those examples, `STDOUT` and `STDERR` are output handles, and `STDIN` and `ARGV` are input handles. They are in all capital letters because they are reserved to Perl, much like the `@ARGV` array and the `%ENV` hash are. Their external associations were set up by your shell.
You will need to open every other filehandle on your own. Although there are many variants, the most common way to call Perl's open() function is with three arguments and one return value:
`*OK* = open(*HANDLE*, *MODE*, *PATHNAME*)`
Where:
*OK* will be some defined value if the open succeeds, but `undef` if it fails;
*HANDLE* should be an undefined scalar variable to be filled in by the `open` function if it succeeds;
*MODE* is the access mode and the encoding format to open the file with;
*PATHNAME* is the external name of the file you want opened.
Most of the complexity of the `open` function lies in the many possible values that the *MODE* parameter can take on.
One last thing before we show you how to open files: opening files does not (usually) automatically lock them in Perl. See <perlfaq5> for how to lock.
Opening Text Files
-------------------
###
Opening Text Files for Reading
If you want to read from a text file, first open it in read-only mode like this:
```
my $filename = "/some/path/to/a/textfile/goes/here";
my $encoding = ":encoding(UTF-8)";
my $handle = undef; # this will be filled in on success
open($handle, "< $encoding", $filename)
|| die "$0: can't open $filename for reading: $!";
```
As with the shell, in Perl the `"<"` is used to open the file in read-only mode. If it succeeds, Perl allocates a brand new filehandle for you and fills in your previously undefined `$handle` argument with a reference to that handle.
Now you may use functions like `readline`, `read`, `getc`, and `sysread` on that handle. Probably the most common input function is the one that looks like an operator:
```
$line = readline($handle);
$line = <$handle>; # same thing
```
Because the `readline` function returns `undef` at end of file or upon error, you will sometimes see it used this way:
```
$line = <$handle>;
if (defined $line) {
# do something with $line
}
else {
# $line is not valid, so skip it
}
```
You can also just quickly `die` on an undefined value this way:
```
$line = <$handle> // die "no input found";
```
However, if hitting EOF is an expected and normal event, you do not want to exit simply because you have run out of input. Instead, you probably just want to exit an input loop. You can then test to see if an actual error has caused the loop to terminate, and act accordingly:
```
while (<$handle>) {
# do something with data in $_
}
if ($!) {
die "unexpected error while reading from $filename: $!";
}
```
**A Note on Encodings**: Having to specify the text encoding every time might seem a bit of a bother. To set up a default encoding for `open` so that you don't have to supply it each time, you can use the `open` pragma:
```
use open qw< :encoding(UTF-8) >;
```
Once you've done that, you can safely omit the encoding part of the open mode:
```
open($handle, "<", $filename)
|| die "$0: can't open $filename for reading: $!";
```
But never use the bare `"<"` without having set up a default encoding first. Otherwise, Perl cannot know which of the many, many, many possible flavors of text file you have, and Perl will have no idea how to correctly map the data in your file into actual characters it can work with. Other common encoding formats including `"ASCII"`, `"ISO-8859-1"`, `"ISO-8859-15"`, `"Windows-1252"`, `"MacRoman"`, and even `"UTF-16LE"`. See <perlunitut> for more about encodings.
###
Opening Text Files for Writing
When you want to write to a file, you first have to decide what to do about any existing contents of that file. You have two basic choices here: to preserve or to clobber.
If you want to preserve any existing contents, then you want to open the file in append mode. As in the shell, in Perl you use `">>"` to open an existing file in append mode. `">>"` creates the file if it does not already exist.
```
my $handle = undef;
my $filename = "/some/path/to/a/textfile/goes/here";
my $encoding = ":encoding(UTF-8)";
open($handle, ">> $encoding", $filename)
|| die "$0: can't open $filename for appending: $!";
```
Now you can write to that filehandle using any of `print`, `printf`, `say`, `write`, or `syswrite`.
As noted above, if the file does not already exist, then the append-mode open will create it for you. But if the file does already exist, its contents are safe from harm because you will be adding your new text past the end of the old text.
On the other hand, sometimes you want to clobber whatever might already be there. To empty out a file before you start writing to it, you can open it in write-only mode:
```
my $handle = undef;
my $filename = "/some/path/to/a/textfile/goes/here";
my $encoding = ":encoding(UTF-8)";
open($handle, "> $encoding", $filename)
|| die "$0: can't open $filename in write-open mode: $!";
```
Here again Perl works just like the shell in that the `">"` clobbers an existing file.
As with the append mode, when you open a file in write-only mode, you can now write to that filehandle using any of `print`, `printf`, `say`, `write`, or `syswrite`.
What about read-write mode? You should probably pretend it doesn't exist, because opening text files in read-write mode is unlikely to do what you would like. See <perlfaq5> for details.
Opening Binary Files
---------------------
If the file to be opened contains binary data instead of text characters, then the `MODE` argument to `open` is a little different. Instead of specifying the encoding, you tell Perl that your data are in raw bytes.
```
my $filename = "/some/path/to/a/binary/file/goes/here";
my $encoding = ":raw :bytes"
my $handle = undef; # this will be filled in on success
```
And then open as before, choosing `"<"`, `">>"`, or `">"` as needed:
```
open($handle, "< $encoding", $filename)
|| die "$0: can't open $filename for reading: $!";
open($handle, ">> $encoding", $filename)
|| die "$0: can't open $filename for appending: $!";
open($handle, "> $encoding", $filename)
|| die "$0: can't open $filename in write-open mode: $!";
```
Alternately, you can change to binary mode on an existing handle this way:
```
binmode($handle) || die "cannot binmode handle";
```
This is especially handy for the handles that Perl has already opened for you.
```
binmode(STDIN) || die "cannot binmode STDIN";
binmode(STDOUT) || die "cannot binmode STDOUT";
```
You can also pass `binmode` an explicit encoding to change it on the fly. This isn't exactly "binary" mode, but we still use `binmode` to do it:
```
binmode(STDIN, ":encoding(MacRoman)") || die "cannot binmode STDIN";
binmode(STDOUT, ":encoding(UTF-8)") || die "cannot binmode STDOUT";
```
Once you have your binary file properly opened in the right mode, you can use all the same Perl I/O functions as you used on text files. However, you may wish to use the fixed-size `read` instead of the variable-sized `readline` for your input.
Here's an example of how to copy a binary file:
```
my $BUFSIZ = 64 * (2 ** 10);
my $name_in = "/some/input/file";
my $name_out = "/some/output/flie";
my($in_fh, $out_fh, $buffer);
open($in_fh, "<", $name_in)
|| die "$0: cannot open $name_in for reading: $!";
open($out_fh, ">", $name_out)
|| die "$0: cannot open $name_out for writing: $!";
for my $fh ($in_fh, $out_fh) {
binmode($fh) || die "binmode failed";
}
while (read($in_fh, $buffer, $BUFSIZ)) {
unless (print $out_fh $buffer) {
die "couldn't write to $name_out: $!";
}
}
close($in_fh) || die "couldn't close $name_in: $!";
close($out_fh) || die "couldn't close $name_out: $!";
```
Opening Pipes
--------------
Perl also lets you open a filehandle into an external program or shell command rather than into a file. You can do this in order to pass data from your Perl program to an external command for further processing, or to receive data from another program for your own Perl program to process.
Filehandles into commands are also known as *pipes*, since they work on similar inter-process communication principles as Unix pipelines. Such a filehandle has an active program instead of a static file on its external end, but in every other sense it works just like a more typical file-based filehandle, with all the techniques discussed earlier in this article just as applicable.
As such, you open a pipe using the same `open` call that you use for opening files, setting the second (`MODE`) argument to special characters that indicate either an input or an output pipe. Use `"-|"` for a filehandle that will let your Perl program read data from an external program, and `"|-"` for a filehandle that will send data to that program instead.
###
Opening a pipe for reading
Let's say you'd like your Perl program to process data stored in a nearby directory called `unsorted`, which contains a number of textfiles. You'd also like your program to sort all the contents from these files into a single, alphabetically sorted list of unique lines before it starts processing them.
You could do this through opening an ordinary filehandle into each of those files, gradually building up an in-memory array of all the file contents you load this way, and finally sorting and filtering that array when you've run out of files to load. *Or*, you could offload all that merging and sorting into your operating system's own `sort` command by opening a pipe directly into its output, and get to work that much faster.
Here's how that might look:
```
open(my $sort_fh, '-|', 'sort -u unsorted/*.txt')
or die "Couldn't open a pipe into sort: $!";
# And right away, we can start reading sorted lines:
while (my $line = <$sort_fh>) {
#
# ... Do something interesting with each $line here ...
#
}
```
The second argument to `open`, `"-|"`, makes it a read-pipe into a separate program, rather than an ordinary filehandle into a file.
Note that the third argument to `open` is a string containing the program name (`sort`) plus all its arguments: in this case, `-u` to specify unqiue sort, and then a fileglob specifying the files to sort. The resulting filehandle `$sort_fh` works just like a read-only (`"<"`) filehandle, and your program can subsequently read data from it as if it were opened onto an ordinary, single file.
###
Opening a pipe for writing
Continuing the previous example, let's say that your program has completed its processing, and the results sit in an array called `@processed`. You want to print these lines to a file called `numbered.txt` with a neatly formatted column of line-numbers.
Certainly you could write your own code to do this โ or, once again, you could kick that work over to another program. In this case, `cat`, running with its own `-n` option to activate line numbering, should do the trick:
```
open(my $cat_fh, '|-', 'cat -n > numbered.txt')
or die "Couldn't open a pipe into cat: $!";
for my $line (@processed) {
print $cat_fh $line;
}
```
Here, we use a second `open` argument of `"|-"`, signifying that the filehandle assigned to `$cat_fh` should be a write-pipe. We can then use it just as we would a write-only ordinary filehandle, including the basic function of `print`-ing data to it.
Note that the third argument, specifying the command that we wish to pipe to, sets up `cat` to redirect its output via that `">"` symbol into the file `numbered.txt`. This can start to look a little tricky, because that same symbol would have meant something entirely different had it showed it in the second argument to `open`! But here in the third argument, it's simply part of the shell command that Perl will open the pipe into, and Perl itself doesn't invest any special meaning to it.
###
Expressing the command as a list
For opening pipes, Perl offers the option to call `open` with a list comprising the desired command and all its own arguments as separate elements, rather than combining them into a single string as in the examples above. For instance, we could have phrased the `open` call in the first example like this:
```
open(my $sort_fh, '-|', 'sort', '-u', glob('unsorted/*.txt'))
or die "Couldn't open a pipe into sort: $!";
```
When you call `open` this way, Perl invokes the given command directly, bypassing the shell. As such, the shell won't try to interpret any special characters within the command's argument list, which might overwise have unwanted effects. This can make for safer, less error-prone `open` calls, useful in cases such as passing in variables as arguments, or even just referring to filenames with spaces in them.
However, when you *do* want to pass a meaningful metacharacter to the shell, such with the `"*"` inside that final `unsorted/*.txt` argument here, you can't use this alternate syntax. In this case, we have worked around it via Perl's handy `glob` built-in function, which evaluates its argument into a list of filenames โ and we can safely pass that resulting list right into `open`, as shown above.
Note also that representing piped-command arguments in list form like this doesn't work on every platform. It will work on any Unix-based OS that provides a real `fork` function (e.g. macOS or Linux), as well as on Windows when running Perl 5.22 or later.
SEE ALSO
---------
The full documentation for [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) provides a thorough reference to this function, beyond the best-practice basics covered here.
AUTHOR and COPYRIGHT
---------------------
Copyright 2013 Tom Christiansen; now maintained by Perl5 Porters
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Test2::EventFacet::About Test2::EventFacet::About
========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::About - Facet with event details.
DESCRIPTION
-----------
This facet has information about the event, such as event package.
FIELDS
------
$string = $about->{details}
$string = $about->details() Summary about the event.
$package = $about->{package}
$package = $about->package() Event package name.
$bool = $about->{no\_display}
$bool = $about->no\_display() True if the event should be skipped by formatters.
$uuid = $about->{uuid}
$uuid = $about->uuid() Will be set to a uuid if uuid tagging was enabled.
$uuid = $about->{eid}
$uuid = $about->eid() A unique (for the test job) identifier for 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 JSON::PP JSON::PP
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONAL INTERFACE](#FUNCTIONAL-INTERFACE)
+ [encode\_json](#encode_json)
+ [decode\_json](#decode_json)
+ [JSON::PP::is\_bool](#JSON::PP::is_bool)
* [OBJECT-ORIENTED INTERFACE](#OBJECT-ORIENTED-INTERFACE)
+ [new](#new)
+ [ascii](#ascii)
+ [latin1](#latin1)
+ [utf8](#utf8)
+ [pretty](#pretty)
+ [indent](#indent)
+ [space\_before](#space_before)
+ [space\_after](#space_after)
+ [relaxed](#relaxed)
+ [canonical](#canonical)
+ [allow\_nonref](#allow_nonref)
+ [allow\_unknown](#allow_unknown)
+ [allow\_blessed](#allow_blessed)
+ [convert\_blessed](#convert_blessed)
+ [allow\_tags](#allow_tags)
+ [boolean\_values](#boolean_values)
+ [filter\_json\_object](#filter_json_object)
+ [filter\_json\_single\_key\_object](#filter_json_single_key_object)
+ [shrink](#shrink)
+ [max\_depth](#max_depth)
+ [max\_size](#max_size)
+ [encode](#encode)
+ [decode](#decode)
+ [decode\_prefix](#decode_prefix)
* [FLAGS FOR JSON::PP ONLY](#FLAGS-FOR-JSON::PP-ONLY)
+ [allow\_singlequote](#allow_singlequote)
+ [allow\_barekey](#allow_barekey)
+ [allow\_bignum](#allow_bignum)
+ [loose](#loose)
+ [escape\_slash](#escape_slash)
+ [indent\_length](#indent_length)
+ [sort\_by](#sort_by)
* [INCREMENTAL PARSING](#INCREMENTAL-PARSING)
+ [incr\_parse](#incr_parse)
+ [incr\_text](#incr_text)
+ [incr\_skip](#incr_skip)
+ [incr\_reset](#incr_reset)
* [MAPPING](#MAPPING)
+ [JSON -> PERL](#JSON-%3E-PERL)
+ [PERL -> JSON](#PERL-%3E-JSON)
+ [OBJECT SERIALISATION](#OBJECT-SERIALISATION)
- [SERIALISATION](#SERIALISATION)
- [DESERIALISATION](#DESERIALISATION)
* [ENCODING/CODESET FLAG NOTES](#ENCODING/CODESET-FLAG-NOTES)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [CURRENT MAINTAINER](#CURRENT-MAINTAINER)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
JSON::PP - JSON::XS compatible pure-Perl module.
SYNOPSIS
--------
```
use JSON::PP;
# exported functions, they croak on error
# and expect/generate UTF-8
$utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
$perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
# OO-interface
$json = JSON::PP->new->ascii->pretty->allow_nonref;
$pretty_printed_json_text = $json->encode( $perl_scalar );
$perl_scalar = $json->decode( $json_text );
# Note that JSON version 2.0 and above will automatically use
# JSON::XS or JSON::PP, so you should be able to just:
use JSON;
```
DESCRIPTION
-----------
JSON::PP is a pure perl JSON decoder/encoder, and (almost) compatible to much faster <JSON::XS> written by Marc Lehmann in C. JSON::PP works as a fallback module when you use [JSON](json) module without having installed JSON::XS.
Because of this fallback feature of JSON.pm, JSON::PP tries not to be more JavaScript-friendly than JSON::XS (i.e. not to escape extra characters such as U+2028 and U+2029, etc), in order for you not to lose such JavaScript-friendliness silently when you use JSON.pm and install JSON::XS for speed or by accident. If you need JavaScript-friendly RFC7159-compliant pure perl module, try <JSON::Tiny>, which is derived from [Mojolicious](mojolicious) web framework and is also smaller and faster than JSON::PP.
JSON::PP has been in the Perl core since Perl 5.14, mainly for CPAN toolchain modules to parse META.json.
FUNCTIONAL INTERFACE
---------------------
This section is taken from JSON::XS almost verbatim. `encode_json` and `decode_json` are exported by default.
### encode\_json
```
$json_text = encode_json $perl_scalar
```
Converts the given Perl data structure to a UTF-8 encoded, binary string (that is, the string contains octets only). Croaks on error.
This function call is functionally identical to:
```
$json_text = JSON::PP->new->utf8->encode($perl_scalar)
```
Except being faster.
### decode\_json
```
$perl_scalar = decode_json $json_text
```
The opposite of `encode_json`: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. Croaks on error.
This function call is functionally identical to:
```
$perl_scalar = JSON::PP->new->utf8->decode($json_text)
```
Except being faster.
###
JSON::PP::is\_bool
```
$is_boolean = JSON::PP::is_bool($scalar)
```
Returns true if the passed scalar represents either JSON::PP::true or JSON::PP::false, two constants that act like `1` and `0` respectively and are also used to represent JSON `true` and `false` in Perl strings.
See [MAPPING](mapping), below, for more information on how JSON values are mapped to Perl.
OBJECT-ORIENTED INTERFACE
--------------------------
This section is also taken from JSON::XS.
The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats.
### new
```
$json = JSON::PP->new
```
Creates a new JSON::PP object that can be used to de/encode JSON strings. All boolean flags described below are by default *disabled* (with the exception of `allow_nonref`, which defaults to *enabled* since version `4.0`).
The mutators for flags all return the JSON::PP object again and thus calls can be chained:
```
my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
=> {"a": [1, 2]}
```
### ascii
```
$json = $json->ascii([$enable])
$enabled = $json->get_ascii
```
If `$enable` is true (or missing), then the `encode` method will not generate characters outside the code range `0..127` (which is ASCII). Any Unicode characters outside that range will be escaped using either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. The resulting encoded JSON text can be treated as a native Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other superset of ASCII.
If `$enable` is false, then the `encode` method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format.
See also the section *ENCODING/CODESET FLAG NOTES* later in this document.
The main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, as the encoded JSON texts will not contain any 8 bit characters.
```
JSON::PP->new->ascii(1)->encode([chr 0x10401])
=> ["\ud801\udc01"]
```
### latin1
```
$json = $json->latin1([$enable])
$enabled = $json->get_latin1
```
If `$enable` is true (or missing), then the `encode` method will encode the resulting JSON text as latin1 (or iso-8859-1), escaping any characters outside the code range `0..255`. The resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. The `decode` method will not be affected in any way by this flag, as `decode` by default expects Unicode, which is a strict superset of latin1.
If `$enable` is false, then the `encode` method will not escape Unicode characters unless required by the JSON syntax or other flags.
See also the section *ENCODING/CODESET FLAG NOTES* later in this document.
The main use for this flag is efficiently encoding binary data as JSON text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting JSON text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for JSON. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders.
```
JSON::PP->new->latin1->encode (["\x{89}\x{abc}"]
=> ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
```
### utf8
```
$json = $json->utf8([$enable])
$enabled = $json->get_utf8
```
If `$enable` is true (or missing), then the `encode` method will encode the JSON result into UTF-8, as required by many protocols, while the `decode` method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range `0..255`, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627.
If `$enable` is false, then the `encode` method will return the JSON string as a (non-encoded) Unicode string, while `decode` expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
See also the section *ENCODING/CODESET FLAG NOTES* later in this document.
Example, output UTF-16BE-encoded JSON:
```
use Encode;
$jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
```
Example, decode UTF-32LE-encoded JSON:
```
use Encode;
$object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
```
### pretty
```
$json = $json->pretty([$enable])
```
This enables (or disables) all of the `indent`, `space_before` and `space_after` (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible.
### indent
```
$json = $json->indent([$enable])
$enabled = $json->get_indent
```
If `$enable` is true (or missing), then the `encode` method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly.
If `$enable` is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any `newlines`.
This setting has no effect when decoding JSON texts.
The default indent space length is three. You can use `indent_length` to change the length.
### space\_before
```
$json = $json->space_before([$enable])
$enabled = $json->get_space_before
```
If `$enable` is true (or missing), then the `encode` method will add an extra optional space before the `:` separating keys from values in JSON objects.
If `$enable` is false, then the `encode` method will not add any extra space at those places.
This setting has no effect when decoding JSON texts. You will also most likely combine this setting with `space_after`.
Example, space\_before enabled, space\_after and indent disabled:
```
{"key" :"value"}
```
### space\_after
```
$json = $json->space_after([$enable])
$enabled = $json->get_space_after
```
If `$enable` is true (or missing), then the `encode` method will add an extra optional space after the `:` separating keys from values in JSON objects and extra whitespace after the `,` separating key-value pairs and array members.
If `$enable` is false, then the `encode` method will not add any extra space at those places.
This setting has no effect when decoding JSON texts.
Example, space\_before and indent disabled, space\_after enabled:
```
{"key": "value"}
```
### relaxed
```
$json = $json->relaxed([$enable])
$enabled = $json->get_relaxed
```
If `$enable` is true (or missing), then `decode` will accept some extensions to normal JSON syntax (see below). `encode` will not be affected in anyway. *Be aware that this option makes you accept invalid JSON texts as if they were valid!*. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)
If `$enable` is false (the default), then `decode` will only accept valid JSON texts.
Currently accepted extensions are:
* list items can have an end-comma
JSON *separates* array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them:
```
[
1,
2, <- this comma not normally allowed
]
{
"k1": "v1",
"k2": "v2", <- this comma not normally allowed
}
```
* shell-style '#'-comments
Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed.
```
[
1, # this comment not allowed in JSON
# neither this one...
]
```
* C-style multiple-line '/\* \*/'-comments (JSON::PP only)
Whenever JSON allows whitespace, C-style multiple-line comments are additionally allowed. Everything between `/*` and `*/` is a comment, after which more white-space and comments are allowed.
```
[
1, /* this comment not allowed in JSON */
/* neither this one... */
]
```
* C++-style one-line '//'-comments (JSON::PP only)
Whenever JSON allows whitespace, C++-style one-line comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed.
```
[
1, // this comment not allowed in JSON
// neither this one...
]
```
* literal ASCII TAB characters in strings
Literal ASCII TAB characters are now allowed in strings (and treated as `\t`).
```
[
"Hello\tWorld",
"Hello<TAB>World", # literal <TAB> would not normally be allowed
]
```
### canonical
```
$json = $json->canonical([$enable])
$enabled = $json->get_canonical
```
If `$enable` is true (or missing), then the `encode` method will output JSON objects by sorting their keys. This is adding a comparatively high overhead.
If `$enable` is false, then the `encode` method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script, and can change even within the same run from 5.18 onwards).
This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl.
This setting has no effect when decoding JSON texts.
This setting has currently no effect on tied hashes.
### allow\_nonref
```
$json = $json->allow_nonref([$enable])
$enabled = $json->get_allow_nonref
```
Unlike other boolean options, this opotion is enabled by default beginning with version `4.0`.
If `$enable` is true (or missing), then the `encode` method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, `decode` will accept those JSON values instead of croaking.
If `$enable` is false, then the `encode` method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, `decode` will croak if given something that is not a JSON object or array.
Example, encode a Perl scalar as JSON value without enabled `allow_nonref`, resulting in an error:
```
JSON::PP->new->allow_nonref(0)->encode ("Hello, World!")
=> hash- or arrayref expected...
```
### allow\_unknown
```
$json = $json->allow_unknown([$enable])
$enabled = $json->get_allow_unknown
```
If `$enable` is true (or missing), then `encode` will *not* throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON `null` value. Note that blessed objects are not included here and are handled separately by c<allow\_blessed>.
If `$enable` is false (the default), then `encode` will throw an exception when it encounters anything it cannot encode as JSON.
This option does not affect `decode` in any way, and it is recommended to leave it off unless you know your communications partner.
### allow\_blessed
```
$json = $json->allow_blessed([$enable])
$enabled = $json->get_allow_blessed
```
See ["OBJECT SERIALISATION"](#OBJECT-SERIALISATION) for details.
If `$enable` is true (or missing), then the `encode` method will not barf when it encounters a blessed reference that it cannot convert otherwise. Instead, a JSON `null` value is encoded instead of the object.
If `$enable` is false (the default), then `encode` will throw an exception when it encounters a blessed object that it cannot convert otherwise.
This setting has no effect on `decode`.
### convert\_blessed
```
$json = $json->convert_blessed([$enable])
$enabled = $json->get_convert_blessed
```
See ["OBJECT SERIALISATION"](#OBJECT-SERIALISATION) for details.
If `$enable` is true (or missing), then `encode`, upon encountering a blessed object, will check for the availability of the `TO_JSON` method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object.
The `TO_JSON` method may safely call die if it wants. If `TO_JSON` returns other blessed objects, those will be handled in the same way. `TO_JSON` must take care of not causing an endless recursion cycle (== crash) in this case. The name of `TO_JSON` was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any `to_json` function or method.
If `$enable` is false (the default), then `encode` will not consider this type of conversion.
This setting has no effect on `decode`.
### allow\_tags
```
$json = $json->allow_tags([$enable])
$enabled = $json->get_allow_tags
```
See ["OBJECT SERIALISATION"](#OBJECT-SERIALISATION) for details.
If `$enable` is true (or missing), then `encode`, upon encountering a blessed object, will check for the availability of the `FREEZE` method on the object's class. If found, it will be used to serialise the object into a nonstandard tagged JSON value (that JSON decoders cannot decode).
It also causes `decode` to parse such tagged JSON values and deserialise them via a call to the `THAW` method.
If `$enable` is false (the default), then `encode` will not consider this type of conversion, and tagged JSON values will cause a parse error in `decode`, as if tags were not part of the grammar.
### boolean\_values
```
$json->boolean_values([$false, $true])
($false, $true) = $json->get_boolean_values
```
By default, JSON booleans will be decoded as overloaded `$JSON::PP::false` and `$JSON::PP::true` objects.
With this method you can specify your own boolean values for decoding - on decode, JSON `false` will be decoded as a copy of `$false`, and JSON `true` will be decoded as `$true` ("copy" here is the same thing as assigning a value to another variable, i.e. `$copy = $false`).
This is useful when you want to pass a decoded data structure directly to other serialisers like YAML, Data::MessagePack and so on.
Note that this works only when you `decode`. You can set incompatible boolean objects (like <boolean>), but when you `encode` a data structure with such boolean objects, you still need to enable `convert_blessed` (and add a `TO_JSON` method if necessary).
Calling this method without any arguments will reset the booleans to their default values.
`get_boolean_values` will return both `$false` and `$true` values, or the empty list when they are set to the default.
### filter\_json\_object
```
$json = $json->filter_json_object([$coderef])
```
When `$coderef` is specified, it will be called from `decode` each time it decodes a JSON object. The only argument is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (or rather a copy of it) is inserted into the deserialised data structure. If it returns an empty list (NOTE: *not* `undef`, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably.
When `$coderef` is omitted or undefined, any existing callback will be removed and `decode` will not change the deserialised hash in any way.
Example, convert all JSON objects into the integer 5:
```
my $js = JSON::PP->new->filter_json_object(sub { 5 });
# returns [5]
$js->decode('[{}]');
# returns 5
$js->decode('{"a":1, "b":2}');
```
### filter\_json\_single\_key\_object
```
$json = $json->filter_json_single_key_object($key [=> $coderef])
```
Works remotely similar to `filter_json_object`, but is only called for JSON objects having a single key named `$key`.
This `$coderef` is called before the one specified via `filter_json_object`, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even `undef` but the empty list), the callback from `filter_json_object` will be called next, as if no single-key callback were specified.
If `$coderef` is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key.
As this callback gets called less often then the `filter_json_object` one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash.
Typical names for the single object key are `__class_whatever__`, or `$__dollars_are_rarely_used__$` or `}ugly_brace_placement`, or even things like `__class_md5sum(classname)__`, to reduce the risk of clashing with real hashes.
Example, decode JSON objects of the form `{ "__widget__" => <id> }` into the corresponding `$WIDGET{<id>}` object:
```
# return whatever is in $WIDGET{5}:
JSON::PP
->new
->filter_json_single_key_object (__widget__ => sub {
$WIDGET{ $_[0] }
})
->decode ('{"__widget__": 5')
# this can be used with a TO_JSON method in some "widget" class
# for serialisation to json:
sub WidgetBase::TO_JSON {
my ($self) = @_;
unless ($self->{id}) {
$self->{id} = ..get..some..id..;
$WIDGET{$self->{id}} = $self;
}
{ __widget__ => $self->{id} }
}
```
### shrink
```
$json = $json->shrink([$enable])
$enabled = $json->get_shrink
```
If `$enable` is true (or missing), the string returned by `encode` will be shrunk (i.e. downgraded if possible).
The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time.
If `$enable` is false, then JSON::PP does nothing.
### max\_depth
```
$json = $json->max_depth([$maximum_nesting_depth])
$max_depth = $json->get_max_depth
```
Sets the maximum nesting level (default `512`) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point.
Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of `{` or `[` characters without their matching closing parenthesis crossed to reach a given character in a string.
Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array.
If no argument is given, the highest possible setting will be used, which is rarely useful.
See ["SECURITY CONSIDERATIONS" in JSON::XS](JSON::XS#SECURITY-CONSIDERATIONS) for more info on why this is useful.
### max\_size
```
$json = $json->max_size([$maximum_string_size])
$max_size = $json->get_max_size
```
Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is `0`, meaning no limit. When `decode` is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on `encode` (yet).
If no argument is given, the limit check will be deactivated (same as when `0` is specified).
See ["SECURITY CONSIDERATIONS" in JSON::XS](JSON::XS#SECURITY-CONSIDERATIONS) for more info on why this is useful.
### encode
```
$json_text = $json->encode($perl_scalar)
```
Converts the given Perl value or data structure to its JSON representation. Croaks on error.
### decode
```
$perl_scalar = $json->decode($json_text)
```
The opposite of `encode`: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.
### decode\_prefix
```
($perl_scalar, $characters) = $json->decode_prefix($json_text)
```
This works like the `decode` method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far.
This is useful if your JSON texts are not delimited by an outer protocol and you need to know where the JSON text ends.
```
JSON::PP->new->decode_prefix ("[1] the tail")
=> ([1], 3)
```
FLAGS FOR JSON::PP ONLY
------------------------
The following flags and properties are for JSON::PP only. If you use any of these, you can't make your application run faster by replacing JSON::PP with JSON::XS. If you need these and also speed boost, you might want to try <Cpanel::JSON::XS>, a fork of JSON::XS by Reini Urban, which supports some of these (with a different set of incompatibilities). Most of these historical flags are only kept for backward compatibility, and should not be used in a new application.
### allow\_singlequote
```
$json = $json->allow_singlequote([$enable])
$enabled = $json->get_allow_singlequote
```
If `$enable` is true (or missing), then `decode` will accept invalid JSON texts that contain strings that begin and end with single quotation marks. `encode` will not be affected in any way. *Be aware that this option makes you accept invalid JSON texts as if they were valid!*. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)
If `$enable` is false (the default), then `decode` will only accept valid JSON texts.
```
$json->allow_singlequote->decode(qq|{"foo":'bar'}|);
$json->allow_singlequote->decode(qq|{'foo':"bar"}|);
$json->allow_singlequote->decode(qq|{'foo':'bar'}|);
```
### allow\_barekey
```
$json = $json->allow_barekey([$enable])
$enabled = $json->get_allow_barekey
```
If `$enable` is true (or missing), then `decode` will accept invalid JSON texts that contain JSON objects whose names don't begin and end with quotation marks. `encode` will not be affected in any way. *Be aware that this option makes you accept invalid JSON texts as if they were valid!*. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)
If `$enable` is false (the default), then `decode` will only accept valid JSON texts.
```
$json->allow_barekey->decode(qq|{foo:"bar"}|);
```
### allow\_bignum
```
$json = $json->allow_bignum([$enable])
$enabled = $json->get_allow_bignum
```
If `$enable` is true (or missing), then `decode` will convert big integers Perl cannot handle as integer into <Math::BigInt> objects and convert floating numbers into <Math::BigFloat> objects. `encode` will convert `Math::BigInt` and `Math::BigFloat` objects into JSON numbers.
```
$json->allow_nonref->allow_bignum;
$bigfloat = $json->decode('2.000000000000000000000000001');
print $json->encode($bigfloat);
# => 2.000000000000000000000000001
```
See also [MAPPING](mapping).
### loose
```
$json = $json->loose([$enable])
$enabled = $json->get_loose
```
If `$enable` is true (or missing), then `decode` will accept invalid JSON texts that contain unescaped [\x00-\x1f\x22\x5c] characters. `encode` will not be affected in any way. *Be aware that this option makes you accept invalid JSON texts as if they were valid!*. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)
If `$enable` is false (the default), then `decode` will only accept valid JSON texts.
```
$json->loose->decode(qq|["abc
def"]|);
```
### escape\_slash
```
$json = $json->escape_slash([$enable])
$enabled = $json->get_escape_slash
```
If `$enable` is true (or missing), then `encode` will explicitly escape *slash* (solidus; `U+002F`) characters to reduce the risk of XSS (cross site scripting) that may be caused by `</script>` in a JSON text, with the cost of bloating the size of JSON texts.
This option may be useful when you embed JSON in HTML, but embedding arbitrary JSON in HTML (by some HTML template toolkit or by string interpolation) is risky in general. You must escape necessary characters in correct order, depending on the context.
`decode` will not be affected in any way.
### indent\_length
```
$json = $json->indent_length($number_of_spaces)
$length = $json->get_indent_length
```
This option is only useful when you also enable `indent` or `pretty`.
JSON::XS indents with three spaces when you `encode` (if requested by `indent` or `pretty`), and the number cannot be changed. JSON::PP allows you to change/get the number of indent spaces with these mutator/accessor. The default number of spaces is three (the same as JSON::XS), and the acceptable range is from `0` (no indentation; it'd be better to disable indentation by `indent(0)`) to `15`.
### sort\_by
```
$json = $json->sort_by($code_ref)
$json = $json->sort_by($subroutine_name)
```
If you just want to sort keys (names) in JSON objects when you `encode`, enable `canonical` option (see above) that allows you to sort object keys alphabetically.
If you do need to sort non-alphabetically for whatever reasons, you can give a code reference (or a subroutine name) to `sort_by`, then the argument will be passed to Perl's `sort` built-in function.
As the sorting is done in the JSON::PP scope, you usually need to prepend `JSON::PP::` to the subroutine name, and the special variables `$a` and `$b` used in the subrontine used by `sort` function.
Example:
```
my %ORDER = (id => 1, class => 2, name => 3);
$json->sort_by(sub {
($ORDER{$JSON::PP::a} // 999) <=> ($ORDER{$JSON::PP::b} // 999)
or $JSON::PP::a cmp $JSON::PP::b
});
print $json->encode([
{name => 'CPAN', id => 1, href => 'http://cpan.org'}
]);
# [{"id":1,"name":"CPAN","href":"http://cpan.org"}]
```
Note that `sort_by` affects all the plain hashes in the data structure. If you need finer control, `tie` necessary hashes with a module that implements ordered hash (such as <Hash::Ordered> and <Tie::IxHash>). `canonical` and `sort_by` don't affect the key order in `tie`d hashes.
```
use Hash::Ordered;
tie my %hash, 'Hash::Ordered',
(name => 'CPAN', id => 1, href => 'http://cpan.org');
print $json->encode([\%hash]);
# [{"name":"CPAN","id":1,"href":"http://cpan.org"}] # order is kept
```
INCREMENTAL PARSING
--------------------
This section is also taken from JSON::XS.
In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using `decode_prefix` to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls).
JSON::PP will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won't stop as early as the full parser, for example, it doesn't detect mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. `max_size`) to ensure the parser will stop parsing in the presence if syntax errors.
The following methods implement this incremental parser.
### incr\_parse
```
$json->incr_parse( [$string] ) # void context
$obj_or_undef = $json->incr_parse( [$string] ) # scalar context
@obj_or_empty = $json->incr_parse( [$string] ) # list context
```
This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional).
If `$string` is given, then this string is appended to the already existing JSON fragment stored in the `$json` object.
After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want.
If the method is called in scalar context, then it will try to extract exactly *one* JSON object. If that is successful, it will return this object, otherwise it will return `undef`. If there is a parse error, this method will croak just as `decode` would do (one can then use `incr_skip` to skip the erroneous part). This is the most common way of using the method.
And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators (other than whitespace) between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost.
Example: Parse some JSON arrays/objects in a given string and return them.
```
my @objs = JSON::PP->new->incr_parse ("[5][7][1,2]");
```
### incr\_text
```
$lvalue_string = $json->incr_text
```
This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This *only* works when a preceding call to `incr_parse` in *scalar context* successfully returned an object. Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it *will* fail under real world conditions). As a special exception, you can also call this method before having parsed anything.
That means you can only use this function to look at or manipulate text before or after complete JSON objects, not while the parser is in the middle of parsing a JSON object.
This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas).
### incr\_skip
```
$json->incr_skip
```
This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after `incr_parse` died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state.
The difference to `incr_reset` is that only text until the parse error occurred is removed.
### incr\_reset
```
$json->incr_reset
```
This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything.
This is useful if you want to repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode.
MAPPING
-------
Most of this section is also taken from JSON::XS.
This section describes how JSON::PP maps Perl values to JSON values and vice versa. These mappings are designed to "do the right thing" in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent).
For the more enlightened: note that in the following descriptions, lowercase *perl* refers to the Perl interpreter, while uppercase *Perl* refers to the abstract Perl language itself.
###
JSON -> PERL
object A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserve object key ordering itself).
array A JSON array becomes a reference to an array in Perl.
string A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary.
number A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers.
If the number consists of digits only, JSON::PP will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string).
Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number).
Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, JSON::PP only guarantees precision up to but not including the least significant bit.
When `allow_bignum` is enabled, big integer values and any numeric values will be converted into <Math::BigInt> and <Math::BigFloat> objects respectively, without becoming string scalars or losing precision.
true, false These JSON atoms become `JSON::PP::true` and `JSON::PP::false`, respectively. They are overloaded to act almost exactly like the numbers `1` and `0`. You can check whether a scalar is a JSON boolean by using the `JSON::PP::is_bool` function.
null A JSON null atom becomes `undef` in Perl.
shell-style comments (`# *text*`) As a nonstandard extension to the JSON syntax that is enabled by the `relaxed` setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line.
tagged values (`(*tag*)*value*`). Another nonstandard extension to the JSON syntax, enabled with the `allow_tags` setting, are tagged values. In this implementation, the *tag* must be a perl package/class name encoded as a JSON string, and the *value* must be a JSON array encoding optional constructor arguments.
See ["OBJECT SERIALISATION"](#OBJECT-SERIALISATION), below, for details.
###
PERL -> JSON
The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value.
hash references Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order. JSON::PP can optionally sort the hash keys (determined by the *canonical* flag and/or *sort\_by* property), so the same data structure will serialise to the same JSON text (given same settings and version of JSON::PP), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality.
array references Perl array references become JSON arrays.
other references Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers `0` and `1`, which get turned into `false` and `true` atoms in JSON. You can also use `JSON::PP::false` and `JSON::PP::true` to improve readability.
```
to_json [\0, JSON::PP::true] # yields [false,true]
```
JSON::PP::true, JSON::PP::false These special values become JSON true and JSON false values, respectively. You can also use `\1` and `\0` directly if you want.
JSON::PP::null This special value becomes JSON null.
blessed objects Blessed objects are not directly representable in JSON, but `JSON::PP` allows various ways of handling objects. See ["OBJECT SERIALISATION"](#OBJECT-SERIALISATION), below, for details.
simple scalars Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: JSON::PP will encode undefined scalars as JSON `null` values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value:
```
# dump as number
encode_json [2] # yields [2]
encode_json [-3.0e17] # yields [-3e+17]
my $value = 5; encode_json [$value] # yields [5]
# used as string, so dump as string
print $value;
encode_json [$value] # yields ["5"]
# undef becomes null
encode_json [undef] # yields [null]
```
You can force the type to be a JSON string by stringifying it:
```
my $x = 3.1; # some variable containing a number
"$x"; # stringified
$x .= ""; # another, more awkward way to stringify
print $x; # perl does it for you, too, quite often
# (but for older perls)
```
You can force the type to be a JSON number by numifying it:
```
my $x = "3"; # some variable containing a string
$x += 0; # numify it, ensuring it will be dumped as a number
$x *= 1; # same thing, the choice is yours.
```
You can not currently force the type in other, less obscure, ways.
Since version 2.91\_01, JSON::PP uses a different number detection logic that converts a scalar that is possible to turn into a number safely. The new logic is slightly faster, and tends to help people who use older perl or who want to encode complicated data structure. However, this may results in a different JSON text from the one JSON::XS encodes (and thus may break tests that compare entire JSON texts). If you do need the previous behavior for compatibility or for finer control, set PERL\_JSON\_PP\_USE\_B environmental variable to true before you `use` JSON::PP (or JSON.pm).
Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's - these cannot be represented in JSON, and it is an error to pass those in.
JSON::PP (and JSON::XS) trusts what you pass to `encode` method (or `encode_json` function) is a clean, validated data structure with values that can be represented as valid JSON values only, because it's not from an external data source (as opposed to JSON texts you pass to `decode` or `decode_json`, which JSON::PP considers tainted and doesn't trust). As JSON::PP doesn't know exactly what you and consumers of your JSON texts want the unexpected values to be (you may want to convert them into null, or to stringify them with or without normalisation (string representation of infinities/NaN may vary depending on platforms), or to croak without conversion), you're advised to do what you and your consumers need before you encode, and also not to numify values that may start with values that look like a number (including infinities/NaN), without validating.
###
OBJECT SERIALISATION
As JSON cannot directly represent Perl objects, you have to choose between a pure JSON representation (without the ability to deserialise the object automatically again), and a nonstandard extension to the JSON syntax, tagged values.
#### SERIALISATION
What happens when `JSON::PP` encounters a Perl object depends on the `allow_blessed`, `convert_blessed`, `allow_tags` and `allow_bignum` settings, which are used in this order:
1. `allow_tags` is enabled and the object has a `FREEZE` method. In this case, `JSON::PP` creates a tagged JSON value, using a nonstandard extension to the JSON syntax.
This works by invoking the `FREEZE` method on the object, with the first argument being the object to serialise, and the second argument being the constant string `JSON` to distinguish it from other serialisers.
The `FREEZE` method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged JSON value in the following format:
```
("classname")[FREEZE return values...]
```
e.g.:
```
("URI")["http://www.google.com/"]
("MyDate")[2013,10,29]
("ImageData::JPEG")["Z3...VlCg=="]
```
For example, the hypothetical `My::Object` `FREEZE` method might use the objects `type` and `id` members to encode the object:
```
sub My::Object::FREEZE {
my ($self, $serialiser) = @_;
($self->{type}, $self->{id})
}
```
2. `convert_blessed` is enabled and the object has a `TO_JSON` method. In this case, the `TO_JSON` method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text.
For example, the following `TO_JSON` method will convert all [URI](uri) objects to JSON strings when serialised. The fact that these values originally were [URI](uri) objects is lost.
```
sub URI::TO_JSON {
my ($uri) = @_;
$uri->as_string
}
```
3. `allow_bignum` is enabled and the object is a `Math::BigInt` or `Math::BigFloat`. The object will be serialised as a JSON number value.
4. `allow_blessed` is enabled. The object will be serialised as a JSON null value.
5. none of the above If none of the settings are enabled or the respective methods are missing, `JSON::PP` throws an exception.
#### DESERIALISATION
For deserialisation there are only two cases to consider: either nonstandard tagging was used, in which case `allow_tags` decides, or objects cannot be automatically be deserialised, in which case you can use postprocessing or the `filter_json_object` or `filter_json_single_key_object` callbacks to get some real objects our of your JSON.
This section only considers the tagged value case: a tagged JSON object is encountered during decoding and `allow_tags` is disabled, a parse error will result (as if tagged values were not part of the grammar).
If `allow_tags` is enabled, `JSON::PP` will look up the `THAW` method of the package/classname used during serialisation (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error.
Otherwise, the `THAW` method is invoked with the classname as first argument, the constant string `JSON` as second argument, and all the values from the JSON array (the values originally returned by the `FREEZE` method) as remaining arguments.
The method must then return the object. While technically you can return any Perl scalar, you might have to enable the `allow_nonref` setting to make that work in all cases, so better return an actual blessed reference.
As an example, let's implement a `THAW` function that regenerates the `My::Object` from the `FREEZE` example earlier:
```
sub My::Object::THAW {
my ($class, $serialiser, $type, $id) = @_;
$class->new (type => $type, id => $id)
}
```
ENCODING/CODESET FLAG NOTES
----------------------------
This section is taken from JSON::XS.
The interested reader might have seen a number of flags that signify encodings or codesets - `utf8`, `latin1` and `ascii`. There seems to be some confusion on what these do, so here is a short comparison:
`utf8` controls whether the JSON text created by `encode` (and expected by `decode`) is UTF-8 encoded or not, while `latin1` and `ascii` only control whether `encode` escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others.
Care has been taken to make all flags symmetrical with respect to `encode` and `decode`, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used - in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere.
Below comes a verbose discussion of these flags. Note that a "codeset" is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and *encodes* them, in our case into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets *and* encodings at the same time, which can be confusing.
`utf8` flag disabled When `utf8` is disabled (the default), then `encode`/`decode` generate and expect Unicode strings, that is, characters with high ordinal Unicode values (> 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except "(re-)interpreting" them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff).
This is useful when you want to do the encoding yourself (e.g. when you want to have UTF-16 encoded JSON texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to UTF-8 you certainly do NOT want to UTF-8 encode your data first and have Perl encode it another time).
`utf8` flag enabled If the `utf8`-flag is enabled, `encode`/`decode` will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8, that is, no "character" of the input string must have any value > 255, as UTF-8 does not allow that.
The `utf8` flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get an UTF-8 encoded octet/binary string in Perl.
`latin1` or `ascii` flags enabled With `latin1` (or `ascii`) enabled, `encode` will escape characters with ordinal values > 255 (> 127 with `ascii`) and encode the remaining characters as specified by the `utf8` flag.
If `utf8` is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values < 256 is the same thing as a ISO-8859-1 string, and a Unicode string with all character values < 128 is the same thing as an ASCII string in Perl).
If `utf8` is enabled, you still get a correct UTF-8-encoded string, regardless of these flags, just some more characters will be escaped using `\uXXXX` then before.
Note that ISO-8859-1-*encoded* strings are not compatible with UTF-8 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 *codeset* being a subset of Unicode), while ASCII is.
Surprisingly, `decode` will ignore these flags and so treat all input values as governed by the `utf8` flag. If it is disabled, this allows you to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.
So neither `latin1` nor `ascii` are incompatible with the `utf8` flag - they only govern when the JSON output engine escapes a character or not.
The main use for `latin1` is to relatively efficiently store binary data as JSON, at the expense of breaking compatibility with most JSON decoders.
The main use for `ascii` is to force the output to not contain characters with values > 127, which means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. This is useful when your channel for JSON transfer is not 8-bit clean or the encoding might be mangled in between (e.g. in mail), and works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world.
BUGS
----
Please report bugs on a specific behavior of this module to RT or GitHub issues (preferred):
<https://github.com/makamaka/JSON-PP/issues>
<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON-PP>
As for new features and requests to change common behaviors, please ask the author of JSON::XS (Marc Lehmann, <schmorp[at]schmorp.de>) first, by email (important!), to keep compatibility among JSON.pm backends.
Generally speaking, if you need something special for you, you are advised to create a new module, maybe based on <JSON::Tiny>, which is smaller and written in a much cleaner way than this module.
SEE ALSO
---------
The *json\_pp* command line utility for quick experiments.
<JSON::XS>, <Cpanel::JSON::XS>, and <JSON::Tiny> for faster alternatives. [JSON](json) and <JSON::MaybeXS> for easy migration.
<JSON::PP::Compat5005> and <JSON::PP::Compat5006> for older perl users.
RFC4627 (<http://www.ietf.org/rfc/rfc4627.txt>)
RFC7159 (<http://www.ietf.org/rfc/rfc7159.txt>)
RFC8259 (<http://www.ietf.org/rfc/rfc8259.txt>)
AUTHOR
------
Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
CURRENT MAINTAINER
-------------------
Kenichi Ishigaki, <ishigaki[at]cpan.org>
COPYRIGHT AND LICENSE
----------------------
Copyright 2007-2016 by Makamaka Hannyaharamitu
Most of the documentation is taken from JSON::XS by Marc Lehmann
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl SDBM_File SDBM\_File
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tie](#Tie)
* [EXPORTS](#EXPORTS)
* [DIAGNOSTICS](#DIAGNOSTICS)
+ [sdbm store returned -1, errno 22, key "..." at ...](#sdbm-store-returned-1,-errno-22,-key-%22...%22-at-...)
* [SECURITY WARNING](#SECURITY-WARNING)
* [BUGS AND WARNINGS](#BUGS-AND-WARNINGS)
NAME
----
SDBM\_File - Tied access to sdbm files
SYNOPSIS
--------
```
use Fcntl; # For O_RDWR, O_CREAT, etc.
use SDBM_File;
tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666)
or die "Couldn't tie SDBM file 'filename': $!; aborting";
# Now read and change the hash
$h{newkey} = newvalue;
print $h{oldkey};
...
untie %h;
```
DESCRIPTION
-----------
`SDBM_File` establishes a connection between a Perl hash variable and a file in SDBM\_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.
### Tie
Use `SDBM_File` with the Perl built-in `tie` function to establish the connection between the variable and the file.
```
tie %hash, 'SDBM_File', $basename, $modeflags, $perms;
tie %hash, 'SDBM_File', $dirfile, $modeflags, $perms, $pagfilename;
```
`$basename` is the base filename for the database. The database is two files with ".dir" and ".pag" extensions appended to `$basename`,
```
$basename.dir (or .sdbm_dir on VMS, per DIRFEXT constant)
$basename.pag
```
The two filenames can also be given separately in full as `$dirfile` and `$pagfilename`. This suits for two files without ".dir" and ".pag" extensions, perhaps for example two files from <File::Temp>.
`$modeflags` can be the following constants from the `Fcntl` module (in the style of the [open(2)](http://man.he.net/man2/open) system call),
```
O_RDONLY read-only access
O_WRONLY write-only access
O_RDWR read and write access
```
If you want to create the file if it does not already exist then bitwise-OR (`|`) `O_CREAT` too. If you omit `O_CREAT` and the database does not already exist then the `tie` call will fail.
```
O_CREAT create database if doesn't already exist
```
`$perms` is the file permissions bits to use if new database files are created. This parameter is mandatory even when not creating a new database. The permissions will be reduced by the user's umask so the usual value here would be 0666, or if some very private data then 0600. (See ["umask" in perlfunc](perlfunc#umask).)
EXPORTS
-------
SDBM\_File optionally exports the following constants:
* `PAGFEXT` - the extension used for the page file, usually `.pag`.
* `DIRFEXT` - the extension used for the directory file, `.dir` everywhere but VMS, where it is `.sdbm_dir`.
* `PAIRMAX` - the maximum size of a stored hash entry, including the length of both the key and value.
These constants can also be used with fully qualified names, eg. `SDBM_File::PAGFEXT`.
DIAGNOSTICS
-----------
On failure, the `tie` call returns an undefined value and probably sets `$!` to contain the reason the file could not be tied.
###
`sdbm 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 WARNING
-----------------
**Do not accept SDBM files from untrusted sources!**
The sdbm file format was designed for speed and convenience, not for portability or security. 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 SDBM 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 diagnostics diagnostics
===========
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 Pod::Simple::PullParserTextToken Pod::Simple::PullParserTextToken
================================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::PullParserTextToken -- text-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->text This returns the text that this token holds. For example, parsing C<foo> will return a C start-token, a text-token, and a C end-token. And if you want to get the "foo" out of the text-token, call `$token->text`
$token->text(*somestring*) This changes the string that this token holds. You probably won't need to do this.
$token->text\_r() This returns a scalar reference to the string that this token holds. This can be useful if you don't want to memory-copy the potentially large text value (well, as large as a paragraph or a verbatim block) as calling $token->text would do.
Or, if you want to alter the value, you can even do things like this:
```
for ( ${ $token->text_r } ) { # Aliases it with $_ !!
s/ The / the /g; # just for example
if( 'A' eq chr(65) ) { # (if in an ASCII world)
tr/\xA0/ /;
tr/\xAD//d;
}
...or however you want to alter the value...
(Note that starting with Perl v5.8, you can use, e.g.,
my $nbsp = chr utf8::unicode_to_native(0xA0);
s/$nbsp/ /g;
to handle the above regardless if it's an ASCII world or not)
}
```
You're unlikely to ever need to construct an object of this class for yourself, but if you want to, call `Pod::Simple::PullParserTextToken->new( *text* )`
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 IPC::Cmd IPC::Cmd
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CLASS METHODS](#CLASS-METHODS)
+ [$ipc\_run\_version = IPC::Cmd->can\_use\_ipc\_run( [VERBOSE] )](#%24ipc_run_version-=-IPC::Cmd-%3Ecan_use_ipc_run(-%5BVERBOSE%5D-))
+ [$ipc\_open3\_version = IPC::Cmd->can\_use\_ipc\_open3( [VERBOSE] )](#%24ipc_open3_version-=-IPC::Cmd-%3Ecan_use_ipc_open3(-%5BVERBOSE%5D-))
+ [$bool = IPC::Cmd->can\_capture\_buffer](#%24bool-=-IPC::Cmd-%3Ecan_capture_buffer)
+ [$bool = IPC::Cmd->can\_use\_run\_forked](#%24bool-=-IPC::Cmd-%3Ecan_use_run_forked)
* [FUNCTIONS](#FUNCTIONS)
+ [$path = can\_run( PROGRAM );](#%24path-=-can_run(-PROGRAM-);)
+ [$ok | ($ok, $err, $full\_buf, $stdout\_buff, $stderr\_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );](#%24ok-%7C-(%24ok,-%24err,-%24full_buf,-%24stdout_buff,-%24stderr_buff)-=-run(-command-=%3E-COMMAND,-%5Bverbose-=%3E-BOOL,-buffer-=%3E-%5C%24SCALAR,-timeout-=%3E-DIGIT%5D-);)
+ [$hashref = run\_forked( COMMAND, { child\_stdin => SCALAR, timeout => DIGIT, stdout\_handler => CODEREF, stderr\_handler => CODEREF} );](#%24hashref-=-run_forked(-COMMAND,-%7B-child_stdin-=%3E-SCALAR,-timeout-=%3E-DIGIT,-stdout_handler-=%3E-CODEREF,-stderr_handler-=%3E-CODEREF%7D-);)
+ [$q = QUOTE](#%24q-=-QUOTE)
* [HOW IT WORKS](#HOW-IT-WORKS)
* [Global Variables](#Global-Variables)
+ [$IPC::Cmd::VERBOSE](#%24IPC::Cmd::VERBOSE)
+ [$IPC::Cmd::USE\_IPC\_RUN](#%24IPC::Cmd::USE_IPC_RUN)
+ [$IPC::Cmd::USE\_IPC\_OPEN3](#%24IPC::Cmd::USE_IPC_OPEN3)
+ [$IPC::Cmd::WARN](#%24IPC::Cmd::WARN)
+ [$IPC::Cmd::INSTANCES](#%24IPC::Cmd::INSTANCES)
+ [$IPC::Cmd::ALLOW\_NULL\_ARGS](#%24IPC::Cmd::ALLOW_NULL_ARGS)
* [Caveats](#Caveats)
* [See Also](#See-Also)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [BUG REPORTS](#BUG-REPORTS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IPC::Cmd - finding and running system commands made easy
SYNOPSIS
--------
```
use IPC::Cmd qw[can_run run run_forked];
my $full_path = can_run('wget') or warn 'wget is not installed!';
### commands can be arrayrefs or strings ###
my $cmd = "$full_path -b theregister.co.uk";
my $cmd = [$full_path, '-b', 'theregister.co.uk'];
### in scalar context ###
my $buffer;
if( scalar run( command => $cmd,
verbose => 0,
buffer => \$buffer,
timeout => 20 )
) {
print "fetched webpage successfully: $buffer\n";
}
### in list context ###
my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
run( command => $cmd, verbose => 0 );
if( $success ) {
print "this is what the command printed:\n";
print join "", @$full_buf;
}
### run_forked example ###
my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
print "this is what wget returned:\n";
print $result->{'stdout'};
}
### check for features
print "IPC::Open3 available: " . IPC::Cmd->can_use_ipc_open3;
print "IPC::Run available: " . IPC::Cmd->can_use_ipc_run;
print "Can capture buffer: " . IPC::Cmd->can_capture_buffer;
### don't have IPC::Cmd be verbose, ie don't print to stdout or
### stderr when running commands -- default is '0'
$IPC::Cmd::VERBOSE = 0;
```
DESCRIPTION
-----------
IPC::Cmd allows you to run commands platform independently, interactively if desired, but have them still work.
The `can_run` function can tell you if a certain binary is installed and if so where, whereas the `run` function can actually execute any of the commands you give it and give you a clear return value, as well as adhere to your verbosity settings.
CLASS METHODS
--------------
###
$ipc\_run\_version = IPC::Cmd->can\_use\_ipc\_run( [VERBOSE] )
Utility function that tells you if `IPC::Run` is available. If the `verbose` flag is passed, it will print diagnostic messages if <IPC::Run> can not be found or loaded.
###
$ipc\_open3\_version = IPC::Cmd->can\_use\_ipc\_open3( [VERBOSE] )
Utility function that tells you if `IPC::Open3` is available. If the verbose flag is passed, it will print diagnostic messages if `IPC::Open3` can not be found or loaded.
###
$bool = IPC::Cmd->can\_capture\_buffer
Utility function that tells you if `IPC::Cmd` is capable of capturing buffers in it's current configuration.
###
$bool = IPC::Cmd->can\_use\_run\_forked
Utility function that tells you if `IPC::Cmd` is capable of providing `run_forked` on the current platform.
FUNCTIONS
---------
###
$path = can\_run( PROGRAM );
`can_run` takes only one argument: the name of a binary you wish to locate. `can_run` works much like the unix binary `which` or the bash command `type`, which scans through your path, looking for the requested binary.
Unlike `which` and `type`, this function is platform independent and will also work on, for example, Win32.
If called in a scalar context it will return the full path to the binary you asked for if it was found, or `undef` if it was not.
If called in a list context and the global variable `$INSTANCES` is a true value, it will return a list of the full paths to instances of the binary where found in `PATH`, or an empty list if it was not found.
###
$ok | ($ok, $err, $full\_buf, $stdout\_buff, $stderr\_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );
`run` takes 4 arguments:
command This is the command to execute. It may be either a string or an array reference. This is a required argument.
See ["Caveats"](#Caveats) for remarks on how commands are parsed and their limitations.
verbose This controls whether all output of a command should also be printed to STDOUT/STDERR or should only be trapped in buffers (NOTE: buffers require <IPC::Run> to be installed, or your system able to work with <IPC::Open3>).
It will default to the global setting of `$IPC::Cmd::VERBOSE`, which by default is 0.
buffer This will hold all the output of a command. It needs to be a reference to a scalar. Note that this will hold both the STDOUT and STDERR messages, and you have no way of telling which is which. If you require this distinction, run the `run` command in list context and inspect the individual buffers.
Of course, this requires that the underlying call supports buffers. See the note on buffers above.
timeout Sets the maximum time the command is allowed to run before aborting, using the built-in `alarm()` call. If the timeout is triggered, the `errorcode` in the return value will be set to an object of the `IPC::Cmd::TimeOut` class. See the ["error message"](#error-message) section below for details.
Defaults to `0`, meaning no timeout is set.
`run` will return a simple `true` or `false` when called in scalar context. In list context, you will be returned a list of the following items:
success A simple boolean indicating if the command executed without errors or not.
error message If the first element of the return value (`success`) was 0, then some error occurred. This second element is the error message the command you requested exited with, if available. This is generally a pretty printed value of `$?` or `$@`. See `perldoc perlvar` for details on what they can contain. If the error was a timeout, the `error message` will be prefixed with the string `IPC::Cmd::TimeOut`, the timeout class.
full\_buffer This is an array reference containing all the output the command generated. Note that buffers are only available if you have <IPC::Run> installed, or if your system is able to work with <IPC::Open3> -- see below). Otherwise, this element will be `undef`.
out\_buffer This is an array reference containing all the output sent to STDOUT the command generated. The notes from ["full\_buffer"](#full_buffer) apply.
error\_buffer This is an arrayreference containing all the output sent to STDERR the command generated. The notes from ["full\_buffer"](#full_buffer) apply.
See the ["HOW IT WORKS"](#HOW-IT-WORKS) section below to see how `IPC::Cmd` decides what modules or function calls to use when issuing a command.
###
$hashref = run\_forked( COMMAND, { child\_stdin => SCALAR, timeout => DIGIT, stdout\_handler => CODEREF, stderr\_handler => CODEREF} );
`run_forked` is used to execute some program or a coderef, optionally feed it with some input, get its return code and output (both stdout and stderr into separate buffers). In addition, it allows to terminate the program if it takes too long to finish.
The important and distinguishing feature of run\_forked is execution timeout which at first seems to be quite a simple task but if you think that the program which you're spawning might spawn some children itself (which in their turn could do the same and so on) it turns out to be not a simple issue.
`run_forked` is designed to survive and successfully terminate almost any long running task, even a fork bomb in case your system has the resources to survive during given timeout.
This is achieved by creating separate watchdog process which spawns the specified program in a separate process session and supervises it: optionally feeds it with input, stores its exit code, stdout and stderr, terminates it in case it runs longer than specified.
Invocation requires the command to be executed or a coderef and optionally a hashref of options:
`timeout` Specify in seconds how long to run the command before it is killed with SIG\_KILL (9), which effectively terminates it and all of its children (direct or indirect).
`child_stdin` Specify some text that will be passed into the `STDIN` of the executed program.
`stdout_handler` Coderef of a subroutine to call when a portion of data is received on STDOUT from the executing program.
`stderr_handler` Coderef of a subroutine to call when a portion of data is received on STDERR from the executing program.
`wait_loop_callback` Coderef of a subroutine to call inside of the main waiting loop (while `run_forked` waits for the external to finish or fail). It is useful to stop running external process before it ends by itself, e.g.
```
my $r = run_forked("some external command", {
'wait_loop_callback' => sub {
if (condition) {
kill(1, $$);
}
},
'terminate_on_signal' => 'HUP',
});
```
Combined with `stdout_handler` and `stderr_handler` allows terminating external command based on its output. Could also be used as a timer without engaging with <alarm> (signals).
Remember that this code could be called every millisecond (depending on the output which external command generates), so try to make it as lightweight as possible.
`discard_output` Discards the buffering of the standard output and standard errors for return by run\_forked(). With this option you have to use the std\*\_handlers to read what the command outputs. Useful for commands that send a lot of output.
`terminate_on_parent_sudden_death` Enable this option if you wish all spawned processes to be killed if the initially spawned process (the parent) is killed or dies without waiting for child processes.
`run_forked` will return a HASHREF with the following keys:
`exit_code` The exit code of the executed program.
`timeout` The number of seconds the program ran for before being terminated, or 0 if no timeout occurred.
`stdout` Holds the standard output of the executed command (or empty string if there was no STDOUT output or if `discard_output` was used; it's always defined!)
`stderr` Holds the standard error of the executed command (or empty string if there was no STDERR output or if `discard_output` was used; it's always defined!)
`merged` Holds the standard output and error of the executed command merged into one stream (or empty string if there was no output at all or if `discard_output` was used; it's always defined!)
`err_msg` Holds some explanation in the case of an error.
###
$q = QUOTE
Returns the character used for quoting strings on this platform. This is usually a `'` (single quote) on most systems, but some systems use different quotes. For example, `Win32` uses `"` (double quote).
You can use it as follows:
```
use IPC::Cmd qw[run QUOTE];
my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;
```
This makes sure that `foo bar` is treated as a string, rather than two separate arguments to the `echo` function.
HOW IT WORKS
-------------
`run` will try to execute your command using the following logic:
* If you have `IPC::Run` installed, and the variable `$IPC::Cmd::USE_IPC_RUN` is set to true (See the ["Global Variables"](#Global-Variables) section) use that to execute the command. You will have the full output available in buffers, interactive commands are sure to work and you are guaranteed to have your verbosity settings honored cleanly.
* Otherwise, if the variable `$IPC::Cmd::USE_IPC_OPEN3` is set to true (See the ["Global Variables"](#Global-Variables) section), try to execute the command using <IPC::Open3>. Buffers will be available on all platforms, interactive commands will still execute cleanly, and also your verbosity settings will be adhered to nicely;
* Otherwise, if you have the `verbose` argument set to true, we fall back to a simple `system()` call. We cannot capture any buffers, but interactive commands will still work.
* Otherwise we will try and temporarily redirect STDERR and STDOUT, do a `system()` call with your command and then re-open STDERR and STDOUT. This is the method of last resort and will still allow you to execute your commands cleanly. However, no buffers will be available.
Global Variables
-----------------
The behaviour of IPC::Cmd can be altered by changing the following global variables:
###
$IPC::Cmd::VERBOSE
This controls whether IPC::Cmd will print any output from the commands to the screen or not. The default is 0.
###
$IPC::Cmd::USE\_IPC\_RUN
This variable controls whether IPC::Cmd will try to use <IPC::Run> when available and suitable.
###
$IPC::Cmd::USE\_IPC\_OPEN3
This variable controls whether IPC::Cmd will try to use <IPC::Open3> when available and suitable. Defaults to true.
###
$IPC::Cmd::WARN
This variable controls whether run-time warnings should be issued, like the failure to load an `IPC::*` module you explicitly requested.
Defaults to true. Turn this off at your own risk.
###
$IPC::Cmd::INSTANCES
This variable controls whether `can_run` will return all instances of the binary it finds in the `PATH` when called in a list context.
Defaults to false, set to true to enable the described behaviour.
###
$IPC::Cmd::ALLOW\_NULL\_ARGS
This variable controls whether `run` will remove any empty/null arguments it finds in command arguments.
Defaults to false, so it will remove null arguments. Set to true to allow them.
Caveats
-------
Whitespace and IPC::Open3 / system() When using `IPC::Open3` or `system`, if you provide a string as the `command` argument, it is assumed to be appropriately escaped. You can use the `QUOTE` constant to use as a portable quote character (see above). However, if you provide an array reference, special rules apply:
If your command contains **special characters** (< > | &), it will be internally stringified before executing the command, to avoid that these special characters are escaped and passed as arguments instead of retaining their special meaning.
However, if the command contained arguments that contained whitespace, stringifying the command would lose the significance of the whitespace. Therefore, `IPC::Cmd` will quote any arguments containing whitespace in your command if the command is passed as an arrayref and contains special characters.
Whitespace and IPC::Run When using `IPC::Run`, if you provide a string as the `command` argument, the string will be split on whitespace to determine the individual elements of your command. Although this will usually just Do What You Mean, it may break if you have files or commands with whitespace in them.
If you do not wish this to happen, you should provide an array reference, where all parts of your command are already separated out. Note however, if there are extra or spurious whitespaces in these parts, the parser or underlying code may not interpret it correctly, and cause an error.
Example: The following code
```
gzip -cdf foo.tar.gz | tar -xf -
```
should either be passed as
```
"gzip -cdf foo.tar.gz | tar -xf -"
```
or as
```
['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']
```
But take care not to pass it as, for example
```
['gzip -cdf foo.tar.gz', '|', 'tar -xf -']
```
Since this will lead to issues as described above.
IO Redirect Currently it is too complicated to parse your command for IO redirections. For capturing STDOUT or STDERR there is a work around however, since you can just inspect your buffers for the contents.
Interleaving STDOUT/STDERR Neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. For short bursts of output from a program, e.g. this sample,
```
for ( 1..4 ) {
$_ % 2 ? print STDOUT $_ : print STDERR $_;
}
```
IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR, meaning the output looks like '13' on STDOUT and '24' on STDERR, instead of
```
1
2
3
4
```
This has been recorded in <rt.cpan.org> as bug #37532: Unable to interleave STDOUT and STDERR.
See Also
---------
<IPC::Run>, <IPC::Open3>
ACKNOWLEDGEMENTS
----------------
Thanks to James Mastros and Martijn van der Streek for their help in getting <IPC::Open3> to behave nicely.
Thanks to Petya Kohts for the `run_forked` code.
BUG REPORTS
------------
Please report bugs or other issues to <[email protected]>.
AUTHOR
------
Original author: Jos Boumans <[email protected]>. Current maintainer: Chris Williams <[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 Test Test
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [QUICK START GUIDE](#QUICK-START-GUIDE)
+ [Functions](#Functions)
* [TEST TYPES](#TEST-TYPES)
* [ONFAIL](#ONFAIL)
* [BUGS and CAVEATS](#BUGS-and-CAVEATS)
* [ENVIRONMENT](#ENVIRONMENT)
* [NOTE](#NOTE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
Test - provides a simple framework for writing test scripts
SYNOPSIS
--------
```
use strict;
use Test;
# use a BEGIN block so we print our plan before MyModule is loaded
BEGIN { plan tests => 14, todo => [3,4] }
# load your module...
use MyModule;
# Helpful notes. All note-lines must start with a "#".
print "# I'm testing MyModule version $MyModule::VERSION\n";
ok(0); # failure
ok(1); # success
ok(0); # ok, expected failure (see todo list, above)
ok(1); # surprise success!
ok(0,1); # failure: '0' ne '1'
ok('broke','fixed'); # failure: 'broke' ne 'fixed'
ok('fixed','fixed'); # success: 'fixed' eq 'fixed'
ok('fixed',qr/x/); # success: 'fixed' =~ qr/x/
ok(sub { 1+1 }, 2); # success: '2' eq '2'
ok(sub { 1+1 }, 3); # failure: '2' ne '3'
my @list = (0,0);
ok @list, 3, "\@list=".join(',',@list); #extra notes
ok 'segmentation fault', '/(?i)success/'; #regex match
skip(
$^O =~ m/MSWin/ ? "Skip if MSWin" : 0, # whether to skip
$foo, $bar # arguments just like for ok(...)
);
skip(
$^O =~ m/MSWin/ ? 0 : "Skip unless MSWin", # whether to skip
$foo, $bar # arguments just like for ok(...)
);
```
DESCRIPTION
-----------
This module simplifies the task of writing test files for Perl modules, such that their output is in the format that <Test::Harness> expects to see.
QUICK START GUIDE
------------------
To write a test for your new (and probably not even done) module, create a new file called *t/test.t* (in a new *t* directory). If you have multiple test files, to test the "foo", "bar", and "baz" feature sets, then feel free to call your files *t/foo.t*, *t/bar.t*, and *t/baz.t*
### Functions
This module defines three public functions, `plan(...)`, `ok(...)`, and `skip(...)`. By default, all three are exported by the `use Test;` statement.
`plan(...)`
```
BEGIN { plan %theplan; }
```
This should be the first thing you call in your test script. It declares your testing plan, how many there will be, if any of them should be allowed to fail, and so on.
Typical usage is just:
```
use Test;
BEGIN { plan tests => 23 }
```
These are the things that you can put in the parameters to plan:
`tests => *number*`
The number of tests in your script. This means all ok() and skip() calls.
`todo => [*1,5,14*]`
A reference to a list of tests which are allowed to fail. See ["TODO TESTS"](#TODO-TESTS).
`onfail => sub { ... }`
`onfail => \&some_sub`
A subroutine reference to be run at the end of the test script, if any of the tests fail. See ["ONFAIL"](#ONFAIL).
You must call `plan(...)` once and only once. You should call it in a `BEGIN {...}` block, like so:
```
BEGIN { plan tests => 23 }
```
`ok(...)`
```
ok(1 + 1 == 2);
ok($have, $expect);
ok($have, $expect, $diagnostics);
```
This function is the reason for `Test`'s existence. It's the basic function that handles printing "`ok`" or "`not ok`", along with the current test number. (That's what `Test::Harness` wants to see.)
In its most basic usage, `ok(...)` simply takes a single scalar expression. If its value is true, the test passes; if false, the test fails. Examples:
```
# Examples of ok(scalar)
ok( 1 + 1 == 2 ); # ok if 1 + 1 == 2
ok( $foo =~ /bar/ ); # ok if $foo contains 'bar'
ok( baz($x + $y) eq 'Armondo' ); # ok if baz($x + $y) returns
# 'Armondo'
ok( @a == @b ); # ok if @a and @b are the same
# length
```
The expression is evaluated in scalar context. So the following will work:
```
ok( @stuff ); # ok if @stuff has any
# elements
ok( !grep !defined $_, @stuff ); # ok if everything in @stuff
# is defined.
```
A special case is if the expression is a subroutine reference (in either `sub {...}` syntax or `\&foo` syntax). In that case, it is executed and its value (true or false) determines if the test passes or fails. For example,
```
ok( sub { # See whether sleep works at least passably
my $start_time = time;
sleep 5;
time() - $start_time >= 4
});
```
In its two-argument form, `ok(*arg1*, *arg2*)` compares the two scalar values to see if they match. They match if both are undefined, or if *arg2* is a regex that matches *arg1*, or if they compare equal with `eq`.
```
# Example of ok(scalar, scalar)
ok( "this", "that" ); # not ok, 'this' ne 'that'
ok( "", undef ); # not ok, "" is defined
```
The second argument is considered a regex if it is either a regex object or a string that looks like a regex. Regex objects are constructed with the qr// operator in recent versions of perl. A string is considered to look like a regex if its first and last characters are "/", or if the first character is "m" and its second and last characters are both the same non-alphanumeric non-whitespace character. These regexp
Regex examples:
```
ok( 'JaffO', '/Jaff/' ); # ok, 'JaffO' =~ /Jaff/
ok( 'JaffO', 'm|Jaff|' ); # ok, 'JaffO' =~ m|Jaff|
ok( 'JaffO', qr/Jaff/ ); # ok, 'JaffO' =~ qr/Jaff/;
ok( 'JaffO', '/(?i)jaff/ ); # ok, 'JaffO' =~ /jaff/i;
```
If either (or both!) is a subroutine reference, it is run and used as the value for comparing. For example:
```
ok sub {
open(OUT, '>', 'x.dat') || die $!;
print OUT "\x{e000}";
close OUT;
my $bytecount = -s 'x.dat';
unlink 'x.dat' or warn "Can't unlink : $!";
return $bytecount;
},
4
;
```
The above test passes two values to `ok(arg1, arg2)` -- the first a coderef, and the second is the number 4. Before `ok` compares them, it calls the coderef, and uses its return value as the real value of this parameter. Assuming that `$bytecount` returns 4, `ok` ends up testing `4 eq 4`. Since that's true, this test passes.
Finally, you can append an optional third argument, in `ok(*arg1*,*arg2*, *note*)`, where *note* is a string value that will be printed if the test fails. This should be some useful information about the test, pertaining to why it failed, and/or a description of the test. For example:
```
ok( grep($_ eq 'something unique', @stuff), 1,
"Something that should be unique isn't!\n".
'@stuff = '.join ', ', @stuff
);
```
Unfortunately, a note cannot be used with the single argument style of `ok()`. That is, if you try `ok(*arg1*, *note*)`, then `Test` will interpret this as `ok(*arg1*, *arg2*)`, and probably end up testing `*arg1* eq *arg2*` -- and that's not what you want!
All of the above special cases can occasionally cause some problems. See ["BUGS and CAVEATS"](#BUGS-and-CAVEATS).
`skip(*skip\_if\_true*, *args...*)`
This is used for tests that under some conditions can be skipped. It's basically equivalent to:
```
if( $skip_if_true ) {
ok(1);
} else {
ok( args... );
}
```
...except that the `ok(1)` emits not just "`ok *testnum*`" but actually "`ok *testnum* # *skip\_if\_true\_value*`".
The arguments after the *skip\_if\_true* are what is fed to `ok(...)` if this test isn't skipped.
Example usage:
```
my $if_MSWin =
$^O =~ m/MSWin/ ? 'Skip if under MSWin' : '';
# A test to be skipped if under MSWin (i.e., run except under
# MSWin)
skip($if_MSWin, thing($foo), thing($bar) );
```
Or, going the other way:
```
my $unless_MSWin =
$^O =~ m/MSWin/ ? '' : 'Skip unless under MSWin';
# A test to be skipped unless under MSWin (i.e., run only under
# MSWin)
skip($unless_MSWin, thing($foo), thing($bar) );
```
The tricky thing to remember is that the first parameter is true if you want to *skip* the test, not *run* it; and it also doubles as a note about why it's being skipped. So in the first codeblock above, read the code as "skip if MSWin -- (otherwise) test whether `thing($foo)` is `thing($bar)`" or for the second case, "skip unless MSWin...".
Also, when your *skip\_if\_reason* string is true, it really should (for backwards compatibility with older Test.pm versions) start with the string "Skip", as shown in the above examples.
Note that in the above cases, `thing($foo)` and `thing($bar)` *are* evaluated -- but as long as the `skip_if_true` is true, then we `skip(...)` just tosses out their value (i.e., not bothering to treat them like values to `ok(...)`. But if you need to *not* eval the arguments when skipping the test, use this format:
```
skip( $unless_MSWin,
sub {
# This code returns true if the test passes.
# (But it doesn't even get called if the test is skipped.)
thing($foo) eq thing($bar)
}
);
```
or even this, which is basically equivalent:
```
skip( $unless_MSWin,
sub { thing($foo) }, sub { thing($bar) }
);
```
That is, both are like this:
```
if( $unless_MSWin ) {
ok(1); # but it actually appends "# $unless_MSWin"
# so that Test::Harness can tell it's a skip
} else {
# Not skipping, so actually call and evaluate...
ok( sub { thing($foo) }, sub { thing($bar) } );
}
```
TEST TYPES
-----------
* NORMAL TESTS
These tests are expected to succeed. Usually, most or all of your tests are in this category. If a normal test doesn't succeed, then that means that something is *wrong*.
* SKIPPED TESTS
The `skip(...)` function is for tests that might or might not be possible to run, depending on the availability of platform-specific features. The first argument should evaluate to true (think "yes, please skip") if the required feature is *not* available. After the first argument, `skip(...)` works exactly the same way as `ok(...)` does.
* TODO TESTS
TODO tests are designed for maintaining an **executable TODO list**. These tests are *expected to fail.* If a TODO test does succeed, then the feature in question shouldn't be on the TODO list, now should it?
Packages should NOT be released with succeeding TODO tests. As soon as a TODO test starts working, it should be promoted to a normal test, and the newly working feature should be documented in the release notes or in the change log.
ONFAIL
------
```
BEGIN { plan test => 4, onfail => sub { warn "CALL 911!" } }
```
Although test failures should be enough, extra diagnostics can be triggered at the end of a test run. `onfail` is passed an array ref of hash refs that describe each test failure. Each hash will contain at least the following fields: `package`, `repetition`, and `result`. (You shouldn't rely on any other fields being present.) If the test had an expected value or a diagnostic (or "note") string, these will also be included.
The *optional* `onfail` hook might be used simply to print out the version of your package and/or how to report problems. It might also be used to generate extremely sophisticated diagnostics for a particularly bizarre test failure. However it's not a panacea. Core dumps or other unrecoverable errors prevent the `onfail` hook from running. (It is run inside an `END` block.) Besides, `onfail` is probably over-kill in most cases. (Your test code should be simpler than the code it is testing, yes?)
BUGS and CAVEATS
-----------------
* `ok(...)`'s special handing of strings which look like they might be regexes can also cause unexpected behavior. An innocent:
```
ok( $fileglob, '/path/to/some/*stuff/' );
```
will fail, since Test.pm considers the second argument to be a regex! The best bet is to use the one-argument form:
```
ok( $fileglob eq '/path/to/some/*stuff/' );
```
* `ok(...)`'s use of string `eq` can sometimes cause odd problems when comparing numbers, especially if you're casting a string to a number:
```
$foo = "1.0";
ok( $foo, 1 ); # not ok, "1.0" ne 1
```
Your best bet is to use the single argument form:
```
ok( $foo == 1 ); # ok "1.0" == 1
```
* As you may have inferred from the above documentation and examples, `ok`'s prototype is `($;$$)` (and, incidentally, `skip`'s is `($;$$$)`). This means, for example, that you can do `ok @foo, @bar` to compare the *size* of the two arrays. But don't be fooled into thinking that `ok @foo, @bar` means a comparison of the contents of two arrays -- you're comparing *just* the number of elements of each. It's so easy to make that mistake in reading `ok @foo, @bar` that you might want to be very explicit about it, and instead write `ok scalar(@foo), scalar(@bar)`.
* This almost definitely doesn't do what you expect:
```
ok $thingy->can('some_method');
```
Why? Because `can` returns a coderef to mean "yes it can (and the method is this...)", and then `ok` sees a coderef and thinks you're passing a function that you want it to call and consider the truth of the result of! I.e., just like:
```
ok $thingy->can('some_method')->();
```
What you probably want instead is this:
```
ok $thingy->can('some_method') && 1;
```
If the `can` returns false, then that is passed to `ok`. If it returns true, then the larger expression `$thingy->can('some_method') && 1` returns 1, which `ok` sees as a simple signal of success, as you would expect.
* The syntax for `skip` is about the only way it can be, but it's still quite confusing. Just start with the above examples and you'll be okay.
Moreover, users may expect this:
```
skip $unless_mswin, foo($bar), baz($quux);
```
to not evaluate `foo($bar)` and `baz($quux)` when the test is being skipped. But in reality, they *are* evaluated, but `skip` just won't bother comparing them if `$unless_mswin` is true.
You could do this:
```
skip $unless_mswin, sub{foo($bar)}, sub{baz($quux)};
```
But that's not terribly pretty. You may find it simpler or clearer in the long run to just do things like this:
```
if( $^O =~ m/MSWin/ ) {
print "# Yay, we're under $^O\n";
ok foo($bar), baz($quux);
ok thing($whatever), baz($stuff);
ok blorp($quux, $whatever);
ok foo($barzbarz), thang($quux);
} else {
print "# Feh, we're under $^O. Watch me skip some tests...\n";
for(1 .. 4) { skip "Skip unless under MSWin" }
}
```
But be quite sure that `ok` is called exactly as many times in the first block as `skip` is called in the second block.
ENVIRONMENT
-----------
If `PERL_TEST_DIFF` environment variable is set, it will be used as a command for comparing unexpected multiline results. If you have GNU diff installed, you might want to set `PERL_TEST_DIFF` to `diff -u`. If you don't have a suitable program, you might install the `Text::Diff` module and then set `PERL_TEST_DIFF` to be `perl -MText::Diff -e 'print diff(@ARGV)'`. If `PERL_TEST_DIFF` isn't set but the `Algorithm::Diff` module is available, then it will be used to show the differences in multiline results.
NOTE
----
A past developer of this module once said that it was no longer being actively developed. However, rumors of its demise were greatly exaggerated. Feedback and suggestions are quite welcome.
Be aware that the main value of this module is its simplicity. Note that there are already more ambitious modules out there, such as <Test::More> and <Test::Unit>.
Some earlier versions of this module had docs with some confusing typos in the description of `skip(...)`.
SEE ALSO
---------
<Test::Harness>
<Test::Simple>, <Test::More>, <Devel::Cover>
<Test::Builder> for building your own testing library.
<Test::Unit> is an interesting XUnit-style testing library.
<Test::Inline> lets you embed tests in code.
AUTHOR
------
Copyright (c) 1998-2000 Joshua Nathaniel Pritikin.
Copyright (c) 2001-2002 Michael G. Schwern.
Copyright (c) 2002-2004 Sean M. Burke.
Current maintainer: Jesse Vincent. <[email protected]>
This package is free software and is provided "as is" without express or implied warranty. It may be used, redistributed and/or modified under the same terms as Perl itself.
perl CPAN::Meta::History::Meta_1_1 CPAN::Meta::History::Meta\_1\_1
===============================
CONTENTS
--------
* [NAME](#NAME)
* [PREFACE](#PREFACE)
* [DESCRIPTION](#DESCRIPTION)
* [Format](#Format)
* [Fields](#Fields)
+ [Ingy's suggestions](#Ingy's-suggestions)
* [History](#History)
NAME
----
CPAN::Meta::History::Meta\_1\_1 - Version 1.1 metadata specification for META.yml
PREFACE
-------
This is a historical copy of the version 1.1 specification for *META.yml* files, copyright by Ken Williams and licensed under the same terms as Perl itself.
Modifications from the original:
* Conversion from the original HTML to POD format
* Include list of valid licenses from <Module::Build> 0.18 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.
DESCRIPTION
-----------
This document describes version 1.1 of the *META.yml* specification.
The *META.yml* file describes important properties of contributed Perl distributions such as the ones found on [CPAN](http://www.cpan.org). It is typically created by tools like <Module::Build> and <ExtUtils::MakeMaker>.
The fields in the *META.yml* file are meant to be helpful to people maintaining module collections (like CPAN), for people writing installation tools (like [CPAN](cpan) or [CPANPLUS](cpanplus)), or just people who want to know some stuff about a distribution before downloading it and starting to install it.
Format
------
*META.yml* files are written in the [YAML](http://www.yaml.org/) format. The reasons we chose YAML instead of, say, XML or Data::Dumper are discussed in [this thread](http://www.nntp.perl.org/group/perl.makemaker/2002/04/msg406.html) on the MakeMaker mailing list.
The first line of a *META.yml* file should be a valid [YAML document header](http://yaml.org/spec/history/2002-10-31.html#syntax-document) like `"--- #YAML:1.0"`
Fields
------
The rest of the META.yml file is one big YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping), whose keys are described here.
name Example: `Module-Build`
The name of the distribution. 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](http://search.cpan.org/author/GAAS/libwww-perl/) distribution.
version Example: `0.16`
The version of the distribution to which the META.yml file refers. This is a mandatory field.
The version is essentially an arbitrary string, but *must* be only ASCII characters, and *strongly should* be of the format integer-dot-digit-digit, i.e. `25.57`, optionally followed by underscore-digit-digit, i.e. `25.57_04`.
The standard tools that deal with module distribution (PAUSE, CPAN, etc.) form an identifier for each distribution by joining the 'name' and 'version' attributes with a dash (`-`) character. Tools who are prepared to deal with distributions that have no version numbers generally omit the dash as well.
license Example: `perl`
a descriptive term for the licenses ... not authoritative, but must be consistent with licensure statements in the READMEs, documentation, etc.
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.
license\_uri This should contain a URI where the exact terms of the license may be found.
(change "unrestricted" to "redistributable"?)
distribution\_type Example: `module`
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.
This field is basically meaningless, and tools (like Module::Build or MakeMaker) will likely stop generating it in the future.
private WTF is going on here?
index\_ignore: any application that indexes the contents of distributions (PAUSE, search.cpan.org) ought to ignore the items (packages, files, directories, namespace hierarchies).
requires Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-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 the [documentation for Module::Build's "requires" parameter](Module::Build::API#requires).
*Note: the exact nature of the fancy specifications like `">= 1.2, != 1.5, < 2.0"` is subject to change. Advance notice will be given here. The simple specifications like `"1.2"` will not change in format.*
recommends Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping) indicating the Perl modules this distribution recommends for enhanced operation.
build\_requires Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-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:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping) indicating the Perl modules that cannot be installed while this distribution is installed. This is a pretty uncommon situation.
- possibly separate out test-time prereqs, complications include: can tests be meaningfully preserved for later running? are test-time prereqs in addition to build-time, or exclusive?
- make official location for installed \*distributions\*, which can contain tests, etc.
dynamic\_config Example: `0`
A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed, or whether this module 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.pm](cpan) to do something useful with it. It can potentially bring lots of security, packaging, and convenience improvements.
generated\_by Example: `Module::Build version 0.16`
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.
###
Ingy's suggestions
short\_description add as field, containing abstract, maximum 80 characters, suggested minimum 40 characters
description long version of abstract, should add?
maturity alpha, beta, gamma, mature, stable
author\_id, owner\_id
categorization, keyword, chapter\_id
URL for further information could default to search.cpan.org on PAUSE
namespaces can be specified for single elements by prepending dotted-form, i.e. "com.example.my\_application.my\_property". Default namespace for META.yml is probably "org.cpan.meta\_author" or something. Precedent for this is Apple's Carbon namespaces, I think.
History
-------
* **March 14, 2003** (Pi day) - created version 1.0 of this document.
* **May 8, 2003** - added the "dynamic\_config" field, which was missing from the initial version.
| programming_docs |
perl Opcode Opcode
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [WARNING](#WARNING)
* [Operator Names and Operator Lists](#Operator-Names-and-Operator-Lists)
* [Opcode Functions](#Opcode-Functions)
* [Manipulating Opsets](#Manipulating-Opsets)
* [TO DO (maybe)](#TO-DO-(maybe))
* [Predefined Opcode Tags](#Predefined-Opcode-Tags)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
Opcode - Disable named opcodes when compiling perl code
SYNOPSIS
--------
```
use Opcode;
```
DESCRIPTION
-----------
Perl code is always 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. The internal format is based on many distinct *opcodes*.
By default no opmask is in effect and any code can be compiled.
The Opcode module allow you to define an *operator mask* to be in effect when perl *next* compiles any code. Attempting to compile code which contains a masked opcode will cause the compilation to fail with an error. The code will not be executed.
NOTE
----
The Opcode module is not usually used directly. See the ops pragma and Safe modules for more typical uses.
WARNING
-------
The Opcode 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 Opcode 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**.
Operator Names and Operator Lists
----------------------------------
The canonical list of operator names is the contents of the array PL\_op\_name defined and initialised in file *opcode.h* of the Perl source distribution (and installed into the perl library).
Each operator has both a terse name (its opname) and a more verbose or recognisable descriptive name. The opdesc function can be used to return a list of descriptions for a list of operators.
Many of the functions and methods listed below take a list of operators as parameters. Most operator lists can be made up of several types of element. Each element can be one of
an operator name (opname) Operator names are typically small lowercase words like enterloop, leaveloop, last, next, redo etc. Sometimes they are rather cryptic like gv2cv, i\_ncmp and ftsvtx.
an operator tag name (optag) Operator tags can be used to refer to groups (or sets) of operators. Tag names always begin with a colon. The Opcode module defines several optags and the user can define others using the define\_optag function.
a negated opname or optag An opname or optag can be prefixed with an exclamation mark, e.g., !mkdir. Negating an opname or optag means remove the corresponding ops from the accumulated set of ops at that point.
an operator set (opset) An *opset* as a binary string of approximately 44 bytes which holds a set or zero or more operators.
The opset and opset\_to\_ops functions can be used to convert from a list of operators to an opset and *vice versa*.
Wherever a list of operators can be given you can use one or more opsets. See also Manipulating Opsets below.
Opcode Functions
-----------------
The Opcode package contains functions for manipulating operator names tags and sets. All are available for export by the package.
opcodes In a scalar context opcodes returns the number of opcodes in this version of perl (around 350 for perl-5.7.0).
In a list context it returns a list of all the operator names. (Not yet implemented, use @names = opset\_to\_ops(full\_opset).)
opset (OP, ...) Returns an opset containing the listed operators.
opset\_to\_ops (OPSET) Returns a list of operator names corresponding to those operators in the set.
opset\_to\_hex (OPSET) Returns a string representation of an opset. Can be handy for debugging.
full\_opset Returns an opset which includes all operators.
empty\_opset Returns an opset which contains no operators.
invert\_opset (OPSET) Returns an opset which is the inverse set of the one supplied.
verify\_opset (OPSET, ...) Returns true if the supplied opset looks like a valid opset (is the right length etc) otherwise it returns false. If an optional second parameter is true then verify\_opset will croak on an invalid opset instead of returning false.
Most of the other Opcode functions call verify\_opset automatically and will croak if given an invalid opset.
define\_optag (OPTAG, OPSET) Define OPTAG as a symbolic name for OPSET. Optag names always start with a colon `:`.
The optag name used must not be defined already (define\_optag will croak if it is already defined). Optag names are global to the perl process and optag definitions cannot be altered or deleted once defined.
It is strongly recommended that applications using Opcode should use a leading capital letter on their tag names since lowercase names are reserved for use by the Opcode module. If using Opcode within a module you should prefix your tags names with the name of your module to ensure uniqueness and thus avoid clashes with other modules.
opmask\_add (OPSET) Adds the supplied opset to the current opmask. Note that there is currently *no* mechanism for unmasking ops once they have been masked. This is intentional.
opmask Returns an opset corresponding to the current opmask.
opdesc (OP, ...) This takes a list of operator names and returns the corresponding list of operator descriptions.
opdump (PAT) Dumps to STDOUT a two column list of op names and op descriptions. If an optional pattern is given then only lines which match the (case insensitive) pattern will be output.
It's designed to be used as a handy command line utility:
```
perl -MOpcode=opdump -e opdump
perl -MOpcode=opdump -e 'opdump Eval'
```
Manipulating Opsets
--------------------
Opsets may be manipulated using the perl bit vector operators & (and), | (or), ^ (xor) and ~ (negate/invert).
However you should never rely on the numerical position of any opcode within the opset. In other words both sides of a bit vector operator should be opsets returned from Opcode functions.
Also, since the number of opcodes in your current version of perl might not be an exact multiple of eight, there may be unused bits in the last byte of an upset. This should not cause any problems (Opcode functions ignore those extra bits) but it does mean that using the ~ operator will typically not produce the same 'physical' opset 'string' as the invert\_opset function.
TO DO (maybe)
--------------
```
$bool = opset_eq($opset1, $opset2) true if opsets are logically
equivalent
$yes = opset_can($opset, @ops) true if $opset has all @ops set
@diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)
```
Predefined Opcode Tags
-----------------------
:base\_core
```
null stub scalar pushmark wantarray const defined undef
rv2sv sassign
rv2av aassign aelem aelemfast aelemfast_lex aslice kvaslice
av2arylen
rv2hv helem hslice kvhslice each values keys exists delete
aeach akeys avalues multideref argelem argdefelem argcheck
preinc i_preinc predec i_predec postinc i_postinc
postdec i_postdec int hex oct abs pow multiply i_multiply
divide i_divide modulo i_modulo add i_add subtract i_subtract
left_shift right_shift bit_and bit_xor bit_or nbit_and
nbit_xor nbit_or sbit_and sbit_xor sbit_or negate i_negate not
complement ncomplement scomplement
lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
slt sgt sle sge seq sne scmp
isa
substr vec stringify study pos length index rindex ord chr
ucfirst lcfirst uc lc fc quotemeta trans transr chop schop
chomp schomp
match split qr
list lslice splice push pop shift unshift reverse
cond_expr flip flop andassign orassign dorassign and or dor xor
warn die lineseq nextstate scope enter leave
rv2cv anoncode prototype coreargs avhvswitch anonconst
entersub leavesub leavesublv return method method_named
method_super method_redir method_redir_super
-- XXX loops via recursion?
cmpchain_and cmpchain_dup
is_bool
is_weak weaken unweaken
leaveeval -- needed for Safe to operate, is safe
without entereval
```
:base\_mem These memory related ops are not included in :base\_core because they can easily be used to implement a resource attack (e.g., consume all available memory).
```
concat multiconcat repeat join range
anonlist anonhash
```
Note that despite the existence of this optag a memory resource attack may still be possible using only :base\_core ops.
Disabling these ops is a *very* heavy handed way to attempt to prevent a memory resource attack. It's probable that a specific memory limit mechanism will be added to perl in the near future.
:base\_loop These loop ops are not included in :base\_core because they can easily be used to implement a resource attack (e.g., consume all available CPU time).
```
grepstart grepwhile
mapstart mapwhile
enteriter iter
enterloop leaveloop unstack
last next redo
goto
```
:base\_io These ops enable *filehandle* (rather than filename) based input and output. These are safe on the assumption that only pre-existing filehandles are available for use. Usually, to create new filehandles other ops such as open would need to be enabled, if you don't take into account the magical open of ARGV.
```
readline rcatline getc read
formline enterwrite leavewrite
print say sysread syswrite send recv
eof tell seek sysseek
readdir telldir seekdir rewinddir
```
:base\_orig These are a hotchpotch of opcodes still waiting to be considered
```
gvsv gv gelem
padsv padav padhv padcv padany padrange introcv clonecv
once
rv2gv refgen srefgen ref refassign lvref lvrefslice lvavref
blessed refaddr reftype
bless -- could be used to change ownership of objects
(reblessing)
regcmaybe regcreset regcomp subst substcont
sprintf prtf -- can core dump
crypt
tie untie
dbmopen dbmclose
sselect select
pipe_op sockpair
getppid getpgrp setpgrp getpriority setpriority
localtime gmtime
entertry leavetry -- can be used to 'hide' fatal errors
entertrycatch poptry catch leavetrycatch -- similar
entergiven leavegiven
enterwhen leavewhen
break continue
smartmatch
pushdefer
custom -- where should this go
ceil floor
```
:base\_math These ops are not included in :base\_core because of the risk of them being used to generate floating point exceptions (which would have to be caught using a $SIG{FPE} handler).
```
atan2 sin cos exp log sqrt
```
These ops are not included in :base\_core because they have an effect beyond the scope of the compartment.
```
rand srand
```
:base\_thread These ops are related to multi-threading.
```
lock
```
:default A handy tag name for a *reasonable* default set of ops. (The current ops allowed are unstable while development continues. It will change.)
```
:base_core :base_mem :base_loop :base_orig :base_thread
```
This list used to contain :base\_io prior to Opcode 1.07.
If safety matters to you (and why else would you be using the Opcode module?) then you should not rely on the definition of this, or indeed any other, optag!
:filesys\_read
```
stat lstat readlink
ftatime ftblk ftchr ftctime ftdir fteexec fteowned
fteread ftewrite ftfile ftis ftlink ftmtime ftpipe
ftrexec ftrowned ftrread ftsgid ftsize ftsock ftsuid
fttty ftzero ftrwrite ftsvtx
fttext ftbinary
fileno
```
:sys\_db
```
ghbyname ghbyaddr ghostent shostent ehostent -- hosts
gnbyname gnbyaddr gnetent snetent enetent -- networks
gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
gsbyname gsbyport gservent sservent eservent -- services
gpwnam gpwuid gpwent spwent epwent getlogin -- users
ggrnam ggrgid ggrent sgrent egrent -- groups
```
:browse A handy tag name for a *reasonable* default set of ops beyond the :default optag. Like :default (and indeed all the other optags) its current definition is unstable while development continues. It will change.
The :browse tag represents the next step beyond :default. It is a superset of the :default ops and adds :filesys\_read the :sys\_db. The intent being that scripts can access more (possibly sensitive) information about your system but not be able to change it.
```
:default :filesys_read :sys_db
```
:filesys\_open
```
sysopen open close
umask binmode
open_dir closedir -- other dir ops are in :base_io
```
:filesys\_write
```
link unlink rename symlink truncate
mkdir rmdir
utime chmod chown
fcntl -- not strictly filesys related, but possibly as
dangerous?
```
:subprocess
```
backtick system
fork
wait waitpid
glob -- access to Cshell via <`rm *`>
```
:ownprocess
```
exec exit kill
time tms -- could be used for timing attacks (paranoid?)
```
:others This tag holds groups of assorted specialist opcodes that don't warrant having optags defined for them.
SystemV Interprocess Communications:
```
msgctl msgget msgrcv msgsnd
semctl semget semop
shmctl shmget shmread shmwrite
```
:load This tag holds opcodes related to loading modules and getting information about calling environment and args.
```
require dofile
caller runcv
```
:still\_to\_be\_decided
```
chdir
flock ioctl
socket getpeername ssockopt
bind connect listen accept shutdown gsockopt getsockname
sleep alarm -- changes global timer state and signal handling
sort -- assorted problems including core dumps
tied -- can be used to access object implementing a tie
pack unpack -- can be used to create/use memory pointers
hintseval -- constant op holding eval hints
entereval -- can be used to hide code from initial compile
reset
dbstate -- perl -d version of nextstate(ment) opcode
```
:dangerous This tag is simply a bucket for opcodes that are unlikely to be used via a tag name but need to be tagged for completeness and documentation.
```
syscall dump chroot
```
SEE ALSO
---------
<ops> -- perl pragma interface to Opcode module.
[Safe](safe) -- Opcode and namespace limited execution compartments
AUTHORS
-------
Originally designed and implemented by Malcolm Beattie, [email protected] as part of Safe version 1.
Split out from Safe module version 1, named opcode tags and other changes added by Tim Bunce.
perl IPC::SysV IPC::SysV
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IPC::SysV - System V IPC constants and system calls
SYNOPSIS
--------
```
use IPC::SysV qw(IPC_STAT IPC_PRIVATE);
```
DESCRIPTION
-----------
`IPC::SysV` defines and conditionally exports all the constants defined in your system include files which are needed by the SysV IPC calls. Common ones include
```
IPC_CREAT IPC_EXCL IPC_NOWAIT IPC_PRIVATE IPC_RMID IPC_SET IPC_STAT
GETVAL SETVAL GETPID GETNCNT GETZCNT GETALL SETALL
SEM_A SEM_R SEM_UNDO
SHM_RDONLY SHM_RND SHMLBA
```
and auxiliary ones
```
S_IRUSR S_IWUSR S_IRWXU
S_IRGRP S_IWGRP S_IRWXG
S_IROTH S_IWOTH S_IRWXO
```
but your system might have more.
ftok( PATH )
ftok( PATH, ID ) Return a key based on PATH and ID, which can be used as a key for `msgget`, `semget` and `shmget`. See [ftok(3)](http://man.he.net/man3/ftok).
If ID is omitted, it defaults to `1`. If a single character is given for ID, the numeric value of that character is used.
shmat( ID, ADDR, FLAG ) Attach the shared memory segment identified by ID to the address space of the calling process. See [shmat(2)](http://man.he.net/man2/shmat).
ADDR should be `undef` unless you really know what you're doing.
shmdt( ADDR ) Detach the shared memory segment located at the address specified by ADDR from the address space of the calling process. See [shmdt(2)](http://man.he.net/man2/shmdt).
memread( ADDR, VAR, POS, SIZE ) Reads SIZE bytes from a memory segment at ADDR starting at position POS. VAR must be a variable that will hold the data read. Returns true if successful, or false if there is an error. memread() taints the variable.
memwrite( ADDR, STRING, POS, SIZE ) Writes SIZE bytes from STRING to a memory segment at ADDR starting at position POS. If STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out SIZE bytes. Returns true if successful, or false if there is an error.
SEE ALSO
---------
<IPC::Msg>, <IPC::Semaphore>, <IPC::SharedMem>, [ftok(3)](http://man.he.net/man3/ftok), [shmat(2)](http://man.he.net/man2/shmat), [shmdt(2)](http://man.he.net/man2/shmdt)
AUTHORS
-------
Graham Barr <[email protected]>, Jarkko Hietaniemi <[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 perlos390 perlos390
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tools](#Tools)
+ [Building a 64-bit Dynamic ASCII Perl](#Building-a-64-bit-Dynamic-ASCII-Perl)
+ [Building a 64-bit Dynamic EBCDIC Perl](#Building-a-64-bit-Dynamic-EBCDIC-Perl)
+ [Setup and utilities for Perl on OS/390](#Setup-and-utilities-for-Perl-on-OS/390)
+ [Useful files for trouble-shooting](#Useful-files-for-trouble-shooting)
- [Shell](#Shell)
- [Dynamic loading](#Dynamic-loading)
- [Optimizing](#Optimizing)
+ [Build Anomalies with Perl on OS/390](#Build-Anomalies-with-Perl-on-OS/390)
+ [Testing Anomalies with Perl on OS/390](#Testing-Anomalies-with-Perl-on-OS/390)
- [Out of Memory (31-bit only)](#Out-of-Memory-(31-bit-only))
+ [Usage Hints for Perl on z/OS](#Usage-Hints-for-Perl-on-z/OS)
+ [Modules and Extensions for Perl on z/OS (Static Only)](#Modules-and-Extensions-for-Perl-on-z/OS-(Static-Only))
+ [Running Perl on z/OS](#Running-Perl-on-z/OS)
* [AUTHORS](#AUTHORS)
* [OTHER SITES](#OTHER-SITES)
* [HISTORY](#HISTORY)
NAME
----
perlos390 - building and installing Perl for z/OS (previously called OS/390)
SYNOPSIS
--------
This document will help you Configure, build, test and install Perl on z/OS Unix System Services.
DESCRIPTION
-----------
This is a ported Perl for z/OS. It has been tested on z/OS 2.4 and should work fine with z/OS 2.5. It may work on other versions or releases, but those are the ones it has been tested on.
The native character set for z/OS is EBCDIC, but it can also run in ASCII mode. Perl can support either, but you have to compile it explicitly for one or the other. You could have both an ASCII perl, and an EBCDIC perl on the same machine. If you use ASCII mode and an ASCII perl, the Encode module shipped with perl can be used to translate files from various EBCDIC code pages for handling by perl, and then back on output
This document describes how to build a 64-bit Dynamic Perl, either ASCII or EBCDIC. You can interactively choose other configurations, as well as many other options in the Configure script that is run as part of the build process. You may need to carry out some system configuration tasks before running Configure, as detailed below.
### Tools
You will want to get GNU make 4.1 or later. GNU make can be downloaded from a port that Rocket Software provides. You will need the z/OS c99 compiler from IBM (though xlc in c99 mode without optimization turned on works in EBCDIC).
If you want the latest development version of Perl, you will need git. You can use git on another platform and transfer the result via sftp or ftp to z/OS. But there is a z/OS native git client port available through Rocket Software.
You may also need the gunzip client port that Rocket Software provides to unzip any zipped tarball you upload to z/OS.
###
Building a 64-bit Dynamic ASCII Perl
For building from an official stable release of Perl, go to <https://www.perl.org/get.html> and choose any one of the "Download latest stable source" buttons. This will get you a tarball. The name of that tarball will be something like 'perl-V.R.M,tar,gz', where V.R.M is the version/release/modification of the perl you are downloading. Do
```
gunzip perl-V.R.M.tar.gz
```
Then one of:
```
tar -xvf perl-V.R.M.tar
pax -r -f perl-V.R.M.tar
```
Either of these will create the source directory. You can rename it to whatever you like; for these instructions, 'perl' is assumed to be the name.
If instead you want the latest unstable development release, using the native git on z/OS, clone Perl:
```
git clone https://github.com/Perl/perl5.git perl
```
Either way, once you have a 'perl' directory containing the source, cd into it, and tag all the code as ASCII:
```
cd perl
chtag -R -h -t -cISO8859-1 *
```
Configure the build environment as 64-bit, Dynamic, ASCII, development, deploying it to */usr/local/perl/ascii*:
```
export PATH=$PWD:$PATH
export LIBPATH=$PWD:$PATH
./Configure -Dprefix=/usr/local/perl/ascii -des -Dusedevel \
-Duse64bitall -Dusedl
```
If you are building from a stable source, you don't need "-Dusedevel". (If you run Configure without options, it will interactively ask you about every possible option based on its probing of what's available on your particular machine, so you can choose as you go along.)
Run GNU make to build Perl
```
make
```
Run tests to ensure Perl is working correctly. Currently, there are about a dozen failing tests out of nearly 2500
```
make test_harness
```
Install Perl into */usr/local/perl/ascii*:
```
make install
```
###
Building a 64-bit Dynamic EBCDIC Perl
You will need a working perl on some box with connectivity to the destination machine. On z/OS, it could be an ASCII perl, or a previous EBCDIC one. Many machines will already have a pre-built perl already running, or one can easily be downloaded from <https://www.perl.org/get.html>.
Follow the directions above in "Building a 64-bit Dynamic ASCII Perl" as far as getting a populated 'perl' directory. Then come back here to proceed.
The downloaded perl will need to be converted to 1047 EBCDIC. To do this:
```
cd perl
Porting/makerel -e
```
If the Porting/makerel step fails with an error that it can not issue the tar command, proceed to issue the command interactively, where V.R.M is the version/release/modification of Perl you are uploading:
```
cd ../
tar cf - --format=ustar perl-V.R.M | gzip --best > perl-V.R.M.tar.gz
```
Use sftp to upload the zipped tar file to z/OS:
```
sftp <your system>
cd /tmp
put perl-V.R.M.tar.gz
```
Unzip and untar the zipped tar file on z/OS:
```
cd /tmp
gunzip perl-V.R.M.tar.gz
```
Then one of:
```
tar -xvf perl-V.R.M.tar
pax -r -f perl-V.R.M.tar
```
You now have the source code for the EBCDIC Perl on z/OS and can proceed to build it. This is analagous to how you would build the code for ASCII, but note: you **should not** tag the code but instead leave it untagged.
Configure the build environment as 64-bit, Dynamic, native, development, deploying it to */usr/local/perl/ebcdic*:
```
export PATH=$PWD:$PATH
export LIBPATH=$PWD:$PATH
./Configure -Dprefix=/usr/local/perl/ebcdic -des -Dusedevel \
-Duse64bitall -Dusedl
```
If you are building from a stable source, you don't need "-Dusedevel". (If you run Configure without options, it will interactively ask you about every possible option based on its probing of what's available on your particular machine, so you can choose as you go along.)
Run GNU make to build Perl
```
make
```
Run tests to ensure Perl is working correctly.
```
make test_harness
```
You might also want to have GNU groff for OS/390 installed before running the "make install" step for Perl.
Install Perl into */usr/local/perl/ebcdic*:
```
make install
```
EBCDIC Perl is still a work in progress. All the core code works as far as we know, but various modules you might want to download from CPAN do not. The failures range from very minor to catastrophic. Many of them are simply bugs in the tests, with the module actually working properly. This happens because, for example, the test is coded to expect a certain character ASCII code point; when it gets the EBCDIC value back instead, it complains. But the code actually worked. Other potential failures that aren't really failures stem from checksums coming out differently, since `A`, for example, has a different bit representation between the character sets. A test that is expecting the ASCII value will show failure, even if the module is working perfectly. Also in sorting, uppercase letters come before lowercase letters on ASCII systems; the reverse on EBCDIC.
Some CPAN modules come bundled with the downloaded perl. And a few of those have yet to be fixed to pass on EBCDIC platforms. As a result they are skipped when you run 'make test'. The current list is:
```
Archive::Tar
Config::Perl::V
CPAN::Meta
CPAN::Meta::YAML
Digest::MD5
Digest::SHA
Encode
ExtUtils::MakeMaker
ExtUtils::Manifest
HTTP::Tiny
IO::Compress
IPC::Cmd
JSON::PP
libnet
MIME::Base64
Module::Metadata
PerlIO::via-QuotedPrint
Pod::Checker
podlators
Pod::Simple
Socket
Test::Harness
```
See also *hints/os390.sh* for other potential gotchas.
###
Setup and utilities for Perl on OS/390
This may also be a good time to ensure that your */etc/protocol* file and either your */etc/resolv.conf* or */etc/hosts* files are in place. The IBM document that describes such USS system setup issues is "z/OS UNIX System Services Planning"
For successful testing you may need to turn on the sticky bit for your world readable /tmp directory if you have not already done so (see man chmod).
###
Useful files for trouble-shooting
If your configuration is failing, read hints/os390.sh This file provides z/OS specific options to direct the build process.
#### Shell
A message of the form:
```
(I see you are using the Korn shell. Some ksh's blow up on Configure,
mainly on older exotic systems. If yours does, try the Bourne shell
instead.)
```
is nothing to worry about at all.
####
Dynamic loading
Dynamic loading is required if you want to use XS modules from CPAN (like DBI (and DBD's), JSON::XS, and Text::CSV\_XS) or update CORE modules from CPAN with newer versions (like Encode) without rebuilding all of the perl binary.
The instructions above will create a dynamic Perl. If you do not want to use dynamic loading, remove the -Dusedl option. See the comments in hints/os390.sh for more information on dynamic loading.
#### Optimizing
Optimization has not been turned on yet. There may be issues if Perl is optimized.
###
Build Anomalies with Perl on OS/390
"Out of memory!" messages during the build of Perl are most often fixed by re building the GNU make utility for OS/390 from a source code kit.
Within USS your */etc/profile* or *$HOME/.profile* may limit your ulimit settings. Check that the following command returns reasonable values:
```
ulimit -a
```
To conserve memory you should have your compiler modules loaded into the Link Pack Area (LPA/ELPA) rather than in a link list or step lib.
If the compiler complains of syntax errors during the build of the Socket extension then be sure to fix the syntax error in the system header /usr/include/sys/socket.h.
###
Testing Anomalies with Perl on OS/390
The "make test" step runs a Perl Verification Procedure, usually before installation. You might encounter STDERR messages even during a successful run of "make test". Here is a guide to some of the more commonly seen anomalies:
####
Out of Memory (31-bit only)
Out of memory problems should not be an issue, unless you are attempting to build a 31-bit Perl.
If you \_are\_ building a 31-bit Perl, the constrained environment may mean you need to change memory options for Perl. In addition to the comments above on memory limitations it is also worth checking for \_CEE\_RUNOPTS in your environment. Perl now has (in miniperlmain.c) a C #pragma for 31-bit only to set CEE run options, but the environment variable wins.
The 31-bit C code asks for:
```
#pragma runopts(HEAP(2M,500K,ANYWHERE,KEEP,8K,4K) STACK(,,ANY,) ALL31(ON))
```
The important parts of that are the second argument (the increment) to HEAP, and allowing the stack to be "Above the (16M) line". If the heap increment is too small then when perl (for example loading unicode/Name.pl) tries to create a "big" (400K+) string it cannot fit in a single segment and you get "Out of Memory!" - even if there is still plenty of memory available.
A related issue is use with perl's malloc. Perl's malloc uses `sbrk()` to get memory, and `sbrk()` is limited to the first allocation so in this case something like:
```
HEAP(8M,500K,ANYWHERE,KEEP,8K,4K)
```
is needed to get through the test suite.
###
Usage Hints for Perl on z/OS
When using Perl on z/OS please keep in mind that the EBCDIC and ASCII character sets are different. See <perlebcdic> for more on such character set issues. Perl builtin functions that may behave differently under EBCDIC are also mentioned in the perlport.pod document.
If you are having trouble with square brackets then consider switching your rlogin or telnet client. Try to avoid older 3270 emulators and ISHELL for working with Perl on USS.
###
Modules and Extensions for Perl on z/OS (Static Only)
Pure Perl (that is non XS) modules may be installed via the usual:
```
perl Makefile.PL
make
make test
make install
```
If you built perl with dynamic loading capability then that would also be the way to build XS based extensions. However, if you built perl with static linking you can still build XS based extensions for z/OS but you will need to follow the instructions in ExtUtils::MakeMaker for building statically linked perl binaries. In the simplest configurations building a static perl + XS extension boils down to:
```
perl Makefile.PL
make
make perl
make test
make install
make -f Makefile.aperl inst_perl MAP_TARGET=perl
```
###
Running Perl on z/OS
To run the 64-bit Dynamic Perl environment, update your PATH and LIBPATH to include the location you installed Perl into, and then run the perl you installed as perlV.R.M where V/R/M is the Version/Release/Modification level of the current development level. If you are running the ASCII/EBCDIC Bi-Modal Perl environment, you also need to set up your ASCII/EBCDIC Bi-Modal environment variables, and ensure any Perl source code you run is tagged appropriately as ASCII or EBCDIC using "chtag -t -c<CCSID>":
For ASCII Only:
```
export _BPXK_AUTOCVT=ON
export _CEE_RUNOPTS="FILETAG(AUTOCVT,AUTOTAG),POSIX(ON)"
export _TAG_REDIR_ERR="txt"
export _TAG_REDIR_IN="txt"
export _TAG_REDIR_OUT="txt"
```
For ASCII or EBCDIC:
```
export PATH=/usr/local/perl/ascii:$PATH
export LIBPATH=/usr/local/perl/ascii/lib:$LIBPATH
perlV.R.M args
```
If tcsh is your login shell then use the setenv command.
AUTHORS
-------
David Fiander and Peter Prymmer with thanks to Dennis Longnecker and William Raffloer for valuable reports, LPAR and PTF feedback. Thanks to Mike MacIsaac and Egon Terwedow for SG24-5944-00. Thanks to Ignasi Roca for pointing out the floating point problems. Thanks to John Goodyear for dynamic loading help.
Mike Fulton and Karl Williamson have provided updates for UTF8, DLL, 64-bit and ASCII/EBCDIC Bi-Modal support
OTHER SITES
------------
<https://github.com/ZOSOpenTools/perlport/> provides documentation and tools for building various z/OS Perl configurations and has some useful tools in the 'bin' directory you may want to use for building z/OS Perl yourself.
HISTORY
-------
Updated 24 December 2021 to enable initial ASCII support
Updated 03 October 2019 for perl-5.33.3+
Updated 28 November 2001 for broken URLs.
Updated 12 March 2001 to mention //'SYS1.TCPPARMS(TCPDATA)'.
Updated 24 January 2001 to mention dynamic loading.
Updated 15 January 2001 for the 5.7.1 release of Perl.
Updated 12 November 2000 for the 5.7.1 release of Perl.
This document was podified for the 5.005\_03 release of Perl 11 March 1999.
This document was originally written by David Fiander for the 5.005 release of Perl.
| programming_docs |
perl perlreguts perlreguts
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [OVERVIEW](#OVERVIEW)
+ [A quick note on terms](#A-quick-note-on-terms)
+ [What is a regular expression engine?](#What-is-a-regular-expression-engine?)
+ [Structure of a Regexp Program](#Structure-of-a-Regexp-Program)
- [High Level](#High-Level)
- [Regops](#Regops)
- [What regop is next?](#What-regop-is-next?)
* [Process Overview](#Process-Overview)
+ [Compilation](#Compilation)
- [Parse Call Graph and a Grammar](#Parse-Call-Graph-and-a-Grammar)
- [Parsing complications](#Parsing-complications)
- [Debug Output](#Debug-Output)
- [Peep-hole Optimisation and Analysis](#Peep-hole-Optimisation-and-Analysis)
+ [Execution](#Execution)
- [Start position and no-match optimisations](#Start-position-and-no-match-optimisations1)
- [Program execution](#Program-execution1)
* [MISCELLANEOUS](#MISCELLANEOUS)
+ [Unicode and Localisation Support](#Unicode-and-Localisation-Support)
+ [Base Structures](#Base-Structures)
- [Perl's pprivate structure](#Perl's-pprivate-structure)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [LICENCE](#LICENCE)
* [REFERENCES](#REFERENCES)
NAME
----
perlreguts - Description of the Perl regular expression engine.
DESCRIPTION
-----------
This document is an attempt to shine some light on the guts of the regex engine and how it works. The regex engine represents a significant chunk of the perl codebase, but is relatively poorly understood. This document is a meagre attempt at addressing this situation. It is derived from the author's experience, comments in the source code, other papers on the regex engine, feedback on the perl5-porters mail list, and no doubt other places as well.
**NOTICE!** It should be clearly understood that the behavior and structures discussed in this represents the state of the engine as the author understood it at the time of writing. It is **NOT** an API definition, it is purely an internals guide for those who want to hack the regex engine, or understand how the regex engine works. Readers of this document are expected to understand perl's regex syntax and its usage in detail. If you want to learn about the basics of Perl's regular expressions, see <perlre>. And if you want to replace the regex engine with your own, see <perlreapi>.
OVERVIEW
--------
###
A quick note on terms
There is some debate as to whether to say "regexp" or "regex". In this document we will use the term "regex" unless there is a special reason not to, in which case we will explain why.
When speaking about regexes we need to distinguish between their source code form and their internal form. In this document we will use the term "pattern" when we speak of their textual, source code form, and the term "program" when we speak of their internal representation. These correspond to the terms *S-regex* and *B-regex* that Mark Jason Dominus employs in his paper on "Rx" ([1] in ["REFERENCES"](#REFERENCES)).
###
What is a regular expression engine?
A regular expression engine is a program that takes a set of constraints specified in a mini-language, and then applies those constraints to a target string, and determines whether or not the string satisfies the constraints. See <perlre> for a full definition of the language.
In less grandiose terms, the first part of the job is to turn a pattern into something the computer can efficiently use to find the matching point in the string, and the second part is performing the search itself.
To do this we need to produce a program by parsing the text. We then need to execute the program to find the point in the string that matches. And we need to do the whole thing efficiently.
###
Structure of a Regexp Program
####
High Level
Although it is a bit confusing and some people object to the terminology, it is worth taking a look at a comment that has been in *regexp.h* for years:
*This is essentially a linear encoding of a nondeterministic finite-state machine (aka syntax charts or "railroad normal form" in parsing technology).*
The term "railroad normal form" is a bit esoteric, with "syntax diagram/charts", or "railroad diagram/charts" being more common terms. Nevertheless it provides a useful mental image of a regex program: each node can be thought of as a unit of track, with a single entry and in most cases a single exit point (there are pieces of track that fork, but statistically not many), and the whole forms a layout with a single entry and single exit point. The matching process can be thought of as a car that moves along the track, with the particular route through the system being determined by the character read at each possible connector point. A car can fall off the track at any point but it may only proceed as long as it matches the track.
Thus the pattern `/foo(?:\w+|\d+|\s+)bar/` can be thought of as the following chart:
```
[start]
|
<foo>
|
+-----+-----+
| | |
<\w+> <\d+> <\s+>
| | |
+-----+-----+
|
<bar>
|
[end]
```
The truth of the matter is that perl's regular expressions these days are much more complex than this kind of structure, but visualising it this way can help when trying to get your bearings, and it matches the current implementation pretty closely.
To be more precise, we will say that a regex program is an encoding of a graph. Each node in the graph corresponds to part of the original regex pattern, such as a literal string or a branch, and has a pointer to the nodes representing the next component to be matched. Since "node" and "opcode" already have other meanings in the perl source, we will call the nodes in a regex program "regops".
The program is represented by an array of `regnode` structures, one or more of which represent a single regop of the program. Struct `regnode` is the smallest struct needed, and has a field structure which is shared with all the other larger structures. (Outside this document, the term "regnode" is sometimes used to mean "regop", which could be confusing.)
The "next" pointers of all regops except `BRANCH` implement concatenation; a "next" pointer with a `BRANCH` on both ends of it is connecting two alternatives. [Here we have one of the subtle syntax dependencies: an individual `BRANCH` (as opposed to a collection of them) is never concatenated with anything because of operator precedence.]
The operand of some types of regop is a literal string; for others, it is a regop leading into a sub-program. In particular, the operand of a `BRANCH` node is the first regop of the branch.
**NOTE**: As the railroad metaphor suggests, this is **not** a tree structure: the tail of the branch connects to the thing following the set of `BRANCH`es. It is a like a single line of railway track that splits as it goes into a station or railway yard and rejoins as it comes out the other side.
#### Regops
The base structure of a regop is defined in *regexp.h* as follows:
```
struct regnode {
U8 flags; /* Various purposes, sometimes overridden */
U8 type; /* Opcode value as specified by regnodes.h */
U16 next_off; /* Offset in size regnode */
};
```
Other larger `regnode`-like structures are defined in *regcomp.h*. They are almost like subclasses in that they have the same fields as `regnode`, with possibly additional fields following in the structure, and in some cases the specific meaning (and name) of some of base fields are overridden. The following is a more complete description.
`regnode_1` `regnode_2` `regnode_1` structures have the same header, followed by a single four-byte argument; `regnode_2` structures contain two two-byte arguments instead:
```
regnode_1 U32 arg1;
regnode_2 U16 arg1; U16 arg2;
```
`regnode_string` `regnode_string` structures, used for literal strings, follow the header with a one-byte length and then the string data. Strings are padded on the tail end with zero bytes so that the total length of the node is a multiple of four bytes:
```
regnode_string char string[1];
U8 str_len; /* overrides flags */
```
`regnode_charclass` Bracketed character classes are represented by `regnode_charclass` structures, which have a four-byte argument and then a 32-byte (256-bit) bitmap indicating which characters in the Latin1 range are included in the class.
```
regnode_charclass U32 arg1;
char bitmap[ANYOF_BITMAP_SIZE];
```
Various flags whose names begin with `ANYOF_` are used for special situations. Above Latin1 matches and things not known until run-time are stored in ["Perl's pprivate structure"](#Perl%27s-pprivate-structure).
`regnode_charclass_posixl` There is also a larger form of a char class structure used to represent POSIX char classes under `/l` matching, called `regnode_charclass_posixl` which has an additional 32-bit bitmap indicating which POSIX char classes have been included.
```
regnode_charclass_posixl U32 arg1;
char bitmap[ANYOF_BITMAP_SIZE];
U32 classflags;
```
*regnodes.h* defines an array called `regarglen[]` which gives the size of each opcode in units of `size regnode` (4-byte). A macro is used to calculate the size of an `EXACT` node based on its `str_len` field.
The regops are defined in *regnodes.h* which is generated from *regcomp.sym* by *regcomp.pl*. Currently the maximum possible number of distinct regops is restricted to 256, with about a quarter already used.
A set of macros makes accessing the fields easier and more consistent. These include `OP()`, which is used to determine the type of a `regnode`-like structure; `NEXT_OFF()`, which is the offset to the next node (more on this later); `ARG()`, `ARG1()`, `ARG2()`, `ARG_SET()`, and equivalents for reading and setting the arguments; and `STR_LEN()`, `STRING()` and `OPERAND()` for manipulating strings and regop bearing types.
####
What regop is next?
There are three distinct concepts of "next" in the regex engine, and it is important to keep them clear.
* There is the "next regnode" from a given regnode, a value which is rarely useful except that sometimes it matches up in terms of value with one of the others, and that sometimes the code assumes this to always be so.
* There is the "next regop" from a given regop/regnode. This is the regop physically located after the current one, as determined by the size of the current regop. This is often useful, such as when dumping the structure we use this order to traverse. Sometimes the code assumes that the "next regnode" is the same as the "next regop", or in other words assumes that the sizeof a given regop type is always going to be one regnode large.
* There is the "regnext" from a given regop. This is the regop which is reached by jumping forward by the value of `NEXT_OFF()`, or in a few cases for longer jumps by the `arg1` field of the `regnode_1` structure. The subroutine `regnext()` handles this transparently. This is the logical successor of the node, which in some cases, like that of the `BRANCH` regop, has special meaning.
Process Overview
-----------------
Broadly speaking, performing a match of a string against a pattern involves the following steps:
A. Compilation
1. Parsing
2. Peep-hole optimisation and analysis
B. Execution
3. Start position and no-match optimisations
4. Program execution Where these steps occur in the actual execution of a perl program is determined by whether the pattern involves interpolating any string variables. If interpolation occurs, then compilation happens at run time. If it does not, then compilation is performed at compile time. (The `/o` modifier changes this, as does `qr//` to a certain extent.) The engine doesn't really care that much.
### Compilation
This code resides primarily in *regcomp.c*, along with the header files *regcomp.h*, *regexp.h* and *regnodes.h*.
Compilation starts with `pregcomp()`, which is mostly an initialisation wrapper which farms work out to two other routines for the heavy lifting: the first is `reg()`, which is the start point for parsing; the second, `study_chunk()`, is responsible for optimisation.
Initialisation in `pregcomp()` mostly involves the creation and data-filling of a special structure, `RExC_state_t` (defined in *regcomp.c*). Almost all internally-used routines in *regcomp.h* take a pointer to one of these structures as their first argument, with the name `pRExC_state`. This structure is used to store the compilation state and contains many fields. Likewise there are many macros which operate on this variable: anything that looks like `RExC_xxxx` is a macro that operates on this pointer/structure.
`reg()` is the start of the parse process. It is responsible for parsing an arbitrary chunk of pattern up to either the end of the string, or the first closing parenthesis it encounters in the pattern. This means it can be used to parse the top-level regex, or any section inside of a grouping parenthesis. It also handles the "special parens" that perl's regexes have. For instance when parsing `/x(?:foo)y/`, `reg()` will at one point be called to parse from the "?" symbol up to and including the ")".
Additionally, `reg()` is responsible for parsing the one or more branches from the pattern, and for "finishing them off" by correctly setting their next pointers. In order to do the parsing, it repeatedly calls out to `regbranch()`, which is responsible for handling up to the first `|` symbol it sees.
`regbranch()` in turn calls `regpiece()` which handles "things" followed by a quantifier. In order to parse the "things", `regatom()` is called. This is the lowest level routine, which parses out constant strings, character classes, and the various special symbols like `$`. If `regatom()` encounters a "(" character it in turn calls `reg()`.
There used to be two main passes involved in parsing, the first to calculate the size of the compiled program, and the second to actually compile it. But now there is only one main pass, with an initial crude guess based on the length of the input pattern, which is increased if necessary as parsing proceeds, and afterwards, trimmed to the actual amount used.
However, it may happen that parsing must be restarted at the beginning when various circumstances occur along the way. An example is if the program turns out to be so large that there are jumps in it that won't fit in the normal 16 bits available. There are two special regops that can hold bigger jump destinations, BRANCHJ and LONGBRANCH. The parse is restarted, and these are used instead of the normal shorter ones. Whenever restarting the parse is required, the function returns failure and sets a flag as to what needs to be done. This is passed up to the top level routine which takes the appropriate action and restarts from scratch. In the case of needing longer jumps, the `RExC_use_BRANCHJ` flag is set in the `RExC_state_t` structure, which the functions know to inspect before deciding how to do branches.
In most instances, the function that discovers the issue sets the causal flag and returns failure immediately. ["Parsing complications"](#Parsing-complications) contains an explicit example of how this works. In other cases, such as a forward reference to a numbered parenthetical grouping, we need to finish the parse to know if that numbered grouping actually appears in the pattern. In those cases, the parse is just redone at the end, with the knowledge of how many groupings occur in it.
The routine `regtail()` is called by both `reg()` and `regbranch()` in order to "set the tail pointer" correctly. When executing and we get to the end of a branch, we need to go to the node following the grouping parens. When parsing, however, we don't know where the end will be until we get there, so when we do we must go back and update the offsets as appropriate. `regtail` is used to make this easier.
A subtlety of the parsing process means that a regex like `/foo/` is originally parsed into an alternation with a single branch. It is only afterwards that the optimiser converts single branch alternations into the simpler form.
####
Parse Call Graph and a Grammar
The call graph looks like this:
```
reg() # parse a top level regex, or inside of
# parens
regbranch() # parse a single branch of an alternation
regpiece() # parse a pattern followed by a quantifier
regatom() # parse a simple pattern
regclass() # used to handle a class
reg() # used to handle a parenthesised
# subpattern
....
...
regtail() # finish off the branch
...
regtail() # finish off the branch sequence. Tie each
# branch's tail to the tail of the
# sequence
# (NEW) In Debug mode this is
# regtail_study().
```
A grammar form might be something like this:
```
atom : constant | class
quant : '*' | '+' | '?' | '{min,max}'
_branch: piece
| piece _branch
| nothing
branch: _branch
| _branch '|' branch
group : '(' branch ')'
_piece: atom | group
piece : _piece
| _piece quant
```
####
Parsing complications
The implication of the above description is that a pattern containing nested parentheses will result in a call graph which cycles through `reg()`, `regbranch()`, `regpiece()`, `regatom()`, `reg()`, `regbranch()` *etc* multiple times, until the deepest level of nesting is reached. All the above routines return a pointer to a `regnode`, which is usually the last regnode added to the program. However, one complication is that reg() returns NULL for parsing `(?:)` syntax for embedded modifiers, setting the flag `TRYAGAIN`. The `TRYAGAIN` propagates upwards until it is captured, in some cases by `regatom()`, but otherwise unconditionally by `regbranch()`. Hence it will never be returned by `regbranch()` to `reg()`. This flag permits patterns such as `(?i)+` to be detected as errors (*Quantifier follows nothing in regex; marked by <-- HERE in m/(?i)+ <-- HERE /*).
Another complication is that the representation used for the program differs if it needs to store Unicode, but it's not always possible to know for sure whether it does until midway through parsing. The Unicode representation for the program is larger, and cannot be matched as efficiently. (See ["Unicode and Localisation Support"](#Unicode-and-Localisation-Support) below for more details as to why.) If the pattern contains literal Unicode, it's obvious that the program needs to store Unicode. Otherwise, the parser optimistically assumes that the more efficient representation can be used, and starts sizing on this basis. However, if it then encounters something in the pattern which must be stored as Unicode, such as an `\x{...}` escape sequence representing a character literal, then this means that all previously calculated sizes need to be redone, using values appropriate for the Unicode representation. This is another instance where the parsing needs to be restarted, and it can and is done immediately. The function returns failure, and sets the flag `RESTART_UTF8` (encapsulated by using the macro `REQUIRE_UTF8`). This restart request is propagated up the call chain in a similar fashion, until it is "caught" in `Perl_re_op_compile()`, which marks the pattern as containing Unicode, and restarts the sizing pass. It is also possible for constructions within run-time code blocks to turn out to need Unicode representation., which is signalled by `S_compile_runtime_code()` returning false to `Perl_re_op_compile()`.
The restart was previously implemented using a `longjmp` in `regatom()` back to a `setjmp` in `Perl_re_op_compile()`, but this proved to be problematic as the latter is a large function containing many automatic variables, which interact badly with the emergent control flow of `setjmp`.
####
Debug Output
Starting in the 5.9.x development version of perl you can `use re Debug => 'PARSE'` to see some trace information about the parse process. We will start with some simple patterns and build up to more complex patterns.
So when we parse `/foo/` we see something like the following table. The left shows what is being parsed, and the number indicates where the next regop would go. The stuff on the right is the trace output of the graph. The names are chosen to be short to make it less dense on the screen. 'tsdy' is a special form of `regtail()` which does some extra analysis.
```
>foo< 1 reg
brnc
piec
atom
>< 4 tsdy~ EXACT <foo> (EXACT) (1)
~ attach to END (3) offset to 2
```
The resulting program then looks like:
```
1: EXACT <foo>(3)
3: END(0)
```
As you can see, even though we parsed out a branch and a piece, it was ultimately only an atom. The final program shows us how things work. We have an `EXACT` regop, followed by an `END` regop. The number in parens indicates where the `regnext` of the node goes. The `regnext` of an `END` regop is unused, as `END` regops mean we have successfully matched. The number on the left indicates the position of the regop in the regnode array.
Now let's try a harder pattern. We will add a quantifier, so now we have the pattern `/foo+/`. We will see that `regbranch()` calls `regpiece()` twice.
```
>foo+< 1 reg
brnc
piec
atom
>o+< 3 piec
atom
>< 6 tail~ EXACT <fo> (1)
7 tsdy~ EXACT <fo> (EXACT) (1)
~ PLUS (END) (3)
~ attach to END (6) offset to 3
```
And we end up with the program:
```
1: EXACT <fo>(3)
3: PLUS(6)
4: EXACT <o>(0)
6: END(0)
```
Now we have a special case. The `EXACT` regop has a `regnext` of 0. This is because if it matches it should try to match itself again. The `PLUS` regop handles the actual failure of the `EXACT` regop and acts appropriately (going to regnode 6 if the `EXACT` matched at least once, or failing if it didn't).
Now for something much more complex: `/x(?:foo*|b[a][rR])(foo|bar)$/`
```
>x(?:foo*|b... 1 reg
brnc
piec
atom
>(?:foo*|b[... 3 piec
atom
>?:foo*|b[a... reg
>foo*|b[a][... brnc
piec
atom
>o*|b[a][rR... 5 piec
atom
>|b[a][rR])... 8 tail~ EXACT <fo> (3)
>b[a][rR])(... 9 brnc
10 piec
atom
>[a][rR])(f... 12 piec
atom
>a][rR])(fo... clas
>[rR])(foo|... 14 tail~ EXACT <b> (10)
piec
atom
>rR])(foo|b... clas
>)(foo|bar)... 25 tail~ EXACT <a> (12)
tail~ BRANCH (3)
26 tsdy~ BRANCH (END) (9)
~ attach to TAIL (25) offset to 16
tsdy~ EXACT <fo> (EXACT) (4)
~ STAR (END) (6)
~ attach to TAIL (25) offset to 19
tsdy~ EXACT <b> (EXACT) (10)
~ EXACT <a> (EXACT) (12)
~ ANYOF[Rr] (END) (14)
~ attach to TAIL (25) offset to 11
>(foo|bar)$< tail~ EXACT <x> (1)
piec
atom
>foo|bar)$< reg
28 brnc
piec
atom
>|bar)$< 31 tail~ OPEN1 (26)
>bar)$< brnc
32 piec
atom
>)$< 34 tail~ BRANCH (28)
36 tsdy~ BRANCH (END) (31)
~ attach to CLOSE1 (34) offset to 3
tsdy~ EXACT <foo> (EXACT) (29)
~ attach to CLOSE1 (34) offset to 5
tsdy~ EXACT <bar> (EXACT) (32)
~ attach to CLOSE1 (34) offset to 2
>$< tail~ BRANCH (3)
~ BRANCH (9)
~ TAIL (25)
piec
atom
>< 37 tail~ OPEN1 (26)
~ BRANCH (28)
~ BRANCH (31)
~ CLOSE1 (34)
38 tsdy~ EXACT <x> (EXACT) (1)
~ BRANCH (END) (3)
~ BRANCH (END) (9)
~ TAIL (END) (25)
~ OPEN1 (END) (26)
~ BRANCH (END) (28)
~ BRANCH (END) (31)
~ CLOSE1 (END) (34)
~ EOL (END) (36)
~ attach to END (37) offset to 1
```
Resulting in the program
```
1: EXACT <x>(3)
3: BRANCH(9)
4: EXACT <fo>(6)
6: STAR(26)
7: EXACT <o>(0)
9: BRANCH(25)
10: EXACT <ba>(14)
12: OPTIMIZED (2 nodes)
14: ANYOF[Rr](26)
25: TAIL(26)
26: OPEN1(28)
28: TRIE-EXACT(34)
[StS:1 Wds:2 Cs:6 Uq:5 #Sts:7 Mn:3 Mx:3 Stcls:bf]
<foo>
<bar>
30: OPTIMIZED (4 nodes)
34: CLOSE1(36)
36: EOL(37)
37: END(0)
```
Here we can see a much more complex program, with various optimisations in play. At regnode 10 we see an example where a character class with only one character in it was turned into an `EXACT` node. We can also see where an entire alternation was turned into a `TRIE-EXACT` node. As a consequence, some of the regnodes have been marked as optimised away. We can see that the `$` symbol has been converted into an `EOL` regop, a special piece of code that looks for `\n` or the end of the string.
The next pointer for `BRANCH`es is interesting in that it points at where execution should go if the branch fails. When executing, if the engine tries to traverse from a branch to a `regnext` that isn't a branch then the engine will know that the entire set of branches has failed.
####
Peep-hole Optimisation and Analysis
The regular expression engine can be a weighty tool to wield. On long strings and complex patterns it can end up having to do a lot of work to find a match, and even more to decide that no match is possible. Consider a situation like the following pattern.
```
'ababababababababababab' =~ /(a|b)*z/
```
The `(a|b)*` part can match at every char in the string, and then fail every time because there is no `z` in the string. So obviously we can avoid using the regex engine unless there is a `z` in the string. Likewise in a pattern like:
```
/foo(\w+)bar/
```
In this case we know that the string must contain a `foo` which must be followed by `bar`. We can use Fast Boyer-Moore matching as implemented in `fbm_instr()` to find the location of these strings. If they don't exist then we don't need to resort to the much more expensive regex engine. Even better, if they do exist then we can use their positions to reduce the search space that the regex engine needs to cover to determine if the entire pattern matches.
There are various aspects of the pattern that can be used to facilitate optimisations along these lines:
* anchored fixed strings
* floating fixed strings
* minimum and maximum length requirements
* start class
* Beginning/End of line positions
Another form of optimisation that can occur is the post-parse "peep-hole" optimisation, where inefficient constructs are replaced by more efficient constructs. The `TAIL` regops which are used during parsing to mark the end of branches and the end of groups are examples of this. These regops are used as place-holders during construction and "always match" so they can be "optimised away" by making the things that point to the `TAIL` point to the thing that `TAIL` points to, thus "skipping" the node.
Another optimisation that can occur is that of "`EXACT` merging" which is where two consecutive `EXACT` nodes are merged into a single regop. An even more aggressive form of this is that a branch sequence of the form `EXACT BRANCH ... EXACT` can be converted into a `TRIE-EXACT` regop.
All of this occurs in the routine `study_chunk()` which uses a special structure `scan_data_t` to store the analysis that it has performed, and does the "peep-hole" optimisations as it goes.
The code involved in `study_chunk()` is extremely cryptic. Be careful. :-)
### Execution
Execution of a regex generally involves two phases, the first being finding the start point in the string where we should match from, and the second being running the regop interpreter.
If we can tell that there is no valid start point then we don't bother running the interpreter at all. Likewise, if we know from the analysis phase that we cannot detect a short-cut to the start position, we go straight to the interpreter.
The two entry points are `re_intuit_start()` and `pregexec()`. These routines have a somewhat incestuous relationship with overlap between their functions, and `pregexec()` may even call `re_intuit_start()` on its own. Nevertheless other parts of the perl source code may call into either, or both.
Execution of the interpreter itself used to be recursive, but thanks to the efforts of Dave Mitchell in the 5.9.x development track, that has changed: now an internal stack is maintained on the heap and the routine is fully iterative. This can make it tricky as the code is quite conservative about what state it stores, with the result that two consecutive lines in the code can actually be running in totally different contexts due to the simulated recursion.
####
Start position and no-match optimisations
`re_intuit_start()` is responsible for handling start points and no-match optimisations as determined by the results of the analysis done by `study_chunk()` (and described in ["Peep-hole Optimisation and Analysis"](#Peep-hole-Optimisation-and-Analysis)).
The basic structure of this routine is to try to find the start- and/or end-points of where the pattern could match, and to ensure that the string is long enough to match the pattern. It tries to use more efficient methods over less efficient methods and may involve considerable cross-checking of constraints to find the place in the string that matches. For instance it may try to determine that a given fixed string must be not only present but a certain number of chars before the end of the string, or whatever.
It calls several other routines, such as `fbm_instr()` which does Fast Boyer Moore matching and `find_byclass()` which is responsible for finding the start using the first mandatory regop in the program.
When the optimisation criteria have been satisfied, `reg_try()` is called to perform the match.
####
Program execution
`pregexec()` is the main entry point for running a regex. It contains support for initialising the regex interpreter's state, running `re_intuit_start()` if needed, and running the interpreter on the string from various start positions as needed. When it is necessary to use the regex interpreter `pregexec()` calls `regtry()`.
`regtry()` is the entry point into the regex interpreter. It expects as arguments a pointer to a `regmatch_info` structure and a pointer to a string. It returns an integer 1 for success and a 0 for failure. It is basically a set-up wrapper around `regmatch()`.
`regmatch` is the main "recursive loop" of the interpreter. It is basically a giant switch statement that implements a state machine, where the possible states are the regops themselves, plus a number of additional intermediate and failure states. A few of the states are implemented as subroutines but the bulk are inline code.
MISCELLANEOUS
-------------
###
Unicode and Localisation Support
When dealing with strings containing characters that cannot be represented using an eight-bit character set, perl uses an internal representation that is a permissive version of Unicode's UTF-8 encoding[2]. This uses single bytes to represent characters from the ASCII character set, and sequences of two or more bytes for all other characters. (See <perlunitut> for more information about the relationship between UTF-8 and perl's encoding, utf8. The difference isn't important for this discussion.)
No matter how you look at it, Unicode support is going to be a pain in a regex engine. Tricks that might be fine when you have 256 possible characters often won't scale to handle the size of the UTF-8 character set. Things you can take for granted with ASCII may not be true with Unicode. For instance, in ASCII, it is safe to assume that `sizeof(char1) == sizeof(char2)`, but in UTF-8 it isn't. Unicode case folding is vastly more complex than the simple rules of ASCII, and even when not using Unicode but only localised single byte encodings, things can get tricky (for example, **LATIN SMALL LETTER SHARP S** (U+00DF, ร) should match 'SS' in localised case-insensitive matching).
Making things worse is that UTF-8 support was a later addition to the regex engine (as it was to perl) and this necessarily made things a lot more complicated. Obviously it is easier to design a regex engine with Unicode support in mind from the beginning than it is to retrofit it to one that wasn't.
Nearly all regops that involve looking at the input string have two cases, one for UTF-8, and one not. In fact, it's often more complex than that, as the pattern may be UTF-8 as well.
Care must be taken when making changes to make sure that you handle UTF-8 properly, both at compile time and at execution time, including when the string and pattern are mismatched.
###
Base Structures
The `regexp` structure described in <perlreapi> is common to all regex engines. Two of its fields are intended for the private use of the regex engine that compiled the pattern. These are the `intflags` and pprivate members. The `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. In the case of the stock engine the structure pointed to by `pprivate` is called `regexp_internal`.
Its `pprivate` and `intflags` fields contain data specific to each engine.
There are two structures used to store a compiled regular expression. One, the `regexp` structure described in <perlreapi> is populated by the engine currently being. used and some of its fields read by perl to implement things such as the stringification of `qr//`.
The other structure is pointed to by the `regexp` struct's `pprivate` and is in addition to `intflags` in the same struct considered to be the property of the regex engine which compiled the regular expression;
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 is the pattern anchored in some way, or what flags were used during the compile, or whether 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. The `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.
As mentioned earlier, in the case of the default engines, the `pprivate` will be a pointer to a regexp\_internal structure which holds the compiled program and any additional data that is private to the regex engine implementation.
####
Perl's `pprivate` structure
The following structure is used as the `pprivate` struct by perl's regex engine. Since it is specific to perl it is only of curiosity value to other engine implementations.
```
typedef struct regexp_internal {
regnode *regstclass;
struct reg_data *data;
struct reg_code_blocks *code_blocks;
U32 proglen;
U32 name_list_idx;
regnode program[1];
} regexp_internal;
```
Description of the attributes is as follows:
`regstclass` Special regop that is used by `re_intuit_start()` to check if a pattern can match at a certain position. For instance if the regex engine knows that the pattern must start with a 'Z' then it can scan the string until it finds one and then launch the regex engine from there. The routine that handles this is called `find_by_class()`. Sometimes this field points at a regop embedded in the program, and sometimes it points at an independent synthetic regop that has been constructed by the optimiser.
`data` This field points at a `reg_data` structure, which is defined as follows
```
struct reg_data {
U32 count;
U8 *what;
void* data[1];
};
```
This structure is used for handling data structures that the regex engine needs to handle specially during a clone or free operation on the compiled product. Each element in the data array has a corresponding element in the what array. During compilation regops that need special structures stored will add an element to each array using the add\_data() routine and then store the index in the regop.
In modern perls the 0th element of this structure is reserved and is NEVER used to store anything of use. This is to allow things that need to index into this array to represent "no value".
`code_blocks` This optional structure is used to manage `(?{})` constructs in the pattern. It is made up of the following structures.
```
/* record the position of a (?{...}) within a pattern */
struct reg_code_block {
STRLEN start;
STRLEN end;
OP *block;
REGEXP *src_regex;
};
/* array of reg_code_block's plus header info */
struct reg_code_blocks {
int refcnt; /* we may be pointed to from a regex
and from the savestack */
int count; /* how many code blocks */
struct reg_code_block *cb; /* array of reg_code_block's */
};
```
`proglen` Stores the length of the compiled program in units of regops.
`name_list_idx` This is the index into the data array where an AV is stored that contains the names of any named capture buffers in the pattern, should there be any. This is only used in the debugging version of the regex engine and when RXp\_PAREN\_NAMES(prog) is true. It will be 0 if there is no such data.
`program` Compiled program. Inlined into the structure so the entire struct can be treated as a single blob.
SEE ALSO
---------
<perlreapi>
<perlre>
<perlunitut>
AUTHOR
------
by Yves Orton, 2006.
With excerpts from Perl, and contributions and suggestions from Ronald J. Kimball, Dave Mitchell, Dominic Dunlop, Mark Jason Dominus, Stephen McCamant, and David Landgren.
Now maintained by Perl 5 Porters.
LICENCE
-------
Same terms as Perl.
REFERENCES
----------
[1] <https://perl.plover.com/Rx/paper/>
[2] <https://www.unicode.org/>
| programming_docs |
perl Test::Builder::TodoDiag Test::Builder::TodoDiag
=======================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::Builder::TodoDiag - Test::Builder subclass of Test2::Event::Diag
DESCRIPTION
-----------
This is used to encapsulate diag messages created inside TODO.
SYNOPSIS
--------
You do not need to use this directly.
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::int32 DBM\_Filter::int32
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter::int32 - 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('int32');
```
DESCRIPTION
-----------
This DBM filter 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.
SEE ALSO
---------
[DBM\_Filter](dbm_filter), <perldbmfilter>
AUTHOR
------
Paul Marquess [email protected]
perl locale locale
======
CONTENTS
--------
* [NAME](#NAME)
* [WARNING](#WARNING)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
locale - Perl pragma to use or avoid POSIX locales for built-in operations
WARNING
-------
DO NOT USE this pragma in scripts that have multiple <threads> active. The locale is not local to a single thread. Another thread may change the locale at any time, which could cause at a minimum that a given thread is operating in a locale it isn't expecting to be in. On some platforms, segfaults can also occur. The locale change need not be explicit; some operations cause perl to change the locale itself. You are vulnerable simply by having done a `"use locale"`.
SYNOPSIS
--------
```
@x = sort @y; # Native-platform/Unicode code point sort order
{
use locale;
@x = sort @y; # Locale-defined sort order
}
@x = sort @y; # Native-platform/Unicode code point sort order
# again
```
DESCRIPTION
-----------
This pragma tells the compiler to enable (or disable) the use of POSIX locales for built-in operations (for example, LC\_CTYPE for regular expressions, LC\_COLLATE for string comparison, and LC\_NUMERIC for number formatting). Each "use locale" or "no locale" affects statements to the end of the enclosing BLOCK.
See <perllocale> for more detailed information on how Perl supports locales.
On systems that don't have locales, this pragma will cause your operations to behave as if in the "C" locale; attempts to change the locale will fail.
perl ptargrep ptargrep
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
ptargrep - Apply pattern matching to the contents of files in a tar archive
SYNOPSIS
--------
```
ptargrep [options] <pattern> <tar file> ...
Options:
--basename|-b ignore directory paths from archive
--ignore-case|-i do case-insensitive pattern matching
--list-only|-l list matching filenames rather than extracting matches
--verbose|-v write debugging message to STDERR
--help|-? detailed help message
```
DESCRIPTION
-----------
This utility allows you to apply pattern matching to **the contents** of files contained in a tar archive. You might use this to identify all files in an archive which contain lines matching the specified pattern and either print out the pathnames or extract the files.
The pattern will be used as a Perl regular expression (as opposed to a simple grep regex).
Multiple tar archive filenames can be specified - they will each be processed in turn.
OPTIONS
-------
**--basename** (alias -b) When matching files are extracted, ignore the directory path from the archive and write to the current directory using the basename of the file from the archive. Beware: if two matching files in the archive have the same basename, the second file extracted will overwrite the first.
**--ignore-case** (alias -i) Make pattern matching case-insensitive.
**--list-only** (alias -l) Print the pathname of each matching file from the archive to STDOUT. Without this option, the default behaviour is to extract each matching file.
**--verbose** (alias -v) Log debugging info to STDERR.
**--help** (alias -?) Display this documentation.
COPYRIGHT
---------
Copyright 2010 Grant McLean <[email protected]>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlstyle perlstyle
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
perlstyle - Perl style guide
DESCRIPTION
-----------
Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain.
The most important thing is to use <strict> and <warnings> in all your code or know the reason why not to. You may turn them off explicitly for particular portions of code via `no warnings` or `no strict`, and this can be limited to the specific warnings or strict features you wish to disable. The **-w** flag and `$^W` variable should not be used for this purpose since they can affect code you use but did not write, such as modules from core or CPAN.
A concise way to arrange for this is to use the [`use VERSION`](perlfunc#use-VERSION) syntax, requesting a version 5.36 or above, which will enable both the `strict` and `warnings` pragmata (as well as several other useful [named features](feature#AVAILABLE-FEATURES)).
```
use v5.36;
```
Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong:
* 4-column indent.
* Opening curly on same line as keyword, if possible, otherwise line up.
* Space before the opening curly of a multi-line BLOCK.
* One-line BLOCK may be put on one line, including curlies.
* No space before the semicolon.
* Semicolon omitted in "short" one-line BLOCK.
* Space around most operators.
* Space around a "complex" subscript (inside brackets).
* Blank lines between chunks that do different things.
* Uncuddled elses.
* No space between function name and its opening parenthesis.
* Space after each comma.
* Long lines broken after an operator (except `and` and `or`).
* Space after last parenthesis matching on current line.
* Line up corresponding items vertically.
* Omit redundant punctuation as long as clarity doesn't suffer.
Larry has his reasons for each of these things, but he doesn't claim that everyone else's mind works the same as his does.
Here are some other more substantive style issues to think about:
* Just because you *CAN* do something a particular way doesn't mean that you *SHOULD* do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance
```
open(my $fh, '<', $foo) || die "Can't open $foo: $!";
```
is better than
```
die "Can't open $foo: $!" unless open(my $fh, '<', $foo);
```
because the second way hides the main point of the statement in a modifier. On the other hand
```
print "Starting analysis\n" if $verbose;
```
is better than
```
$verbose && print "Starting analysis\n";
```
because the main point isn't whether the user typed **-v** or not.
Similarly, just because an operator lets you assume default arguments doesn't mean that you have to make use of the defaults. The defaults are there for lazy systems programmers writing one-shot programs. If you want your program to be readable, consider supplying the argument.
Along the same lines, just because you *CAN* omit parentheses in many places doesn't mean that you ought to:
```
return print reverse sort num values %array;
return print(reverse(sort num (values(%array))));
```
When in doubt, parenthesize. At the very least it will let some poor schmuck bounce on the % key in **vi**.
Even if you aren't in doubt, consider the mental welfare of the person who has to maintain the code after you, and who will probably put parentheses in the wrong place.
* Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the `last` operator so you can exit in the middle. Just "outdent" it a little to make it more visible:
```
LINE:
for (;;) {
statements;
last LINE if $foo;
next LINE if /^#/;
statements;
}
```
* Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example.
* Avoid using `grep()` (or `map()`) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a `foreach()` loop or the `system()` function instead.
* For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test `$]` (`$PERL_VERSION` in `English`) to see if it will be there. The `Config` module will also let you interrogate values determined by the **Configure** program when Perl was installed.
* Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.
* While short identifiers like `$gotit` are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read `$var_names_like_this` than `$VarNamesLikeThis`, especially for non-native speakers of English. It's also a simple rule that works consistently with `VAR_NAMES_LIKE_THIS`.
Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for "pragma" modules like `integer` and `strict`. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.
* You may find it helpful to use letter case to indicate the scope or nature of a variable. For example:
```
$ALL_CAPS_HERE constants only (beware clashes with perl vars!)
$Some_Caps_Here package-wide global/static
$no_caps_here function scope my() or local() variables
```
Function and method names seem to work best as all lowercase. E.g., `$obj->as_string()`.
You can use a leading underscore to indicate that a variable or function should not be used outside the package that defined it.
* If you have a really hairy regular expression, use the `/x` or `/xx` modifiers and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes.
* Use the new `and` and `or` operators to avoid having to parenthesize list operators so much, and to reduce the incidence of punctuation operators like `&&` and `||`. Call your subroutines as if they were functions or list operators to avoid excessive ampersands and parentheses.
* Use here documents instead of repeated `print()` statements.
* Line up corresponding things vertically, especially if it'd be too long to fit on one line anyway.
```
$IDX = $ST_MTIME;
$IDX = $ST_ATIME if $opt_u;
$IDX = $ST_CTIME if $opt_c;
$IDX = $ST_SIZE if $opt_s;
mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";
chdir($tmpdir) or die "can't chdir $tmpdir: $!";
mkdir 'tmp', 0777 or die "can't mkdir $tmpdir/tmp: $!";
```
* Always check the return codes of system calls. Good error messages should go to `STDERR`, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example:
```
opendir(my $dh, $dir) or die "can't opendir $dir: $!";
```
* Line up your transliterations when it makes sense:
```
tr [abc]
[xyz];
```
* Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with `use strict` and `use warnings` in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind.
* Try to document your code and use Pod formatting in a consistent way. Here are commonly expected conventions:
+ use `C<>` for function, variable and module names (and more generally anything that can be considered part of code, like filehandles or specific values). Note that function names are considered more readable with parentheses after their name, that is `function()`.
+ use `B<>` for commands names like **cat** or **grep**.
+ use `F<>` or `C<>` for file names. `F<>` should be the only Pod code for file names, but as most Pod formatters render it as italic, Unix and Windows paths with their slashes and backslashes may be less readable, and better rendered with `C<>`.
* Be consistent.
* Be nice.
perl B::Concise B::Concise
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE](#EXAMPLE)
* [OPTIONS](#OPTIONS)
+ [Options for Opcode Ordering](#Options-for-Opcode-Ordering)
+ [Options for Line-Style](#Options-for-Line-Style)
+ [Options for tree-specific formatting](#Options-for-tree-specific-formatting)
+ [Options controlling sequence numbering](#Options-controlling-sequence-numbering)
+ [Other options](#Other-options)
+ [Option Stickiness](#Option-Stickiness)
* [ABBREVIATIONS](#ABBREVIATIONS)
+ [OP class abbreviations](#OP-class-abbreviations)
+ [OP flags abbreviations](#OP-flags-abbreviations)
* [FORMATTING SPECIFICATIONS](#FORMATTING-SPECIFICATIONS)
+ [Special Patterns](#Special-Patterns)
+ [# Variables](#%23-Variables)
* [One-Liner Command tips](#One-Liner-Command-tips)
* [Using B::Concise outside of the O framework](#Using-B::Concise-outside-of-the-O-framework)
+ [Example: Altering Concise Renderings](#Example:-Altering-Concise-Renderings)
+ [set\_style()](#set_style())
+ [set\_style\_standard($name)](#set_style_standard(%24name))
+ [add\_style ()](#add_style-())
+ [add\_callback ()](#add_callback-())
+ [Running B::Concise::compile()](#Running-B::Concise::compile())
+ [B::Concise::reset\_sequence()](#B::Concise::reset_sequence())
+ [Errors](#Errors)
* [AUTHOR](#AUTHOR)
NAME
----
B::Concise - Walk Perl syntax tree, printing concise info about ops
SYNOPSIS
--------
```
perl -MO=Concise[,OPTIONS] foo.pl
use B::Concise qw(set_style add_callback);
```
DESCRIPTION
-----------
This compiler backend prints the internal OPs of a Perl program's syntax tree in one of several space-efficient text formats suitable for debugging the inner workings of perl or other compiler backends. It can print OPs in the order they appear in the OP tree, in the order they will execute, or in a text approximation to their tree structure, and the format of the information displayed is customizable. Its function is similar to that of perl's **-Dx** debugging flag or the **B::Terse** module, but it is more sophisticated and flexible.
EXAMPLE
-------
Here's two outputs (or 'renderings'), using the -exec and -basic (i.e. default) formatting conventions on the same code snippet.
```
% perl -MO=Concise,-exec -e '$a = $b + 42'
1 <0> enter
2 <;> nextstate(main 1 -e:1) v
3 <#> gvsv[*b] s
4 <$> const[IV 42] s
* 5 <2> add[t3] sK/2
6 <#> gvsv[*a] s
7 <2> sassign vKS/2
8 <@> leave[1 ref] vKP/REFC
```
In this -exec rendering, each opcode is executed in the order shown. The add opcode, marked with '\*', is discussed in more detail.
The 1st column is the op's sequence number, starting at 1, and is displayed in base 36 by default. Here they're purely linear; the sequences are very helpful when looking at code with loops and branches.
The symbol between angle brackets indicates the op's type, for example; <2> is a BINOP, <@> a LISTOP, and <#> is a PADOP, which is used in threaded perls. (see ["OP class abbreviations"](#OP-class-abbreviations)).
The opname, as in **'add[t1]'**, may be followed by op-specific information in parentheses or brackets (ex **'[t1]'**).
The op-flags (ex **'sK/2'**) are described in (["OP flags abbreviations"](#OP-flags-abbreviations)).
```
% perl -MO=Concise -e '$a = $b + 42'
8 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 1 -e:1) v ->3
7 <2> sassign vKS/2 ->8
* 5 <2> add[t1] sK/2 ->6
- <1> ex-rv2sv sK/1 ->4
3 <$> gvsv(*b) s ->4
4 <$> const(IV 42) s ->5
- <1> ex-rv2sv sKRM*/1 ->7
6 <$> gvsv(*a) s ->7
```
The default rendering is top-down, so they're not in execution order. This form reflects the way the stack is used to parse and evaluate expressions; the add operates on the two terms below it in the tree.
Nullops appear as `ex-opname`, where *opname* is an op that has been optimized away by perl. They're displayed with a sequence-number of '-', because they are not executed (they don't appear in previous example), they're printed here because they reflect the parse.
The arrow points to the sequence number of the next op; they're not displayed in -exec mode, for obvious reasons.
Note that because this rendering was done on a non-threaded perl, the PADOPs in the previous examples are now SVOPs, and some (but not all) of the square brackets have been replaced by round ones. This is a subtle feature to provide some visual distinction between renderings on threaded and un-threaded perls.
OPTIONS
-------
Arguments that don't start with a hyphen are taken to be the names of subroutines or formats to render; if no such functions are specified, the main body of the program (outside any subroutines, and not including use'd or require'd files) is rendered. Passing `BEGIN`, `UNITCHECK`, `CHECK`, `INIT`, or `END` will cause all of the corresponding special blocks to be printed. Arguments must follow options.
Options affect how things are rendered (ie printed). They're presented here by their visual effect, 1st being strongest. They're grouped according to how they interrelate; within each group the options are mutually exclusive (unless otherwise stated).
###
Options for Opcode Ordering
These options control the 'vertical display' of opcodes. The display 'order' is also called 'mode' elsewhere in this document.
**-basic**
Print OPs in the order they appear in the OP tree (a preorder traversal, starting at the root). The indentation of each OP shows its level in the tree, and the '->' at the end of the line indicates the next opcode in execution order. This mode is the default, so the flag is included simply for completeness.
**-exec**
Print OPs in the order they would normally execute (for the majority of constructs this is a postorder traversal of the tree, ending at the root). In most cases the OP that usually follows a given OP will appear directly below it; alternate paths are shown by indentation. In cases like loops when control jumps out of a linear path, a 'goto' line is generated.
**-tree**
Print OPs in a text approximation of a tree, with the root of the tree at the left and 'left-to-right' order of children transformed into 'top-to-bottom'. Because this mode grows both to the right and down, it isn't suitable for large programs (unless you have a very wide terminal).
###
Options for Line-Style
These options select the line-style (or just style) used to render each opcode, and dictates what info is actually printed into each line.
**-concise**
Use the author's favorite set of formatting conventions. This is the default, of course.
**-terse**
Use formatting conventions that emulate the output of **B::Terse**. The basic mode is almost indistinguishable from the real **B::Terse**, and the exec mode looks very similar, but is in a more logical order and lacks curly brackets. **B::Terse** doesn't have a tree mode, so the tree mode is only vaguely reminiscent of **B::Terse**.
**-linenoise**
Use formatting conventions in which the name of each OP, rather than being written out in full, is represented by a one- or two-character abbreviation. This is mainly a joke.
**-debug**
Use formatting conventions reminiscent of CPAN module **B::Debug**; these aren't very concise at all.
**-env**
Use formatting conventions read from the environment variables `B_CONCISE_FORMAT`, `B_CONCISE_GOTO_FORMAT`, and `B_CONCISE_TREE_FORMAT`.
###
Options for tree-specific formatting
**-compact**
Use a tree format in which the minimum amount of space is used for the lines connecting nodes (one character in most cases). This squeezes out a few precious columns of screen real estate.
**-loose**
Use a tree format that uses longer edges to separate OP nodes. This format tends to look better than the compact one, especially in ASCII, and is the default.
**-vt**
Use tree connecting characters drawn from the VT100 line-drawing set. This looks better if your terminal supports it.
**-ascii**
Draw the tree with standard ASCII characters like `+` and `|`. These don't look as clean as the VT100 characters, but they'll work with almost any terminal (or the horizontal scrolling mode of less(1)) and are suitable for text documentation or email. This is the default.
These are pairwise exclusive, i.e. compact or loose, vt or ascii.
###
Options controlling sequence numbering
**-base***n*
Print OP sequence numbers in base *n*. If *n* is greater than 10, the digit for 11 will be 'a', and so on. If *n* is greater than 36, the digit for 37 will be 'A', and so on until 62. Values greater than 62 are not currently supported. The default is 36.
**-bigendian**
Print sequence numbers with the most significant digit first. This is the usual convention for Arabic numerals, and the default.
**-littleendian**
Print sequence numbers with the least significant digit first. This is obviously mutually exclusive with bigendian.
###
Other options
**-src**
With this option, the rendering of each statement (starting with the nextstate OP) will be preceded by the 1st line of source code that generates it. For example:
```
1 <0> enter
# 1: my $i;
2 <;> nextstate(main 1 junk.pl:1) v:{
3 <0> padsv[$i:1,10] vM/LVINTRO
# 3: for $i (0..9) {
4 <;> nextstate(main 3 junk.pl:3) v:{
5 <0> pushmark s
6 <$> const[IV 0] s
7 <$> const[IV 9] s
8 <{> enteriter(next->j last->m redo->9)[$i:1,10] lKS
k <0> iter s
l <|> and(other->9) vK/1
# 4: print "line ";
9 <;> nextstate(main 2 junk.pl:4) v
a <0> pushmark s
b <$> const[PV "line "] s
c <@> print vK
# 5: print "$i\n";
...
```
**-stash="somepackage"**
With this, "somepackage" will be required, then the stash is inspected, and each function is rendered.
The following options are pairwise exclusive.
**-main**
Include the main program in the output, even if subroutines were also specified. This rendering is normally suppressed when a subroutine name or reference is given.
**-nomain**
This restores the default behavior after you've changed it with '-main' (it's not normally needed). If no subroutine name/ref is given, main is rendered, regardless of this flag.
**-nobanner**
Renderings usually include a banner line identifying the function name or stringified subref. This suppresses the printing of the banner.
TBC: Remove the stringified coderef; while it provides a 'cookie' for each function rendered, the cookies used should be 1,2,3.. not a random hex-address. It also complicates string comparison of two different trees.
**-banner**
restores default banner behavior.
**-banneris** => subref TBC: a hookpoint (and an option to set it) for a user-supplied function to produce a banner appropriate for users needs. It's not ideal, because the rendering-state variables, which are a natural candidate for use in concise.t, are unavailable to the user.
###
Option Stickiness
If you invoke Concise more than once in a program, you should know that the options are 'sticky'. This means that the options you provide in the first call will be remembered for the 2nd call, unless you re-specify or change them.
ABBREVIATIONS
-------------
The concise style uses symbols to convey maximum info with minimal clutter (like hex addresses). With just a little practice, you can start to see the flowers, not just the branches, in the trees.
###
OP class abbreviations
These symbols appear before the op-name, and indicate the B:: namespace that represents the ops in your Perl code.
```
0 OP (aka BASEOP) An OP with no children
1 UNOP An OP with one child
+ UNOP_AUX A UNOP with auxillary fields
2 BINOP An OP with two children
| LOGOP A control branch OP
@ LISTOP An OP that could have lots of children
/ PMOP An OP with a regular expression
$ SVOP An OP with an SV
" PVOP An OP with a string
{ LOOP An OP that holds pointers for a loop
; COP An OP that marks the start of a statement
# PADOP An OP with a GV on the pad
. METHOP An OP with method call info
```
###
OP flags abbreviations
OP flags are either public or private. The public flags alter the behavior of each opcode in consistent ways, and are represented by 0 or more single characters.
```
v OPf_WANT_VOID Want nothing (void context)
s OPf_WANT_SCALAR Want single value (scalar context)
l OPf_WANT_LIST Want list of any length (list context)
Want is unknown
K OPf_KIDS There is a firstborn child.
P OPf_PARENS This operator was parenthesized.
(Or block needs explicit scope entry.)
R OPf_REF Certified reference.
(Return container, not containee).
M OPf_MOD Will modify (lvalue).
S OPf_STACKED Some arg is arriving on the stack.
* OPf_SPECIAL Do something weird for this op (see op.h)
```
Private flags, if any are set for an opcode, are displayed after a '/'
```
8 <@> leave[1 ref] vKP/REFC ->(end)
7 <2> sassign vKS/2 ->8
```
They're opcode specific, and occur less often than the public ones, so they're represented by short mnemonics instead of single-chars; see B::Op\_private and *regen/op\_private* for more details.
FORMATTING SPECIFICATIONS
--------------------------
For each line-style ('concise', 'terse', 'linenoise', etc.) there are 3 format-specs which control how OPs are rendered.
The first is the 'default' format, which is used in both basic and exec modes to print all opcodes. The 2nd, goto-format, is used in exec mode when branches are encountered. They're not real opcodes, and are inserted to look like a closing curly brace. The tree-format is tree specific.
When a line is rendered, the correct format-spec is copied and scanned for the following items; data is substituted in, and other manipulations like basic indenting are done, for each opcode rendered.
There are 3 kinds of items that may be populated; special patterns, #vars, and literal text, which is copied verbatim. (Yes, it's a set of s///g steps.)
###
Special Patterns
These items are the primitives used to perform indenting, and to select text from amongst alternatives.
**(x(***exec\_text***;***basic\_text***)x)**
Generates *exec\_text* in exec mode, or *basic\_text* in basic mode.
**(\*(***text***)\*)**
Generates one copy of *text* for each indentation level.
**(\*(***text1***;***text2***)\*)**
Generates one fewer copies of *text1* than the indentation level, followed by one copy of *text2* if the indentation level is more than 0.
**(?(***text1***#***var**Text2***)?)**
If the value of *var* is true (not empty or zero), generates the value of *var* surrounded by *text1* and *Text2*, otherwise nothing.
**~**
Any number of tildes and surrounding whitespace will be collapsed to a single space.
###
# Variables
These #vars represent opcode properties that you may want as part of your rendering. The '#' is intended as a private sigil; a #var's value is interpolated into the style-line, much like "read $this".
These vars take 3 forms:
**#***var*
A property named 'var' is assumed to exist for the opcodes, and is interpolated into the rendering.
**#***var**N*
Generates the value of *var*, left justified to fill *N* spaces. Note that this means while you can have properties 'foo' and 'foo2', you cannot render 'foo2', but you could with 'foo2a'. You would be wise not to rely on this behavior going forward ;-)
**#***Var*
This ucfirst form of #var generates a tag-value form of itself for display; it converts '#Var' into a 'Var => #var' style, which is then handled as described above. (Imp-note: #Vars cannot be used for conditional-fills, because the => #var transform is done after the check for #Var's value).
The following variables are 'defined' by B::Concise; when they are used in a style, their respective values are plugged into the rendering of each opcode.
Only some of these are used by the standard styles, the others are provided for you to delve into optree mechanics, should you wish to add a new style (see ["add\_style"](#add_style) below) that uses them. You can also add new ones using ["add\_callback"](#add_callback).
**#addr**
The address of the OP, in hexadecimal.
**#arg**
The OP-specific information of the OP (such as the SV for an SVOP, the non-local exit pointers for a LOOP, etc.) enclosed in parentheses.
**#class**
The B-determined class of the OP, in all caps.
**#classsym**
A single symbol abbreviating the class of the OP.
**#coplabel**
The label of the statement or block the OP is the start of, if any.
**#exname**
The name of the OP, or 'ex-foo' if the OP is a null that used to be a foo.
**#extarg**
The target of the OP, or nothing for a nulled OP.
**#firstaddr**
The address of the OP's first child, in hexadecimal.
**#flags**
The OP's flags, abbreviated as a series of symbols.
**#flagval**
The numeric value of the OP's flags.
**#hints**
The COP's hint flags, rendered with abbreviated names if possible. An empty string if this is not a COP. Here are the symbols used:
```
$ strict refs
& strict subs
* strict vars
x$ explicit use/no strict refs
x& explicit use/no strict subs
x* explicit use/no strict vars
i integers
l locale
b bytes
{ block scope
% localise %^H
< open in
> open out
I overload int
F overload float
B overload binary
S overload string
R overload re
T taint
E eval
X filetest access
U utf-8
us use feature 'unicode_strings'
fea=NNN feature bundle number
```
**#hintsval**
The numeric value of the COP's hint flags, or an empty string if this is not a COP.
**#hyphseq**
The sequence number of the OP, or a hyphen if it doesn't have one.
**#label**
'NEXT', 'LAST', or 'REDO' if the OP is a target of one of those in exec mode, or empty otherwise.
**#lastaddr**
The address of the OP's last child, in hexadecimal.
**#name**
The OP's name.
**#NAME**
The OP's name, in all caps.
**#next**
The sequence number of the OP's next OP.
**#nextaddr**
The address of the OP's next OP, in hexadecimal.
**#noise**
A one- or two-character abbreviation for the OP's name.
**#private**
The OP's private flags, rendered with abbreviated names if possible.
**#privval**
The numeric value of the OP's private flags.
**#seq**
The sequence number of the OP. Note that this is a sequence number generated by B::Concise.
**#opt**
Whether or not the op has been optimized by the peephole optimizer.
**#sibaddr**
The address of the OP's next youngest sibling, in hexadecimal.
**#svaddr**
The address of the OP's SV, if it has an SV, in hexadecimal.
**#svclass**
The class of the OP's SV, if it has one, in all caps (e.g., 'IV').
**#svval**
The value of the OP's SV, if it has one, in a short human-readable format.
**#targ**
The numeric value of the OP's targ.
**#targarg**
The name of the variable the OP's targ refers to, if any, otherwise the letter t followed by the OP's targ in decimal.
**#targarglife**
Same as **#targarg**, but followed by the COP sequence numbers that delimit the variable's lifetime (or 'end' for a variable in an open scope) for a variable.
**#typenum**
The numeric value of the OP's type, in decimal.
One-Liner Command tips
-----------------------
perl -MO=Concise,bar foo.pl Renders only bar() from foo.pl. To see main, drop the ',bar'. To see both, add ',-main'
perl -MDigest::MD5=md5 -MO=Concise,md5 -e1 Identifies md5 as an XS function. The export is needed so that BC can find it in main.
perl -MPOSIX -MO=Concise,\_POSIX\_ARG\_MAX -e1 Identifies \_POSIX\_ARG\_MAX as a constant sub, optimized to an IV. Although POSIX isn't entirely consistent across platforms, this is likely to be present in virtually all of them.
perl -MPOSIX -MO=Concise,a -e 'print \_POSIX\_SAVED\_IDS' This renders a print statement, which includes a call to the function. It's identical to rendering a file with a use call and that single statement, except for the filename which appears in the nextstate ops.
perl -MPOSIX -MO=Concise,a -e 'sub a{\_POSIX\_SAVED\_IDS}' This is **very** similar to previous, only the first two ops differ. This subroutine rendering is more representative, insofar as a single main program will have many subs.
perl -MB::Concise -e 'B::Concise::compile("-exec","-src", \%B::Concise::)->()' This renders all functions in the B::Concise package with the source lines. It eschews the O framework so that the stashref can be passed directly to B::Concise::compile(). See -stash option for a more convenient way to render a package.
Using B::Concise outside of the O framework
--------------------------------------------
The common (and original) usage of B::Concise was for command-line renderings of simple code, as given in EXAMPLE. But you can also use **B::Concise** from your code, and call compile() directly, and repeatedly. By doing so, you can avoid the compile-time only operation of O.pm, and even use the debugger to step through B::Concise::compile() itself.
Once you're doing this, you may alter Concise output by adding new rendering styles, and by optionally adding callback routines which populate new variables, if such were referenced from those (just added) styles.
###
Example: Altering Concise Renderings
```
use B::Concise qw(set_style add_callback);
add_style($yourStyleName => $defaultfmt, $gotofmt, $treefmt);
add_callback
( sub {
my ($h, $op, $format, $level, $stylename) = @_;
$h->{variable} = some_func($op);
});
$walker = B::Concise::compile(@options,@subnames,@subrefs);
$walker->();
```
###
set\_style()
**set\_style** accepts 3 arguments, and updates the three format-specs comprising a line-style (basic-exec, goto, tree). It has one minor drawback though; it doesn't register the style under a new name. This can become an issue if you render more than once and switch styles. Thus you may prefer to use add\_style() and/or set\_style\_standard() instead.
###
set\_style\_standard($name)
This restores one of the standard line-styles: `terse`, `concise`, `linenoise`, `debug`, `env`, into effect. It also accepts style names previously defined with add\_style().
###
add\_style ()
This subroutine accepts a new style name and three style arguments as above, and creates, registers, and selects the newly named style. It is an error to re-add a style; call set\_style\_standard() to switch between several styles.
###
add\_callback ()
If your newly minted styles refer to any new #variables, you'll need to define a callback subroutine that will populate (or modify) those variables. They are then available for use in the style you've chosen.
The callbacks are called for each opcode visited by Concise, in the same order as they are added. Each subroutine is passed five parameters.
```
1. A hashref, containing the variable names and values which are
populated into the report-line for the op
2. the op, as a B<B::OP> object
3. a reference to the format string
4. the formatting (indent) level
5. the selected stylename
```
To define your own variables, simply add them to the hash, or change existing values if you need to. The level and format are passed in as references to scalars, but it is unlikely that they will need to be changed or even used.
###
Running B::Concise::compile()
**compile** accepts options as described above in ["OPTIONS"](#OPTIONS), and arguments, which are either coderefs, or subroutine names.
It constructs and returns a $treewalker coderef, which when invoked, traverses, or walks, and renders the optrees of the given arguments to STDOUT. You can reuse this, and can change the rendering style used each time; thereafter the coderef renders in the new style.
**walk\_output** lets you change the print destination from STDOUT to another open filehandle, or into a string passed as a ref (unless you've built perl with -Uuseperlio).
```
my $walker = B::Concise::compile('-terse','aFuncName', \&aSubRef); # 1
walk_output(\my $buf);
$walker->(); # 1 renders -terse
set_style_standard('concise'); # 2
$walker->(); # 2 renders -concise
$walker->(@new); # 3 renders whatever
print "3 different renderings: terse, concise, and @new: $buf\n";
```
When $walker is called, it traverses the subroutines supplied when it was created, and renders them using the current style. You can change the style afterwards in several different ways:
```
1. call C<compile>, altering style or mode/order
2. call C<set_style_standard>
3. call $walker, passing @new options
```
Passing new options to the $walker is the easiest way to change amongst any pre-defined styles (the ones you add are automatically recognized as options), and is the only way to alter rendering order without calling compile again. Note however that rendering state is still shared amongst multiple $walker objects, so they must still be used in a coordinated manner.
###
B::Concise::reset\_sequence()
This function (not exported) lets you reset the sequence numbers (note that they're numbered arbitrarily, their goal being to be human readable). Its purpose is mostly to support testing, i.e. to compare the concise output from two identical anonymous subroutines (but different instances). Without the reset, B::Concise, seeing that they're separate optrees, generates different sequence numbers in the output.
### Errors
Errors in rendering (non-existent function-name, non-existent coderef) are written to the STDOUT, or wherever you've set it via walk\_output().
Errors using the various \*style\* calls, and bad args to walk\_output(), result in die(). Use an eval if you wish to catch these errors and continue processing.
AUTHOR
------
Stephen McCamant, <[email protected]>.
| programming_docs |
perl Math::BigRat Math::BigRat
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [MATH LIBRARY](#MATH-LIBRARY)
* [METHODS](#METHODS)
* [NUMERIC LITERALS](#NUMERIC-LITERALS)
+ [Hexadecimal, octal, and binary floating point literals](#Hexadecimal,-octal,-and-binary-floating-point-literals)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
Math::BigRat - arbitrary size rational number math package
SYNOPSIS
--------
```
use Math::BigRat;
my $x = Math::BigRat->new('3/7'); $x += '5/9';
print $x->bstr(), "\n";
print $x ** 2, "\n";
my $y = Math::BigRat->new('inf');
print "$y ", ($y->is_inf ? 'is' : 'is not'), " infinity\n";
my $z = Math::BigRat->new(144); $z->bsqrt();
```
DESCRIPTION
-----------
Math::BigRat complements Math::BigInt and Math::BigFloat by providing support for arbitrary big rational numbers.
###
MATH LIBRARY
You can change the underlying module that does the low-level math operations by using:
```
use Math::BigRat try => 'GMP';
```
Note: This needs Math::BigInt::GMP installed.
The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
```
use Math::BigRat try => 'Foo,Math::BigInt::Bar';
```
If you want to get warned when the fallback occurs, replace "try" with "lib":
```
use Math::BigRat lib => 'Foo,Math::BigInt::Bar';
```
If you want the code to die instead, replace "try" with "only":
```
use Math::BigRat only => 'Foo,Math::BigInt::Bar';
```
METHODS
-------
Any methods not listed here are derived from Math::BigFloat (or Math::BigInt), so make sure you check these two modules for further information.
new()
```
$x = Math::BigRat->new('1/3');
```
Create a new Math::BigRat object. Input can come in various forms:
```
$x = Math::BigRat->new(123); # scalars
$x = Math::BigRat->new('inf'); # infinity
$x = Math::BigRat->new('123.3'); # float
$x = Math::BigRat->new('1/3'); # simple string
$x = Math::BigRat->new('1 / 3'); # spaced
$x = Math::BigRat->new('1 / 0.1'); # w/ floats
$x = Math::BigRat->new(Math::BigInt->new(3)); # BigInt
$x = Math::BigRat->new(Math::BigFloat->new('3.1')); # BigFloat
$x = Math::BigRat->new(Math::BigInt::Lite->new('2')); # BigLite
# You can also give D and N as different objects:
$x = Math::BigRat->new(
Math::BigInt->new(-123),
Math::BigInt->new(7),
); # => -123/7
```
numerator()
```
$n = $x->numerator();
```
Returns a copy of the numerator (the part above the line) as signed BigInt.
denominator()
```
$d = $x->denominator();
```
Returns a copy of the denominator (the part under the line) as positive BigInt.
parts()
```
($n, $d) = $x->parts();
```
Return a list consisting of (signed) numerator and (unsigned) denominator as BigInts.
dparts() Returns the integer part and the fraction part.
fparts() Returns the smallest possible numerator and denominator so that the numerator divided by the denominator gives back the original value. For finite numbers, both values are integers. Mnemonic: fraction.
numify()
```
my $y = $x->numify();
```
Returns the object as a scalar. This will lose some data if the object cannot be represented by a normal Perl scalar (integer or float), so use ["as\_int()"](#as_int%28%29) or ["as\_float()"](#as_float%28%29) instead.
This routine is automatically used whenever a scalar is required:
```
my $x = Math::BigRat->new('3/1');
@array = (0, 1, 2, 3);
$y = $array[$x]; # set $y to 3
```
as\_int()
as\_number()
```
$x = Math::BigRat->new('13/7');
print $x->as_int(), "\n"; # '1'
```
Returns a copy of the object as BigInt, truncated to an integer.
`as_number()` is an alias for `as_int()`.
as\_float()
```
$x = Math::BigRat->new('13/7');
print $x->as_float(), "\n"; # '1'
$x = Math::BigRat->new('2/3');
print $x->as_float(5), "\n"; # '0.66667'
```
Returns a copy of the object as BigFloat, preserving the accuracy as wanted, or the default of 40 digits.
This method was added in v0.22 of Math::BigRat (April 2008).
as\_hex()
```
$x = Math::BigRat->new('13');
print $x->as_hex(), "\n"; # '0xd'
```
Returns the BigRat as hexadecimal string. Works only for integers.
as\_bin()
```
$x = Math::BigRat->new('13');
print $x->as_bin(), "\n"; # '0x1101'
```
Returns the BigRat as binary string. Works only for integers.
as\_oct()
```
$x = Math::BigRat->new('13');
print $x->as_oct(), "\n"; # '015'
```
Returns the BigRat as octal string. Works only for integers.
from\_hex()
```
my $h = Math::BigRat->from_hex('0x10');
```
Create a BigRat from a hexadecimal number in string form.
from\_oct()
```
my $o = Math::BigRat->from_oct('020');
```
Create a BigRat from an octal number in string form.
from\_bin()
```
my $b = Math::BigRat->from_bin('0b10000000');
```
Create a BigRat from an binary number in string form.
bnan()
```
$x = Math::BigRat->bnan();
```
Creates a new BigRat object representing NaN (Not A Number). If used on an object, it will set it to NaN:
```
$x->bnan();
```
bzero()
```
$x = Math::BigRat->bzero();
```
Creates a new BigRat object representing zero. If used on an object, it will set it to zero:
```
$x->bzero();
```
binf()
```
$x = Math::BigRat->binf($sign);
```
Creates a new BigRat object representing infinity. The optional argument is either '-' or '+', indicating whether you want infinity or minus infinity. If used on an object, it will set it to infinity:
```
$x->binf();
$x->binf('-');
```
bone()
```
$x = Math::BigRat->bone($sign);
```
Creates a new BigRat object representing one. The optional argument is either '-' or '+', indicating whether you want one or minus one. If used on an object, it will set it to one:
```
$x->bone(); # +1
$x->bone('-'); # -1
```
length()
```
$len = $x->length();
```
Return the length of $x in digits for integer values.
digit()
```
print Math::BigRat->new('123/1')->digit(1); # 1
print Math::BigRat->new('123/1')->digit(-1); # 3
```
Return the N'ths digit from X when X is an integer value.
bnorm()
```
$x->bnorm();
```
Reduce the number to the shortest form. This routine is called automatically whenever it is needed.
bfac()
```
$x->bfac();
```
Calculates the factorial of $x. For instance:
```
print Math::BigRat->new('3/1')->bfac(), "\n"; # 1*2*3
print Math::BigRat->new('5/1')->bfac(), "\n"; # 1*2*3*4*5
```
Works currently only for integers.
bround()/round()/bfround() Are not yet implemented.
bmod()
```
$x->bmod($y);
```
Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the result is identical to the remainder after floored division (F-division). If, in addition, both $x and $y are integers, the result is identical to the result from Perl's % operator.
bmodinv()
```
$x->bmodinv($mod); # modular multiplicative inverse
```
Returns the multiplicative inverse of `$x` modulo `$mod`. If
```
$y = $x -> copy() -> bmodinv($mod)
```
then `$y` is the number closest to zero, and with the same sign as `$mod`, satisfying
```
($x * $y) % $mod = 1 % $mod
```
If `$x` and `$y` are non-zero, they must be relative primes, i.e., `bgcd($y, $mod)==1`. '`NaN`' is returned when no modular multiplicative inverse exists.
bmodpow()
```
$num->bmodpow($exp,$mod); # modular exponentiation
# ($num**$exp % $mod)
```
Returns the value of `$num` taken to the power `$exp` in the modulus `$mod` using binary exponentiation. `bmodpow` is far superior to writing
```
$num ** $exp % $mod
```
because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers.
`bmodpow` also supports negative exponents.
```
bmodpow($num, -1, $mod)
```
is exactly equivalent to
```
bmodinv($num, $mod)
```
bneg()
```
$x->bneg();
```
Used to negate the object in-place.
is\_one()
```
print "$x is 1\n" if $x->is_one();
```
Return true if $x is exactly one, otherwise false.
is\_zero()
```
print "$x is 0\n" if $x->is_zero();
```
Return true if $x is exactly zero, otherwise false.
is\_pos()/is\_positive()
```
print "$x is >= 0\n" if $x->is_positive();
```
Return true if $x is positive (greater than or equal to zero), otherwise false. Please note that '+inf' is also positive, while 'NaN' and '-inf' aren't.
`is_positive()` is an alias for `is_pos()`.
is\_neg()/is\_negative()
```
print "$x is < 0\n" if $x->is_negative();
```
Return true if $x is negative (smaller than zero), otherwise false. Please note that '-inf' is also negative, while 'NaN' and '+inf' aren't.
`is_negative()` is an alias for `is_neg()`.
is\_int()
```
print "$x is an integer\n" if $x->is_int();
```
Return true if $x has a denominator of 1 (e.g. no fraction parts), otherwise false. Please note that '-inf', 'inf' and 'NaN' aren't integer.
is\_odd()
```
print "$x is odd\n" if $x->is_odd();
```
Return true if $x is odd, otherwise false.
is\_even()
```
print "$x is even\n" if $x->is_even();
```
Return true if $x is even, otherwise false.
bceil()
```
$x->bceil();
```
Set $x to the next bigger integer value (e.g. truncate the number to integer and then increment it by one).
bfloor()
```
$x->bfloor();
```
Truncate $x to an integer value.
bint()
```
$x->bint();
```
Round $x towards zero.
bsqrt()
```
$x->bsqrt();
```
Calculate the square root of $x.
broot()
```
$x->broot($n);
```
Calculate the N'th root of $x.
badd()
```
$x->badd($y);
```
Adds $y to $x and returns the result.
bmul()
```
$x->bmul($y);
```
Multiplies $y to $x and returns the result.
bsub()
```
$x->bsub($y);
```
Subtracts $y from $x and returns the result.
bdiv()
```
$q = $x->bdiv($y);
($q, $r) = $x->bdiv($y);
```
In scalar context, divides $x by $y and returns the result. In list context, does floored division (F-division), returning an integer $q and a remainder $r so that $x = $q \* $y + $r. The remainer (modulo) is equal to what is returned by `$x->bmod($y)`.
binv()
```
$x->binv();
```
Inverse of $x.
bdec()
```
$x->bdec();
```
Decrements $x by 1 and returns the result.
binc()
```
$x->binc();
```
Increments $x by 1 and returns the result.
copy()
```
my $z = $x->copy();
```
Makes a deep copy of the object.
Please see the documentation in <Math::BigInt> for further details.
bstr()/bsstr()
```
my $x = Math::BigRat->new('8/4');
print $x->bstr(), "\n"; # prints 1/2
print $x->bsstr(), "\n"; # prints 1/2
```
Return a string representing this object.
bcmp()
```
$x->bcmp($y);
```
Compares $x with $y and takes the sign into account. Returns -1, 0, 1 or undef.
bacmp()
```
$x->bacmp($y);
```
Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or undef.
beq()
```
$x -> beq($y);
```
Returns true if and only if $x is equal to $y, and false otherwise.
bne()
```
$x -> bne($y);
```
Returns true if and only if $x is not equal to $y, and false otherwise.
blt()
```
$x -> blt($y);
```
Returns true if and only if $x is equal to $y, and false otherwise.
ble()
```
$x -> ble($y);
```
Returns true if and only if $x is less than or equal to $y, and false otherwise.
bgt()
```
$x -> bgt($y);
```
Returns true if and only if $x is greater than $y, and false otherwise.
bge()
```
$x -> bge($y);
```
Returns true if and only if $x is greater than or equal to $y, and false otherwise.
blsft()/brsft() Used to shift numbers left/right.
Please see the documentation in <Math::BigInt> for further details.
band()
```
$x->band($y); # bitwise and
```
bior()
```
$x->bior($y); # bitwise inclusive or
```
bxor()
```
$x->bxor($y); # bitwise exclusive or
```
bnot()
```
$x->bnot(); # bitwise not (two's complement)
```
bpow()
```
$x->bpow($y);
```
Compute $x \*\* $y.
Please see the documentation in <Math::BigInt> for further details.
blog()
```
$x->blog($base, $accuracy); # logarithm of x to the base $base
```
If `$base` is not defined, Euler's number (e) is used:
```
print $x->blog(undef, 100); # log(x) to 100 digits
```
bexp()
```
$x->bexp($accuracy); # calculate e ** X
```
Calculates two integers A and B so that A/B is equal to `e ** $x`, where `e` is Euler's number.
This method was added in v0.20 of Math::BigRat (May 2007).
See also `blog()`.
bnok()
```
$x->bnok($y); # x over y (binomial coefficient n over k)
```
Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to:
```
( n ) n!
| - | = -------
( k ) k!(n-k)!
```
This method was added in v0.20 of Math::BigRat (May 2007).
config()
```
Math::BigRat->config("trap_nan" => 1); # set
$accu = Math::BigRat->config("accuracy"); # get
```
Set or get configuration parameter values. Read-only parameters are marked as RO. Read-write parameters are marked as RW. The following parameters are supported.
```
Parameter RO/RW Description
Example
============================================================
lib RO Name of the math backend library
Math::BigInt::Calc
lib_version RO Version of the math backend library
0.30
class RO The class of config you just called
Math::BigRat
version RO version number of the class you used
0.10
upgrade RW To which class numbers are upgraded
undef
downgrade RW To which class numbers are downgraded
undef
precision RW Global precision
undef
accuracy RW Global accuracy
undef
round_mode RW Global round mode
even
div_scale RW Fallback accuracy for div, sqrt etc.
40
trap_nan RW Trap NaNs
undef
trap_inf RW Trap +inf/-inf
undef
```
NUMERIC LITERALS
-----------------
After `use Math::BigRat ':constant'` all numeric literals in the given scope are converted to `Math::BigRat` objects. This conversion happens at compile time. Every non-integer is convert to a NaN.
For example,
```
perl -MMath::BigRat=:constant -le 'print 2**150'
```
prints the exact value of `2**150`. Note that without conversion of constants to objects the expression `2**150` is calculated using Perl scalars, which leads to an inaccurate result.
Please note that strings are not affected, so that
```
use Math::BigRat qw/:constant/;
$x = "1234567890123456789012345678901234567890"
+ "123456789123456789";
```
does give you what you expect. You need an explicit Math::BigRat->new() around at least one of the operands. You should also quote large constants to prevent loss of precision:
```
use Math::BigRat;
$x = Math::BigRat->new("1234567889123456789123456789123456789");
```
Without the quotes Perl first converts the large number to a floating point constant at compile time, and then converts the result to a Math::BigRat object at run time, which results in an inaccurate result.
###
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. Below are some examples of different ways to write the number decimal 314.
Hexadecimal floating point literals:
```
0x1.3ap+8 0X1.3AP+8
0x1.3ap8 0X1.3AP8
0x13a0p-4 0X13A0P-4
```
Octal floating point literals (with "0" prefix):
```
01.164p+8 01.164P+8
01.164p8 01.164P8
011640p-4 011640P-4
```
Octal floating point literals (with "0o" prefix) (requires v5.34.0):
```
0o1.164p+8 0O1.164P+8
0o1.164p8 0O1.164P8
0o11640p-4 0O11640P-4
```
Binary floating point literals:
```
0b1.0011101p+8 0B1.0011101P+8
0b1.0011101p8 0B1.0011101P8
0b10011101000p-2 0B10011101000P-2
```
BUGS
----
Please report any bugs or feature requests to `bug-math-bigrat at rt.cpan.org`, or through the web interface at <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigRat> (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::BigRat
```
You can also look for information at:
* GitHub
<https://github.com/pjacklam/p5-Math-BigRat>
* RT: CPAN's request tracker
<https://rt.cpan.org/Dist/Display.html?Name=Math-BigRat>
* MetaCPAN
<https://metacpan.org/release/Math-BigRat>
* CPAN Testers Matrix
<http://matrix.cpantesters.org/?dist=Math-BigRat>
* CPAN Ratings
<https://cpanratings.perl.org/dist/Math-BigRat>
LICENSE
-------
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<bigrat>, <Math::BigFloat> and <Math::BigInt> as well as the backends <Math::BigInt::FastCalc>, <Math::BigInt::GMP>, and <Math::BigInt::Pari>.
AUTHORS
-------
* Tels <http://bloodgate.com/> 2001-2009.
* Maintained by Peter John Acklam <[email protected]> 2011-
perl Test2::Hub::Interceptor Test2::Hub::Interceptor
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Hub::Interceptor - Hub used by interceptor to grab results.
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 Encode::GSM0338 Encode::GSM0338
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Septets](#Septets)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::GSM0338 -- ETSI GSM 03.38 Encoding
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$gsm0338 = encode("gsm0338", $unicode); # loads Encode::GSM0338 implicitly
$unicode = decode("gsm0338", $gsm0338); # ditto
```
DESCRIPTION
-----------
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 this module.
This module implements only *GSM 7 bit Default Alphabet* and *GSM 7 bit default alphabet extension table* according to standard 3GPP TS 23.038 version 16. Therefore *National Language Single Shift* and *National Language Locking Shift* are not implemented nor supported.
### Septets
This modules operates with octets (like any other Encode module) and not with packed septets (unlike other GSM standards). Therefore for processing binary SMS or parts of GSM TPDU payload (3GPP TS 23.040) it is needed to do conversion between octets and packed septets. For this purpose perl's `pack` and `unpack` functions may be useful:
```
$bytes = substr(pack('(b*)*', unpack '(A7)*', unpack 'b*', $septets), 0, $num_of_septets);
$unicode = decode('GSM0338', $bytes);
$bytes = encode('GSM0338', $unicode);
$septets = pack 'b*', join '', map { substr $_, 0, 7 } unpack '(A8)*', unpack 'b*', $bytes;
$num_of_septets = length $bytes;
```
Please note that for correct decoding of packed septets it is required to know number of septets packed in binary buffer as binary buffer is always padded with zero bits and 7 zero bits represents character `@`. Number of septets is also stored in TPDU payload when dealing with 3GPP TS 23.040.
BUGS
----
Encode::GSM0338 2.7 and older versions (part of Encode 3.06) incorrectly handled zero bytes (character `@`). This was fixed in Encode::GSM0338 version 2.8 (part of Encode 3.07).
SEE ALSO
---------
[3GPP TS 23.038](https://www.3gpp.org/dynareport/23038.htm)
[ETSI TS 123 038 V16.0.0 (2020-07)](https://www.etsi.org/deliver/etsi_ts/123000_123099/123038/16.00.00_60/ts_123038v160000p.pdf)
[Encode](encode)
| programming_docs |
perl Test2::Event::Skip Test2::Event::Skip
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ACCESSORS](#ACCESSORS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Skip - Skip event type
DESCRIPTION
-----------
Skip events bump test counts just like <Test2::Event::Ok> events, but they can never fail.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Skip;
my $ctx = context();
my $event = $ctx->skip($name, $reason);
```
or:
```
my $ctx = context();
my $event = $ctx->send_event(
'Skip',
name => $name,
reason => $reason,
);
```
ACCESSORS
---------
$reason = $e->reason The original true/false value of whatever was passed into the event (but reduced down to 1 or 0).
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://www.perl.com/perl/misc/Artistic.html*
perl Pod::Simple::Subclassing Pod::Simple::Subclassing
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Events](#Events)
* [More Pod::Simple Methods](#More-Pod::Simple-Methods)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Subclassing -- write a formatter as a Pod::Simple subclass
SYNOPSIS
--------
```
package Pod::SomeFormatter;
use Pod::Simple;
@ISA = qw(Pod::Simple);
$VERSION = '1.01';
use strict;
sub _handle_element_start {
my($parser, $element_name, $attr_hash_r) = @_;
...
}
sub _handle_element_end {
my($parser, $element_name, $attr_hash_r) = @_;
# NOTE: $attr_hash_r is only present when $element_name is "over" or "begin"
# The remaining code excerpts will mostly ignore this $attr_hash_r, as it is
# mostly useless. It is documented where "over-*" and "begin" events are
# documented.
...
}
sub _handle_text {
my($parser, $text) = @_;
...
}
1;
```
DESCRIPTION
-----------
This document is about using Pod::Simple to write a Pod processor, generally a Pod formatter. If you just want to know about using an existing Pod formatter, instead see its documentation and see also the docs in <Pod::Simple>.
**The zeroeth step** in writing a Pod formatter is to make sure that there isn't already a decent one in CPAN. See <http://search.cpan.org/>, and run a search on the name of the format you want to render to. Also consider joining the Pod People list <http://lists.perl.org/showlist.cgi?name=pod-people> and asking whether anyone has a formatter for that format -- maybe someone cobbled one together but just hasn't released it.
**The first step** in writing a Pod processor is to read <perlpodspec>, which contains information on writing a Pod parser (which has been largely taken care of by Pod::Simple), but also a lot of requirements and recommendations for writing a formatter.
**The second step** is to actually learn the format you're planning to format to -- or at least as much as you need to know to represent Pod, which probably isn't much.
**The third step** is to pick which of Pod::Simple's interfaces you want to use:
Pod::Simple The basic <Pod::Simple> interface that uses `_handle_element_start()`, `_handle_element_end()` and `_handle_text()`.
Pod::Simple::Methody The <Pod::Simple::Methody> interface is event-based, similar to that of <HTML::Parser> or <XML::Parser>'s "Handlers".
Pod::Simple::PullParser <Pod::Simple::PullParser> provides a token-stream interface, sort of like <HTML::TokeParser>'s interface.
Pod::Simple::SimpleTree <Pod::Simple::SimpleTree> provides a simple tree interface, rather like <XML::Parser>'s "Tree" interface. Users familiar with XML handling will be comfortable with this interface. Users interested in outputting XML, should look into the modules that produce an XML representation of the Pod stream, notably <Pod::Simple::XMLOutStream>; you can feed the output of such a class to whatever XML parsing system you are most at home with.
**The last step** is to write your code based on how the events (or tokens, or tree-nodes, or the XML, or however you're parsing) will map to constructs in the output format. Also be sure to consider how to escape text nodes containing arbitrary text, and what to do with text nodes that represent preformatted text (from verbatim sections).
Events
------
TODO intro... mention that events are supplied for implicits, like for missing >'s
In the following section, we use XML to represent the event structure associated with a particular construct. That is, an opening tag represents the element start, the attributes of that opening tag are the attributes given to the callback, and the closing tag represents the end element.
Three callback methods must be supplied by a class extending <Pod::Simple> to receive the corresponding event:
`$parser->_handle_element_start( *element\_name*, *attr\_hashref* )`
`$parser->_handle_element_end( *element\_name* )`
`$parser->_handle_text( *text\_string* )`
Here's the comprehensive list of values you can expect as *element\_name* in your implementation of `_handle_element_start` and `_handle_element_end`::
events with an element\_name of Document Parsing a document produces this event structure:
```
<Document start_line="543">
...all events...
</Document>
```
The value of the *start\_line* attribute will be the line number of the first Pod directive in the document.
If there is no Pod in the given document, then the event structure will be this:
```
<Document contentless="1" start_line="543">
</Document>
```
In that case, the value of the *start\_line* attribute will not be meaningful; under current implementations, it will probably be the line number of the last line in the file.
events with an element\_name of Para Parsing a plain (non-verbatim, non-directive, non-data) paragraph in a Pod document produces this event structure:
```
<Para start_line="543">
...all events in this paragraph...
</Para>
```
The value of the *start\_line* attribute will be the line number of the start of the paragraph.
For example, parsing this paragraph of Pod:
```
The value of the I<start_line> attribute will be the
line number of the start of the paragraph.
```
produces this event structure:
```
<Para start_line="129">
The value of the
<I>
start_line
</I>
attribute will be the line number of the first Pod directive
in the document.
</Para>
```
events with an element\_name of B, C, F, or I. Parsing a B<...> formatting code (or of course any of its semantically identical syntactic variants B<< ... >>, or B<<<< ... >>>>, etc.) produces this event structure:
```
<B>
...stuff...
</B>
```
Currently, there are no attributes conveyed.
Parsing C, F, or I codes produce the same structure, with only a different element name.
If your parser object has been set to accept other formatting codes, then they will be presented like these B/C/F/I codes -- i.e., without any attributes.
events with an element\_name of S Normally, parsing an S<...> sequence produces this event structure, just as if it were a B/C/F/I code:
```
<S>
...stuff...
</S>
```
However, Pod::Simple (and presumably all derived parsers) offers the `nbsp_for_S` option which, if enabled, will suppress all S events, and instead change all spaces in the content to non-breaking spaces. This is intended for formatters that output to a format that has no code that means the same as S<...>, but which has a code/character that means non-breaking space.
events with an element\_name of X Normally, parsing an X<...> sequence produces this event structure, just as if it were a B/C/F/I code:
```
<X>
...stuff...
</X>
```
However, Pod::Simple (and presumably all derived parsers) offers the `nix_X_codes` option which, if enabled, will suppress all X events and ignore their content. For formatters/processors that don't use X events, this is presumably quite useful.
events with an element\_name of L Because the L<...> is the most complex construct in the language, it should not surprise you that the events it generates are the most complex in the language. Most of complexity is hidden away in the attribute values, so for those of you writing a Pod formatter that produces a non-hypertextual format, you can just ignore the attributes and treat an L event structure like a formatting element that (presumably) doesn't actually produce a change in formatting. That is, the content of the L event structure (as opposed to its attributes) is always what text should be displayed.
There are, at first glance, three kinds of L links: URL, man, and pod.
When a L<*some\_url*> code is parsed, it produces this event structure:
```
<L content-implicit="yes" raw="that_url" to="that_url" type="url">
that_url
</L>
```
The `type="url"` attribute is always specified for this type of L code.
For example, this Pod source:
```
L<http://www.perl.com/CPAN/authors/>
```
produces this event structure:
```
<L content-implicit="yes" raw="http://www.perl.com/CPAN/authors/" to="http://www.perl.com/CPAN/authors/" type="url">
http://www.perl.com/CPAN/authors/
</L>
```
When a L<*manpage(section)*> code is parsed (and these are fairly rare and not terribly useful), it produces this event structure:
```
<L content-implicit="yes" raw="manpage(section)" to="manpage(section)" type="man">
manpage(section)
</L>
```
The `type="man"` attribute is always specified for this type of L code.
For example, this Pod source:
```
L<crontab(5)>
```
produces this event structure:
```
<L content-implicit="yes" raw="crontab(5)" to="crontab(5)" type="man">
crontab(5)
</L>
```
In the rare cases where a man page link has a section specified, that text appears in a *section* attribute. For example, this Pod source:
```
L<crontab(5)/"ENVIRONMENT">
```
will produce this event structure:
```
<L content-implicit="yes" raw="crontab(5)/"ENVIRONMENT"" section="ENVIRONMENT" to="crontab(5)" type="man">
"ENVIRONMENT" in crontab(5)
</L>
```
In the rare case where the Pod document has code like L<*sometext*|*manpage(section)*>, then the *sometext* will appear as the content of the element, the *manpage(section)* text will appear only as the value of the *to* attribute, and there will be no `content-implicit="yes"` attribute (whose presence means that the Pod parser had to infer what text should appear as the link text -- as opposed to cases where that attribute is absent, which means that the Pod parser did *not* have to infer the link text, because that L code explicitly specified some link text.)
For example, this Pod source:
```
L<hell itself!|crontab(5)>
```
will produce this event structure:
```
<L raw="hell itself!|crontab(5)" to="crontab(5)" type="man">
hell itself!
</L>
```
The last type of L structure is for links to/within Pod documents. It is the most complex because it can have a *to* attribute, *or* a *section* attribute, or both. The `type="pod"` attribute is always specified for this type of L code.
In the most common case, the simple case of a L<podpage> code produces this event structure:
```
<L content-implicit="yes" raw="podpage" to="podpage" type="pod">
podpage
</L>
```
For example, this Pod source:
```
L<Net::Ping>
```
produces this event structure:
```
<L content-implicit="yes" raw="Net::Ping" to="Net::Ping" type="pod">
Net::Ping
</L>
```
In cases where there is link-text explicitly specified, it is to be found in the content of the element (and not the attributes), just as with the L<*sometext*|*manpage(section)*> case discussed above. For example, this Pod source:
```
L<Perl Error Messages|perldiag>
```
produces this event structure:
```
<L raw="Perl Error Messages|perldiag" to="perldiag" type="pod">
Perl Error Messages
</L>
```
In cases of links to a section in the current Pod document, there is a *section* attribute instead of a *to* attribute. For example, this Pod source:
```
L</"Member Data">
```
produces this event structure:
```
<L content-implicit="yes" raw="/"Member Data"" section="Member Data" type="pod">
"Member Data"
</L>
```
As another example, this Pod source:
```
L<the various attributes|/"Member Data">
```
produces this event structure:
```
<L raw="the various attributes|/"Member Data"" section="Member Data" type="pod">
the various attributes
</L>
```
In cases of links to a section in a different Pod document, there are both a *section* attribute and a <to> attribute. For example, this Pod source:
```
L<perlsyn/"Basic BLOCKs and Switch Statements">
```
produces this event structure:
```
<L content-implicit="yes" raw="perlsyn/"Basic BLOCKs and Switch Statements"" section="Basic BLOCKs and Switch Statements" to="perlsyn" type="pod">
"Basic BLOCKs and Switch Statements" in perlsyn
</L>
```
As another example, this Pod source:
```
L<SWITCH statements|perlsyn/"Basic BLOCKs and Switch Statements">
```
produces this event structure:
```
<L raw="SWITCH statements|perlsyn/"Basic BLOCKs and Switch Statements"" section="Basic BLOCKs and Switch Statements" to="perlsyn" type="pod">
SWITCH statements
</L>
```
Incidentally, note that we do not distinguish between these syntaxes:
```
L</"Member Data">
L<"Member Data">
L</Member Data>
L<Member Data> [deprecated syntax]
```
That is, they all produce the same event structure (for the most part), namely:
```
<L content-implicit="yes" raw="$depends_on_syntax" section="Member Data" type="pod">
"Member Data"
</L>
```
The *raw* attribute depends on what the raw content of the `L<>` is, so that is why the event structure is the same "for the most part".
If you have not guessed it yet, the *raw* attribute contains the raw, original, unescaped content of the `L<>` formatting code. In addition to the examples above, take notice of the following event structure produced by the following `L<>` formatting code.
```
L<click B<here>|page/About the C<-M> switch>
<L raw="click B<here>|page/About the C<-M> switch" section="About the -M switch" to="page" type="pod">
click B<here>
</L>
```
Specifically, notice that the formatting codes are present and unescaped in *raw*.
There is a known bug in the *raw* attribute where any surrounding whitespace is condensed into a single ' '. For example, given L< link>, *raw* will be " link".
events with an element\_name of E or Z While there are Pod codes E<...> and Z<>, these *do not* produce any E or Z events -- that is, there are no such events as E or Z.
events with an element\_name of Verbatim When a Pod verbatim paragraph (AKA "codeblock") is parsed, it produces this event structure:
```
<Verbatim start_line="543" xml:space="preserve">
...text...
</Verbatim>
```
The value of the *start\_line* attribute will be the line number of the first line of this verbatim block. The *xml:space* attribute is always present, and always has the value "preserve".
The text content will have tabs already expanded.
events with an element\_name of head1 .. head4 When a "=head1 ..." directive is parsed, it produces this event structure:
```
<head1>
...stuff...
</head1>
```
For example, a directive consisting of this:
```
=head1 Options to C<new> et al.
```
will produce this event structure:
```
<head1 start_line="543">
Options to
<C>
new
</C>
et al.
</head1>
```
"=head2" through "=head4" directives are the same, except for the element names in the event structure.
events with an element\_name of encoding In the default case, the events corresponding to `=encoding` directives are not emitted. They are emitted if `keep_encoding_directive` is true. In that case they produce event structures like ["events with an element\_name of head1 .. head4"](#events-with-an-element_name-of-head1-..-head4) above.
events with an element\_name of over-bullet When an "=over ... =back" block is parsed where the items are a bulleted list, it will produce this event structure:
```
<over-bullet indent="4" start_line="543">
<item-bullet start_line="545">
...Stuff...
</item-bullet>
...more item-bullets...
</over-bullet fake-closer="1">
```
The attribute *fake-closer* is only present if it is a true value; it is not present if it is a false value. It is shown in the above example to illustrate where the attribute is (in the **closing** tag). It signifies that the `=over` did not have a matching `=back`, and thus Pod::Simple had to create a fake closer.
For example, this Pod source:
```
=over
=item *
Something
=back
```
Would produce an event structure that does **not** have the *fake-closer* attribute, whereas this Pod source:
```
=over
=item *
Gasp! An unclosed =over block!
```
would. The rest of the over-\* examples will not demonstrate this attribute, but they all can have it. See <Pod::Checker>'s source for an example of this attribute being used.
The value of the *indent* attribute is whatever value is after the "=over" directive, as in "=over 8". If no such value is specified in the directive, then the *indent* attribute has the value "4".
For example, this Pod source:
```
=over
=item *
Stuff
=item *
Bar I<baz>!
=back
```
produces this event structure:
```
<over-bullet indent="4" start_line="10">
<item-bullet start_line="12">
Stuff
</item-bullet>
<item-bullet start_line="14">
Bar <I>baz</I>!
</item-bullet>
</over-bullet>
```
events with an element\_name of over-number When an "=over ... =back" block is parsed where the items are a numbered list, it will produce this event structure:
```
<over-number indent="4" start_line="543">
<item-number number="1" start_line="545">
...Stuff...
</item-number>
...more item-number...
</over-bullet>
```
This is like the "over-bullet" event structure; but note that the contents are "item-number" instead of "item-bullet", and note that they will have a "number" attribute, which some formatters/processors may ignore (since, for example, there's no need for it in HTML when producing an "<UL><LI>...</LI>...</UL>" structure), but which any processor may use.
Note that the values for the *number* attributes of "item-number" elements in a given "over-number" area *will* start at 1 and go up by one each time. If the Pod source doesn't follow that order (even though it really should!), whatever numbers it has will be ignored (with the correct values being put in the *number* attributes), and an error message might be issued to the user.
events with an element\_name of over-text These events are somewhat unlike the other over-\* structures, as far as what their contents are. When an "=over ... =back" block is parsed where the items are a list of text "subheadings", it will produce this event structure:
```
<over-text indent="4" start_line="543">
<item-text>
...stuff...
</item-text>
...stuff (generally Para or Verbatim elements)...
<item-text>
...more item-text and/or stuff...
</over-text>
```
The *indent* and *fake-closer* attributes are as with the other over-\* events.
For example, this Pod source:
```
=over
=item Foo
Stuff
=item Bar I<baz>!
Quux
=back
```
produces this event structure:
```
<over-text indent="4" start_line="20">
<item-text start_line="22">
Foo
</item-text>
<Para start_line="24">
Stuff
</Para>
<item-text start_line="26">
Bar
<I>
baz
</I>
!
</item-text>
<Para start_line="28">
Quux
</Para>
</over-text>
```
events with an element\_name of over-block These events are somewhat unlike the other over-\* structures, as far as what their contents are. When an "=over ... =back" block is parsed where there are no items, it will produce this event structure:
```
<over-block indent="4" start_line="543">
...stuff (generally Para or Verbatim elements)...
</over-block>
```
The *indent* and *fake-closer* attributes are as with the other over-\* events.
For example, this Pod source:
```
=over
For cutting off our trade with all parts of the world
For transporting us beyond seas to be tried for pretended offenses
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
```
will produce this event structure:
```
<over-block indent="4" start_line="2">
<Para start_line="4">
For cutting off our trade with all parts of the world
</Para>
<Para start_line="6">
For transporting us beyond seas to be tried for pretended offenses
</Para>
<Para start_line="8">
He is at this time transporting large armies of [...more text...]
</Para>
</over-block>
```
events with an element\_name of over-empty **Note: These events are only triggered if `parse_empty_lists()` is set to a true value.**
These events are somewhat unlike the other over-\* structures, as far as what their contents are. When an "=over ... =back" block is parsed where there is no content, it will produce this event structure:
```
<over-empty indent="4" start_line="543">
</over-empty>
```
The *indent* and *fake-closer* attributes are as with the other over-\* events.
For example, this Pod source:
```
=over
=over
=back
=back
```
will produce this event structure:
```
<over-block indent="4" start_line="1">
<over-empty indent="4" start_line="3">
</over-empty>
</over-block>
```
Note that the outer `=over` is a block because it has no `=item`s but still has content: the inner `=over`. The inner `=over`, in turn, is completely empty, and is treated as such.
events with an element\_name of item-bullet See ["events with an element\_name of over-bullet"](#events-with-an-element_name-of-over-bullet), above.
events with an element\_name of item-number See ["events with an element\_name of over-number"](#events-with-an-element_name-of-over-number), above.
events with an element\_name of item-text See ["events with an element\_name of over-text"](#events-with-an-element_name-of-over-text), above.
events with an element\_name of for TODO...
events with an element\_name of Data TODO...
More Pod::Simple Methods
-------------------------
Pod::Simple provides a lot of methods that aren't generally interesting to the end user of an existing Pod formatter, but some of which you might find useful in writing a Pod formatter. They are listed below. The first several methods (the accept\_\* methods) are for declaring the capabilities of your parser, notably what `=for *targetname*` sections it's interested in, what extra N<...> codes it accepts beyond the ones described in the *perlpod*.
`$parser->accept_targets( *SOMEVALUE* )`
As the parser sees sections like:
```
=for html <img src="fig1.jpg">
```
or
```
=begin html
<img src="fig1.jpg">
=end html
```
...the parser will ignore these sections unless your subclass has specified that it wants to see sections targeted to "html" (or whatever the formatter name is).
If you want to process all sections, even if they're not targeted for you, call this before you start parsing:
```
$parser->accept_targets('*');
```
`$parser->accept_targets_as_text( *SOMEVALUE* )`
This is like accept\_targets, except that it specifies also that the content of sections for this target should be treated as Pod text even if the target name in "=for *targetname*" doesn't start with a ":".
At time of writing, I don't think you'll need to use this.
`$parser->accept_codes( *Codename*, *Codename*... )`
This tells the parser that you accept additional formatting codes, beyond just the standard ones (I B C L F S X, plus the two weird ones you don't actually see in the parse tree, Z and E). For example, to also accept codes "N", "R", and "W":
```
$parser->accept_codes( qw( N R W ) );
```
**TODO: document how this interacts with =extend, and long element names**
`$parser->accept_directive_as_data( *directive\_name* )`
`$parser->accept_directive_as_verbatim( *directive\_name* )`
`$parser->accept_directive_as_processed( *directive\_name* )`
In the unlikely situation that you need to tell the parser that you will accept additional directives ("=foo" things), you need to first set the parser to treat its content as data (i.e., not really processed at all), or as verbatim (mostly just expanding tabs), or as processed text (parsing formatting codes like B<...>).
For example, to accept a new directive "=method", you'd presumably use:
```
$parser->accept_directive_as_processed("method");
```
so that you could have Pod lines like:
```
=method I<$whatever> thing B<um>
```
Making up your own directives breaks compatibility with other Pod formatters, in a way that using "=for *target* ..." lines doesn't; however, you may find this useful if you're making a Pod superset format where you don't need to worry about compatibility.
`$parser->nbsp_for_S( *BOOLEAN* );`
Setting this attribute to a true value (and by default it is false) will turn "S<...>" sequences into sequences of words separated by `\xA0` (non-breaking space) characters. For example, it will take this:
```
I like S<Dutch apple pie>, don't you?
```
and treat it as if it were:
```
I like DutchE<nbsp>appleE<nbsp>pie, don't you?
```
This is handy for output formats that don't have anything quite like an "S<...>" code, but which do have a code for non-breaking space.
There is currently no method for going the other way; but I can probably provide one upon request.
`$parser->version_report()`
This returns a string reporting the $VERSION value from your module (and its classname) as well as the $VERSION value of Pod::Simple. Note that <perlpodspec> requires output formats (wherever possible) to note this detail in a comment in the output format. For example, for some kind of SGML output format:
```
print OUT "<!-- \n", $parser->version_report, "\n -->";
```
`$parser->pod_para_count()`
This returns the count of Pod paragraphs seen so far.
`$parser->line_count()`
This is the current line number being parsed. But you might find the "line\_number" event attribute more accurate, when it is present.
`$parser->nix_X_codes( *SOMEVALUE* )`
This attribute, when set to a true value (and it is false by default) ignores any "X<...>" sequences in the document being parsed. Many formats don't actually use the content of these codes, so have no reason to process them.
`$parser->keep_encoding_directive( *SOMEVALUE* )`
This attribute, when set to a true value (it is false by default) will keep `=encoding` and its content in the event structure. Most formats don't actually need to process the content of an `=encoding` directive, even when this directive sets the encoding and the processor makes use of the encoding information. Indeed, it is possible to know the encoding without processing the directive content.
`$parser->merge_text( *SOMEVALUE* )`
This attribute, when set to a true value (and it is false by default) makes sure that only one event (or token, or node) will be created for any single contiguous sequence of text. For example, consider this somewhat contrived example:
```
I just LOVE Z<>hotE<32>apple pie!
```
When that is parsed and events are about to be called on it, it may actually seem to be four different text events, one right after another: one event for "I just LOVE ", one for "hot", one for " ", and one for "apple pie!". But if you have merge\_text on, then you're guaranteed that it will be fired as one text event: "I just LOVE hot apple pie!".
`$parser->code_handler( *CODE\_REF* )`
This specifies code that should be called when a code line is seen (i.e., a line outside of the Pod). Normally this is undef, meaning that no code should be called. If you provide a routine, it should start out like this:
```
sub get_code_line { # or whatever you'll call it
my($line, $line_number, $parser) = @_;
...
}
```
Note, however, that sometimes the Pod events aren't processed in exactly the same order as the code lines are -- i.e., if you have a file with Pod, then code, then more Pod, sometimes the code will be processed (via whatever you have code\_handler call) before the all of the preceding Pod has been processed.
`$parser->cut_handler( *CODE\_REF* )`
This is just like the code\_handler attribute, except that it's for "=cut" lines, not code lines. The same caveats apply. "=cut" lines are unlikely to be interesting, but this is included for completeness.
`$parser->pod_handler( *CODE\_REF* )`
This is just like the code\_handler attribute, except that it's for "=pod" lines, not code lines. The same caveats apply. "=pod" lines are unlikely to be interesting, but this is included for completeness.
`$parser->whiteline_handler( *CODE\_REF* )`
This is just like the code\_handler attribute, except that it's for lines that are seemingly blank but have whitespace (" " and/or "\t") on them, not code lines. The same caveats apply. These lines are unlikely to be interesting, but this is included for completeness.
`$parser->whine( *linenumber*, *complaint string* )`
This notes a problem in the Pod, which will be reported in the "Pod Errors" section of the document and/or sent to STDERR, depending on the values of the attributes `no_whining`, `no_errata_section`, and `complain_stderr`.
`$parser->scream( *linenumber*, *complaint string* )`
This notes an error like `whine` does, except that it is not suppressible with `no_whining`. This should be used only for very serious errors.
`$parser->source_dead(1)`
This aborts parsing of the current document, by switching on the flag that indicates that EOF has been seen. In particularly drastic cases, you might want to do this. It's rather nicer than just calling `die`!
`$parser->hide_line_numbers( *SOMEVALUE* )`
Some subclasses that indiscriminately dump event attributes (well, except for ones beginning with "~") can use this object attribute for refraining to dump the "start\_line" attribute.
`$parser->no_whining( *SOMEVALUE* )`
This attribute, if set to true, will suppress reports of non-fatal error messages. The default value is false, meaning that complaints *are* reported. How they get reported depends on the values of the attributes `no_errata_section` and `complain_stderr`.
`$parser->no_errata_section( *SOMEVALUE* )`
This attribute, if set to true, will suppress generation of an errata section. The default value is false -- i.e., an errata section will be generated.
`$parser->complain_stderr( *SOMEVALUE* )`
This attribute, if set to true will send complaints to STDERR. The default value is false -- i.e., complaints do not go to STDERR.
`$parser->bare_output( *SOMEVALUE* )`
Some formatter subclasses use this as a flag for whether output should have prologue and epilogue code omitted. For example, setting this to true for an HTML formatter class should omit the "<html><head><title>...</title><body>..." prologue and the "</body></html>" epilogue.
If you want to set this to true, you should probably also set `no_whining` or at least `no_errata_section` to true.
`$parser->preserve_whitespace( *SOMEVALUE* )`
If you set this attribute to a true value, the parser will try to preserve whitespace in the output. This means that such formatting conventions as two spaces after periods will be preserved by the parser. This is primarily useful for output formats that treat whitespace as significant (such as text or \*roff, but not HTML).
`$parser->parse_empty_lists( *SOMEVALUE* )`
If this attribute is set to true, the parser will not ignore empty `=over`/`=back` blocks. The type of `=over` will be *empty*, documented above, ["events with an element\_name of over-empty"](#events-with-an-element_name-of-over-empty).
SEE ALSO
---------
<Pod::Simple> -- event-based Pod-parsing framework
<Pod::Simple::Methody> -- like Pod::Simple, but each sort of event calls its own method (like `start_head3`)
<Pod::Simple::PullParser> -- a Pod-parsing framework like Pod::Simple, but with a token-stream interface
<Pod::Simple::SimpleTree> -- a Pod-parsing framework like Pod::Simple, but with a tree interface
<Pod::Simple::Checker> -- a simple Pod::Simple subclass that reads documents, and then makes a plaintext report of any errors found in the document
<Pod::Simple::DumpAsXML> -- for dumping Pod documents as tidily indented XML, showing each event on its own line
<Pod::Simple::XMLOutStream> -- dumps a Pod document as XML (without introducing extra whitespace as Pod::Simple::DumpAsXML does).
<Pod::Simple::DumpAsText> -- for dumping Pod documents as tidily indented text, showing each event on its own line
<Pod::Simple::LinkSection> -- class for objects representing the values of the TODO and TODO attributes of L<...> elements
<Pod::Escapes> -- the module that Pod::Simple uses for evaluating E<...> content
<Pod::Simple::Text> -- a simple plaintext formatter for Pod
<Pod::Simple::TextContent> -- like Pod::Simple::Text, but makes no effort for indent or wrap the text being formatted
<Pod::Simple::HTML> -- a simple HTML formatter for Pod
<perlpod>
<perlpodspec>
<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!
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]`
| programming_docs |
perl Pod::Perldoc::BaseTo Pod::Perldoc::BaseTo
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::BaseTo - Base for Pod::Perldoc formatters
SYNOPSIS
--------
```
package Pod::Perldoc::ToMyFormat;
use parent qw( Pod::Perldoc::BaseTo );
...
```
DESCRIPTION
-----------
This package is meant as a base of Pod::Perldoc formatters, like <Pod::Perldoc::ToText>, <Pod::Perldoc::ToMan>, etc.
It provides default implementations for the methods
```
is_pageable
write_with_binmode
output_extension
_perldoc_elem
```
The concrete formatter must implement
```
new
parse_from_file
```
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 Test2::API::InterceptResult::Hub Test2::API::InterceptResult::Hub
================================
CONTENTS
--------
* [NAME](#NAME)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::InterceptResult::Hub - Hub used by InterceptResult.
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::IPC::Driver Test2::IPC::Driver
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [LOADING DRIVERS](#LOADING-DRIVERS)
* [WRITING DRIVERS](#WRITING-DRIVERS)
+ [METHODS SUBCLASSES MUST IMPLEMENT](#METHODS-SUBCLASSES-MUST-IMPLEMENT)
+ [METHODS SUBCLASSES MAY IMPLEMENT OR OVERRIDE](#METHODS-SUBCLASSES-MAY-IMPLEMENT-OR-OVERRIDE)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::IPC::Driver - Base class for Test2 IPC drivers.
SYNOPSIS
--------
```
package Test2::IPC::Driver::MyDriver;
use base 'Test2::IPC::Driver';
...
```
METHODS
-------
$self->abort($msg) If an IPC encounters a fatal error it should use this. This will print the message to STDERR with `'IPC Fatal Error: '` prefixed to it, then it will forcefully exit 255. IPC errors may occur in threads or processes other than the main one, this method provides the best chance of the harness noticing the error.
$self->abort\_trace($msg) This is the same as `$ipc->abort($msg)` except that it uses `Carp::longmess` to add a stack trace to the message.
LOADING DRIVERS
----------------
Test2::IPC::Driver has an `import()` method. All drivers inherit this import method. This import method registers the driver.
In most cases you just need to load the desired IPC driver to make it work. You should load this driver as early as possible. A warning will be issued if you load it too late for it to be effective.
```
use Test2::IPC::Driver::MyDriver;
...
```
WRITING DRIVERS
----------------
```
package Test2::IPC::Driver::MyDriver;
use strict;
use warnings;
use base 'Test2::IPC::Driver';
sub is_viable {
return 0 if $^O eq 'win32'; # Will not work on windows.
return 1;
}
sub add_hub {
my $self = shift;
my ($hid) = @_;
... # Make it possible to contact the hub
}
sub drop_hub {
my $self = shift;
my ($hid) = @_;
... # Nothing should try to reach the hub anymore.
}
sub send {
my $self = shift;
my ($hid, $e, $global) = @_;
... # Send the event to the proper hub.
# This may notify other procs/threads that there is a pending event.
Test2::API::test2_ipc_set_pending($uniq_val);
}
sub cull {
my $self = shift;
my ($hid) = @_;
my @events = ...; # Here is where you get the events for the hub
return @events;
}
sub waiting {
my $self = shift;
... # Notify all listening procs and threads that the main
... # process/thread is waiting for them to finish.
}
1;
```
###
METHODS SUBCLASSES MUST IMPLEMENT
$ipc->is\_viable This should return true if the driver works in the current environment. This should return false if it does not. This is a CLASS method.
$ipc->add\_hub($hid) This is used to alert the driver that a new hub is expecting events. The driver should keep track of the process and thread ids, the hub should only be dropped by the proc+thread that started it.
```
sub add_hub {
my $self = shift;
my ($hid) = @_;
... # Make it possible to contact the hub
}
```
$ipc->drop\_hub($hid) This is used to alert the driver that a hub is no longer accepting events. The driver should keep track of the process and thread ids, the hub should only be dropped by the proc+thread that started it (This is the drivers responsibility to enforce).
```
sub drop_hub {
my $self = shift;
my ($hid) = @_;
... # Nothing should try to reach the hub anymore.
}
```
$ipc->send($hid, $event);
$ipc->send($hid, $event, $global); Used to send events from the current process/thread to the specified hub in its process+thread.
```
sub send {
my $self = shift;
my ($hid, $e) = @_;
... # Send the event to the proper hub.
# This may notify other procs/threads that there is a pending event.
Test2::API::test2_ipc_set_pending($uniq_val);
}
```
If `$global` is true then the driver should send the event to all hubs in all processes and threads.
@events = $ipc->cull($hid) Used to collect events that have been sent to the specified hub.
```
sub cull {
my $self = shift;
my ($hid) = @_;
my @events = ...; # Here is where you get the events for the hub
return @events;
}
```
$ipc->waiting() This is called in the parent process when it is complete and waiting for all child processes and threads to complete.
```
sub waiting {
my $self = shift;
... # Notify all listening procs and threads that the main
... # process/thread is waiting for them to finish.
}
```
###
METHODS SUBCLASSES MAY IMPLEMENT OR OVERRIDE
$ipc->driver\_abort($msg) This is a hook called by `Test2::IPC::Driver->abort()`. This is your chance to cleanup when an abort happens. You cannot prevent the abort, but you can gracefully except it.
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 Time::tm Time::tm
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
NAME
----
Time::tm - internal object used by Time::gmtime and Time::localtime
SYNOPSIS
--------
Don't use this module directly.
DESCRIPTION
-----------
This module is used internally as a base class by Time::localtime And Time::gmtime functions. It creates a Time::tm struct object which is addressable just like's C's tm structure from *time.h*; namely with sec, min, hour, mday, mon, year, wday, yday, and isdst.
This class is an internal interface only.
AUTHOR
------
Tom Christiansen
perl mro mro
===
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OVERVIEW](#OVERVIEW)
* [The C3 MRO](#The-C3-MRO)
+ [What is C3?](#What-is-C3?)
+ [How does C3 work](#How-does-C3-work)
* [Functions](#Functions)
+ [mro::get\_linear\_isa($classname[, $type])](#mro::get_linear_isa(%24classname%5B,-%24type%5D))
+ [mro::set\_mro ($classname, $type)](#mro::set_mro-(%24classname,-%24type))
+ [mro::get\_mro($classname)](#mro::get_mro(%24classname))
+ [mro::get\_isarev($classname)](#mro::get_isarev(%24classname))
+ [mro::is\_universal($classname)](#mro::is_universal(%24classname))
+ [mro::invalidate\_all\_method\_caches()](#mro::invalidate_all_method_caches())
+ [mro::method\_changed\_in($classname)](#mro::method_changed_in(%24classname))
+ [mro::get\_pkg\_gen($classname)](#mro::get_pkg_gen(%24classname))
+ [next::method](#next::method)
+ [next::can](#next::can)
+ [maybe::next::method](#maybe::next::method)
* [SEE ALSO](#SEE-ALSO)
+ [The original Dylan paper](#The-original-Dylan-paper)
+ [Python 2.3 MRO](#Python-2.3-MRO)
+ [Class::C3](#Class::C3)
* [AUTHOR](#AUTHOR)
NAME
----
mro - Method Resolution Order
SYNOPSIS
--------
```
use mro; # enables next::method and friends globally
use mro 'dfs'; # enable DFS MRO for this class (Perl default)
use mro 'c3'; # enable C3 MRO for this class
```
DESCRIPTION
-----------
The "mro" namespace provides several utilities for dealing with method resolution order and method caching in general.
These interfaces are only available in Perl 5.9.5 and higher. See <MRO::Compat> on CPAN for a mostly forwards compatible implementation for older Perls.
OVERVIEW
--------
It's possible to change the MRO of a given class either by using `use mro` as shown in the synopsis, or by using the ["mro::set\_mro"](#mro%3A%3Aset_mro) function below.
The special methods `next::method`, `next::can`, and `maybe::next::method` are not available until this `mro` module has been loaded via `use` or `require`.
The C3 MRO
-----------
In addition to the traditional Perl default MRO (depth first search, called `DFS` here), Perl now offers the C3 MRO as well. Perl's support for C3 is based on the work done in Stevan Little's module <Class::C3>, and most of the C3-related documentation here is ripped directly from there.
###
What is C3?
C3 is the name of an algorithm which aims to provide a sane method resolution order under multiple inheritance. It was first introduced in the language Dylan (see links in the ["SEE ALSO"](#SEE-ALSO) section), and then later adopted as the preferred MRO (Method Resolution Order) for the new-style classes in Python 2.3. Most recently it has been adopted as the "canonical" MRO for Raku classes.
###
How does C3 work
C3 works by always preserving local precedence ordering. This essentially means that no class will appear before any of its subclasses. Take, for instance, the classic diamond inheritance pattern:
```
<A>
/ \
<B> <C>
\ /
<D>
```
The standard Perl 5 MRO would be (D, B, A, C). The result being that **A** appears before **C**, even though **C** is the subclass of **A**. The C3 MRO algorithm however, produces the following order: (D, B, C, A), which does not have this issue.
This example is fairly trivial; for more complex cases and a deeper explanation, see the links in the ["SEE ALSO"](#SEE-ALSO) section.
Functions
---------
###
mro::get\_linear\_isa($classname[, $type])
Returns an arrayref which is the linearized MRO of the given class. Uses whichever MRO is currently in effect for that class by default, or the given MRO (either `c3` or `dfs` if specified as `$type`).
The linearized MRO of a class is an ordered array of all of the classes one would search when resolving a method on that class, starting with the class itself.
If the requested class doesn't yet exist, this function will still succeed, and return `[ $classname ]`
Note that `UNIVERSAL` (and any members of `UNIVERSAL`'s MRO) are not part of the MRO of a class, even though all classes implicitly inherit methods from `UNIVERSAL` and its parents.
###
mro::set\_mro ($classname, $type)
Sets the MRO of the given class to the `$type` argument (either `c3` or `dfs`).
###
mro::get\_mro($classname)
Returns the MRO of the given class (either `c3` or `dfs`).
###
mro::get\_isarev($classname)
Gets the `mro_isarev` for this class, returned as an arrayref of class names. These are every class that "isa" the given class name, even if the isa relationship is indirect. This is used internally by the MRO code to keep track of method/MRO cache invalidations.
As with `mro::get_linear_isa` above, `UNIVERSAL` is special. `UNIVERSAL` (and parents') isarev lists do not include every class in existence, even though all classes are effectively descendants for method inheritance purposes.
###
mro::is\_universal($classname)
Returns a boolean status indicating whether or not the given classname is either `UNIVERSAL` itself, or one of `UNIVERSAL`'s parents by `@ISA` inheritance.
Any class for which this function returns true is "universal" in the sense that all classes potentially inherit methods from it.
###
mro::invalidate\_all\_method\_caches()
Increments `PL_sub_generation`, which invalidates method caching in all packages.
###
mro::method\_changed\_in($classname)
Invalidates the method cache of any classes dependent on the given class. This is not normally necessary. The only known case where pure perl code can confuse the method cache is when you manually install a new constant subroutine by using a readonly scalar value, like the internals of <constant> do. If you find another case, please report it so we can either fix it or document the exception here.
###
mro::get\_pkg\_gen($classname)
Returns an integer which is incremented every time a real local method in the package `$classname` changes, or the local `@ISA` of `$classname` is modified.
This is intended for authors of modules which do lots of class introspection, as it allows them to very quickly check if anything important about the local properties of a given class have changed since the last time they looked. It does not increment on method/`@ISA` changes in superclasses.
It's still up to you to seek out the actual changes, and there might not actually be any. Perhaps all of the changes since you last checked cancelled each other out and left the package in the state it was in before.
This integer normally starts off at a value of `1` when a package stash is instantiated. Calling it on packages whose stashes do not exist at all will return `0`. If a package stash is completely deleted (not a normal occurrence, but it can happen if someone does something like `undef %PkgName::`), the number will be reset to either `0` or `1`, depending on how completely the package was wiped out.
###
next::method
This is somewhat like `SUPER`, but it uses the C3 method resolution order to get better consistency in multiple inheritance situations. Note that while inheritance in general follows whichever MRO is in effect for the given class, `next::method` only uses the C3 MRO.
One generally uses it like so:
```
sub some_method {
my $self = shift;
my $superclass_answer = $self->next::method(@_);
return $superclass_answer + 1;
}
```
Note that you don't (re-)specify the method name. It forces you to always use the same method name as the method you started in.
It can be called on an object or a class, of course.
The way it resolves which actual method to call is:
1. First, it determines the linearized C3 MRO of the object or class it is being called on.
2. Then, it determines the class and method name of the context it was invoked from.
3. Finally, it searches down the C3 MRO list until it reaches the contextually enclosing class, then searches further down the MRO list for the next method with the same name as the contextually enclosing method.
Failure to find a next method will result in an exception being thrown (see below for alternatives).
This is substantially different than the behavior of `SUPER` under complex multiple inheritance. (This becomes obvious when one realizes that the common superclasses in the C3 linearizations of a given class and one of its parents will not always be ordered the same for both.)
**Caveat**: Calling `next::method` from methods defined outside the class:
There is an edge case when using `next::method` from within a subroutine which was created in a different module than the one it is called from. It sounds complicated, but it really isn't. Here is an example which will not work correctly:
```
*Foo::foo = sub { (shift)->next::method(@_) };
```
The problem exists because the anonymous subroutine being assigned to the `*Foo::foo` glob will show up in the call stack as being called `__ANON__` and not `foo` as you might expect. Since `next::method` uses `caller` to find the name of the method it was called in, it will fail in this case.
But fear not, there's a simple solution. The module `Sub::Name` will reach into the perl internals and assign a name to an anonymous subroutine for you. Simply do this:
```
use Sub::Name 'subname';
*Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };
```
and things will Just Work.
###
next::can
This is similar to `next::method`, but just returns either a code reference or `undef` to indicate that no further methods of this name exist.
###
maybe::next::method
In simple cases, it is equivalent to:
```
$self->next::method(@_) if $self->next::can;
```
But there are some cases where only this solution works (like `goto &maybe::next::method`);
SEE ALSO
---------
###
The original Dylan paper
<http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.19.3910&rep=rep1&type=pdf>
###
Python 2.3 MRO
<https://www.python.org/download/releases/2.3/mro/>
###
Class::C3
<Class::C3>
AUTHOR
------
Brandon L. Black, <[email protected]>
Based on Stevan Little's <Class::C3>
perl instmodsh instmodsh
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
instmodsh - A shell to examine installed modules
SYNOPSIS
--------
```
instmodsh
```
DESCRIPTION
-----------
A little interface to ExtUtils::Installed to examine installed modules, validate your packlists and even create a tarball from an installed module.
SEE ALSO
---------
ExtUtils::Installed
perl Benchmark Benchmark
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods](#Methods)
+ [Standard Exports](#Standard-Exports)
+ [Optional Exports](#Optional-Exports)
+ [:hireswallclock](#:hireswallclock)
* [Benchmark Object](#Benchmark-Object)
* [NOTES](#NOTES)
* [EXAMPLES](#EXAMPLES)
* [INHERITANCE](#INHERITANCE)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
NAME
----
Benchmark - benchmark running times of Perl code
SYNOPSIS
--------
```
use Benchmark qw(:all) ;
timethis ($count, "code");
# Use Perl code in strings...
timethese($count, {
'Name1' => '...code1...',
'Name2' => '...code2...',
});
# ... or use subroutine references.
timethese($count, {
'Name1' => sub { ...code1... },
'Name2' => sub { ...code2... },
});
# cmpthese can be used both ways as well
cmpthese($count, {
'Name1' => '...code1...',
'Name2' => '...code2...',
});
cmpthese($count, {
'Name1' => sub { ...code1... },
'Name2' => sub { ...code2... },
});
# ...or in two stages
$results = timethese($count,
{
'Name1' => sub { ...code1... },
'Name2' => sub { ...code2... },
},
'none'
);
cmpthese( $results ) ;
$t = timeit($count, '...other code...')
print "$count loops of other code took:",timestr($t),"\n";
$t = countit($time, '...other code...')
$count = $t->iters ;
print "$count loops of other code took:",timestr($t),"\n";
# enable hires wallclock timing if possible
use Benchmark ':hireswallclock';
```
DESCRIPTION
-----------
The Benchmark module encapsulates a number of routines to help you figure out how long it takes to execute some code.
timethis - run a chunk of code several times
timethese - run several chunks of code several times
cmpthese - print results of timethese as a comparison chart
timeit - run a chunk of code and see how long it goes
countit - see how many times a chunk of code runs in a given time
### Methods
new Returns the current time. Example:
```
use Benchmark;
$t0 = Benchmark->new;
# ... your code here ...
$t1 = Benchmark->new;
$td = timediff($t1, $t0);
print "the code took:",timestr($td),"\n";
```
debug Enables or disable debugging by setting the `$Benchmark::Debug` flag:
```
Benchmark->debug(1);
$t = timeit(10, ' 5 ** $Global ');
Benchmark->debug(0);
```
iters Returns the number of iterations.
###
Standard Exports
The following routines will be exported into your namespace if you use the Benchmark module:
timeit(COUNT, CODE) Arguments: COUNT is the number of times to run the loop, and CODE is the code to run. CODE may be either a code reference or a string to be eval'd; either way it will be run in the caller's package.
Returns: a Benchmark object.
timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] ) Time COUNT iterations of CODE. CODE may be a string to eval or a code reference; either way the CODE will run in the caller's package. Results will be printed to STDOUT as TITLE followed by the times. TITLE defaults to "timethis COUNT" if none is provided. STYLE determines the format of the output, as described for timestr() below.
The COUNT can be zero or negative: this means the *minimum number of CPU seconds* to run. A zero signifies the default of 3 seconds. For example to run at least for 10 seconds:
```
timethis(-10, $code)
```
or to run two pieces of code tests for at least 3 seconds:
```
timethese(0, { test1 => '...', test2 => '...'})
```
CPU seconds is, in UNIX terms, the user time plus the system time of the process itself, as opposed to the real (wallclock) time and the time spent by the child processes. Less than 0.1 seconds is not accepted (-0.01 as the count, for example, will cause a fatal runtime exception).
Note that the CPU seconds is the **minimum** time: CPU scheduling and other operating system factors may complicate the attempt so that a little bit more time is spent. The benchmark output will, however, also tell the number of `$code` runs/second, which should be a more interesting number than the actually spent seconds.
Returns a Benchmark object.
timethese ( COUNT, CODEHASHREF, [ STYLE ] ) The CODEHASHREF is a reference to a hash containing names as keys and either a string to eval or a code reference for each value. For each (KEY, VALUE) pair in the CODEHASHREF, this routine will call
```
timethis(COUNT, VALUE, KEY, STYLE)
```
The routines are called in string comparison order of KEY.
The COUNT can be zero or negative, see timethis().
Returns a hash reference of Benchmark objects, keyed by name.
timediff ( T1, T2 ) Returns the difference between two Benchmark times as a Benchmark object suitable for passing to timestr().
timestr ( TIMEDIFF, [ STYLE, [ FORMAT ] ] ) Returns a string that formats the times in the TIMEDIFF object in the requested STYLE. TIMEDIFF is expected to be a Benchmark object similar to that returned by timediff().
STYLE can be any of 'all', 'none', 'noc', 'nop' or 'auto'. 'all' shows each of the 5 times available ('wallclock' time, user time, system time, user time of children, and system time of children). 'noc' shows all except the two children times. 'nop' shows only wallclock and the two children times. 'auto' (the default) will act as 'all' unless the children times are both zero, in which case it acts as 'noc'. 'none' prevents output.
FORMAT is the [printf(3)](http://man.he.net/man3/printf)-style format specifier (without the leading '%') to use to print the times. It defaults to '5.2f'.
###
Optional Exports
The following routines will be exported into your namespace if you specifically ask that they be imported:
clearcache ( COUNT ) Clear the cached time for COUNT rounds of the null loop.
clearallcache ( ) Clear all cached times.
cmpthese ( COUNT, CODEHASHREF, [ STYLE ] )
cmpthese ( RESULTSHASHREF, [ STYLE ] ) Optionally calls timethese(), then outputs comparison chart. This:
```
cmpthese( -1, { a => "++\$i", b => "\$i *= 2" } ) ;
```
outputs a chart like:
```
Rate b a
b 2831802/s -- -61%
a 7208959/s 155% --
```
This chart is sorted from slowest to fastest, and shows the percent speed difference between each pair of tests.
`cmpthese` can also be passed the data structure that timethese() returns:
```
$results = timethese( -1,
{ a => "++\$i", b => "\$i *= 2" } ) ;
cmpthese( $results );
```
in case you want to see both sets of results. If the first argument is an unblessed hash reference, that is RESULTSHASHREF; otherwise that is COUNT.
Returns a reference to an ARRAY of rows, each row is an ARRAY of cells from the above chart, including labels. This:
```
my $rows = cmpthese( -1,
{ a => '++$i', b => '$i *= 2' }, "none" );
```
returns a data structure like:
```
[
[ '', 'Rate', 'b', 'a' ],
[ 'b', '2885232/s', '--', '-59%' ],
[ 'a', '7099126/s', '146%', '--' ],
]
```
**NOTE**: This result value differs from previous versions, which returned the `timethese()` result structure. If you want that, just use the two statement `timethese`...`cmpthese` idiom shown above.
Incidentally, note the variance in the result values between the two examples; this is typical of benchmarking. If this were a real benchmark, you would probably want to run a lot more iterations.
countit(TIME, CODE) Arguments: TIME is the minimum length of time to run CODE for, and CODE is the code to run. CODE may be either a code reference or a string to be eval'd; either way it will be run in the caller's package.
TIME is *not* negative. countit() will run the loop many times to calculate the speed of CODE before running it for TIME. The actual time run for will usually be greater than TIME due to system clock resolution, so it's best to look at the number of iterations divided by the times that you are concerned with, not just the iterations.
Returns: a Benchmark object.
disablecache ( ) Disable caching of timings for the null loop. This will force Benchmark to recalculate these timings for each new piece of code timed.
enablecache ( ) Enable caching of timings for the null loop. The time taken for COUNT rounds of the null loop will be calculated only once for each different COUNT used.
timesum ( T1, T2 ) Returns the sum of two Benchmark times as a Benchmark object suitable for passing to timestr().
###
:hireswallclock
If the Time::HiRes module has been installed, you can specify the special tag `:hireswallclock` for Benchmark (if Time::HiRes is not available, the tag will be silently ignored). This tag will cause the wallclock time to be measured in microseconds, instead of integer seconds. Note though that the speed computations are still conducted in CPU time, not wallclock time.
Benchmark Object
-----------------
Many of the functions in this module return a Benchmark object, or in the case of `timethese()`, a reference to a hash, the values of which are Benchmark objects. This is useful if you want to store or further process results from Benchmark functions.
Internally the Benchmark object holds timing values, described in ["NOTES"](#NOTES) below. The following methods can be used to access them:
cpu\_p Total CPU (User + System) of the main (parent) process.
cpu\_c Total CPU (User + System) of any children processes.
cpu\_a Total CPU of parent and any children processes.
real Real elapsed time "wallclock seconds".
iters Number of iterations run.
The following illustrates use of the Benchmark object:
```
$result = timethis(100000, sub { ... });
print "total CPU = ", $result->cpu_a, "\n";
```
NOTES
-----
The data is stored as a list of values from the time and times functions:
```
($real, $user, $system, $children_user, $children_system, $iters)
```
in seconds for the whole loop (not divided by the number of rounds).
The timing is done using time(3) and times(3).
Code is executed in the caller's package.
The time of the null loop (a loop with the same number of rounds but empty loop body) is subtracted from the time of the real loop.
The null loop times can be cached, the key being the number of rounds. The caching can be controlled using calls like these:
```
clearcache($key);
clearallcache();
disablecache();
enablecache();
```
Caching is off by default, as it can (usually slightly) decrease accuracy and does not usually noticeably affect runtimes.
EXAMPLES
--------
For example,
```
use Benchmark qw( cmpthese ) ;
$x = 3;
cmpthese( -5, {
a => sub{$x*$x},
b => sub{$x**2},
} );
```
outputs something like this:
```
Benchmark: running a, b, each for at least 5 CPU seconds...
Rate b a
b 1559428/s -- -62%
a 4152037/s 166% --
```
while
```
use Benchmark qw( timethese cmpthese ) ;
$x = 3;
$r = timethese( -5, {
a => sub{$x*$x},
b => sub{$x**2},
} );
cmpthese $r;
```
outputs something like this:
```
Benchmark: running a, b, each for at least 5 CPU seconds...
a: 10 wallclock secs ( 5.14 usr + 0.13 sys = 5.27 CPU) @ 3835055.60/s (n=20210743)
b: 5 wallclock secs ( 5.41 usr + 0.00 sys = 5.41 CPU) @ 1574944.92/s (n=8520452)
Rate b a
b 1574945/s -- -59%
a 3835056/s 144% --
```
INHERITANCE
-----------
Benchmark inherits from no other class, except of course from Exporter.
CAVEATS
-------
Comparing eval'd strings with code references will give you inaccurate results: a code reference will show a slightly slower execution time than the equivalent eval'd string.
The real time timing is done using time(2) and the granularity is therefore only one second.
Short tests may produce negative figures because perl can appear to take longer to execute the empty loop than a short test; try:
```
timethis(100,'1');
```
The system time of the null loop might be slightly more than the system time of the loop with the actual code and therefore the difference might end up being < 0.
SEE ALSO
---------
<Devel::NYTProf> - a Perl code profiler
AUTHORS
-------
Jarkko Hietaniemi <*[email protected]*>, Tim Bunce <*[email protected]*>
MODIFICATION HISTORY
---------------------
September 8th, 1994; by Tim Bunce.
March 28th, 1997; by Hugo van der Sanden: added support for code references and the already documented 'debug' method; revamped documentation.
April 04-07th, 1997: by Jarkko Hietaniemi, added the run-for-some-time functionality.
September, 1999; by Barrie Slaymaker: math fixes and accuracy and efficiency tweaks. Added cmpthese(). A result is now returned from timethese(). Exposed countit() (was runfor()).
December, 2001; by Nicholas Clark: make timestr() recognise the style 'none' and return an empty string. If cmpthese is calling timethese, make it pass the style in. (so that 'none' will suppress output). Make sub new dump its debugging output to STDERR, to be consistent with everything else. All bugs found while writing a regression test.
September, 2002; by Jarkko Hietaniemi: add ':hireswallclock' special tag.
February, 2004; by Chia-liang Kao: make cmpthese and timestr use time statistics for children instead of parent when the style is 'nop'.
November, 2007; by Christophe Grosjean: make cmpthese and timestr compute time consistently with style argument, default is 'all' not 'noc' any more.
| programming_docs |
perl pod2man pod2man
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [EXIT STATUS](#EXIT-STATUS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [EXAMPLES](#EXAMPLES)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
pod2man - Convert POD data to formatted \*roff input
SYNOPSIS
--------
pod2man [**--center**=*string*] [**--date**=*string*] [**--errors**=*style*] [**--fixed**=*font*] [**--fixedbold**=*font*] [**--fixeditalic**=*font*] [**--fixedbolditalic**=*font*] [**--name**=*name*] [**--nourls**] [**--official**] [**--release**=*version*] [**--section**=*manext*] [**--quotes**=*quotes*] [**--lquote**=*quote*] [**--rquote**=*quote*] [**--stderr**] [**--utf8**] [**--verbose**] [*input* [*output*] ...]
pod2man **--help**
DESCRIPTION
-----------
**pod2man** is a front-end for Pod::Man, using it to generate \*roff input from POD source. The resulting \*roff code is suitable for display on a terminal using nroff(1), normally via man(1), or printing using troff(1).
*input* is the file to read for POD source (the POD can be embedded in code). If *input* isn't given, it defaults to `STDIN`. *output*, if given, is the file to which to write the formatted output. If *output* isn't given, the formatted output is written to `STDOUT`. Several POD files can be processed in the same **pod2man** invocation (saving module load and compile times) by providing multiple pairs of *input* and *output* files on the command line.
**--section**, **--release**, **--center**, **--date**, and **--official** can be used to set the headers and footers to use; if not given, Pod::Man will assume various defaults. See below or <Pod::Man> for details.
**pod2man** assumes that your \*roff formatters have a fixed-width font named `CW`. If yours is called something else (like `CR`), use **--fixed** to specify it. This generally only matters for troff output for printing. Similarly, you can set the fonts used for bold, italic, and bold italic fixed-width output.
Besides the obvious pod conversions, Pod::Man, and therefore pod2man also takes care of formatting func(), func(n), and simple variable references like $foo or @bar so you don't have to use code escapes for them; complex expressions like `$fred{'stuff'}` will still need to be escaped, though. It also translates dashes that aren't used as hyphens into en dashes, makes long dashes--like this--into proper em dashes, fixes "paired quotes," and takes care of several other troff-specific tweaks. See <Pod::Man> for complete information.
OPTIONS
-------
**-c** *string*, **--center**=*string*
Sets the centered page header for the `.TH` macro to *string*. The default is "User Contributed Perl Documentation", but also see **--official** below.
**-d** *string*, **--date**=*string*
Set the left-hand footer string for the `.TH` macro to *string*. By default, the modification date of the input file will be used, or the current date if input comes from `STDIN`, and will be based on UTC (so that the output will be reproducible regardless of local time zone).
**--errors**=*style*
Set the error handling style. `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 `die`.
**--fixed**=*font*
The fixed-width font to use for verbatim text and code. Defaults to `CW`. Some systems may want `CR` instead. Only matters for troff(1) output.
**--fixedbold**=*font*
Bold version of the fixed-width font. Defaults to `CB`. Only matters for troff(1) output.
**--fixeditalic**=*font*
Italic version of the fixed-width font (actually, something of a misnomer, since most fixed-width fonts only have an oblique version, not an italic version). Defaults to `CI`. Only matters for troff(1) output.
**--fixedbolditalic**=*font*
Bold italic (probably actually oblique) version of the fixed-width font. Pod::Man doesn't assume you have this, and defaults to `CB`. Some systems (such as Solaris) have this font available as `CX`. Only matters for troff(1) output.
**-h**, **--help**
Print out usage information.
**-l**, **--lax**
No longer used. **pod2man** used to check its input for validity as a manual page, but this should now be done by [podchecker(1)](http://man.he.net/man1/podchecker) instead. Accepted for backward compatibility; this option no longer does anything.
**--lquote**=*quote*
**--rquote**=*quote*
Sets the quote marks used to surround C<> text. **--lquote** sets the left quote mark and **--rquote** sets the right quote mark. Either may also be set to the special value `none`, in which case no quote mark is added on that side of C<> text (but the font is still changed for troff output).
Also see the **--quotes** option, which can be used to set both quotes at once. If both **--quotes** and one of the other options is set, **--lquote** or **--rquote** overrides **--quotes**.
**-n** *name*, **--name**=*name*
Set the name of the manual page for the `.TH` macro to *name*. Without this option, the manual name is set to the uppercased base name of the file being converted unless the manual section is 3, in which case the path is parsed to see if it is a Perl module path. If it is, a path like `.../lib/Pod/Man.pm` is converted into a name like `Pod::Man`. This option, if given, overrides any automatic determination of the name.
Although one does not have to follow this convention, be aware that the convention for UNIX man pages for commands is for the man page title to be in all-uppercase, even if the command isn't.
This option is probably not useful when converting multiple POD files at once.
When converting POD source from standard input, the name will be set to `STDIN` if this option is not provided. Providing this option is strongly recommended to set a meaningful manual page name.
**--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 flag, if given, 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.
**-o**, **--official**
Set the default header to indicate that this page is part of the standard Perl release, if **--center** is not also given.
**-q** *quotes*, **--quotes**=*quotes*
Sets the quote marks used to surround C<> text to *quotes*. If *quotes* 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.
*quotes* may also be set to the special value `none`, in which case no quote marks are added around C<> text (but the font is still changed for troff output).
Also see the **--lquote** and **--rquote** options, which can be used to set the left and right quotes independently. If both **--quotes** and one of the other options is set, **--lquote** or **--rquote** overrides **--quotes**.
**-r** *version*, **--release**=*version*
Set the centered footer for the `.TH` macro to *version*. By default, this is set to the version of Perl you run **pod2man** under. Setting this to the empty string will cause some \*roff implementations to use the system default value.
Note that some system `an` macro sets assume that the centered footer will be a modification date and will prepend something like "Last modified: ". If this is the case for your target system, you may want to set **--release** to the last modified date and **--date** to the version number.
**-s** *string*, **--section**=*string*
Set the section for the `.TH` macro. The standard section numbering convention is to use 1 for user commands, 2 for system calls, 3 for functions, 4 for devices, 5 for file formats, 6 for games, 7 for miscellaneous information, and 8 for administrator commands. There is a lot of variation here, however; some systems (like Solaris) use 4 for file formats, 5 for miscellaneous information, and 7 for devices. Still others use 1m instead of 8, or some mix of both. About the only section numbers that are reliably consistent are 1, 2, and 3.
By default, section 1 will be used unless the file ends in `.pm`, in which case section 3 will be selected.
**--stderr**
By default, **pod2man** dies if any errors are detected in the POD input. If **--stderr** is given and no **--errors** flag is present, errors are sent to standard error, but **pod2man** does not abort. This is equivalent to `--errors=stderr` and is supported for backward compatibility.
**-u**, **--utf8**
By default, **pod2man** produces the most conservative possible \*roff output to try to ensure that it will work with as many different \*roff implementations as possible. Many \*roff implementations cannot handle non-ASCII characters, so this means all non-ASCII characters are converted either to a \*roff escape sequence that tries to create a properly accented character (at least for troff output) or to `X`.
This option says to instead output literal UTF-8 characters. If your \*roff implementation can handle it, this is the best output format to use and avoids corruption of documents containing non-ASCII characters. However, be warned that \*roff source with literal UTF-8 characters is not supported by many implementations and may even result in segfaults and other bad behavior.
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 warn, which by default results in a **pod2man** failure. Use the `=encoding` command to declare the encoding. See [perlpod(1)](http://man.he.net/man1/perlpod) for more information.
**-v**, **--verbose**
Print out the name of each output file as it is being generated.
EXIT STATUS
------------
As long as all documents processed result in some output, even if that output includes errata (a `POD ERRORS` section generated with `--errors=pod`), **pod2man** will exit with status 0. If any of the documents being processed do not result in an output document, **pod2man** will exit with status 1. If there are syntax errors in a POD document being processed and the error handling style is set to the default of `die`, **pod2man** will abort immediately with exit status 255.
DIAGNOSTICS
-----------
If **pod2man** fails with errors, see <Pod::Man> and <Pod::Simple> for information about what those errors might mean.
EXAMPLES
--------
```
pod2man program > program.1
pod2man SomeModule.pm /usr/perl/man/man3/SomeModule.3
pod2man --section=7 note.pod > note.7
```
If you would like to print out a lot of man page continuously, you probably want to set the C and D registers to set contiguous page numbering and even/odd paging, at least on some versions of man(7).
```
troff -man -rC1 -rD1 perl.1 perldata.1 perlsyn.1 ...
```
To get index entries on `STDERR`, turn on the F register, as in:
```
troff -man -rF1 perl.1
```
The indexing merely outputs messages via `.tm` for each major page, section, subsection, item, and any `X<>` directives. See <Pod::Man> for more details.
BUGS
----
Lots of this documentation is duplicated from <Pod::Man>.
AUTHOR
------
Russ Allbery <[email protected]>, based *very* heavily on the original **pod2man** by Larry Wall and Tom Christiansen.
COPYRIGHT AND LICENSE
----------------------
Copyright 1999-2001, 2004, 2006, 2008, 2010, 2012-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::Man>, <Pod::Simple>, [man(1)](http://man.he.net/man1/man), [nroff(1)](http://man.he.net/man1/nroff), [perlpod(1)](http://man.he.net/man1/perlpod), [podchecker(1)](http://man.he.net/man1/podchecker), [perlpodstyle(1)](http://man.he.net/man1/perlpodstyle), [troff(1)](http://man.he.net/man1/troff), [man(7)](http://man.he.net/man7/man)
The man page documenting the an macro set may be [man(5)](http://man.he.net/man5/man) instead of [man(7)](http://man.he.net/man7/man) on your system.
The current version of this script 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 Test2::API::InterceptResult::Event Test2::API::InterceptResult::Event
==================================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [!!! IMPORTANT NOTES ON DESIGN !!!](#!!!-IMPORTANT-NOTES-ON-DESIGN-!!!)
+ [ATTRIBUTES](#ATTRIBUTES)
+ [DUPLICATION](#DUPLICATION)
+ [CONDENSED MULTI-FACET DATA](#CONDENSED-MULTI-FACET-DATA)
+ [DIRECT ARBITRARY FACET ACCESS](#DIRECT-ARBITRARY-FACET-ACCESS)
+ [TRACE FACET](#TRACE-FACET)
+ [ASSERT FACET](#ASSERT-FACET)
+ [SUBTESTS (PARENT FACET)](#SUBTESTS-(PARENT-FACET))
+ [CONTROL FACET (BAILOUT, ENCODING)](#CONTROL-FACET-(BAILOUT,-ENCODING))
+ [PLAN FACET](#PLAN-FACET)
+ [AMNESTY FACET (TODO AND SKIP)](#AMNESTY-FACET-(TODO-AND-SKIP))
+ [ERROR FACET (CAPTURED EXCEPTIONS)](#ERROR-FACET-(CAPTURED-EXCEPTIONS))
+ [INFO FACET (DIAG, NOTE)](#INFO-FACET-(DIAG,-NOTE))
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::InterceptResult::Event - Representation of an event for use in testing other test tools.
DESCRIPTION
-----------
`intercept { ... }` from <Test2::API> returns an instance of <Test2::API::InterceptResult> which is a blessed arrayref of <Test2::API::InterceptResult::Event> objects.
This POD documents the methods of these events, which are mainly provided for you to use when testing your test tools.
SYNOPSIS
--------
```
use Test2::V0;
use Test2::API qw/intercept/;
my $events = intercept {
ok(1, "A passing assertion");
plan(1);
};
# This will convert all events into instances of
# Test2::API::InterceptResult::Event. Until we do this they are the
# original Test::Event::* instances
$events->upgrade(in_place => 1);
# Now we can get individual events in this form
my $assert = $events->[0];
my $plan = $events->[1];
# Or we can operate on all events at once:
my $flattened = $events->flatten;
is(
$flattened,
[
{
causes_failure => 0,
name => 'A passing assertion',
pass => 1,
trace_file => 'xxx.t',
trace_line => 5,
},
{
causes_failure => 0,
plan => 1,
trace_file => 'xxx.t',
trace_line => 6,
},
],
"Flattened both events and returned an arrayref of the results
);
```
METHODS
-------
###
!!! IMPORTANT NOTES ON DESIGN !!!
Please pay attention to what these return, many return a scalar when applicable or an empty list when not (as opposed to undef). Many also always return a list of 0 or more items. Some always return a scalar. Note that none of the methods care about context, their behavior is consistent regardless of scalar, list, or void context.
This was done because this class was specifically designed to be used in a list and generate more lists in bulk operations. Sometimes in a map you want nothing to show up for the event, and you do not want an undef in its place. In general single event instances are not going to be used alone, though that is allowed.
As a general rule any method prefixed with `the_` implies the event should have exactly 1 of the specified item, and and exception will be thrown if there are 0, or more than 1 of the item.
### ATTRIBUTES
$hashref = $event->facet\_data This will return the facet data hashref, which is all Test2 cares about for any given event.
$class = $event->result\_class This is normally <Test2::API::InterceptResult>. This is set at construction so that subtest results can be turned into instances of it on demand.
### DUPLICATION
$copy = $event->clone Create a deep copy of the event. Modifying either event will not effect the other.
###
CONDENSED MULTI-FACET DATA
$bool = $event->causes\_failure
$bool = $event->causes\_fail These are both aliases of the same functionality.
This will always return either a true value, or a false value. This never returns a list.
This method may be relatively slow (still super fast) because it determines pass or fail by creating an instance of <Test2::Hub> and asking it to process the event, and then asks the hub for its pass/fail state. This is slower than bulding in logic to do the check, but it is more reliable as it will always tell you what the hub thinks, so the logic will never be out of date relative to the Test2 logic that actually cares.
STRING\_OR\_EMPTY\_LIST = $event->brief Not all events have a brief, some events are not rendered by the formatter, others have no "brief" data worth seeing. When this is the case an empty list is returned. This is done intentionally so it can be used in a map operation without having `undef` being included in the result.
When a brief can be generated it is always a single 1-line string, and is returned as-is, not in a list.
Possible briefs:
```
# From control facets
"BAILED OUT"
"BAILED OUT: $why"
# From error facets
"ERROR"
"ERROR: $message"
"ERROR: $partial_message [...]"
"ERRORS: $first_error_message [...]"
# From assert facets
"PASS"
"FAIL"
"PASS with amnesty"
"FAIL with amnesty"
# From plan facets
"PLAN $count"
"NO PLAN"
"SKIP ALL"
"SKIP ALL: $why"
```
Note that only the first applicable brief is returned. This is essnetially a poor-mans TAP that only includes facets that could (but not necessarily do) cause a failure.
$hashref = $event->flatten
$hashref = $event->flatten(include\_subevents => 1) This ALWAYS returns a hashref. This puts all the most useful data for the most interesting facets into a single hashref for easy validation.
If there are no meaningful facets this will return an empty hashref.
If given the 'include\_subevents' parameter it will also include subtest data:
Here is a list of EVERY possible field. If a field is not applicable it will not be present.
always present
```
causes_failure => 1, # Always present
```
Present if the event has a trace facet
```
trace_line => 42,
trace_file => 'Foo/Bar.pm',
trace_details => 'Extra trace details', # usually not present
```
If an assertion is present
```
pass => 0,
name => "1 + 1 = 2, so math works",
```
If a plan is present:
```
plan => $count_or_SKIP_ALL_or_NO_PLAN,
```
If amnesty facets are present You get an array for each type that is present.
```
todo => [ # Yes you could be under multiple todos, this will list them all.
"I will fix this later",
"I promise to fix these",
],
skip => ["This will format the main drive, do not run"],
... => ["Other amnesty"]
```
If Info (note/diag) facets are present You get an arrayref for any that are present, the key is not defined if they are not present.
```
diag => [
"Test failed at Foo/Bar.pm line 42",
"You forgot to tie your boots",
],
note => ["Your boots are red"],
... => ["Other info"],
```
If error facets are present Always an arrayref
```
error => [
"non fatal error (does not cause test failure, just an FYI",
"FATAL: This is a fatal error (causes failure)",
],
# Errors can have alternative tags, but in practice are always 'error',
# listing this for completeness.
... => [ ... ]
```
Present if the event is a subtest
```
subtest => {
count => 2, # Number of assertions made
failed => 1, # Number of test failures seen
is_passing => 0, # Boolean, true if the test would be passing
# after the events are processed.
plan => 2, # Plan, either a number, undef, 'SKIP', or 'NO PLAN'
follows_plan => 1, # True if there is a plan and it was followed.
# False if the plan and assertions did not
# match, undef if no plan was present in the
# event list.
bailed_out => "foo", # if there was a bail-out in the
# events in this will be a string explaining
# why there was a bailout, if no reason was
# given this will simply be set to true (1).
skip_reason => "foo", # If there was a skip_all this will give the
# reason.
},
```
if `(include_subtest => 1)` was provided as a parameter then the following will be included. This is the result of turning all subtest child events into an <Test2::API::InterceptResult> instance and calling the `flatten` method on it.
```
subevents => Test2::API::InterceptResult->new(@child_events)->flatten(...),
```
If a bail-out is being requested If no reason was given this will be set to 1.
```
bailed_out => "reason",
```
$hashref = $event->summary() This returns a limited summary. See `flatten()`, which is usually a better option.
```
{
brief => $event->brief || '',
causes_failure => $event->causes_failure,
trace_line => $event->trace_line,
trace_file => $event->trace_file,
trace_tool => $event->trace_subname,
trace_details => $event->trace_details,
facets => [ sort keys(%{$event->{+FACET_DATA}}) ],
}
```
###
DIRECT ARBITRARY FACET ACCESS
@list\_of\_facets = $event->facet($name) This always returns a list of 0 or more items. This fetches the facet instances from the event. For facets like 'assert' this will always return 0 or 1 item. For events like 'info' (diags, notes) this will return 0 or more instances, once for each instance of the facet.
These will be blessed into the proper <Test2::EventFacet> subclass. If no subclass can be found it will be blessed as an <Test2::API::InterceptResult::Facet> generic facet class.
$undef\_or\_facet = $event->the\_facet($name) If you know you will have exactly 1 instance of a facet you can call this.
If you are correct and there is exactly one instance of the facet it will always return the hashref.
If there are 0 instances of the facet this will reutrn undef, not an empty list.
If there are more than 1 instance this will throw an exception because your assumption was incorrect.
###
TRACE FACET
@list\_of\_facets = $event->trace TODO
$undef\_or\_hashref = $event->the\_trace This returns the trace hashref, or undef if it is not present.
$undef\_or\_arrayref = $event->frame If a trace is present, and has a caller frame, this will be an arrayref:
```
[$package, $file, $line, $subname]
```
If the trace is not present, or has no caller frame this will return undef.
$undef\_or\_string = $event->trace\_details This is usually undef, but occasionally has a string that overrides the file/line number debugging a trace usually provides on test failure.
$undef\_or\_string = $event->trace\_package Same as `(caller())[0]`, the first element of the trace frame.
Will be undef if not present.
$undef\_or\_string = $event->trace\_file Same as `(caller())[1]`, the second element of the trace frame.
Will be undef if not present.
$undef\_or\_integer = $event->trace\_line Same as `(caller())[2]`, the third element of the trace frame.
Will be undef if not present.
$undef\_or\_string = $event->trace\_subname
$undef\_or\_string = $event->trace\_tool Aliases for the same thing
Same as `(caller($level))[4]`, the fourth element of the trace frame.
Will be undef if not present.
$undef\_or\_string = $event->trace\_signature A string that is a unique signature for the trace. If a single context generates multiple events they will all have the same signature. This can be used to tie assertions and diagnostics sent as seperate events together after the fact.
###
ASSERT FACET
$bool = $event->has\_assert Returns true if the event has an assert facet, false if it does not.
$undef\_or\_hashref = $event->the\_assert Returns the assert facet if present, undef if it is not.
@list\_of\_facets = $event->assert TODO
EMPTY\_LIST\_OR\_STRING = $event->assert\_brief Returns a string giving a brief of the assertion if an assertion is present. Returns an empty list if no assertion is present.
###
SUBTESTS (PARENT FACET)
$bool = $event->has\_subtest True if a subetest is present in this event.
$undef\_or\_hashref = $event->the\_subtest Get the one subtest if present, otherwise undef.
@list\_of\_facets = $event->subtest TODO
EMPTY\_LIST\_OR\_OBJECT = $event->subtest\_result Returns an empty list if there is no subtest.
Get an instance of <Test2::API::InterceptResult> representing the subtest.
###
CONTROL FACET (BAILOUT, ENCODING)
$bool = $event->has\_bailout True if there was a bailout
$undef\_hashref = $event->the\_bailout Return the control facet if it requested a bailout.
EMPTY\_LIST\_OR\_HASHREF = $event->bailout Get a list of 0 or 1 hashrefs. The hashref will be the control facet if a bail-out was requested.
EMPTY\_LIST\_OR\_STRING = $event->bailout\_brief Get the brief of the balout if present.
EMPTY\_LIST\_OR\_STRING = $event->bailout\_reason Get the reason for the bailout, an empty string if no reason was provided, or an empty list if there was no bailout.
###
PLAN FACET
TODO
$bool = $event->has\_plan
$undef\_or\_hashref = $event->the\_plan
@list\_if\_hashrefs = $event->plan
EMPTY\_LIST\_OR\_STRING $event->plan\_brief ###
AMNESTY FACET (TODO AND SKIP)
TODO
$event->has\_amnesty
$event->the\_amnesty
$event->amnesty
$event->amnesty\_reasons
$event->has\_todos
$event->todos
$event->todo\_reasons
$event->has\_skips
$event->skips
$event->skip\_reasons
$event->has\_other\_amnesty
$event->other\_amnesty
$event->other\_amnesty\_reasons ###
ERROR FACET (CAPTURED EXCEPTIONS)
TODO
$event->has\_errors
$event->the\_errors
$event->errors
$event->error\_messages
$event->error\_brief ###
INFO FACET (DIAG, NOTE)
TODO
$event->has\_info
$event->the\_info
$event->info
$event->info\_messages
$event->has\_diags
$event->diags
$event->diag\_messages
$event->has\_notes
$event->notes
$event->note\_messages
$event->has\_other\_info
$event->other\_info
$event->other\_info\_messages 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 Test2::EventFacet::Info::Table Test2::EventFacet::Info::Table
==============================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ATTRIBUTES](#ATTRIBUTES)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Info::Table - Intermediary representation of a table.
DESCRIPTION
-----------
Intermediary representation of a table for use in specialized <Test::API::Context> methods which generate <Test2::EventFacet::Info> facets.
SYNOPSIS
--------
```
use Test2::EventFacet::Info::Table;
use Test2::API qw/context/;
sub my_tool {
my $ctx = context();
...
$ctx->fail(
$name,
"failure diag message",
Test2::EventFacet::Info::Table->new(
# Required
rows => [['a', 'b'], ['c', 'd'], ...],
# Strongly Recommended
as_string => "... string to print when table cannot be rendered ...",
# Optional
header => ['col1', 'col2'],
collapse => $bool,
no_collapse => ['col1', ...],
),
);
...
$ctx->release;
}
my_tool();
```
ATTRIBUTES
----------
$header\_aref = $t->header()
$rows\_aref = $t->rows()
$bool = $t->collapse()
$aref = $t->no\_collapse() The above are all directly tied to the table hashref structure described in <Test2::EventFacet::Info>.
$str = $t->as\_string() This returns the string form of the table if it was set, otherwise it returns the string `"<TABLE NOT DISPLAYED>"`.
$href = $t->as\_hash() This returns the data structure used for tables by <Test2::EventFacet::Info>.
%args = $t->info\_args() This returns the arguments that should be used to construct the proper <Test2::EventFacet::Info> structure.
```
return (table => $t->as_hash(), details => $t->as_string());
```
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::Man Pod::Man
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [ENVIRONMENT](#ENVIRONMENT)
* [BUGS](#BUGS)
* [CAVEATS](#CAVEATS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Man - Convert POD data to formatted \*roff input
SYNOPSIS
--------
```
use Pod::Man;
my $parser = Pod::Man->new (release => $VERSION, section => 8);
# Read POD from STDIN and write to STDOUT.
$parser->parse_file (\*STDIN);
# Read POD from file.pod and write to file.1.
$parser->parse_from_file ('file.pod', 'file.1');
```
DESCRIPTION
-----------
Pod::Man is a module to convert documentation in the POD format (the preferred language for documenting Perl) into \*roff input using the man macro set. The resulting \*roff code is suitable for display on a terminal using [nroff(1)](http://man.he.net/man1/nroff), normally via [man(1)](http://man.he.net/man1/man), or printing using [troff(1)](http://man.he.net/man1/troff). It is conventionally invoked using the driver script **pod2man**, but it can also be used directly.
As a derived class from Pod::Simple, Pod::Man supports the same methods and interfaces. See <Pod::Simple> for all the details.
new() can take options, in the form of key/value pairs that control the behavior of the parser. See below for details.
If no options are given, Pod::Man uses the name of the input file with any trailing `.pod`, `.pm`, or `.pl` stripped as the man page title, to section 1 unless the file ended in `.pm` in which case it defaults to section 3, to a centered title of "User Contributed Perl Documentation", to a centered footer of the Perl version it is run with, and to a left-hand footer of the modification date of its input (or the current date if given `STDIN` for input).
Pod::Man assumes that your \*roff formatters have a fixed-width font named `CW`. If yours is called something else (like `CR`), use the `fixed` option to specify it. This generally only matters for troff output for printing. Similarly, you can set the fonts used for bold, italic, and bold italic fixed-width output.
Besides the obvious pod conversions, Pod::Man also takes care of formatting func(), func(3), and simple variable references like $foo or @bar so you don't have to use code escapes for them; complex expressions like `$fred{'stuff'}` will still need to be escaped, though. It also translates dashes that aren't used as hyphens into en dashes, makes long dashes--like this--into proper em dashes, fixes "paired quotes," makes C++ look right, puts a little space between double underscores, makes ALLCAPS a teeny bit smaller in **troff**, and escapes stuff that \*roff treats as special so that you don't have to.
The recognized options to new() are as follows. All options take a single argument.
center Sets the centered page header for the `.TH` macro. The default, if this option is not specified, is "User Contributed Perl Documentation".
date Sets the left-hand footer for the `.TH` macro. If this option is not set, the contents of the environment variable POD\_MAN\_DATE, if set, will be used. Failing that, the value of SOURCE\_DATE\_EPOCH, the modification date of the input file, or the current time if stat() can't find that file (which will be the case if the input is from `STDIN`) will be used. If obtained from the file modification date or the current time, the date will be formatted as `YYYY-MM-DD` and will be based on UTC (so that the output will be reproducible regardless of local time zone).
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`.
fixed The fixed-width font to use for verbatim text and code. Defaults to `CW`. Some systems may want `CR` instead. Only matters for **troff** output.
fixedbold Bold version of the fixed-width font. Defaults to `CB`. Only matters for **troff** output.
fixeditalic Italic version of the fixed-width font (actually, something of a misnomer, since most fixed-width fonts only have an oblique version, not an italic version). Defaults to `CI`. Only matters for **troff** output.
fixedbolditalic Bold italic (probably actually oblique) version of the fixed-width font. Pod::Man doesn't assume you have this, and defaults to `CB`. Some systems (such as Solaris) have this font available as `CX`. Only matters for **troff** output.
lquote rquote Sets the quote marks used to surround C<> text. `lquote` sets the left quote mark and `rquote` sets the right quote mark. Either may also be set to the special value `none`, in which case no quote mark is added on that side of C<> text (but the font is still changed for troff output).
Also see the `quotes` option, which can be used to set both quotes at once. If both `quotes` and one of the other options is set, `lquote` or `rquote` overrides `quotes`.
name Set the name of the manual page for the `.TH` macro. Without this option, the manual name is set to the uppercased base name of the file being converted unless the manual section is 3, in which case the path is parsed to see if it is a Perl module path. If it is, a path like `.../lib/Pod/Man.pm` is converted into a name like `Pod::Man`. This option, if given, overrides any automatic determination of the name.
If generating a manual page from standard input, the name will be set to `STDIN` if this option is not provided. Providing this option is strongly recommended to set a meaningful manual page name.
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 (but the font is still changed for troff output).
Also see the `lquote` and `rquote` options, which can be used to set the left and right quotes independently. If both `quotes` and one of the other options is set, `lquote` or `rquote` overrides `quotes`.
release Set the centered footer for the `.TH` macro. By default, this is set to the version of Perl you run Pod::Man under. Setting this to the empty string will cause some \*roff implementations to use the system default value.
Note that some system `an` macro sets assume that the centered footer will be a modification date and will prepend something like "Last modified: ". If this is the case for your target system, you may want to set `release` to the last modified date and `date` to the version number.
section Set the section for the `.TH` macro. The standard section numbering convention is to use 1 for user commands, 2 for system calls, 3 for functions, 4 for devices, 5 for file formats, 6 for games, 7 for miscellaneous information, and 8 for administrator commands. There is a lot of variation here, however; some systems (like Solaris) use 4 for file formats, 5 for miscellaneous information, and 7 for devices. Still others use 1m instead of 8, or some mix of both. About the only section numbers that are reliably consistent are 1, 2, and 3.
By default, section 1 will be used unless the file ends in `.pm` in which case section 3 will be selected.
stderr Send error messages about invalid POD to standard error instead of appending a POD ERRORS section to the generated \*roff 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::Man produces the most conservative possible \*roff output to try to ensure that it will work with as many different \*roff implementations as possible. Many \*roff implementations cannot handle non-ASCII characters, so this means all non-ASCII characters are converted either to a \*roff escape sequence that tries to create a properly accented character (at least for troff output) or to `X`.
If this option is set, Pod::Man will instead output UTF-8. If your \*roff implementation can handle it, this is the best output format to use and avoids corruption of documents containing non-ASCII characters. However, be warned that \*roff source with literal UTF-8 characters is not supported by many implementations and may even result in segfaults and other bad behavior.
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.
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
-----------
roff font should be 1 or 2 chars, not "%s" (F) You specified a \*roff font (using `fixed`, `fixedbold`, etc.) that wasn't either one or two characters. Pod::Man doesn't support \*roff fonts longer than two characters, although some \*roff extensions do (the canonical versions of **nroff** and **troff** don't either).
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`.
ENVIRONMENT
-----------
PERL\_CORE If set and Encode is not available, silently fall back to non-UTF-8 mode without complaining to standard error. This environment variable is set during Perl core builds, which build Encode after podlators. Encode is expected to not (yet) be available in that case.
POD\_MAN\_DATE If set, this will be used as the value of the left-hand footer unless the `date` option is explicitly set, overriding the timestamp of the input file or the current time. This is primarily useful to ensure reproducible builds of the same output file given the same source and Pod::Man version, even when file timestamps may not be consistent.
SOURCE\_DATE\_EPOCH If set, and POD\_MAN\_DATE and the `date` options are not set, this will be used as the modification time of the source file, overriding the timestamp of the input file or the current time. It should be set to the desired time in seconds since UNIX epoch. This is primarily useful to ensure reproducible builds of the same output file given the same source and Pod::Man version, even when file timestamps may not be consistent. See <https://reproducible-builds.org/specs/source-date-epoch/> for the full specification.
(Arguably, according to the specification, this variable should be used only if the timestamp of the input file is not available and Pod::Man uses the current time. However, for reproducible builds in Debian, results were more reliable if this variable overrode the timestamp of the input file.)
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.
There is currently no way to turn off the guesswork that tries to format unmarked text appropriately, and sometimes it isn't wanted (particularly when using POD to document something other than Perl). Most of the work toward fixing this has now been done, however, and all that's still needed is a user interface.
The NAME section should be recognized specially and index entries emitted for everything in that section. This would have to be deferred until the next section, since extraneous things in NAME tends to confuse various man page processors. Currently, no index entries are emitted for anything in NAME.
Pod::Man doesn't handle font names longer than two characters. Neither do most **troff** implementations, but GNU troff does as an extension. It would be nice to support as an option for those who want to use it.
The preamble added to each output file is rather verbose, and most of it is only necessary in the presence of non-ASCII characters. It would ideally be nice if all of those definitions were only output if needed, perhaps on the fly as the characters are used.
Pod::Man is excessively slow.
CAVEATS
-------
If Pod::Man 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::Man and was passed in from outside. This maintains consistency regardless of PERL\_UNICODE and other settings.
The handling of hyphens and em dashes is somewhat fragile, and one may get the wrong one under some circumstances. This should only matter for **troff** output.
When and whether to use small caps is somewhat tricky, and Pod::Man doesn't necessarily get it right.
Converting neutral double quotes to properly matched double quotes doesn't work unless there are no formatting codes between the quote marks. This only matters for troff output.
AUTHOR
------
Russ Allbery <[email protected]>, based *very* heavily on the original **pod2man** by Tom Christiansen <[email protected]>. The modifications to work with Pod::Simple instead of Pod::Parser were originally contributed by Sean Burke <[email protected]> (but I've since hacked them beyond recognition and all bugs are mine).
COPYRIGHT AND LICENSE
----------------------
Copyright 1999-2010, 2012-2019 Russ Allbery <[email protected]>
Substantial contributions by Sean Burke <[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>, [perlpod(1)](http://man.he.net/man1/perlpod), [pod2man(1)](http://man.he.net/man1/pod2man), [nroff(1)](http://man.he.net/man1/nroff), [troff(1)](http://man.he.net/man1/troff), [man(1)](http://man.he.net/man1/man), [man(7)](http://man.he.net/man7/man)
Ossanna, Joseph F., and Brian W. Kernighan. "Troff User's Manual," Computing Science Technical Report No. 54, AT&T Bell Laboratories. This is the best documentation of standard **nroff** and **troff**. At the time of this writing, it's available at <http://www.troff.org/54.pdf>.
The man page documenting the man macro set may be [man(5)](http://man.he.net/man5/man) instead of [man(7)](http://man.he.net/man7/man) on your system. Also, please see [pod2man(1)](http://man.he.net/man1/pod2man) for extensive documentation on writing manual pages if you've not done it before and aren't familiar with the conventions.
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 File::Spec::Unix File::Spec::Unix
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::Unix - File::Spec for Unix, base for other File::Spec modules
SYNOPSIS
--------
```
require File::Spec::Unix; # Done automatically by File::Spec
```
DESCRIPTION
-----------
Methods for manipulating file specifications. Other File::Spec modules, such as File::Spec::Mac, inherit from File::Spec::Unix and override specific methods.
METHODS
-------
canonpath() No physical check on the filesystem, but a logical cleanup of a path. On UNIX eliminates successive slashes and successive "/.".
```
$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 OS2. Of course, if this is the root directory, don't cut off the trailing slash :-)
catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename
curdir Returns a string representation of the current directory. "." on UNIX.
devnull Returns a string representation of the null device. "/dev/null" on UNIX.
rootdir Returns a string representation of the root directory. "/" on UNIX.
tmpdir Returns a string representation of the first writable directory from the following list or the current directory if none from the list are writable:
```
$ENV{TMPDIR}
/tmp
```
If running under taint mode, and if $ENV{TMPDIR} is tainted, it is not used.
updir Returns a string representation of the parent directory. ".." on UNIX.
no\_upwards Given a list of file names, strip out those that refer to a parent directory. (Does not strip symlinks, only '.', '..', and equivalents.)
case\_tolerant Returns a true or false value indicating, respectively, that alphabetic is not or is significant when comparing file specifications.
file\_name\_is\_absolute Takes as argument a path and returns true if it is an 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 as an array.
join join is the same as catfile.
splitpath
```
($volume,$directories,$file) = File::Spec->splitpath( $path );
($volume,$directories,$file) = File::Spec->splitpath( $path,
$no_file );
```
Splits a path into volume, directory, and filename portions. On systems with no concept of volume, returns '' for volume.
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%28%29).
```
@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 OSs.
On Unix,
```
File::Spec->splitdir( "/a/b//c/" );
```
Yields:
```
( '', 'a', 'b', '', 'c', '' )
```
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 needed (though if the directory portion doesn't start with '/' it is not added). On other OSs, $volume is significant.
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) 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).
On systems that have a grammar that indicates filenames, this ignores the $base filename. 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).
No checks against the filesystem are made, so the result may not be correct if `$base` contains symbolic links. (Apply [Cwd::abs\_path()](cwd#abs_path) beforehand if that is a concern.) 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) 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).
On systems that have a grammar that indicates filenames, this ignores the $base filename. Otherwise all path components are assumed to be directories.
If $path is absolute, it is cleaned up and returned using ["canonpath()"](#canonpath%28%29).
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.
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.
Please submit bug reports at <https://github.com/Perl/perl5/issues>.
SEE ALSO
---------
<File::Spec>
| programming_docs |
perl ExtUtils::testlib ExtUtils::testlib
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::testlib - add blib/\* directories to @INC
SYNOPSIS
--------
```
use ExtUtils::testlib;
```
DESCRIPTION
-----------
After an extension has been built and before it is installed it may be desirable to test it bypassing `make test`. By adding
```
use ExtUtils::testlib;
```
to a test program the intermediate directories used by `make` are added to @INC.
perl Test2::Util::HashBase Test2::Util::HashBase
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [THIS IS A BUNDLED COPY OF HASHBASE](#THIS-IS-A-BUNDLED-COPY-OF-HASHBASE)
* [METHODS](#METHODS)
+ [PROVIDED BY HASH BASE](#PROVIDED-BY-HASH-BASE)
+ [HOOKS](#HOOKS)
* [ACCESSORS](#ACCESSORS)
+ [READ/WRITE](#READ/WRITE)
+ [READ ONLY](#READ-ONLY)
+ [DEPRECATED SETTER](#DEPRECATED-SETTER)
+ [NO SETTER](#NO-SETTER)
+ [NO READER](#NO-READER)
+ [CONSTANT ONLY](#CONSTANT-ONLY)
* [SUBCLASSING](#SUBCLASSING)
* [GETTING A LIST OF ATTRIBUTES FOR A CLASS](#GETTING-A-LIST-OF-ATTRIBUTES-FOR-A-CLASS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Util::HashBase - Build hash based classes.
SYNOPSIS
--------
A class:
```
package My::Class;
use strict;
use warnings;
# Generate 3 accessors
use Test2::Util::HashBase qw/foo -bar ^baz <bat >ban +boo/;
# Chance to initialize defaults
sub init {
my $self = shift; # No other args
$self->{+FOO} ||= "foo";
$self->{+BAR} ||= "bar";
$self->{+BAZ} ||= "baz";
$self->{+BAT} ||= "bat";
$self->{+BAN} ||= "ban";
$self->{+BOO} ||= "boo";
}
sub print {
print join ", " => map { $self->{$_} } FOO, BAR, BAZ, BAT, BAN, BOO;
}
```
Subclass it
```
package My::Subclass;
use strict;
use warnings;
# Note, you should subclass before loading HashBase.
use base 'My::Class';
use Test2::Util::HashBase qw/bub/;
sub init {
my $self = shift;
# We get the constants from the base class for free.
$self->{+FOO} ||= 'SubFoo';
$self->{+BUB} ||= 'bub';
$self->SUPER::init();
}
```
use it:
```
package main;
use strict;
use warnings;
use My::Class;
# These are all functionally identical
my $one = My::Class->new(foo => 'MyFoo', bar => 'MyBar');
my $two = My::Class->new({foo => 'MyFoo', bar => 'MyBar'});
my $three = My::Class->new(['MyFoo', 'MyBar']);
# Readers!
my $foo = $one->foo; # 'MyFoo'
my $bar = $one->bar; # 'MyBar'
my $baz = $one->baz; # Defaulted to: 'baz'
my $bat = $one->bat; # Defaulted to: 'bat'
# '>ban' means setter only, no reader
# '+boo' means no setter or reader, just the BOO constant
# Setters!
$one->set_foo('A Foo');
#'-bar' means read-only, so the setter will throw an exception (but is defined).
$one->set_bar('A bar');
# '^baz' means deprecated setter, this will warn about the setter being
# deprecated.
$one->set_baz('A Baz');
# '<bat' means no setter defined at all
# '+boo' means no setter or reader, just the BOO constant
$one->{+FOO} = 'xxx';
```
DESCRIPTION
-----------
This package is used to generate classes based on hashrefs. Using this class will give you a `new()` method, as well as generating accessors you request. Generated accessors will be getters, `set_ACCESSOR` setters will also be generated for you. You also get constants for each accessor (all caps) which return the key into the hash for that accessor. Single inheritance is also supported.
THIS IS A BUNDLED COPY OF HASHBASE
-----------------------------------
This is a bundled copy of <Object::HashBase>. This file was generated using the `/home/exodist/perl5/perlbrew/perls/main/bin/hashbase_inc.pl` script.
METHODS
-------
###
PROVIDED BY HASH BASE
$it = $class->new(%PAIRS)
$it = $class->new(\%PAIRS)
$it = $class->new(\@ORDERED\_VALUES) Create a new instance.
HashBase will not export `new()` if there is already a `new()` method in your packages inheritance chain.
**If you do not want this method you can define your own** you just have to declare it before loading <Test2::Util::HashBase>.
```
package My::Package;
# predeclare new() so that HashBase does not give us one.
sub new;
use Test2::Util::HashBase qw/foo bar baz/;
# Now we define our own new method.
sub new { ... }
```
This makes it so that HashBase sees that you have your own `new()` method. Alternatively you can define the method before loading HashBase instead of just declaring it, but that scatters your use statements.
The most common way to create an object is to pass in key/value pairs where each key is an attribute and each value is what you want assigned to that attribute. No checking is done to verify the attributes or values are valid, you may do that in `init()` if desired.
If you would like, you can pass in a hashref instead of pairs. When you do so the hashref will be copied, and the copy will be returned blessed as an object. There is no way to ask HashBase to bless a specific hashref.
In some cases an object may only have 1 or 2 attributes, in which case a hashref may be too verbose for your liking. In these cases you can pass in an arrayref with only values. The values will be assigned to attributes in the order the attributes were listed. When there is inheritance involved the attributes from parent classes will come before subclasses.
### HOOKS
$self->init() This gives you the chance to set some default values to your fields. The only argument is `$self` with its indexes already set from the constructor.
**Note:** Test2::Util::HashBase checks for an init using `$class->can('init')` during construction. It DOES NOT call `can()` on the created object. Also note that the result of the check is cached, it is only ever checked once, the first time an instance of your class is created. This means that adding an `init()` method AFTER the first construction will result in it being ignored.
ACCESSORS
---------
###
READ/WRITE
To generate accessors you list them when using the module:
```
use Test2::Util::HashBase qw/foo/;
```
This will generate the following subs in your namespace:
foo() Getter, used to get the value of the `foo` field.
set\_foo() Setter, used to set the value of the `foo` field.
FOO() Constant, returns the field `foo`'s key into the class hashref. Subclasses will also get this function as a constant, not simply a method, that means it is copied into the subclass namespace.
The main reason for using these constants is to help avoid spelling mistakes and similar typos. It will not help you if you forget to prefix the '+' though.
###
READ ONLY
```
use Test2::Util::HashBase qw/-foo/;
```
set\_foo() Throws an exception telling you the attribute is read-only. This is exported to override any active setters for the attribute in a parent class.
###
DEPRECATED SETTER
```
use Test2::Util::HashBase qw/^foo/;
```
set\_foo() This will set the value, but it will also warn you that the method is deprecated.
###
NO SETTER
```
use Test2::Util::HashBase qw/<foo/;
```
Only gives you a reader, no `set_foo` method is defined at all.
###
NO READER
```
use Test2::Util::HashBase qw/>foo/;
```
Only gives you a write (`set_foo`), no `foo` method is defined at all.
###
CONSTANT ONLY
```
use Test2::Util::HashBase qw/+foo/;
```
This does not create any methods for you, it just adds the `FOO` constant.
SUBCLASSING
-----------
You can subclass an existing HashBase class.
```
use base 'Another::HashBase::Class';
use Test2::Util::HashBase qw/foo bar baz/;
```
The base class is added to `@ISA` for you, and all constants from base classes are added to subclasses automatically.
GETTING A LIST OF ATTRIBUTES FOR A CLASS
-----------------------------------------
Test2::Util::HashBase provides a function for retrieving a list of attributes for an Test2::Util::HashBase class.
@list = Test2::Util::HashBase::attr\_list($class)
@list = $class->Test2::Util::HashBase::attr\_list() Either form above will work. This will return a list of attributes defined on the object. This list is returned in the attribute definition order, parent class attributes are listed before subclass attributes. Duplicate attributes will be removed before the list is returned.
**Note:** This list is used in the `$class->new(\@ARRAY)` constructor to determine the attribute to which each value will be paired.
SOURCE
------
The source code repository for HashBase can be found at *http://github.com/Test-More/HashBase/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2017 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 Env Env
===
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LIMITATIONS](#LIMITATIONS)
* [AUTHOR](#AUTHOR)
NAME
----
Env - perl module that imports environment variables as scalars or arrays
SYNOPSIS
--------
```
use Env;
use Env qw(PATH HOME TERM);
use Env qw($SHELL @LD_LIBRARY_PATH);
```
DESCRIPTION
-----------
Perl maintains environment variables in a special hash named `%ENV`. For when this access method is inconvenient, the Perl module `Env` allows environment variables to be treated as scalar or array variables.
The `Env::import()` function ties environment variables with suitable names to global Perl variables with the same names. By default it ties all existing environment variables (`keys %ENV`) to scalars. If the `import` function receives arguments, it takes them to be a list of variables to tie; it's okay if they don't yet exist. The scalar type prefix '$' is inferred for any element of this list not prefixed by '$' or '@'. Arrays are implemented in terms of `split` and `join`, using `$Config::Config{path_sep}` as the delimiter.
After an environment variable is tied, merely use it like a normal variable. You may access its value
```
@path = split(/:/, $PATH);
print join("\n", @LD_LIBRARY_PATH), "\n";
```
or modify it
```
$PATH .= ":/any/path";
push @LD_LIBRARY_PATH, $dir;
```
however you'd like. Bear in mind, however, that each access to a tied array variable requires splitting the environment variable's string anew.
The code:
```
use Env qw(@PATH);
push @PATH, '/any/path';
```
is almost equivalent to:
```
use Env qw(PATH);
$PATH .= ":/any/path";
```
except that if `$ENV{PATH}` started out empty, the second approach leaves it with the (odd) value "`:/any/path`", but the first approach leaves it with "`/any/path`".
To remove a tied environment variable from the environment, assign it the undefined value
```
undef $PATH;
undef @LD_LIBRARY_PATH;
```
LIMITATIONS
-----------
On VMS systems, arrays tied to environment variables are read-only. Attempting to change anything will cause a warning.
AUTHOR
------
Chip Salzenberg <*[email protected]*> and Gregor N. Purdy <*[email protected]*>
perl h2ph h2ph
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [ENVIRONMENT](#ENVIRONMENT)
* [FILES](#FILES)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [BUGS](#BUGS)
NAME
----
h2ph - convert .h C header files to .ph Perl header files
SYNOPSIS
--------
**h2ph [-d destination directory] [-r | -a] [-l] [-h] [-e] [-D] [-Q] [headerfiles]**
DESCRIPTION
-----------
*h2ph* converts any C header files specified to the corresponding Perl header file format. It is most easily run while in /usr/include:
```
cd /usr/include; h2ph * sys/*
```
or
```
cd /usr/include; h2ph * sys/* arpa/* netinet/*
```
or
```
cd /usr/include; h2ph -r -l .
```
The output files are placed in the hierarchy rooted at Perl's architecture dependent library directory. You can specify a different hierarchy with a **-d** switch.
If run with no arguments, filters standard input to standard output.
OPTIONS
-------
-d destination\_dir Put the resulting **.ph** files beneath **destination\_dir**, instead of beneath the default Perl library location (`$Config{'installsitearch'}`).
-r Run recursively; if any of **headerfiles** are directories, then run *h2ph* on all files in those directories (and their subdirectories, etc.). **-r** and **-a** are mutually exclusive.
-a Run automagically; convert **headerfiles**, as well as any **.h** files which they include. This option will search for **.h** files in all directories which your C compiler ordinarily uses. **-a** and **-r** are mutually exclusive.
-l Symbolic links will be replicated in the destination directory. If **-l** is not specified, then links are skipped over.
-h Put 'hints' in the .ph files which will help in locating problems with *h2ph*. In those cases when you **require** a **.ph** file containing syntax errors, instead of the cryptic
```
[ some error condition ] at (eval mmm) line nnn
```
you will see the slightly more helpful
```
[ some error condition ] at filename.ph line nnn
```
However, the **.ph** files almost double in size when built using **-h**.
-e If an error is encountered during conversion, output file will be removed and a warning emitted instead of terminating the conversion immediately.
-D Include the code from the **.h** file as a comment in the **.ph** file. This is primarily used for debugging *h2ph*.
-Q 'Quiet' mode; don't print out the names of the files being converted.
ENVIRONMENT
-----------
No environment variables are used.
FILES
-----
```
/usr/include/*.h
/usr/include/sys/*.h
```
etc.
AUTHOR
------
Larry Wall
SEE ALSO
---------
perl(1)
DIAGNOSTICS
-----------
The usual warnings if it can't read or write the files involved.
BUGS
----
Doesn't construct the %sizeof array for you.
It doesn't handle all C constructs, but it does attempt to isolate definitions inside evals so that you can get at the definitions that it can translate.
It's only intended as a rough tool. You may need to dicker with the files produced.
You have to run this program by hand; it's not run as part of the Perl installation.
Doesn't handle complicated expressions built piecemeal, a la:
```
enum {
FIRST_VALUE,
SECOND_VALUE,
#ifdef ABC
THIRD_VALUE
#endif
};
```
Doesn't necessarily locate all of your C compiler's internally-defined symbols.
perl experimental experimental
============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Ordering matters](#Ordering-matters)
+ [Disclaimer](#Disclaimer)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
experimental - Experimental features made easy
VERSION
-------
version 0.027
SYNOPSIS
--------
```
use experimental 'lexical_subs', 'signatures';
my sub plus_one($value) { $value + 1 }
```
DESCRIPTION
-----------
This pragma provides an easy and convenient way to enable or disable experimental features.
Every version of perl has some number of features present but considered "experimental." For much of the life of Perl 5, this was only a designation found in the documentation. Starting in Perl v5.10.0, and more aggressively in v5.18.0, experimental features were placed behind pragmata used to enable the feature and disable associated warnings.
The `experimental` pragma exists to combine the required incantations into a single interface stable across releases of perl. For every experimental feature, this should enable the feature and silence warnings for the enclosing lexical scope:
```
use experimental 'feature-name';
```
To disable the feature and, if applicable, re-enable any warnings, use:
```
no experimental 'feature-name';
```
The supported features, documented further below, are:
* `args_array_with_signatures` - allow `@_` to be used in signatured subs.
This is supported on perl 5.20.0 and above, but is likely to be removed in the future.
* `array_base` - allow the use of `$[` to change the starting index of `@array`.
This was removed in perl 5.30.0.
* `autoderef` - allow push, each, keys, and other built-ins on references.
This was added in perl 5.14.0 and removed in perl 5.24.0.
* `bitwise` - allow the new stringwise bit operators
This was added in perl 5.22.0.
* `builtin` - allow the use of the functions in the builtin:: namespace
This was added in perl 5.36.0
* `const_attr` - allow the :const attribute on subs
This was added in perl 5.22.0.
* `declared_refs` - enables aliasing via assignment to references
This was added in perl 5.26.0.
* `defer` - enables the use of defer blocks
This was added in perl 5.36.0
* `for_list` - allows iterating over multiple values at a time with `for`
This was added in perl 5.36.0
* `isa` - allow the use of the `isa` infix operator
This was added in perl 5.32.0.
* `lexical_topic` - allow the use of lexical `$_` via `my $_`.
This was added in perl 5.10.0 and removed in perl 5.24.0.
* `lexical_subs` - allow the use of lexical subroutines.
This was added in 5.18.0.
* `postderef` - allow the use of postfix dereferencing expressions
This was added in perl 5.20.0, and became non-experimental (and always enabled) in 5.24.0.
* `postderef_qq` - allow the use of postfix dereferencing expressions inside interpolating strings
This was added in perl 5.20.0, and became non-experimental (and always enabled) in 5.24.0.
* `re_strict` - enables strict mode in regular expressions
This was added in perl 5.22.0.
* `refaliasing` - allow aliasing via `\$x = \$y`
This was added in perl 5.22.0.
* `regex_sets` - allow extended bracketed character classes in regexps
This was added in perl 5.18.0.
* `signatures` - allow subroutine signatures (for named arguments)
This was added in perl 5.20.0.
* `smartmatch` - allow the use of `~~`
This was added in perl 5.10.0, but it should be noted there are significant incompatibilities between 5.10.0 and 5.10.1.
* `switch` - allow the use of `~~`, given, and when
This was added in perl 5.10.0.
* `try` - allow the use of `try` and `catch`
This was added in perl 5.34.0
* `win32_perlio` - allows the use of the :win32 IO layer.
This was added on perl 5.22.0.
###
Ordering matters
Using this pragma to 'enable an experimental feature' is another way of saying that this pragma will disable the warnings which would result from using that feature. Therefore, the order in which pragmas are applied is important. In particular, you probably want to enable experimental features *after* you enable warnings:
```
use warnings;
use experimental 'smartmatch';
```
You also need to take care with modules that enable warnings for you. A common example being Moose. In this example, warnings for the 'smartmatch' feature are first turned on by the warnings pragma, off by the experimental pragma and back on again by the Moose module (fix is to switch the last two lines):
```
use warnings;
use experimental 'smartmatch';
use Moose;
```
### Disclaimer
Because of the nature of the features it enables, forward compatibility can not be guaranteed in any way.
SEE ALSO
---------
[perlexperiment](https://perldoc.perl.org/5.36.0/perlexperiment) contains more information about experimental features.
AUTHOR
------
Leon Timmermans <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2013 by Leon Timmermans.
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 Term::ANSIColor Term::ANSIColor
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Supported Colors](#Supported-Colors)
+ [Function Interface](#Function-Interface)
+ [Constant Interface](#Constant-Interface)
+ [The Color Stack](#The-Color-Stack)
+ [Supporting CLICOLOR](#Supporting-CLICOLOR)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [ENVIRONMENT](#ENVIRONMENT)
* [COMPATIBILITY](#COMPATIBILITY)
* [RESTRICTIONS](#RESTRICTIONS)
* [NOTES](#NOTES)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Term::ANSIColor - Color screen output using ANSI escape sequences
SYNOPSIS
--------
```
use Term::ANSIColor;
print color('bold blue');
print "This text is bold blue.\n";
print color('reset');
print "This text is normal.\n";
print colored("Yellow on magenta.", 'yellow on_magenta'), "\n";
print "This text is normal.\n";
print colored(['yellow on_magenta'], 'Yellow on magenta.', "\n");
print colored(['red on_bright_yellow'], 'Red on bright yellow.', "\n");
print colored(['bright_red on_black'], 'Bright red on black.', "\n");
print "\n";
# Map escape sequences back to color names.
use Term::ANSIColor 1.04 qw(uncolor);
my @names = uncolor('01;31');
print join(q{ }, @names), "\n";
# Strip all color escape sequences.
use Term::ANSIColor 2.01 qw(colorstrip);
print colorstrip("\e[1mThis is bold\e[0m"), "\n";
# Determine whether a color is valid.
use Term::ANSIColor 2.02 qw(colorvalid);
my $valid = colorvalid('blue bold', 'on_magenta');
print "Color string is ", $valid ? "valid\n" : "invalid\n";
# Create new aliases for colors.
use Term::ANSIColor 4.00 qw(coloralias);
coloralias('alert', 'red');
print "Alert is ", coloralias('alert'), "\n";
print colored("This is in red.", 'alert'), "\n";
use Term::ANSIColor qw(:constants);
print BOLD, BLUE, "This text is in bold blue.\n", RESET;
use Term::ANSIColor qw(:constants);
{
local $Term::ANSIColor::AUTORESET = 1;
print BOLD BLUE "This text is in bold blue.\n";
print "This text is normal.\n";
}
use Term::ANSIColor 2.00 qw(:pushpop);
print PUSHCOLOR RED ON_GREEN "This text is red on green.\n";
print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n";
print RESET BRIGHT_BLUE "This text is just bright blue.\n";
print POPCOLOR "Back to red on green.\n";
print LOCALCOLOR GREEN ON_BLUE "This text is green on blue.\n";
print "This text is red on green.\n";
{
local $Term::ANSIColor::AUTOLOCAL = 1;
print ON_BLUE "This text is red on blue.\n";
print "This text is red on green.\n";
}
print POPCOLOR "Back to whatever we started as.\n";
```
DESCRIPTION
-----------
This module has two interfaces, one through color() and colored() and the other through constants. It also offers the utility functions uncolor(), colorstrip(), colorvalid(), and coloralias(), which have to be explicitly imported to be used (see ["SYNOPSIS"](#SYNOPSIS)).
If you are using Term::ANSIColor in a console command, consider supporting the CLICOLOR standard. See ["Supporting CLICOLOR"](#Supporting-CLICOLOR) for more information.
See ["COMPATIBILITY"](#COMPATIBILITY) for the versions of Term::ANSIColor that introduced particular features and the versions of Perl that included them.
###
Supported Colors
Terminal emulators that support color divide into four types: ones that support only eight colors, ones that support sixteen, ones that support 256, and ones that support 24-bit color. This module provides the ANSI escape codes for all of them. These colors are referred to as ANSI colors 0 through 7 (normal), 8 through 15 (16-color), 16 through 255 (256-color), and true color (called direct-color by **xterm**).
Unfortunately, interpretation of colors 0 through 7 often depends on whether the emulator supports eight colors or sixteen colors. Emulators that only support eight colors (such as the Linux console) will display colors 0 through 7 with normal brightness and ignore colors 8 through 15, treating them the same as white. Emulators that support 16 colors, such as gnome-terminal, normally display colors 0 through 7 as dim or darker versions and colors 8 through 15 as normal brightness. On such emulators, the "normal" white (color 7) usually is shown as pale grey, requiring bright white (15) to be used to get a real white color. Bright black usually is a dark grey color, although some terminals display it as pure black. Some sixteen-color terminal emulators also treat normal yellow (color 3) as orange or brown, and bright yellow (color 11) as yellow.
Following the normal convention of sixteen-color emulators, this module provides a pair of attributes for each color. For every normal color (0 through 7), the corresponding bright color (8 through 15) is obtained by prepending the string `bright_` to the normal color name. For example, `red` is color 1 and `bright_red` is color 9. The same applies for background colors: `on_red` is the normal color and `on_bright_red` is the bright color. Capitalize these strings for the constant interface.
There is unfortunately no way to know whether the current emulator supports more than eight colors, which makes the choice of colors difficult. The most conservative choice is to use only the regular colors, which are at least displayed on all emulators. However, they will appear dark in sixteen-color terminal emulators, including most common emulators in UNIX X environments. If you know the display is one of those emulators, you may wish to use the bright variants instead. Even better, offer the user a way to configure the colors for a given application to fit their terminal emulator.
For 256-color emulators, this module additionally provides `ansi0` through `ansi15`, which are the same as colors 0 through 15 in sixteen-color emulators but use the 256-color escape syntax, `grey0` through `grey23` ranging from nearly black to nearly white, and a set of RGB colors. The RGB colors are of the form `rgb*RGB*` where *R*, *G*, and *B* are numbers from 0 to 5 giving the intensity of red, green, and blue. The grey and RGB colors are also available as `ansi16` through `ansi255` if you want simple names for all 256 colors. `on_` variants of all of these colors are also provided. These colors may be ignored completely on non-256-color terminals or may be misinterpreted and produce random behavior. Additional attributes such as blink, italic, or bold may not work with the 256-color palette.
For true color emulators, this module supports attributes of the form `r*NNN*g*NNN*b*NNN*` and `on_r*NNN*g*NNN*b*NNN*` for all values of *NNN* between 0 and 255. These represent foreground and background colors, respectively, with the RGB values given by the *NNN* numbers. These colors may be ignored completely on non-true-color terminals or may be misinterpreted and produce random behavior.
###
Function Interface
The function interface uses attribute strings to describe the colors and text attributes to assign to text. The recognized non-color attributes are clear, reset, bold, dark, faint, italic, underline, underscore, blink, reverse, and concealed. Clear and reset (reset to default attributes), dark and faint (dim and saturated), and underline and underscore are equivalent, so use whichever is the most intuitive to you.
Note that not all attributes are supported by all terminal types, and some terminals may not support any of these sequences. Dark and faint, italic, blink, and concealed in particular are frequently not implemented.
The recognized normal foreground color attributes (colors 0 to 7) are:
```
black red green yellow blue magenta cyan white
```
The corresponding bright foreground color attributes (colors 8 to 15) are:
```
bright_black bright_red bright_green bright_yellow
bright_blue bright_magenta bright_cyan bright_white
```
The recognized normal background color attributes (colors 0 to 7) are:
```
on_black on_red on_green on yellow
on_blue on_magenta on_cyan on_white
```
The recognized bright background color attributes (colors 8 to 15) are:
```
on_bright_black on_bright_red on_bright_green on_bright_yellow
on_bright_blue on_bright_magenta on_bright_cyan on_bright_white
```
For 256-color terminals, the recognized foreground colors are:
```
ansi0 .. ansi255
grey0 .. grey23
```
plus `rgb*RGB*` for *R*, *G*, and *B* values from 0 to 5, such as `rgb000` or `rgb515`. Similarly, the recognized background colors are:
```
on_ansi0 .. on_ansi255
on_grey0 .. on_grey23
```
plus `on_rgb*RGB*` for *R*, *G*, and *B* values from 0 to 5.
For true color terminals, the recognized foreground colors are `r*RRR*g*GGG*b*BBB*` for *RRR*, *GGG*, and *BBB* values between 0 and 255. Similarly, the recognized background colors are `on_r*RRR*g*GGG*b*BBB*` for *RRR*, *GGG*, and *BBB* values between 0 and 255.
For any of the above listed attributes, case is not significant.
Attributes, once set, last until they are unset (by printing the attribute `clear` or `reset`). Be careful to do this, or otherwise your attribute will last after your script is done running, and people get very annoyed at having their prompt and typing changed to weird colors.
color(ATTR[, ATTR ...]) color() takes any number of strings as arguments and considers them to be space-separated lists of attributes. It then forms and returns the escape sequence to set those attributes. It doesn't print it out, just returns it, so you'll have to print it yourself if you want to. This is so that you can save it as a string, pass it to something else, send it to a file handle, or do anything else with it that you might care to. color() throws an exception if given an invalid attribute.
colored(STRING, ATTR[, ATTR ...])
colored(ATTR-REF, STRING[, STRING...]) As an aid in resetting colors, colored() takes a scalar as the first argument and any number of attribute strings as the second argument and returns the scalar wrapped in escape codes so that the attributes will be set as requested before the string and reset to normal after the string. Alternately, you can pass a reference to an array as the first argument, and then the contents of that array will be taken as attributes and color codes and the remainder of the arguments as text to colorize.
Normally, colored() just puts attribute codes at the beginning and end of the string, but if you set $Term::ANSIColor::EACHLINE to some string, that string will be considered the line delimiter and the attribute will be set at the beginning of each line of the passed string and reset at the end of each line. This is often desirable if the output contains newlines and you're using background colors, since a background color that persists across a newline is often interpreted by the terminal as providing the default background color for the next line. Programs like pagers can also be confused by attributes that span lines. Normally you'll want to set $Term::ANSIColor::EACHLINE to `"\n"` to use this feature.
Particularly consider setting $Term::ANSIColor::EACHLINE if you are interleaving output to standard output and standard error and you aren't flushing standard output (via autoflush() or setting `$|`). If you don't, the code to reset the color may unexpectedly sit in the standard output buffer rather than going to the display, causing standard error output to appear in the wrong color.
uncolor(ESCAPE) uncolor() performs the opposite translation as color(), turning escape sequences into a list of strings corresponding to the attributes being set by those sequences. uncolor() will never return `ansi16` through `ansi255`, instead preferring the `grey` and `rgb` names (and likewise for `on_ansi16` through `on_ansi255`).
colorstrip(STRING[, STRING ...]) colorstrip() removes all color escape sequences from the provided strings, returning the modified strings separately in array context or joined together in scalar context. Its arguments are not modified.
colorvalid(ATTR[, ATTR ...]) colorvalid() takes attribute strings the same as color() and returns true if all attributes are known and false otherwise.
coloralias(ALIAS[, ATTR ...]) If ATTR is specified, it is interpreted as a list of space-separated strings naming attributes or existing aliases. In this case, coloralias() sets up an alias of ALIAS for the set of attributes given by ATTR. From that point forward, ALIAS can be passed into color(), colored(), and colorvalid() and will have the same meaning as the sequence of attributes given in ATTR. One possible use of this facility is to give more meaningful names to the 256-color RGB colors. Only ASCII alphanumerics, `.`, `_`, and `-` are allowed in alias names.
If ATTR includes aliases, those aliases will be expanded at definition time and their values will be used to define the new alias. This means that if you define an alias A in terms of another alias B, and then later redefine alias B, the value of alias A will not change.
If ATTR is not specified, coloralias() returns the standard attribute or attributes to which ALIAS is aliased, if any, or undef if ALIAS does not exist. If it is aliased to multiple attributes, the return value will be a single string and the attributes will be separated by spaces.
This is the same facility used by the ANSI\_COLORS\_ALIASES environment variable (see ["ENVIRONMENT"](#ENVIRONMENT) below) but can be used at runtime, not just when the module is loaded.
Later invocations of coloralias() with the same ALIAS will override earlier aliases. There is no way to remove an alias.
Aliases have no effect on the return value of uncolor().
**WARNING**: Aliases are global and affect all callers in the same process. There is no way to set an alias limited to a particular block of code or a particular object.
###
Constant Interface
Alternately, if you import `:constants`, you can use the following constants directly:
```
CLEAR RESET BOLD DARK
FAINT ITALIC UNDERLINE UNDERSCORE
BLINK REVERSE CONCEALED
BLACK RED GREEN YELLOW
BLUE MAGENTA CYAN WHITE
BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW
BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE
ON_BLACK ON_RED ON_GREEN ON_YELLOW
ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE
ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW
ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE
```
These are the same as color('attribute') and can be used if you prefer typing:
```
print BOLD BLUE ON_WHITE "Text", RESET, "\n";
```
to
```
print colored ("Text", 'bold blue on_white'), "\n";
```
(Note that the newline is kept separate to avoid confusing the terminal as described above since a background color is being used.)
If you import `:constants256`, you can use the following constants directly:
```
ANSI0 .. ANSI255
GREY0 .. GREY23
RGBXYZ (for X, Y, and Z values from 0 to 5, like RGB000 or RGB515)
ON_ANSI0 .. ON_ANSI255
ON_GREY0 .. ON_GREY23
ON_RGBXYZ (for X, Y, and Z values from 0 to 5)
```
Note that `:constants256` does not include the other constants, so if you want to mix both, you need to include `:constants` as well. You may want to explicitly import at least `RESET`, as in:
```
use Term::ANSIColor 4.00 qw(RESET :constants256);
```
True color and aliases are not supported by the constant interface.
When using the constants, if you don't want to have to remember to add the `, RESET` at the end of each print line, you can set $Term::ANSIColor::AUTORESET to a true value. Then, the display mode will automatically be reset if there is no comma after the constant. In other words, with that variable set:
```
print BOLD BLUE "Text\n";
```
will reset the display mode afterward, whereas:
```
print BOLD, BLUE, "Text\n";
```
will not. If you are using background colors, you will probably want to either use say() (in newer versions of Perl) or print the newline with a separate print statement to avoid confusing the terminal.
If $Term::ANSIColor::AUTOLOCAL is set (see below), it takes precedence over $Term::ANSIColor::AUTORESET, and the latter is ignored.
The subroutine interface has the advantage over the constants interface in that only two subroutines are exported into your namespace, versus thirty-eight in the constants interface, and aliases and true color attributes are supported. On the flip side, the constants interface has the advantage of better compile time error checking, since misspelled names of colors or attributes in calls to color() and colored() won't be caught until runtime whereas misspelled names of constants will be caught at compile time. So, pollute your namespace with almost two dozen subroutines that you may not even use that often, or risk a silly bug by mistyping an attribute. Your choice, TMTOWTDI after all.
###
The Color Stack
You can import `:pushpop` and maintain a stack of colors using PUSHCOLOR, POPCOLOR, and LOCALCOLOR. PUSHCOLOR takes the attribute string that starts its argument and pushes it onto a stack of attributes. POPCOLOR removes the top of the stack and restores the previous attributes set by the argument of a prior PUSHCOLOR. LOCALCOLOR surrounds its argument in a PUSHCOLOR and POPCOLOR so that the color resets afterward.
If $Term::ANSIColor::AUTOLOCAL is set, each sequence of color constants will be implicitly preceded by LOCALCOLOR. In other words, the following:
```
{
local $Term::ANSIColor::AUTOLOCAL = 1;
print BLUE "Text\n";
}
```
is equivalent to:
```
print LOCALCOLOR BLUE "Text\n";
```
If $Term::ANSIColor::AUTOLOCAL is set, it takes precedence over $Term::ANSIColor::AUTORESET, and the latter is ignored.
When using PUSHCOLOR, POPCOLOR, and LOCALCOLOR, it's particularly important to not put commas between the constants.
```
print PUSHCOLOR BLUE "Text\n";
```
will correctly push BLUE onto the top of the stack.
```
print PUSHCOLOR, BLUE, "Text\n"; # wrong!
```
will not, and a subsequent pop won't restore the correct attributes. PUSHCOLOR pushes the attributes set by its argument, which is normally a string of color constants. It can't ask the terminal what the current attributes are.
###
Supporting CLICOLOR
<https://bixense.com/clicolors/> proposes a standard for enabling and disabling color output from console commands using two environment variables, CLICOLOR and CLICOLOR\_FORCE. Term::ANSIColor cannot automatically support this standard, since the correct action depends on where the output is going and Term::ANSIColor may be used in a context where colors should always be generated even if CLICOLOR is set in the environment. But you can use the supported environment variable ANSI\_COLORS\_DISABLED to implement CLICOLOR in your own programs with code like this:
```
if (exists($ENV{CLICOLOR}) && $ENV{CLICOLOR} == 0) {
if (!$ENV{CLICOLOR_FORCE}) {
$ENV{ANSI_COLORS_DISABLED} = 1;
}
}
```
If you are using the constant interface, be sure to include this code before you use any color constants (such as at the very top of your script), since this environment variable is only honored the first time a color constant is seen.
Be aware that this will export ANSI\_COLORS\_DISABLED to any child processes of your program as well.
DIAGNOSTICS
-----------
Bad color mapping %s (W) The specified color mapping from ANSI\_COLORS\_ALIASES is not valid and could not be parsed. It was ignored.
Bad escape sequence %s (F) You passed an invalid ANSI escape sequence to uncolor().
Bareword "%s" not allowed while "strict subs" in use (F) You probably mistyped a constant color name such as:
```
$Foobar = FOOBAR . "This line should be blue\n";
```
or:
```
@Foobar = FOOBAR, "This line should be blue\n";
```
This will only show up under use strict (another good reason to run under use strict).
Cannot alias standard color %s (F) The alias name passed to coloralias() matches a standard color name. Standard color names cannot be aliased.
Cannot alias standard color %s in %s (W) The same, but in ANSI\_COLORS\_ALIASES. The color mapping was ignored.
Invalid alias name %s (F) You passed an invalid alias name to coloralias(). Alias names must consist only of alphanumerics, `.`, `-`, and `_`.
Invalid alias name %s in %s (W) You specified an invalid alias name on the left hand of the equal sign in a color mapping in ANSI\_COLORS\_ALIASES. The color mapping was ignored.
Invalid attribute name %s (F) You passed an invalid attribute name to color(), colored(), or coloralias().
Invalid attribute name %s in %s (W) You specified an invalid attribute name on the right hand of the equal sign in a color mapping in ANSI\_COLORS\_ALIASES. The color mapping was ignored.
Name "%s" used only once: possible typo (W) You probably mistyped a constant color name such as:
```
print FOOBAR "This text is color FOOBAR\n";
```
It's probably better to always use commas after constant names in order to force the next error.
No comma allowed after filehandle (F) You probably mistyped a constant color name such as:
```
print FOOBAR, "This text is color FOOBAR\n";
```
Generating this fatal compile error is one of the main advantages of using the constants interface, since you'll immediately know if you mistype a color name.
No name for escape sequence %s (F) The ANSI escape sequence passed to uncolor() contains escapes which aren't recognized and can't be translated to names.
ENVIRONMENT
-----------
ANSI\_COLORS\_ALIASES This environment variable allows the user to specify custom color aliases that will be understood by color(), colored(), and colorvalid(). None of the other functions will be affected, and no new color constants will be created. The custom colors are aliases for existing color names; no new escape sequences can be introduced. Only alphanumerics, `.`, `_`, and `-` are allowed in alias names.
The format is:
```
ANSI_COLORS_ALIASES='newcolor1=oldcolor1,newcolor2=oldcolor2'
```
Whitespace is ignored. The alias value can be a single attribute or a space-separated list of attributes.
For example the [Solarized](https://ethanschoonover.com/solarized) colors can be mapped with:
```
ANSI_COLORS_ALIASES='\
base00=bright_yellow, on_base00=on_bright_yellow,\
base01=bright_green, on_base01=on_bright_green, \
base02=black, on_base02=on_black, \
base03=bright_black, on_base03=on_bright_black, \
base0=bright_blue, on_base0=on_bright_blue, \
base1=bright_cyan, on_base1=on_bright_cyan, \
base2=white, on_base2=on_white, \
base3=bright_white, on_base3=on_bright_white, \
orange=bright_red, on_orange=on_bright_red, \
violet=bright_magenta,on_violet=on_bright_magenta'
```
This environment variable is read and applied when the Term::ANSIColor module is loaded and is then subsequently ignored. Changes to ANSI\_COLORS\_ALIASES after the module is loaded will have no effect. See coloralias() for an equivalent facility that can be used at runtime.
ANSI\_COLORS\_DISABLED If this environment variable is set to a true value, all of the functions defined by this module (color(), colored(), and all of the constants) will not output any escape sequences and instead will just return the empty string or pass through the original text as appropriate. This is intended to support easy use of scripts using this module on platforms that don't support ANSI escape sequences.
NO\_COLOR If this environment variable is set to any value, it suppresses generation of escape sequences the same as if ANSI\_COLORS\_DISABLED is set to a true value. This implements the <https://no-color.org/> informal standard. Programs that want to enable color despite NO\_COLOR being set will need to unset that environment variable before any constant or function provided by this module is used.
COMPATIBILITY
-------------
Term::ANSIColor was first included with Perl in Perl 5.6.0.
The uncolor() function and support for ANSI\_COLORS\_DISABLED were added in Term::ANSIColor 1.04, included in Perl 5.8.0.
Support for dark was added in Term::ANSIColor 1.08, included in Perl 5.8.4.
The color stack, including the `:pushpop` import tag, PUSHCOLOR, POPCOLOR, LOCALCOLOR, and the $Term::ANSIColor::AUTOLOCAL variable, was added in Term::ANSIColor 2.00, included in Perl 5.10.1.
colorstrip() was added in Term::ANSIColor 2.01 and colorvalid() was added in Term::ANSIColor 2.02, both included in Perl 5.11.0.
Support for colors 8 through 15 (the `bright_` variants) was added in Term::ANSIColor 3.00, included in Perl 5.13.3.
Support for italic was added in Term::ANSIColor 3.02, included in Perl 5.17.1.
Support for colors 16 through 256 (the `ansi`, `rgb`, and `grey` colors), the `:constants256` import tag, the coloralias() function, and support for the ANSI\_COLORS\_ALIASES environment variable were added in Term::ANSIColor 4.00, included in Perl 5.17.8.
$Term::ANSIColor::AUTOLOCAL was changed to take precedence over $Term::ANSIColor::AUTORESET, rather than the other way around, in Term::ANSIColor 4.00, included in Perl 5.17.8.
`ansi16` through `ansi255`, as aliases for the `rgb` and `grey` colors, and the corresponding `on_ansi` names and `ANSI` and `ON_ANSI` constants were added in Term::ANSIColor 4.06, included in Perl 5.25.7.
Support for true color (the `rNNNgNNNbNNN` and `on_rNNNgNNNbNNN` attributes), defining aliases in terms of other aliases, and aliases mapping to multiple attributes instead of only a single attribute was added in Term::ANSIColor 5.00.
Support for NO\_COLOR was added in Term::ANSIColor 5.01.
RESTRICTIONS
------------
Both colored() and many uses of the color constants will add the reset escape sequence after a newline. If a program mixes colored output to standard output with output to standard error, this can result in the standard error text having the wrong color because the reset escape sequence hasn't yet been flushed to the display (since standard output to a terminal is line-buffered by default). To avoid this, either set autoflush() on STDOUT or set $Term::ANSIColor::EACHLINE to `"\n"`.
It would be nice if one could leave off the commas around the constants entirely and just say:
```
print BOLD BLUE ON_WHITE "Text\n" RESET;
```
but the syntax of Perl doesn't allow this. You need a comma after the string. (Of course, you may consider it a bug that commas between all the constants aren't required, in which case you may feel free to insert commas unless you're using $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR.)
For easier debugging, you may prefer to always use the commas when not setting $Term::ANSIColor::AUTORESET or PUSHCOLOR/POPCOLOR so that you'll get a fatal compile error rather than a warning.
It's not possible to use this module to embed formatting and color attributes using Perl formats. They replace the escape character with a space (as documented in [perlform(1)](http://man.he.net/man1/perlform)), resulting in garbled output from the unrecognized attribute. Even if there were a way around that problem, the format doesn't know that the non-printing escape sequence is zero-length and would incorrectly format the output. For formatted output using color or other attributes, either use sprintf() instead or use formline() and then add the color or other attributes after formatting and before output.
NOTES
-----
The codes generated by this module are standard terminal control codes, complying with ECMA-048 and ISO 6429 (generally referred to as "ANSI color" for the color codes). The non-color control codes (bold, dark, italic, underline, and reverse) are part of the earlier ANSI X3.64 standard for control sequences for video terminals and peripherals.
Note that not all displays are ISO 6429-compliant, or even X3.64-compliant (or are even attempting to be so). This module will not work as expected on displays that do not honor these escape sequences, such as cmd.exe, 4nt.exe, and command.com under either Windows NT or Windows 2000. They may just be ignored, or they may display as an ESC character followed by some apparent garbage.
Jean Delvare provided the following table of different common terminal emulators and their support for the various attributes and others have helped me flesh it out:
```
clear bold faint under blink reverse conceal
------------------------------------------------------------------------
xterm yes yes no yes yes yes yes
linux yes yes yes bold yes yes no
rxvt yes yes no yes bold/black yes no
dtterm yes yes yes yes reverse yes yes
teraterm yes reverse no yes rev/red yes no
aixterm kinda normal no yes no yes yes
PuTTY yes color no yes no yes no
Windows yes no no no no yes no
Cygwin SSH yes yes no color color color yes
Terminal.app yes yes no yes yes yes yes
```
Windows is Windows telnet, Cygwin SSH is the OpenSSH implementation under Cygwin on Windows NT, and Mac Terminal is the Terminal application in Mac OS X. Where the entry is other than yes or no, that emulator displays the given attribute as something else instead. Note that on an aixterm, clear doesn't reset colors; you have to explicitly set the colors back to what you want. More entries in this table are welcome.
Support for code 3 (italic) is rare and therefore not mentioned in that table. It is not believed to be fully supported by any of the terminals listed, although it's displayed as green in the Linux console, but it is reportedly supported by urxvt.
Note that codes 6 (rapid blink) and 9 (strike-through) are specified in ANSI X3.64 and ECMA-048 but are not commonly supported by most displays and emulators and therefore aren't supported by this module. ECMA-048 also specifies a large number of other attributes, including a sequence of attributes for font changes, Fraktur characters, double-underlining, framing, circling, and overlining. As none of these attributes are widely supported or useful, they also aren't currently supported by this module.
Most modern X terminal emulators support 256 colors. Known to not support those colors are aterm, rxvt, Terminal.app, and TTY/VC.
For information on true color support in various terminal emulators, see [True Colour support](https://gist.github.com/XVilka/8346728).
AUTHORS
-------
Original idea (using constants) by Zenin, reimplemented using subs by Russ Allbery <[email protected]>, and then combined with the original idea by Russ with input from Zenin. 256-color support is based on work by Kurt Starsinic. Russ Allbery now maintains this module.
PUSHCOLOR, POPCOLOR, and LOCALCOLOR were contributed by openmethods.com voice solutions.
COPYRIGHT AND LICENSE
----------------------
Copyright 1996-1998, 2000-2002, 2005-2006, 2008-2018, 2020 Russ Allbery <[email protected]>
Copyright 1996 Zenin
Copyright 2012 Kurt Starsinic <[email protected]>
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
The CPAN module <Term::ExtendedColor> provides a different and more comprehensive interface for 256-color emulators that may be more convenient. The CPAN module <Win32::Console::ANSI> provides ANSI color (and other escape sequence) support in the Win32 Console environment. The CPAN module <Term::Chrome> provides a different interface using objects and operator overloading.
ECMA-048 is available on-line (at least at the time of this writing) at <https://www.ecma-international.org/publications/standards/Ecma-048.htm>.
ISO 6429 is available from ISO for a charge; the author of this module does not own a copy of it. Since the source material for ISO 6429 was ECMA-048 and the latter is available for free, there seems little reason to obtain the ISO standard.
The 256-color control sequences are documented at <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html> (search for 256-color).
Information about true color support in various terminal emulators and test programs you can run to check the true color support in your terminal emulator are available at <https://gist.github.com/XVilka/8346728>.
[CLICOLORS](https://bixense.com/clicolors/) and [NO\_COLOR](https://no-color.org/) are useful standards to be aware of, and ideally follow, for any application using color. Term::ANSIColor complies with the latter.
The current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/ansicolor/>. It is also part of the Perl core distribution as of 5.6.0.
| programming_docs |
perl ExtUtils::MM_NW5 ExtUtils::MM\_NW5
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::MM\_NW5 - methods to override UN\*X behaviour in ExtUtils::MakeMaker
SYNOPSIS
--------
```
use ExtUtils::MM_NW5; # 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 We're Netware in addition to being Windows.
init\_platform Add Netware macros.
LIBPTH, BASE\_IMPORT, NLM\_VERSION, MPKTOOL, TOOLPATH, BOOT\_SYMBOL, NLM\_SHORT\_NAME, INCLUDE, PATH, MM\_NW5\_REVISION
platform\_constants Add Netware macros initialized above to the Makefile.
static\_lib\_pure\_cmd Defines how to run the archive utility
xs\_static\_lib\_is\_xs dynamic\_lib Override of utility methods for OS-specific work.
perl Encode::EBCDIC Encode::EBCDIC
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::EBCDIC - EBCDIC Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$posix_bc = encode("posix-bc", $utf8); # loads Encode::EBCDIC implicitly
$utf8 = decode("", $posix_bc); # ditto
```
ABSTRACT
--------
This module implements various EBCDIC-Based encodings. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
cp37
cp500
cp875
cp1026
cp1047
posix-bc
```
DESCRIPTION
-----------
To find how to use this module in detail, see [Encode](encode).
SEE ALSO
---------
[Encode](encode), <perlebcdic>
perl blib blib
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
blib - Use MakeMaker's uninstalled version of a package
SYNOPSIS
--------
```
perl -Mblib script [args...]
perl -Mblib=dir script [args...]
```
DESCRIPTION
-----------
Looks for MakeMaker-like *'blib'* directory structure starting in *dir* (or current directory) and working back up to five levels of '..'.
Intended for use on command line with **-M** option as a way of testing arbitrary scripts against an uninstalled version of a package.
However it is possible to :
```
use blib;
or
use blib '..';
```
etc. if you really must.
BUGS
----
Pollutes global name space for development only task.
AUTHOR
------
Nick Ing-Simmons [email protected]
perl CPAN::FirstTime CPAN::FirstTime
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LICENSE](#LICENSE)
NAME
----
CPAN::FirstTime - Utility for CPAN::Config file Initialization
SYNOPSIS
--------
CPAN::FirstTime::init()
DESCRIPTION
-----------
The init routine asks a few questions and writes a CPAN/Config.pm or CPAN/MyConfig.pm file (depending on what it is currently using).
In the following all questions and explanations regarding config variables are collected.
allow\_installing\_module\_downgrades The CPAN shell can watch the `blib/` directories that are built up before running `make test` to determine whether the current distribution will end up with modules being overwritten with decreasing module version numbers. It can then let the build of this distro fail when it discovers a downgrade.
Do you want to allow installing distros with decreasing module versions compared to what you have installed (yes, no, ask/yes, ask/no)?
allow\_installing\_outdated\_dists The CPAN shell can watch the `blib/` directories that are built up before running `make test` to determine whether the current distribution contains modules that are indexed with a distro with a higher distro-version number than the current one. It can then let the build of this distro fail when it would not represent the most up-to-date version of the distro.
Note: choosing anything but 'yes' for this option will need CPAN::DistnameInfo being installed for taking effect.
Do you want to allow installing distros that are not indexed as the highest distro-version for all contained modules (yes, no, ask/yes, ask/no)?
auto\_commit Normally CPAN.pm keeps config variables in memory and changes need to be saved in a separate 'o conf commit' command to make them permanent between sessions. If you set the 'auto\_commit' option to true, changes to a config variable are always automatically committed to disk.
Always commit changes to config variables to disk?
build\_cache CPAN.pm can limit the size of the disk area for keeping the build directories with all the intermediate files.
Cache size for build directory (in MB)?
build\_dir Directory where the build process takes place?
build\_dir\_reuse Until version 1.88 CPAN.pm never trusted the contents of the build\_dir directory between sessions. Since 1.88\_58 CPAN.pm has a YAML-based mechanism that makes it possible to share the contents of the build\_dir/ directory between different sessions with the same version of perl. People who prefer to test things several days before installing will like this feature because it saves a lot of time.
If you say yes to the following question, CPAN will try to store enough information about the build process so that it can pick up in future sessions at the same state of affairs as it left a previous session.
Store and re-use state information about distributions between CPAN.pm sessions?
build\_requires\_install\_policy When a module declares another one as a 'build\_requires' prerequisite this means that the other module is only needed for building or testing the module but need not be installed permanently. In this case you may wish to install that other module nonetheless or just keep it in the 'build\_dir' directory to have it available only temporarily. Installing saves time on future installations but makes the perl installation bigger.
You can choose if you want to always install (yes), never install (no) or be always asked. In the latter case you can set the default answer for the question to yes (ask/yes) or no (ask/no).
Policy on installing 'build\_requires' modules (yes, no, ask/yes, ask/no)?
cache\_metadata To considerably speed up the initial CPAN shell startup, it is possible to use Storable to create a cache of metadata. If Storable is not available, the normal index mechanism will be used.
Note: this mechanism is not used when use\_sqlite is on and SQLite is running.
Cache metadata (yes/no)?
check\_sigs CPAN packages can be digitally signed by authors and thus verified with the security provided by strong cryptography. The exact mechanism is defined in the Module::Signature module. While this is generally considered a good thing, it is not always convenient to the end user to install modules that are signed incorrectly or where the key of the author is not available or where some prerequisite for Module::Signature has a bug and so on.
With the check\_sigs parameter you can turn signature checking on and off. The default is off for now because the whole tool chain for the functionality is not yet considered mature by some. The author of CPAN.pm would recommend setting it to true most of the time and turning it off only if it turns out to be annoying.
Note that if you do not have Module::Signature installed, no signature checks will be performed at all.
Always try to check and verify signatures if a SIGNATURE file is in the package and Module::Signature is installed (yes/no)?
cleanup\_after\_install Users who install modules and do not intend to look back, can free occupied disk space quickly by letting CPAN.pm cleanup each build directory immediately after a successful install.
Remove build directory after a successful install? (yes/no)?
colorize\_output When you have Term::ANSIColor installed, you can turn on colorized output to have some visual differences between normal CPAN.pm output, warnings, debugging output, and the output of the modules being installed. Set your favorite colors after some experimenting with the Term::ANSIColor module.
Please note that on Windows platforms colorized output also requires the Win32::Console::ANSI module.
Do you want to turn on colored output?
colorize\_print Color for normal output?
colorize\_warn Color for warnings?
colorize\_debug Color for debugging messages?
commandnumber\_in\_prompt The prompt of the cpan shell can contain the current command number for easier tracking of the session or be a plain string.
Do you want the command number in the prompt (yes/no)?
connect\_to\_internet\_ok If you have never defined your own `urllist` in your configuration then `CPAN.pm` will be hesitant to use the built in default sites for downloading. It will ask you once per session if a connection to the internet is OK and only if you say yes, it will try to connect. But to avoid this question, you can choose your favorite download sites once and get away with it. Or, if you have no favorite download sites answer yes to the following question.
If no urllist has been chosen yet, would you prefer CPAN.pm to connect to the built-in default sites without asking? (yes/no)?
ftp\_passive Shall we always set the FTP\_PASSIVE environment variable when dealing with ftp download (yes/no)?
ftpstats\_period Statistics about downloads are truncated by size and period simultaneously.
How many days shall we keep statistics about downloads?
ftpstats\_size Statistics about downloads are truncated by size and period simultaneously. Setting this to zero or negative disables download statistics.
How many items shall we keep in the statistics about downloads?
getcwd CPAN.pm changes the current working directory often and needs to determine its own current working directory. Per default it uses Cwd::cwd but if this doesn't work on your system for some reason, alternatives can be configured according to the following table:
```
cwd Cwd::cwd
getcwd Cwd::getcwd
fastcwd Cwd::fastcwd
getdcwd Cwd::getdcwd
backtickcwd external command cwd
```
Preferred method for determining the current working directory?
halt\_on\_failure Normally, CPAN.pm continues processing the full list of targets and dependencies, even if one of them fails. However, you can specify that CPAN should halt after the first failure. (Note that optional recommended or suggested modules that fail will not cause a halt.)
Do you want to halt on failure (yes/no)?
histfile If you have one of the readline packages (Term::ReadLine::Perl, Term::ReadLine::Gnu, possibly others) installed, the interactive CPAN shell will have history support. The next two questions deal with the filename of the history file and with its size. If you do not want to set this variable, please hit SPACE ENTER to the following question.
File to save your history?
histsize Number of lines to save?
inactivity\_timeout Sometimes you may wish to leave the processes run by CPAN alone without caring about them. Because the Makefile.PL or the Build.PL sometimes contains question you're expected to answer, you can set a timer that will kill a 'perl Makefile.PL' process after the specified time in seconds.
If you set this value to 0, these processes will wait forever. This is the default and recommended setting.
Timeout for inactivity during {Makefile,Build}.PL?
index\_expire The CPAN indexes are usually rebuilt once or twice per hour, but the typical CPAN mirror mirrors only once or twice per day. Depending on the quality of your mirror and your desire to be on the bleeding edge, you may want to set the following value to more or less than one day (which is the default). It determines after how many days CPAN.pm downloads new indexes.
Let the index expire after how many days?
inhibit\_startup\_message When the CPAN shell is started it normally displays a greeting message that contains the running version and the status of readline support.
Do you want to turn this message off?
keep\_source\_where Unless you are accessing the CPAN on your filesystem via a file: URL, CPAN.pm needs to keep the source files it downloads somewhere. Please supply a directory where the downloaded files are to be kept.
Download target directory?
load\_module\_verbosity When CPAN.pm loads a module it needs for some optional feature, it usually reports about module name and version. Choose 'v' to get this message, 'none' to suppress it.
Verbosity level for loading modules (none or v)?
makepl\_arg Every Makefile.PL is run by perl in a separate process. Likewise we run 'make' and 'make install' in separate processes. If you have any parameters (e.g. PREFIX, UNINST or the like) you want to pass to the calls, please specify them here.
If you don't understand this question, just press ENTER.
Typical frequently used settings:
```
PREFIX=~/perl # non-root users (please see manual for more hints)
```
Parameters for the 'perl Makefile.PL' command?
make\_arg Parameters for the 'make' command? Typical frequently used setting:
```
-j3 # dual processor system (on GNU make)
```
Your choice:
make\_install\_arg Parameters for the 'make install' command? Typical frequently used setting:
```
UNINST=1 # to always uninstall potentially conflicting files
# (but do NOT use with local::lib or INSTALL_BASE)
```
Your choice:
make\_install\_make\_command Do you want to use a different make command for 'make install'? Cautious people will probably prefer:
```
su root -c make
or
sudo make
or
/path1/to/sudo -u admin_account /path2/to/make
```
or some such. Your choice:
mbuildpl\_arg A Build.PL is run by perl in a separate process. Likewise we run './Build' and './Build install' in separate processes. If you have any parameters you want to pass to the calls, please specify them here.
Typical frequently used settings:
```
--install_base /home/xxx # different installation directory
```
Parameters for the 'perl Build.PL' command?
mbuild\_arg Parameters for the './Build' command? Setting might be:
```
--extra_linker_flags -L/usr/foo/lib # non-standard library location
```
Your choice:
mbuild\_install\_arg Parameters for the './Build install' command? Typical frequently used setting:
```
--uninst 1 # uninstall conflicting files
# (but do NOT use with local::lib or INSTALL_BASE)
```
Your choice:
mbuild\_install\_build\_command Do you want to use a different command for './Build install'? Sudo users will probably prefer:
```
su root -c ./Build
or
sudo ./Build
or
/path1/to/sudo -u admin_account ./Build
```
or some such. Your choice:
pager What is your favorite pager program?
prefer\_installer When you have Module::Build installed and a module comes with both a Makefile.PL and a Build.PL, which shall have precedence?
The main two standard installer modules are the old and well established ExtUtils::MakeMaker (for short: EUMM) which uses the Makefile.PL. And the next generation installer Module::Build (MB) which works with the Build.PL (and often comes with a Makefile.PL too). If a module comes only with one of the two we will use that one but if both are supplied then a decision must be made between EUMM and MB. See also http://rt.cpan.org/Ticket/Display.html?id=29235 for a discussion about the right default.
Or, as a third option you can choose RAND which will make a random decision (something regular CPAN testers will enjoy).
In case you can choose between running a Makefile.PL or a Build.PL, which installer would you prefer (EUMM or MB or RAND)?
prefs\_dir CPAN.pm can store customized build environments based on regular expressions for distribution names. These are YAML files where the default options for CPAN.pm and the environment can be overridden and dialog sequences can be stored that can later be executed by an Expect.pm object. The CPAN.pm distribution comes with some prefab YAML files that cover sample distributions that can be used as blueprints to store your own prefs. Please check out the distroprefs/ directory of the CPAN.pm distribution to get a quick start into the prefs system.
Directory where to store default options/environment/dialogs for building modules that need some customization?
prerequisites\_policy The CPAN module can detect when a module which you are trying to build depends on prerequisites. If this happens, it can build the prerequisites for you automatically ('follow'), ask you for confirmation ('ask'), or just ignore them ('ignore'). Choosing 'follow' also sets PERL\_AUTOINSTALL and PERL\_EXTUTILS\_AUTOINSTALL for "--defaultdeps" if not already set.
Please set your policy to one of the three values.
Policy on building prerequisites (follow, ask or ignore)?
pushy\_https Boolean. Defaults to true. If this option is true, the cpan shell will use https://cpan.org/ to download stuff from the CPAN. It will fall back to http://cpan.org/ if it can't handle https for some reason (missing modules, missing programs). Whenever it falls back to the http protocol, it will issue a warning.
If this option is true, the option `urllist` will be ignored. Consequently, if you want to work with local mirrors via your own configured list of URLs, you will have to choose no below.
Do you want to turn the pushy\_https behaviour on?
randomize\_urllist CPAN.pm can introduce some randomness when using hosts for download that are configured in the urllist parameter. Enter a numeric value between 0 and 1 to indicate how often you want to let CPAN.pm try a random host from the urllist. A value of one specifies to always use a random host as the first try. A value of zero means no randomness at all. Anything in between specifies how often, on average, a random host should be tried first.
Randomize parameter
recommends\_policy (Experimental feature!) Some CPAN modules recommend additional, optional dependencies. These should generally be installed except in resource constrained environments. When this policy is true, recommended modules will be included with required modules.
Include recommended modules?
scan\_cache By default, each time the CPAN module is started, cache scanning is performed to keep the cache size in sync ('atstart'). Alternatively, scanning and cleanup can happen when CPAN exits ('atexit'). To prevent any cache cleanup, answer 'never'.
Perform cache scanning ('atstart', 'atexit' or 'never')?
shell What is your favorite shell?
show\_unparsable\_versions During the 'r' command CPAN.pm finds modules without version number. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable.
Show all individual modules that have no $VERSION?
show\_upload\_date The 'd' and the 'm' command normally only show you information they have in their in-memory database and thus will never connect to the internet. If you set the 'show\_upload\_date' variable to true, 'm' and 'd' will additionally show you the upload date of the module or distribution. Per default this feature is off because it may require a net connection to get at the upload date.
Always try to show upload date with 'd' and 'm' command (yes/no)?
show\_zero\_versions During the 'r' command CPAN.pm finds modules with a version number of zero. When the command finishes, it prints a report about this. If you want this report to be very verbose, say yes to the following variable.
Show all individual modules that have a $VERSION of zero?
suggests\_policy (Experimental feature!) Some CPAN modules suggest additional, optional dependencies. These 'suggest' dependencies provide enhanced operation. When this policy is true, suggested modules will be included with required modules.
Include suggested modules?
tar\_verbosity When CPAN.pm uses the tar command, which switch for the verbosity shall be used? Choose 'none' for quiet operation, 'v' for file name listing, 'vv' for full listing.
Tar command verbosity level (none or v or vv)?
term\_is\_latin The next option deals with the charset (a.k.a. character set) your terminal supports. In general, CPAN is English speaking territory, so the charset does not matter much but some CPAN have names that are outside the ASCII range. If your terminal supports UTF-8, you should say no to the next question. If it expects ISO-8859-1 (also known as LATIN1) then you should say yes. If it supports neither, your answer does not matter because you will not be able to read the names of some authors anyway. If you answer no, names will be output in UTF-8.
Your terminal expects ISO-8859-1 (yes/no)?
term\_ornaments When using Term::ReadLine, you can turn ornaments on so that your input stands out against the output from CPAN.pm.
Do you want to turn ornaments on?
test\_report The goal of the CPAN Testers project (http://testers.cpan.org/) is to test as many CPAN packages as possible on as many platforms as possible. This provides valuable feedback to module authors and potential users to identify bugs or platform compatibility issues and improves the overall quality and value of CPAN.
One way you can contribute is to send test results for each module that you install. If you install the CPAN::Reporter module, you have the option to automatically generate and deliver test reports to CPAN Testers whenever you run tests on a CPAN package.
See the CPAN::Reporter documentation for additional details and configuration settings. If your firewall blocks outgoing traffic, you may need to configure CPAN::Reporter before sending reports.
Generate test reports if CPAN::Reporter is installed (yes/no)?
perl5lib\_verbosity When CPAN.pm extends @INC via PERL5LIB, it prints a list of directories added (or a summary of how many directories are added). Choose 'v' to get this message, 'none' to suppress it.
Verbosity level for PERL5LIB changes (none or v)?
prefer\_external\_tar Per default all untar operations are done with the perl module Archive::Tar; by setting this variable to true the external tar command is used if available; on Unix this is usually preferred because they have a reliable and fast gnutar implementation.
Use the external tar program instead of Archive::Tar?
trust\_test\_report\_history When a distribution has already been tested by CPAN::Reporter on this machine, CPAN can skip the test phase and just rely on the test report history instead.
Note that this will not apply to distributions that failed tests because of missing dependencies. Also, tests can be run regardless of the history using "force".
Do you want to rely on the test report history (yes/no)?
urllist\_ping\_external When automatic selection of the nearest cpan mirrors is performed, turn on the use of the external ping via Net::Ping::External. This is recommended in the case the local network has a transparent proxy.
Do you want to use the external ping command when autoselecting mirrors?
urllist\_ping\_verbose When automatic selection of the nearest cpan mirrors is performed, this option can be used to turn on verbosity during the selection process.
Do you want to see verbosity turned on when autoselecting mirrors?
use\_prompt\_default When this is true, CPAN will set PERL\_MM\_USE\_DEFAULT to a true value. This causes ExtUtils::MakeMaker (and compatible) prompts to use default values instead of stopping to prompt you to answer questions. It also sets NONINTERACTIVE\_TESTING to a true value to signal more generally that distributions should not try to interact with you.
Do you want to use prompt defaults (yes/no)?
use\_sqlite CPAN::SQLite is a layer between the index files that are downloaded from the CPAN and CPAN.pm that speeds up metadata queries and reduces memory consumption of CPAN.pm considerably.
Use CPAN::SQLite if available? (yes/no)?
version\_timeout This timeout prevents CPAN from hanging when trying to parse a pathologically coded $VERSION from a module.
The default is 15 seconds. If you set this value to 0, no timeout will occur, but this is not recommended.
Timeout for parsing module versions?
yaml\_load\_code Both YAML.pm and YAML::Syck are capable of deserialising code. As this requires a string eval, which might be a security risk, you can use this option to enable or disable the deserialisation of code via CPAN::DeferredCode. (Note: This does not work under perl 5.6)
Do you want to enable code deserialisation (yes/no)?
yaml\_module At the time of this writing (2009-03) there are three YAML implementations working: YAML, YAML::Syck, and YAML::XS. The latter two are faster but need a C compiler installed on your system. There may be more alternative YAML conforming modules. When I tried two other players, YAML::Tiny and YAML::Perl, they seemed not powerful enough to work with CPAN.pm. This may have changed in the meantime.
Which YAML implementation would you prefer?
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl perlsource perlsource
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FINDING YOUR WAY AROUND](#FINDING-YOUR-WAY-AROUND)
+ [C code](#C-code)
+ [Core modules](#Core-modules)
+ [Tests](#Tests)
+ [Documentation](#Documentation)
+ [Hacking tools and documentation](#Hacking-tools-and-documentation)
+ [Build system](#Build-system)
+ [AUTHORS](#AUTHORS)
+ [MANIFEST](#MANIFEST)
NAME
----
perlsource - A guide to the Perl source tree
DESCRIPTION
-----------
This document describes the layout of the Perl source tree. If you're hacking on the Perl core, this will help you find what you're looking for.
FINDING YOUR WAY AROUND
------------------------
The Perl source tree is big. Here's some of the thing you'll find in it:
###
C code
The C source code and header files mostly live in the root of the source tree. There are a few platform-specific directories which contain C code. In addition, some of the modules shipped with Perl include C or XS code.
See <perlinterp> for more details on the files that make up the Perl interpreter, as well as details on how it works.
###
Core modules
Modules shipped as part of the Perl core live in four subdirectories. Two of these directories contain modules that live in the core, and two contain modules that can also be released separately on CPAN. Modules which can be released on cpan are known as "dual-life" modules.
* *lib/*
This directory contains pure-Perl modules which are only released as part of the core. This directory contains *all* of the modules and their tests, unlike other core modules.
* *ext/*
Like *lib/*, this directory contains modules which are only released as part of the core. Unlike *lib/*, however, a module under *ext/* generally has a CPAN-style directory- and file-layout and its own *Makefile.PL*. There is no expectation that a module under *ext/* will work with earlier versions of Perl 5. Hence, such a module may take full advantage of syntactical and other improvements in Perl 5 blead.
* *dist/*
This directory is for dual-life modules where the blead source is canonical. Note that some modules in this directory may not yet have been released separately on CPAN. Modules under *dist/* should make an effort to work with earlier versions of Perl 5.
* *cpan/*
This directory contains dual-life modules where the CPAN module is canonical. Do not patch these modules directly! Changes to these modules should be submitted to the maintainer of the CPAN module. Once those changes are applied and released, the new version of the module will be incorporated into the core.
For some dual-life modules, it has not yet been determined if the CPAN version or the blead source is canonical. Until that is done, those modules should be in *cpan/*.
### Tests
The Perl core has an extensive test suite. If you add new tests (or new modules with tests), you may need to update the *t/TEST* file so that the tests are run.
* Module tests
Tests for core modules in the *lib/* directory are right next to the module itself. For example, we have *lib/strict.pm* and *lib/strict.t*.
Tests for modules in *ext/* and the dual-life modules are in *t/* subdirectories for each module, like a standard CPAN distribution.
* *t/base/*
Tests for the absolute basic functionality of Perl. This includes `if`, basic file reads and writes, simple regexes, etc. These are run first in the test suite and if any of them fail, something is *really* broken.
* *t/cmd/*
Tests for basic control structures, `if`/`else`, `while`, subroutines, etc.
* *t/comp/*
Tests for basic issues of how Perl parses and compiles itself.
* *t/io/*
Tests for built-in IO functions, including command line arguments.
* *t/mro/*
Tests for perl's method resolution order implementations (see <mro>).
* *t/op/*
Tests for perl's built in functions that don't fit into any of the other directories.
* *t/opbasic/*
Tests for perl's built in functions which, like those in *t/op/*, do not fit into any of the other directories, but which, in addition, cannot use *t/test.pl*,as that program depends on functionality which the test file itself is testing.
* *t/re/*
Tests for regex related functions or behaviour. (These used to live in t/op).
* *t/run/*
Tests for features of how perl actually runs, including exit codes and handling of PERL\* environment variables.
* *t/uni/*
Tests for the core support of Unicode.
* *t/win32/*
Windows-specific tests.
* *t/porting/*
Tests the state of the source tree for various common errors. For example, it tests that everyone who is listed in the git log has a corresponding entry in the *AUTHORS* file.
* *t/lib/*
The old home for the module tests, you shouldn't put anything new in here. There are still some bits and pieces hanging around in here that need to be moved. Perhaps you could move them? Thanks!
### Documentation
All of the core documentation intended for end users lives in *pod/*. Individual modules in *lib/*, *ext/*, *dist/*, and *cpan/* usually have their own documentation, either in the *Module.pm* file or an accompanying *Module.pod* file.
Finally, documentation intended for core Perl developers lives in the *Porting/* directory.
###
Hacking tools and documentation
The *Porting* directory contains a grab bag of code and documentation intended to help porters work on Perl. Some of the highlights include:
* *check\**
These are scripts which will check the source things like ANSI C violations, POD encoding issues, etc.
* *Maintainers*, *Maintainers.pl*, and *Maintainers.pm*
These files contain information on who maintains which modules. Run `perl Porting/Maintainers -M Module::Name` to find out more information about a dual-life module.
* *podtidy*
Tidies a pod file. It's a good idea to run this on a pod file you've patched.
###
Build system
The Perl build system on \*nix-like systems starts with the *Configure* script in the root directory.
Platform-specific pieces of the build system also live in platform-specific directories like *win32/*, *vms/*, etc. Windows and VMS have their own Configure-like scripts, in their respective directories.
The *Configure* script (or a platform-specific similar script) is ultimately responsible for generating a *Makefile* from *Makefile.SH*.
The build system that Perl uses is called metaconfig. This system is maintained separately from the Perl core, and knows about the platform-specific Configure-like scripts, as well as *Configure* itself.
The metaconfig system has its own git repository. Please see its README file in <https://github.com/Perl/metaconfig> for more details.
The *Cross* directory contains various files related to cross-compiling Perl. See *Cross/README* for more details.
### *AUTHORS*
This file lists everyone who's contributed to Perl. If you submit a patch, you should add your name to this file as part of the patch.
### *MANIFEST*
The *MANIFEST* file in the root of the source tree contains a list of every file in the Perl core, as well as a brief description of each file.
You can get an overview of all the files with this command:
```
% perl -lne 'print if /^[^\/]+\.[ch]\s+/' MANIFEST
```
perl Math::BigFloat Math::BigFloat
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Input](#Input)
+ [Output](#Output)
* [METHODS](#METHODS)
+ [Configuration methods](#Configuration-methods)
+ [Constructor methods](#Constructor-methods)
+ [Arithmetic methods](#Arithmetic-methods)
+ [ACCURACY AND PRECISION](#ACCURACY-AND-PRECISION)
+ [Rounding](#Rounding)
* [NUMERIC LITERALS](#NUMERIC-LITERALS)
+ [Hexadecimal, octal, and binary floating point literals](#Hexadecimal,-octal,-and-binary-floating-point-literals)
+ [Math library](#Math-library)
+ [Using Math::BigInt::Lite](#Using-Math::BigInt::Lite)
* [EXPORTS](#EXPORTS)
* [CAVEATS](#CAVEATS)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
Math::BigFloat - arbitrary size floating point math package
SYNOPSIS
--------
```
use Math::BigFloat;
# Configuration methods (may be used as class methods and instance methods)
Math::BigFloat->accuracy(); # get class accuracy
Math::BigFloat->accuracy($n); # set class accuracy
Math::BigFloat->precision(); # get class precision
Math::BigFloat->precision($n); # set class precision
Math::BigFloat->round_mode(); # get class rounding mode
Math::BigFloat->round_mode($m); # set global round mode, must be one of
# 'even', 'odd', '+inf', '-inf', 'zero',
# 'trunc', or 'common'
Math::BigFloat->config("lib"); # name of backend math library
# Constructor methods (when the class methods below are used as instance
# methods, the value is assigned the invocand)
$x = Math::BigFloat->new($str); # defaults to 0
$x = Math::BigFloat->new('0x123'); # from hexadecimal
$x = Math::BigFloat->new('0o377'); # from octal
$x = Math::BigFloat->new('0b101'); # from binary
$x = Math::BigFloat->from_hex('0xc.afep+3'); # from hex
$x = Math::BigFloat->from_hex('cafe'); # ditto
$x = Math::BigFloat->from_oct('1.3267p-4'); # from octal
$x = Math::BigFloat->from_oct('01.3267p-4'); # ditto
$x = Math::BigFloat->from_oct('0o1.3267p-4'); # ditto
$x = Math::BigFloat->from_oct('0377'); # ditto
$x = Math::BigFloat->from_bin('0b1.1001p-4'); # from binary
$x = Math::BigFloat->from_bin('0101'); # ditto
$x = Math::BigFloat->from_ieee754($b, "binary64"); # from IEEE-754 bytes
$x = Math::BigFloat->bzero(); # create a +0
$x = Math::BigFloat->bone(); # create a +1
$x = Math::BigFloat->bone('-'); # create a -1
$x = Math::BigFloat->binf(); # create a +inf
$x = Math::BigFloat->binf('-'); # create a -inf
$x = Math::BigFloat->bnan(); # create a Not-A-Number
$x = Math::BigFloat->bpi(); # returns pi
$y = $x->copy(); # make a copy (unlike $y = $x)
$y = $x->as_int(); # return as BigInt
# Boolean methods (these don't modify the invocand)
$x->is_zero(); # if $x is 0
$x->is_one(); # if $x is +1
$x->is_one("+"); # ditto
$x->is_one("-"); # if $x is -1
$x->is_inf(); # if $x is +inf or -inf
$x->is_inf("+"); # if $x is +inf
$x->is_inf("-"); # if $x is -inf
$x->is_nan(); # if $x is NaN
$x->is_positive(); # if $x > 0
$x->is_pos(); # ditto
$x->is_negative(); # if $x < 0
$x->is_neg(); # ditto
$x->is_odd(); # if $x is odd
$x->is_even(); # if $x is even
$x->is_int(); # if $x is an integer
# Comparison methods
$x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0)
$x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0)
$x->beq($y); # true if and only if $x == $y
$x->bne($y); # true if and only if $x != $y
$x->blt($y); # true if and only if $x < $y
$x->ble($y); # true if and only if $x <= $y
$x->bgt($y); # true if and only if $x > $y
$x->bge($y); # true if and only if $x >= $y
# Arithmetic methods
$x->bneg(); # negation
$x->babs(); # absolute value
$x->bsgn(); # sign function (-1, 0, 1, or NaN)
$x->bnorm(); # normalize (no-op)
$x->binc(); # increment $x by 1
$x->bdec(); # decrement $x by 1
$x->badd($y); # addition (add $y to $x)
$x->bsub($y); # subtraction (subtract $y from $x)
$x->bmul($y); # multiplication (multiply $x by $y)
$x->bmuladd($y,$z); # $x = $x * $y + $z
$x->bdiv($y); # division (floored), set $x to quotient
# return (quo,rem) or quo if scalar
$x->btdiv($y); # division (truncated), set $x to quotient
# return (quo,rem) or quo if scalar
$x->bmod($y); # modulus (x % y)
$x->btmod($y); # modulus (truncated)
$x->bmodinv($mod); # modular multiplicative inverse
$x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod)
$x->bpow($y); # power of arguments (x ** y)
$x->blog(); # logarithm of $x to base e (Euler's number)
$x->blog($base); # logarithm of $x to base $base (e.g., base 2)
$x->bexp(); # calculate e ** $x where e is Euler's number
$x->bnok($y); # x over y (binomial coefficient n over k)
$x->bsin(); # sine
$x->bcos(); # cosine
$x->batan(); # inverse tangent
$x->batan2($y); # two-argument inverse tangent
$x->bsqrt(); # calculate square root
$x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->blsft($n); # left shift $n places in base 2
$x->blsft($n,$b); # left shift $n places in base $b
# returns (quo,rem) or quo (scalar context)
$x->brsft($n); # right shift $n places in base 2
$x->brsft($n,$b); # right shift $n places in base $b
# returns (quo,rem) or quo (scalar context)
# Bitwise methods
$x->band($y); # bitwise and
$x->bior($y); # bitwise inclusive or
$x->bxor($y); # bitwise exclusive or
$x->bnot(); # bitwise not (two's complement)
# Rounding methods
$x->round($A,$P,$mode); # round to accuracy or precision using
# rounding mode $mode
$x->bround($n); # accuracy: preserve $n digits
$x->bfround($n); # $n > 0: round to $nth digit left of dec. point
# $n < 0: round to $nth digit right of dec. point
$x->bfloor(); # round towards minus infinity
$x->bceil(); # round towards plus infinity
$x->bint(); # round towards zero
# Other mathematical methods
$x->bgcd($y); # greatest common divisor
$x->blcm($y); # least common multiple
# Object property methods (do not modify the invocand)
$x->sign(); # the sign, either +, - or NaN
$x->digit($n); # the nth digit, counting from the right
$x->digit(-$n); # the nth digit, counting from the left
$x->length(); # return number of digits in number
($xl,$f) = $x->length(); # length of number and length of fraction
# part, latter is always 0 digits long
# for Math::BigInt objects
$x->mantissa(); # return (signed) mantissa as BigInt
$x->exponent(); # return exponent as BigInt
$x->parts(); # return (mantissa,exponent) as BigInt
$x->sparts(); # mantissa and exponent (as integers)
$x->nparts(); # mantissa and exponent (normalised)
$x->eparts(); # mantissa and exponent (engineering notation)
$x->dparts(); # integer and fraction part
$x->fparts(); # numerator and denominator
$x->numerator(); # numerator
$x->denominator(); # denominator
# Conversion methods (do not modify the invocand)
$x->bstr(); # decimal notation, possibly zero padded
$x->bsstr(); # string in scientific notation with integers
$x->bnstr(); # string in normalized notation
$x->bestr(); # string in engineering notation
$x->bdstr(); # string in decimal notation
$x->as_hex(); # as signed hexadecimal string with prefixed 0x
$x->as_bin(); # as signed binary string with prefixed 0b
$x->as_oct(); # as signed octal string with prefixed 0
$x->to_ieee754($format); # to bytes encoded according to IEEE 754-2008
# Other conversion methods
$x->numify(); # return as scalar (might overflow or underflow)
```
DESCRIPTION
-----------
Math::BigFloat provides support for arbitrary precision floating point. Overloading is also provided for Perl operators.
All operators (including basic math operations) are overloaded if you declare your big floating point numbers as
```
$x = Math::BigFloat -> new('12_3.456_789_123_456_789E-2');
```
Operations with overloaded operators preserve the arguments, which is exactly what you expect.
### Input
Input values to these routines may be any scalar number or string that looks like a number. Anything that is accepted by Perl as a literal numeric constant should be accepted by this module.
* Leading and trailing whitespace is ignored.
* Leading zeros are ignored, except for floating point numbers with a binary exponent, in which case the number is interpreted as an octal floating point number. For example, "01.4p+0" gives 1.5, "00.4p+0" gives 0.5, but "0.4p+0" gives a NaN. And while "0377" gives 255, "0377p0" gives 255.
* If the string has a "0x" or "0X" prefix, it is interpreted as a hexadecimal number.
* If the string has a "0o" or "0O" prefix, it is interpreted as an octal number. A floating point literal with a "0" prefix is also interpreted as an octal number.
* If the string has a "0b" or "0B" prefix, it is interpreted as a binary number.
* Underline characters are allowed in the same way as they are allowed in literal numerical constants.
* If the string can not be interpreted, NaN is returned.
* For hexadecimal, octal, and binary floating point numbers, the exponent must be separated from the significand (mantissa) by the letter "p" or "P", not "e" or "E" as with decimal numbers.
Some examples of valid string input
```
Input string Resulting value
123 123
1.23e2 123
12300e-2 123
67_538_754 67538754
-4_5_6.7_8_9e+0_1_0 -4567890000000
0x13a 314
0x13ap0 314
0x1.3ap+8 314
0x0.00013ap+24 314
0x13a000p-12 314
0o472 314
0o1.164p+8 314
0o0.0001164p+20 314
0o1164000p-10 314
0472 472 Note!
01.164p+8 314
00.0001164p+20 314
01164000p-10 314
0b100111010 314
0b1.0011101p+8 314
0b0.00010011101p+12 314
0b100111010000p-3 314
0x1.921fb5p+1 3.14159262180328369140625e+0
0o1.2677025p1 2.71828174591064453125
01.2677025p1 2.71828174591064453125
0b1.1001p-4 9.765625e-2
```
### Output
Output values are usually Math::BigFloat objects.
Boolean operators `is_zero()`, `is_one()`, `is_inf()`, etc. return true or false.
Comparison operators `bcmp()` and `bacmp()`) return -1, 0, 1, or undef.
METHODS
-------
Math::BigFloat supports all methods that Math::BigInt supports, except it calculates non-integer results when possible. Please see <Math::BigInt> for a full description of each method. Below are just the most important differences:
###
Configuration methods
accuracy()
```
$x->accuracy(5); # local for $x
CLASS->accuracy(5); # global for all members of CLASS
# Note: This also applies to new()!
$A = $x->accuracy(); # read out accuracy that affects $x
$A = CLASS->accuracy(); # read out global accuracy
```
Set or get the global or local accuracy, aka how many significant digits the results have. If you set a global accuracy, then this also applies to new()!
Warning! The accuracy *sticks*, e.g. once you created a number under the influence of `CLASS->accuracy($A)`, all results from math operations with that number will also be rounded.
In most cases, you should probably round the results explicitly using one of ["round()" in Math::BigInt](Math::BigInt#round%28%29), ["bround()" in Math::BigInt](Math::BigInt#bround%28%29) or ["bfround()" in Math::BigInt](Math::BigInt#bfround%28%29) or by passing the desired accuracy to the math operation as additional parameter:
```
my $x = Math::BigInt->new(30000);
my $y = Math::BigInt->new(7);
print scalar $x->copy()->bdiv($y, 2); # print 4300
print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
```
precision()
```
$x->precision(-2); # local for $x, round at the second
# digit right of the dot
$x->precision(2); # ditto, round at the second digit
# left of the dot
CLASS->precision(5); # Global for all members of CLASS
# This also applies to new()!
CLASS->precision(-5); # ditto
$P = CLASS->precision(); # read out global precision
$P = $x->precision(); # read out precision that affects $x
```
Note: You probably want to use ["accuracy()"](#accuracy%28%29) instead. With ["accuracy()"](#accuracy%28%29) you set the number of digits each result should have, with ["precision()"](#precision%28%29) you set the place where to round!
###
Constructor methods
from\_hex()
```
$x -> from_hex("0x1.921fb54442d18p+1");
$x = Math::BigFloat -> from_hex("0x1.921fb54442d18p+1");
```
Interpret input as a hexadecimal string.A prefix ("0x", "x", ignoring case) is optional. A single underscore character ("\_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.
If called as an instance method, the value is assigned to the invocand.
from\_oct()
```
$x -> from_oct("1.3267p-4");
$x = Math::BigFloat -> from_oct("1.3267p-4");
```
Interpret input as an octal string. A single underscore character ("\_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.
If called as an instance method, the value is assigned to the invocand.
from\_bin()
```
$x -> from_bin("0b1.1001p-4");
$x = Math::BigFloat -> from_bin("0b1.1001p-4");
```
Interpret input as a hexadecimal string. A prefix ("0b" or "b", ignoring case) is optional. A single underscore character ("\_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits.
If called as an instance method, the value is assigned to the invocand.
from\_ieee754() Interpret the input as a value encoded as described in IEEE754-2008. The input can be given as a byte string, hex string or binary string. The input is assumed to be in big-endian byte-order.
```
# both $dbl and $mbf are 3.141592...
$bytes = "\x40\x09\x21\xfb\x54\x44\x2d\x18";
$dbl = unpack "d>", $bytes;
$mbf = Math::BigFloat -> from_ieee754($bytes, "binary64");
```
bpi()
```
print Math::BigFloat->bpi(100), "\n";
```
Calculate PI to N digits (including the 3 before the dot). The result is rounded according to the current rounding mode, which defaults to "even".
This method was added in v1.87 of Math::BigInt (June 2007).
###
Arithmetic methods
bmuladd()
```
$x->bmuladd($y,$z);
```
Multiply $x by $y, and then add $z to the result.
This method was added in v1.87 of Math::BigInt (June 2007).
bdiv()
```
$q = $x->bdiv($y);
($q, $r) = $x->bdiv($y);
```
In scalar context, divides $x by $y and returns the result to the given or default accuracy/precision. In list context, does floored division (F-division), returning an integer $q and a remainder $r so that $x = $q \* $y + $r. The remainer (modulo) is equal to what is returned by `$x->bmod($y)`.
bmod()
```
$x->bmod($y);
```
Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the result is identical to the remainder after floored division (F-division). If, in addition, both $x and $y are integers, the result is identical to the result from Perl's % operator.
bexp()
```
$x->bexp($accuracy); # calculate e ** X
```
Calculates the expression `e ** $x` where `e` is Euler's number.
This method was added in v1.82 of Math::BigInt (April 2007).
bnok()
```
$x->bnok($y); # x over y (binomial coefficient n over k)
```
Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to:
```
( n ) n!
| - | = -------
( k ) k!(n-k)!
```
This method was added in v1.84 of Math::BigInt (April 2007).
bsin()
```
my $x = Math::BigFloat->new(1);
print $x->bsin(100), "\n";
```
Calculate the sinus of $x, modifying $x in place.
This method was added in v1.87 of Math::BigInt (June 2007).
bcos()
```
my $x = Math::BigFloat->new(1);
print $x->bcos(100), "\n";
```
Calculate the cosinus of $x, modifying $x in place.
This method was added in v1.87 of Math::BigInt (June 2007).
batan()
```
my $x = Math::BigFloat->new(1);
print $x->batan(100), "\n";
```
Calculate the arcus tanges of $x, modifying $x in place. See also ["batan2()"](#batan2%28%29).
This method was added in v1.87 of Math::BigInt (June 2007).
batan2()
```
my $y = Math::BigFloat->new(2);
my $x = Math::BigFloat->new(3);
print $y->batan2($x), "\n";
```
Calculate the arcus tanges of `$y` divided by `$x`, modifying $y in place. See also ["batan()"](#batan%28%29).
This method was added in v1.87 of Math::BigInt (June 2007).
as\_float() This method is called when Math::BigFloat encounters an object it doesn't know how to handle. For instance, assume $x is a Math::BigFloat, or subclass thereof, and $y is defined, but not a Math::BigFloat, or subclass thereof. If you do
```
$x -> badd($y);
```
$y needs to be converted into an object that $x can deal with. This is done by first checking if $y is something that $x might be upgraded to. If that is the case, no further attempts are made. The next is to see if $y supports the method `as_float()`. The method `as_float()` is expected to return either an object that has the same class as $x, a subclass thereof, or a string that `ref($x)->new()` can parse to create an object.
In Math::BigFloat, `as_float()` has the same effect as `copy()`.
to\_ieee754() Encodes the invocand as a byte string in the given format as specified in IEEE 754-2008. Note that the encoded value is the nearest possible representation of the value. This value might not be exactly the same as the value in the invocand.
```
# $x = 3.1415926535897932385
$x = Math::BigFloat -> bpi(30);
$b = $x -> to_ieee754("binary64"); # encode as 8 bytes
$h = unpack "H*", $b; # "400921fb54442d18"
# 3.141592653589793115997963...
$y = Math::BigFloat -> from_ieee754($h, "binary64");
```
All binary formats in IEEE 754-2008 are accepted. For convenience, som aliases are recognized: "half" for "binary16", "single" for "binary32", "double" for "binary64", "quadruple" for "binary128", "octuple" for "binary256", and "sexdecuple" for "binary512".
See also <https://en.wikipedia.org/wiki/IEEE_754>.
###
ACCURACY AND PRECISION
See also: [Rounding](#Rounding).
Math::BigFloat supports both precision (rounding to a certain place before or after the dot) and accuracy (rounding to a certain number of digits). For a full documentation, examples and tips on these topics please see the large section about rounding in <Math::BigInt>.
Since things like `sqrt(2)` or `1 / 3` must presented with a limited accuracy lest a operation consumes all resources, each operation produces no more than the requested number of digits.
If there is no global precision or accuracy set, **and** the operation in question was not called with a requested precision or accuracy, **and** the input $x has no accuracy or precision set, then a fallback parameter will be used. For historical reasons, it is called `div_scale` and can be accessed via:
```
$d = Math::BigFloat->div_scale(); # query
Math::BigFloat->div_scale($n); # set to $n digits
```
The default value for `div_scale` is 40.
In case the result of one operation has more digits than specified, it is rounded. The rounding mode taken is either the default mode, or the one supplied to the operation after the *scale*:
```
$x = Math::BigFloat->new(2);
Math::BigFloat->accuracy(5); # 5 digits max
$y = $x->copy()->bdiv(3); # gives 0.66667
$y = $x->copy()->bdiv(3,6); # gives 0.666667
$y = $x->copy()->bdiv(3,6,undef,'odd'); # gives 0.666667
Math::BigFloat->round_mode('zero');
$y = $x->copy()->bdiv(3,6); # will also give 0.666667
```
Note that `Math::BigFloat->accuracy()` and `Math::BigFloat->precision()` set the global variables, and thus **any** newly created number will be subject to the global rounding **immediately**. This means that in the examples above, the `3` as argument to `bdiv()` will also get an accuracy of **5**.
It is less confusing to either calculate the result fully, and afterwards round it explicitly, or use the additional parameters to the math functions like so:
```
use Math::BigFloat;
$x = Math::BigFloat->new(2);
$y = $x->copy()->bdiv(3);
print $y->bround(5),"\n"; # gives 0.66667
or
use Math::BigFloat;
$x = Math::BigFloat->new(2);
$y = $x->copy()->bdiv(3,5); # gives 0.66667
print "$y\n";
```
### Rounding
bfround ( +$scale ) Rounds to the $scale'th place left from the '.', counting from the dot. The first digit is numbered 1.
bfround ( -$scale ) Rounds to the $scale'th place right from the '.', counting from the dot.
bfround ( 0 ) Rounds to an integer.
bround ( +$scale ) Preserves accuracy to $scale digits from the left (aka significant digits) and pads the rest with zeros. If the number is between 1 and -1, the significant digits count from the first non-zero after the '.'
bround ( -$scale ) and bround ( 0 ) These are effectively no-ops.
All rounding functions take as a second parameter a rounding mode from one of the following: 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'.
The default rounding mode is 'even'. By using `Math::BigFloat->round_mode($round_mode);` you can get and set the default mode for subsequent rounding. The usage of `$Math::BigFloat::$round_mode` is no longer supported. The second parameter to the round functions then overrides the default temporarily.
The `as_number()` function returns a BigInt from a Math::BigFloat. It uses 'trunc' as rounding mode to make it equivalent to:
```
$x = 2.5;
$y = int($x) + 2;
```
You can override this by passing the desired rounding mode as parameter to `as_number()`:
```
$x = Math::BigFloat->new(2.5);
$y = $x->as_number('odd'); # $y = 3
```
NUMERIC LITERALS
-----------------
After `use Math::BigFloat ':constant'` all numeric literals in the given scope are converted to `Math::BigFloat` objects. This conversion happens at compile time.
For example,
```
perl -MMath::BigFloat=:constant -le 'print 2e-150'
```
prints the exact value of `2e-150`. Note that without conversion of constants the expression `2e-150` is calculated using Perl scalars, which leads to an inaccuracte result.
Note that strings are not affected, so that
```
use Math::BigFloat qw/:constant/;
$y = "1234567890123456789012345678901234567890"
+ "123456789123456789";
```
does not give you what you expect. You need an explicit Math::BigFloat->new() around at least one of the operands. You should also quote large constants to prevent loss of precision:
```
use Math::BigFloat;
$x = Math::BigFloat->new("1234567889123456789123456789123456789");
```
Without the quotes Perl converts the large number to a floating point constant at compile time, and then converts the result to a Math::BigFloat object at runtime, which results in an inaccurate result.
###
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. Below are some examples of different ways to write the number decimal 314.
Hexadecimal floating point literals:
```
0x1.3ap+8 0X1.3AP+8
0x1.3ap8 0X1.3AP8
0x13a0p-4 0X13A0P-4
```
Octal floating point literals (with "0" prefix):
```
01.164p+8 01.164P+8
01.164p8 01.164P8
011640p-4 011640P-4
```
Octal floating point literals (with "0o" prefix) (requires v5.34.0):
```
0o1.164p+8 0O1.164P+8
0o1.164p8 0O1.164P8
0o11640p-4 0O11640P-4
```
Binary floating point literals:
```
0b1.0011101p+8 0B1.0011101P+8
0b1.0011101p8 0B1.0011101P8
0b10011101000p-2 0B10011101000P-2
```
###
Math library
Math with the numbers is done (by default) by a module called Math::BigInt::Calc. This is equivalent to saying:
```
use Math::BigFloat lib => "Calc";
```
You can change this by using:
```
use Math::BigFloat lib => "GMP";
```
**Note**: General purpose packages should not be explicit about the library to use; let the script author decide which is best.
Note: The keyword 'lib' will warn when the requested library could not be loaded. To suppress the warning use 'try' instead:
```
use Math::BigFloat try => "GMP";
```
If your script works with huge numbers and Calc is too slow for them, you can also for the loading of one of these libraries and if none of them can be used, the code will die:
```
use Math::BigFloat only => "GMP,Pari";
```
The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
```
use Math::BigFloat lib => "Foo,Math::BigInt::Bar";
```
See the respective low-level library documentation for further details.
See <Math::BigInt> for more details about using a different low-level library.
###
Using Math::BigInt::Lite
For backwards compatibility reasons it is still possible to request a different storage class for use with Math::BigFloat:
```
use Math::BigFloat with => 'Math::BigInt::Lite';
```
However, this request is ignored, as the current code now uses the low-level math library for directly storing the number parts.
EXPORTS
-------
`Math::BigFloat` exports nothing by default, but can export the `bpi()` method:
```
use Math::BigFloat qw/bpi/;
print bpi(10), "\n";
```
CAVEATS
-------
Do not try to be clever to insert some operations in between switching libraries:
```
require Math::BigFloat;
my $matter = Math::BigFloat->bone() + 4; # load BigInt and Calc
Math::BigFloat->import( lib => 'Pari' ); # load Pari, too
my $anti_matter = Math::BigFloat->bone()+4; # now use Pari
```
This will create objects with numbers stored in two different backend libraries, and **VERY BAD THINGS** will happen when you use these together:
```
my $flash_and_bang = $matter + $anti_matter; # Don't do this!
```
stringify, bstr() Both stringify and bstr() now drop the leading '+'. The old code would return '+1.23', the new returns '1.23'. See the documentation in <Math::BigInt> for reasoning and details.
brsft() The following will probably not print what you expect:
```
my $c = Math::BigFloat->new('3.14159');
print $c->brsft(3,10),"\n"; # prints 0.00314153.1415
```
It prints both quotient and remainder, since print calls `brsft()` in list context. Also, `$c->brsft()` will modify $c, so be careful. You probably want to use
```
print scalar $c->copy()->brsft(3,10),"\n";
# or if you really want to modify $c
print scalar $c->brsft(3,10),"\n";
```
instead.
Modifying and = Beware of:
```
$x = Math::BigFloat->new(5);
$y = $x;
```
It will not do what you think, e.g. making a copy of $x. Instead it just makes a second reference to the **same** object and stores it in $y. Thus anything that modifies $x will modify $y (except overloaded math operators), and vice versa. See <Math::BigInt> for details and how to avoid that.
precision() vs. accuracy() A common pitfall is to use ["precision()"](#precision%28%29) when you want to round a result to a certain number of digits:
```
use Math::BigFloat;
Math::BigFloat->precision(4); # does not do what you
# think it does
my $x = Math::BigFloat->new(12345); # rounds $x to "12000"!
print "$x\n"; # print "12000"
my $y = Math::BigFloat->new(3); # rounds $y to "0"!
print "$y\n"; # print "0"
$z = $x / $y; # 12000 / 0 => NaN!
print "$z\n";
print $z->precision(),"\n"; # 4
```
Replacing ["precision()"](#precision%28%29) with ["accuracy()"](#accuracy%28%29) is probably not what you want, either:
```
use Math::BigFloat;
Math::BigFloat->accuracy(4); # enables global rounding:
my $x = Math::BigFloat->new(123456); # rounded immediately
# to "12350"
print "$x\n"; # print "123500"
my $y = Math::BigFloat->new(3); # rounded to "3
print "$y\n"; # print "3"
print $z = $x->copy()->bdiv($y),"\n"; # 41170
print $z->accuracy(),"\n"; # 4
```
What you want to use instead is:
```
use Math::BigFloat;
my $x = Math::BigFloat->new(123456); # no rounding
print "$x\n"; # print "123456"
my $y = Math::BigFloat->new(3); # no rounding
print "$y\n"; # print "3"
print $z = $x->copy()->bdiv($y,4),"\n"; # 41150
print $z->accuracy(),"\n"; # undef
```
In addition to computing what you expected, the last example also does **not** "taint" the result with an accuracy or precision setting, which would influence any further operation.
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::BigFloat
```
You can also look for information at:
* GitHub
<https://github.com/pjacklam/p5-Math-BigInt>
* RT: CPAN's request tracker
<https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
* MetaCPAN
<https://metacpan.org/release/Math-BigInt>
* CPAN Testers Matrix
<http://matrix.cpantesters.org/?dist=Math-BigInt>
* CPAN Ratings
<https://cpanratings.perl.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.
SEE ALSO
---------
<Math::BigInt> and <Math::BigInt> as well as the backends <Math::BigInt::FastCalc>, <Math::BigInt::GMP>, and <Math::BigInt::Pari>.
The pragmas <bignum>, <bigint> and <bigrat>.
AUTHORS
-------
* Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
* Completely rewritten by Tels <http://bloodgate.com> in 2001-2008.
* Florian Ragwitz <[email protected]>, 2010.
* Peter John Acklam <[email protected]>, 2011-.
| programming_docs |
perl perldtrace perldtrace
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [HISTORY](#HISTORY)
* [PROBES](#PROBES)
* [EXAMPLES](#EXAMPLES)
* [REFERENCES](#REFERENCES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
perldtrace - Perl's support for DTrace
SYNOPSIS
--------
```
# dtrace -Zn 'perl::sub-entry, perl::sub-return { trace(copyinstr(arg0)) }'
dtrace: description 'perl::sub-entry, perl::sub-return ' matched 10 probes
# perl -E 'sub outer { inner(@_) } sub inner { say shift } outer("hello")'
hello
(dtrace output)
CPU ID FUNCTION:NAME
0 75915 Perl_pp_entersub:sub-entry BEGIN
0 75915 Perl_pp_entersub:sub-entry import
0 75922 Perl_pp_leavesub:sub-return import
0 75922 Perl_pp_leavesub:sub-return BEGIN
0 75915 Perl_pp_entersub:sub-entry outer
0 75915 Perl_pp_entersub:sub-entry inner
0 75922 Perl_pp_leavesub:sub-return inner
0 75922 Perl_pp_leavesub:sub-return outer
```
DESCRIPTION
-----------
DTrace is a framework for comprehensive system- and application-level tracing. Perl is a DTrace *provider*, meaning it exposes several *probes* for instrumentation. You can use these in conjunction with kernel-level probes, as well as probes from other providers such as MySQL, in order to diagnose software defects, or even just your application's bottlenecks.
Perl must be compiled with the `-Dusedtrace` option in order to make use of the provided probes. While DTrace aims to have no overhead when its instrumentation is not active, Perl's support itself cannot uphold that guarantee, so it is built without DTrace probes under most systems. One notable exception is that Mac OS X ships a */usr/bin/perl* with DTrace support enabled.
HISTORY
-------
5.10.1 Perl's initial DTrace support was added, providing `sub-entry` and `sub-return` probes.
5.14.0 The `sub-entry` and `sub-return` probes gain a fourth argument: the package name of the function.
5.16.0 The `phase-change` probe was added.
5.18.0 The `op-entry`, `loading-file`, and `loaded-file` probes were added.
PROBES
------
sub-entry(SUBNAME, FILE, LINE, PACKAGE) Traces the entry of any subroutine. Note that all of the variables refer to the subroutine that is being invoked; there is currently no way to get ahold of any information about the subroutine's *caller* from a DTrace action.
```
:*perl*::sub-entry {
printf("%s::%s entered at %s line %d\n",
copyinstr(arg3), copyinstr(arg0), copyinstr(arg1), arg2);
}
```
sub-return(SUBNAME, FILE, LINE, PACKAGE) Traces the exit of any subroutine. Note that all of the variables refer to the subroutine that is returning; there is currently no way to get ahold of any information about the subroutine's *caller* from a DTrace action.
```
:*perl*::sub-return {
printf("%s::%s returned at %s line %d\n",
copyinstr(arg3), copyinstr(arg0), copyinstr(arg1), arg2);
}
```
phase-change(NEWPHASE, OLDPHASE) Traces changes to Perl's interpreter state. You can internalize this as tracing changes to Perl's `${^GLOBAL_PHASE}` variable, especially since the values for `NEWPHASE` and `OLDPHASE` are the strings that `${^GLOBAL_PHASE}` reports.
```
:*perl*::phase-change {
printf("Phase changed from %s to %s\n",
copyinstr(arg1), copyinstr(arg0));
}
```
op-entry(OPNAME) Traces the execution of each opcode in the Perl runloop. This probe is fired before the opcode is executed. When the Perl debugger is enabled, the DTrace probe is fired *after* the debugger hooks (but still before the opcode itself is executed).
```
:*perl*::op-entry {
printf("About to execute opcode %s\n", copyinstr(arg0));
}
```
loading-file(FILENAME) Fires when Perl is about to load an individual file, whether from `use`, `require`, or `do`. This probe fires before the file is read from disk. The filename argument is converted to local filesystem paths instead of providing `Module::Name`-style names.
```
:*perl*:loading-file {
printf("About to load %s\n", copyinstr(arg0));
}
```
loaded-file(FILENAME) Fires when Perl has successfully loaded an individual file, whether from `use`, `require`, or `do`. This probe fires after the file is read from disk and its contents evaluated. The filename argument is converted to local filesystem paths instead of providing `Module::Name`-style names.
```
:*perl*:loaded-file {
printf("Successfully loaded %s\n", copyinstr(arg0));
}
```
EXAMPLES
--------
Most frequently called functions
```
# dtrace -qZn 'sub-entry { @[strjoin(strjoin(copyinstr(arg3),"::"),copyinstr(arg0))] = count() } END {trunc(@, 10)}'
Class::MOP::Attribute::slots 400
Try::Tiny::catch 411
Try::Tiny::try 411
Class::MOP::Instance::inline_slot_access 451
Class::MOP::Class::Immutable::Trait:::around 472
Class::MOP::Mixin::AttributeCore::has_initializer 496
Class::MOP::Method::Wrapped::__ANON__ 544
Class::MOP::Package::_package_stash 737
Class::MOP::Class::initialize 1128
Class::MOP::get_metaclass_by_name 1204
```
Trace function calls
```
# dtrace -qFZn 'sub-entry, sub-return { trace(copyinstr(arg0)) }'
0 -> Perl_pp_entersub BEGIN
0 <- Perl_pp_leavesub BEGIN
0 -> Perl_pp_entersub BEGIN
0 -> Perl_pp_entersub import
0 <- Perl_pp_leavesub import
0 <- Perl_pp_leavesub BEGIN
0 -> Perl_pp_entersub BEGIN
0 -> Perl_pp_entersub dress
0 <- Perl_pp_leavesub dress
0 -> Perl_pp_entersub dirty
0 <- Perl_pp_leavesub dirty
0 -> Perl_pp_entersub whiten
0 <- Perl_pp_leavesub whiten
0 <- Perl_dounwind BEGIN
```
Function calls during interpreter cleanup
```
# dtrace -Zn 'phase-change /copyinstr(arg0) == "END"/ { self->ending = 1 } sub-entry /self->ending/ { trace(copyinstr(arg0)) }'
CPU ID FUNCTION:NAME
1 77214 Perl_pp_entersub:sub-entry END
1 77214 Perl_pp_entersub:sub-entry END
1 77214 Perl_pp_entersub:sub-entry cleanup
1 77214 Perl_pp_entersub:sub-entry _force_writable
1 77214 Perl_pp_entersub:sub-entry _force_writable
```
System calls at compile time
```
# dtrace -qZn 'phase-change /copyinstr(arg0) == "START"/ { self->interesting = 1 } phase-change /copyinstr(arg0) == "RUN"/ { self->interesting = 0 } syscall::: /self->interesting/ { @[probefunc] = count() } END { trunc(@, 3) }'
lseek 310
read 374
stat64 1056
```
Perl functions that execute the most opcodes
```
# dtrace -qZn 'sub-entry { self->fqn = strjoin(copyinstr(arg3), strjoin("::", copyinstr(arg0))) } op-entry /self->fqn != ""/ { @[self->fqn] = count() } END { trunc(@, 3) }'
warnings::unimport 4589
Exporter::Heavy::_rebuild_cache 5039
Exporter::import 14578
```
REFERENCES
----------
DTrace Dynamic Tracing Guide <http://dtrace.org/guide/preface.html>
DTrace: Dynamic Tracing in Oracle Solaris, Mac OS X and FreeBSD <https://www.amazon.com/DTrace-Dynamic-Tracing-Solaris-FreeBSD/dp/0132091518/>
SEE ALSO
---------
<Devel::DTrace::Provider>
This CPAN module lets you create application-level DTrace probes written in Perl.
AUTHORS
-------
Shawn M Moore `[email protected]`
perl perlpod perlpod
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Ordinary Paragraph](#Ordinary-Paragraph)
+ [Verbatim Paragraph](#Verbatim-Paragraph)
+ [Command Paragraph](#Command-Paragraph)
+ [Formatting Codes](#Formatting-Codes)
+ [The Intent](#The-Intent)
+ [Embedding Pods in Perl Modules](#Embedding-Pods-in-Perl-Modules)
+ [Hints for Writing Pod](#Hints-for-Writing-Pod)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perlpod - the Plain Old Documentation format
DESCRIPTION
-----------
Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules.
Translators are available for converting Pod to various formats like plain text, HTML, man pages, and more.
Pod markup consists of three basic kinds of paragraphs: [ordinary](#Ordinary-Paragraph), [verbatim](#Verbatim-Paragraph), and [command](#Command-Paragraph).
###
Ordinary Paragraph
Most paragraphs in your documentation will be ordinary blocks of text, like this one. You can simply type in your text without any markup whatsoever, and with just a blank line before and after. When it gets formatted, it will undergo minimal formatting, like being rewrapped, probably put into a proportionally spaced font, and maybe even justified.
You can use formatting codes in ordinary paragraphs, for **bold**, *italic*, `code-style`, [hyperlinks](perlfaq), and more. Such codes are explained in the "[Formatting Codes](#Formatting-Codes)" section, below.
###
Verbatim Paragraph
Verbatim paragraphs are usually used for presenting a codeblock or other text which does not require any special parsing or formatting, and which shouldn't be wrapped.
A verbatim paragraph is distinguished by having its first character be a space or a tab. (And commonly, all its lines begin with spaces and/or tabs.) It should be reproduced exactly, with tabs assumed to be on 8-column boundaries. There are no special formatting codes, so you can't italicize or anything like that. A \ means \, and nothing else.
###
Command Paragraph
A command paragraph is used for special treatment of whole chunks of text, usually as headings or parts of lists.
All command paragraphs (which are typically only one line long) start with "=", followed by an identifier, followed by arbitrary text that the command can use however it pleases. Currently recognized commands are
```
=pod
=head1 Heading Text
=head2 Heading Text
=head3 Heading Text
=head4 Heading Text
=head5 Heading Text
=head6 Heading Text
=over indentlevel
=item stuff
=back
=begin format
=end format
=for format text...
=encoding type
=cut
```
To explain them each in detail:
`=head1 *Heading Text*`
`=head2 *Heading Text*`
`=head3 *Heading Text*`
`=head4 *Heading Text*`
`=head5 *Heading Text*`
`=head6 *Heading Text*`
Head1 through head6 produce headings, head1 being the highest level. The text in the rest of this paragraph is the content of the heading. For example:
```
=head2 Object Attributes
```
The text "Object Attributes" comprises the heading there. The text in these heading commands can use formatting codes, as seen here:
```
=head2 Possible Values for C<$/>
```
Such commands are explained in the "[Formatting Codes](#Formatting-Codes)" section, below.
Note that `head5` and `head6` were introduced in 2020 and in <Pod::Simple> 3.41, released in October 2020, so they might not be supported on the Pod parser you use.
`=over *indentlevel*`
`=item *stuff...*`
`=back`
Item, over, and back require a little more explanation: "=over" starts a region specifically for the generation of a list using "=item" commands, or for indenting (groups of) normal paragraphs. At the end of your list, use "=back" to end it. The *indentlevel* option to "=over" indicates how far over to indent, generally in ems (where one em is the width of an "M" in the document's base font) or roughly comparable units; if there is no *indentlevel* option, it defaults to four. (And some formatters may just ignore whatever *indentlevel* you provide.) In the *stuff* in `=item *stuff...*`, you may use formatting codes, as seen here:
```
=item Using C<$|> to Control Buffering
```
Such commands are explained in the "[Formatting Codes](#Formatting-Codes)" section, below.
Note also that there are some basic rules to using "=over" ... "=back" regions:
* Don't use "=item"s outside of an "=over" ... "=back" region.
* The first thing after the "=over" command should be an "=item", unless there aren't going to be any items at all in this "=over" ... "=back" region.
* Don't put "=head*n*" commands inside an "=over" ... "=back" region.
* And perhaps most importantly, keep the items consistent: either use "=item \*" for all of them, to produce bullets; or use "=item 1.", "=item 2.", etc., to produce numbered lists; or use "=item foo", "=item bar", etc.--namely, things that look nothing like bullets or numbers. (If you have a list that contains both: 1) things that don't look like bullets nor numbers, plus 2) things that do, you should preface the bullet- or number-like items with `Z<>`. See [Z<>](#Z%3C%3E-a-null-%28zero-effect%29-formatting-code) below for an example.)
If you start with bullets or numbers, stick with them, as formatters use the first "=item" type to decide how to format the list.
`=cut` To end a Pod block, use a blank line, then a line beginning with "=cut", and a blank line after it. This lets Perl (and the Pod formatter) know that this is where Perl code is resuming. (The blank line before the "=cut" is not technically necessary, but many older Pod processors require it.)
`=pod` The "=pod" command by itself doesn't do much of anything, but it signals to Perl (and Pod formatters) that a Pod block starts here. A Pod block starts with *any* command paragraph, so a "=pod" command is usually used just when you want to start a Pod block with an ordinary paragraph or a verbatim paragraph. For example:
```
=item stuff()
This function does stuff.
=cut
sub stuff {
...
}
=pod
Remember to check its return value, as in:
stuff() || die "Couldn't do stuff!";
=cut
```
`=begin *formatname*`
`=end *formatname*`
`=for *formatname* *text...*`
For, begin, and end will let you have regions of text/code/data that are not generally interpreted as normal Pod text, but are passed directly to particular formatters, or are otherwise special. A formatter that can use that format will use the region, otherwise it will be completely ignored.
A command "=begin *formatname*", some paragraphs, and a command "=end *formatname*", mean that the text/data in between is meant for formatters that understand the special format called *formatname*. For example,
```
=begin html
<hr> <img src="thang.png">
<p> This is a raw HTML paragraph </p>
=end html
```
The command "=for *formatname* *text...*" specifies that the remainder of just this paragraph (starting right after *formatname*) is in that special format.
```
=for html <hr> <img src="thang.png">
<p> This is a raw HTML paragraph </p>
```
This means the same thing as the above "=begin html" ... "=end html" region.
That is, with "=for", you can have only one paragraph's worth of text (i.e., the text in "=foo targetname text..."), but with "=begin targetname" ... "=end targetname", you can have any amount of stuff in between. (Note that there still must be a blank line after the "=begin" command and a blank line before the "=end" command.)
Here are some examples of how to use these:
```
=begin html
<br>Figure 1.<br><IMG SRC="figure1.png"><br>
=end html
=begin text
---------------
| foo |
| bar |
---------------
^^^^ Figure 1. ^^^^
=end text
```
Some format names that formatters currently are known to accept include "roff", "man", "latex", "tex", "text", and "html". (Some formatters will treat some of these as synonyms.)
A format name of "comment" is common for just making notes (presumably to yourself) that won't appear in any formatted version of the Pod document:
```
=for comment
Make sure that all the available options are documented!
```
Some *formatnames* will require a leading colon (as in `"=for :formatname"`, or `"=begin :formatname" ... "=end :formatname"`), to signal that the text is not raw data, but instead *is* Pod text (i.e., possibly containing formatting codes) that's just not for normal formatting (e.g., may not be a normal-use paragraph, but might be for formatting as a footnote).
`=encoding *encodingname*` This command is used for declaring the encoding of a document. Most users won't need this; but if your encoding isn't US-ASCII, then put a `=encoding *encodingname*` command very early in the document so that pod formatters will know how to decode the document. For *encodingname*, use a name recognized by the <Encode::Supported> module. Some pod formatters may try to guess between a Latin-1 or CP-1252 versus UTF-8 encoding, but they may guess wrong. It's best to be explicit if you use anything besides strict ASCII. Examples:
```
=encoding latin1
=encoding utf8
=encoding koi8-r
=encoding ShiftJIS
=encoding big5
```
`=encoding` affects the whole document, and must occur only once.
And don't forget, all commands but `=encoding` last up until the end of its *paragraph*, not its line. So in the examples below, you can see that every command needs the blank line after it, to end its paragraph. (And some older Pod translators may require the `=encoding` line to have a following blank line as well, even though it should be legal to omit.)
Some examples of lists include:
```
=over
=item *
First item
=item *
Second item
=back
=over
=item Foo()
Description of Foo function
=item Bar()
Description of Bar function
=back
```
###
Formatting Codes
In ordinary paragraphs and in some command paragraphs, various formatting codes (a.k.a. "interior sequences") can be used:
`I<text>` -- italic text Used for emphasis ("`be I<careful!>`") and parameters ("`redo I<LABEL>`")
`B<text>` -- bold text Used for switches ("`perl's B<-n> switch`"), programs ("`some systems provide a B<chfn> for that`"), emphasis ("`be B<careful!>`"), and so on ("`and that feature is known as B<autovivification>`").
`C<code>` -- code text Renders code in a typewriter font, or gives some other indication that this represents program text ("`C<gmtime($^T)>`") or some other form of computerese ("`C<drwxr-xr-x>`").
`L<name>` -- a hyperlink There are various syntaxes, listed below. In the syntaxes given, `text`, `name`, and `section` cannot contain the characters '/' and '|'; and any '<' or '>' should be matched.
* `L<name>`
Link to a Perl manual page (e.g., `L<Net::Ping>`). Note that `name` should not contain spaces. This syntax is also occasionally used for references to Unix man pages, as in `L<crontab(5)>`.
* `L<name/"sec">` or `L<name/sec>`
Link to a section in other manual page. E.g., `L<perlsyn/"For Loops">`
* `L</"sec">` or `L</sec>`
Link to a section in this manual page. E.g., `L</"Object Methods">`
A section is started by the named heading or item. For example, `L<perlvar/$.>` or `L<perlvar/"$.">` both link to the section started by "`=item $.`" in perlvar. And `L<perlsyn/For Loops>` or `L<perlsyn/"For Loops">` both link to the section started by "`=head2 For Loops`" in perlsyn.
To control what text is used for display, you use "`L<text|...>`", as in:
* `L<text|name>`
Link this text to that manual page. E.g., `L<Perl Error Messages|perldiag>`
* `L<text|name/"sec">` or `L<text|name/sec>`
Link this text to that section in that manual page. E.g., `L<postfix "if"|perlsyn/"Statement Modifiers">`
* `L<text|/"sec">` or `L<text|/sec>` or `L<text|"sec">`
Link this text to that section in this manual page. E.g., `L<the various attributes|/"Member Data">`
Or you can link to a web page:
* `L<scheme:...>`
`L<text|scheme:...>`
Links to an absolute URL. For example, `L<http://www.perl.org/>` or `L<The Perl Home Page|http://www.perl.org/>`.
`E<escape>` -- a character escape Very similar to HTML/XML `&*foo*;` "entity references":
* `E<lt>` -- a literal < (less than)
* `E<gt>` -- a literal > (greater than)
* `E<verbar>` -- a literal | (*ver*tical *bar*)
* `E<sol>` -- a literal / (*sol*idus)
The above four are optional except in other formatting codes, notably `L<...>`, and when preceded by a capital letter.
* `E<htmlname>`
Some non-numeric HTML entity name, such as `E<eacute>`, meaning the same thing as `é` in HTML -- i.e., a lowercase e with an acute (/-shaped) accent.
* `E<number>`
The ASCII/Latin-1/Unicode character with that number. A leading "0x" means that *number* is hex, as in `E<0x201E>`. A leading "0" means that *number* is octal, as in `E<075>`. Otherwise *number* is interpreted as being in decimal, as in `E<181>`.
Note that older Pod formatters might not recognize octal or hex numeric escapes, and that many formatters cannot reliably render characters above 255. (Some formatters may even have to use compromised renderings of Latin-1/CP-1252 characters, like rendering `E<eacute>` as just a plain "e".)
`F<filename>` -- used for filenames Typically displayed in italics. Example: "`F<.cshrc>`"
`S<text>` -- text contains non-breaking spaces This means that the words in *text* should not be broken across lines. Example: `S<$x ? $y : $z>`.
`X<topic name>` -- an index entry This is ignored by most formatters, but some may use it for building indexes. It always renders as empty-string. Example: `X<absolutizing relative URLs>`
`Z<>` -- a null (zero-effect) formatting code This is rarely used. It's one way to get around using an E<...> code sometimes. For example, instead of "`NE<lt>3`" (for "N<3") you could write "`NZ<><3`" (the "Z<>" breaks up the "N" and the "<" so they can't be considered the part of a (fictitious) "N<...>" code).
Another use is to indicate that *stuff* in `=item Z<>*stuff...*` is not to be considered to be a bullet or number. For example, without the `Z<>`, the line
```
=item Z<>500 Server error
```
could possibly be parsed as an item in a numbered list when it isn't meant to be.
Still another use is to maintain visual space between `=item` lines. If you specify
```
=item foo
=item bar
```
it will typically get rendered as
```
foo
bar
```
That may be what you want, but if what you really want is
```
foo
bar
```
you can use `Z<>` to accomplish that
```
=item foo
Z<>
=item bar
```
Most of the time, you will need only a single set of angle brackets to delimit the beginning and end of formatting codes. However, sometimes you will want to put a real right angle bracket (a greater-than sign, '>') inside of a formatting code. This is particularly common when using a formatting code to provide a different font-type for a snippet of code. As with all things in Perl, there is more than one way to do it. One way is to simply escape the closing bracket using an `E` code:
```
C<$a E<lt>=E<gt> $b>
```
This will produce: "`$a <=> $b`"
A more readable, and perhaps more "plain" way is to use an alternate set of delimiters that doesn't require a single ">" to be escaped. Doubled angle brackets ("<<" and ">>") may be used *if and only if there is whitespace right after the opening delimiter and whitespace right before the closing delimiter!* For example, the following will do the trick:
```
C<< $a <=> $b >>
```
In fact, you can use as many repeated angle-brackets as you like so long as you have the same number of them in the opening and closing delimiters, and make sure that whitespace immediately follows the last '<' of the opening delimiter, and immediately precedes the first '>' of the closing delimiter. (The whitespace is ignored.) So the following will also work:
```
C<<< $a <=> $b >>>
C<<<< $a <=> $b >>>>
```
And they all mean exactly the same as this:
```
C<$a E<lt>=E<gt> $b>
```
The multiple-bracket form does not affect the interpretation of the contents of the formatting code, only how it must end. That means that the examples above are also exactly the same as this:
```
C<< $a E<lt>=E<gt> $b >>
```
As a further example, this means that if you wanted to put these bits of code in `C` (code) style:
```
open(X, ">>thing.dat") || die $!
$foo->bar();
```
you could do it like so:
```
C<<< open(X, ">>thing.dat") || die $! >>>
C<< $foo->bar(); >>
```
which is presumably easier to read than the old way:
```
C<open(X, "E<gt>E<gt>thing.dat") || die $!>
C<$foo-E<gt>bar();>
```
This is currently supported by pod2text (Pod::Text), pod2man (Pod::Man), and any other pod2xxx or Pod::Xxxx translators that use Pod::Parser 1.093 or later, or Pod::Tree 1.02 or later.
###
The Intent
The intent is simplicity of use, not power of expression. Paragraphs look like paragraphs (block format), so that they stand out visually, and so that I could run them through `fmt` easily to reformat them (that's F7 in my version of **vi**, or Esc Q in my version of **emacs**). I wanted the translator to always leave the `'` and ``` and `"` quotes alone, in verbatim mode, so I could slurp in a working program, shift it over four spaces, and have it print out, er, verbatim. And presumably in a monospace font.
The Pod format is not necessarily sufficient for writing a book. Pod is just meant to be an idiot-proof common source for nroff, HTML, TeX, and other markup languages, as used for online documentation. Translators exist for **pod2text**, **pod2html**, **pod2man** (that's for nroff(1) and troff(1)), **pod2latex**, and **pod2fm**. Various others are available in CPAN.
###
Embedding Pods in Perl Modules
You can embed Pod documentation in your Perl modules and scripts. Start your documentation with an empty line, a "=head1" command at the beginning, and end it with a "=cut" command and an empty line. The **perl** executable will ignore the Pod text. You can place a Pod statement where **perl** expects the beginning of a new statement, but not within a statement, as that would result in an error. See any of the supplied library modules for examples.
If you're going to put your Pod at the end of the file, and you're using an `__END__` or `__DATA__` cut mark, make sure to put an empty line there before the first Pod command.
```
__END__
=head1 NAME
Time::Local - efficiently compute time from local and GMT time
```
Without that empty line before the "=head1", many translators wouldn't have recognized the "=head1" as starting a Pod block.
###
Hints for Writing Pod
* The **podchecker** command is provided for checking Pod syntax for errors and warnings. For example, it checks for completely blank lines in Pod blocks and for unknown commands and formatting codes. You should still also pass your document through one or more translators and proofread the result, or print out the result and proofread that. Some of the problems found may be bugs in the translators, which you may or may not wish to work around.
* If you're more familiar with writing in HTML than with writing in Pod, you can try your hand at writing documentation in simple HTML, and converting it to Pod with the experimental <Pod::HTML2Pod> module, (available in CPAN), and looking at the resulting code. The experimental <Pod::PXML> module in CPAN might also be useful.
* Many older Pod translators require the lines before every Pod command and after every Pod command (including "=cut"!) to be a blank line. Having something like this:
```
# - - - - - - - - - - - -
=item $firecracker->boom()
This noisily detonates the firecracker object.
=cut
sub boom {
...
```
...will make such Pod translators completely fail to see the Pod block at all.
Instead, have it like this:
```
# - - - - - - - - - - - -
=item $firecracker->boom()
This noisily detonates the firecracker object.
=cut
sub boom {
...
```
* Some older Pod translators require paragraphs (including command paragraphs like "=head2 Functions") to be separated by *completely* empty lines. If you have an apparently empty line with some spaces on it, this might not count as a separator for those translators, and that could cause odd formatting.
* Older translators might add wording around an L<> link, so that `L<Foo::Bar>` may become "the Foo::Bar manpage", for example. So you shouldn't write things like `the L<foo> documentation`, if you want the translated document to read sensibly. Instead, write `the L<Foo::Bar|Foo::Bar> documentation` or `L<the Foo::Bar documentation|Foo::Bar>`, to control how the link comes out.
* Going past the 70th column in a verbatim block might be ungracefully wrapped by some formatters.
SEE ALSO
---------
<perlpodspec>, ["PODs: Embedded Documentation" in perlsyn](perlsyn#PODs%3A-Embedded-Documentation), <perlnewmod>, <perldoc>, <pod2html>, <pod2man>, <podchecker>.
AUTHOR
------
Larry Wall, Sean M. Burke
| programming_docs |
perl perlfilter perlfilter
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [CONCEPTS](#CONCEPTS)
* [USING FILTERS](#USING-FILTERS)
* [WRITING A SOURCE FILTER](#WRITING-A-SOURCE-FILTER)
* [WRITING A SOURCE FILTER IN C](#WRITING-A-SOURCE-FILTER-IN-C)
* [CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE](#CREATING-A-SOURCE-FILTER-AS-A-SEPARATE-EXECUTABLE)
* [WRITING A SOURCE FILTER IN PERL](#WRITING-A-SOURCE-FILTER-IN-PERL)
* [USING CONTEXT: THE DEBUG FILTER](#USING-CONTEXT:-THE-DEBUG-FILTER)
* [CONCLUSION](#CONCLUSION)
* [LIMITATIONS](#LIMITATIONS)
* [THINGS TO LOOK OUT FOR](#THINGS-TO-LOOK-OUT-FOR)
* [REQUIREMENTS](#REQUIREMENTS)
* [AUTHOR](#AUTHOR)
* [Copyrights](#Copyrights)
NAME
----
perlfilter - Source Filters
DESCRIPTION
-----------
This article is about a little-known feature of Perl called *source filters*. Source filters alter the program text of a module before Perl sees it, much as a C preprocessor alters the source text of a C program before the compiler sees it. This article tells you more about what source filters are, how they work, and how to write your own.
The original purpose of source filters was to let you encrypt your program source to prevent casual piracy. This isn't all they can do, as you'll soon learn. But first, the basics.
CONCEPTS
--------
Before the Perl interpreter can execute a Perl script, it must first read it from a file into memory for parsing and compilation. If that script itself includes other scripts with a `use` or `require` statement, then each of those scripts will have to be read from their respective files as well.
Now think of each logical connection between the Perl parser and an individual file as a *source stream*. A source stream is created when the Perl parser opens a file, it continues to exist as the source code is read into memory, and it is destroyed when Perl is finished parsing the file. If the parser encounters a `require` or `use` statement in a source stream, a new and distinct stream is created just for that file.
The diagram below represents a single source stream, with the flow of source from a Perl script file on the left into the Perl parser on the right. This is how Perl normally operates.
```
file -------> parser
```
There are two important points to remember:
1. Although there can be any number of source streams in existence at any given time, only one will be active.
2. Every source stream is associated with only one file.
A source filter is a special kind of Perl module that intercepts and modifies a source stream before it reaches the parser. A source filter changes our diagram like this:
```
file ----> filter ----> parser
```
If that doesn't make much sense, consider the analogy of a command pipeline. Say you have a shell script stored in the compressed file *trial.gz*. The simple pipeline command below runs the script without needing to create a temporary file to hold the uncompressed file.
```
gunzip -c trial.gz | sh
```
In this case, the data flow from the pipeline can be represented as follows:
```
trial.gz ----> gunzip ----> sh
```
With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser:
```
compressed gunzip
Perl program ---> source filter ---> parser
```
USING FILTERS
--------------
So how do you use a source filter in a Perl script? Above, I said that a source filter is just a special kind of module. Like all Perl modules, a source filter is invoked with a use statement.
Say you want to pass your Perl source through the C preprocessor before execution. As it happens, the source filters distribution comes with a C preprocessor filter module called Filter::cpp.
Below is an example program, `cpp_test`, which makes use of this filter. Line numbers have been added to allow specific lines to be referenced easily.
```
1: use Filter::cpp;
2: #define TRUE 1
3: $a = TRUE;
4: print "a = $a\n";
```
When you execute this script, Perl creates a source stream for the file. Before the parser processes any of the lines from the file, the source stream looks like this:
```
cpp_test ---------> parser
```
Line 1, `use Filter::cpp`, includes and installs the `cpp` filter module. All source filters work this way. The use statement is compiled and executed at compile time, before any more of the file is read, and it attaches the cpp filter to the source stream behind the scenes. Now the data flow looks like this:
```
cpp_test ----> cpp filter ----> parser
```
As the parser reads the second and subsequent lines from the source stream, it feeds those lines through the `cpp` source filter before processing them. The `cpp` filter simply passes each line through the real C preprocessor. The output from the C preprocessor is then inserted back into the source stream by the filter.
```
.-> cpp --.
| |
| |
| <-'
cpp_test ----> cpp filter ----> parser
```
The parser then sees the following code:
```
use Filter::cpp;
$a = 1;
print "a = $a\n";
```
Let's consider what happens when the filtered code includes another module with use:
```
1: use Filter::cpp;
2: #define TRUE 1
3: use Fred;
4: $a = TRUE;
5: print "a = $a\n";
```
The `cpp` filter does not apply to the text of the Fred module, only to the text of the file that used it (`cpp_test`). Although the use statement on line 3 will pass through the cpp filter, the module that gets included (`Fred`) will not. The source streams look like this after line 3 has been parsed and before line 4 is parsed:
```
cpp_test ---> cpp filter ---> parser (INACTIVE)
Fred.pm ----> parser
```
As you can see, a new stream has been created for reading the source from `Fred.pm`. This stream will remain active until all of `Fred.pm` has been parsed. The source stream for `cpp_test` will still exist, but is inactive. Once the parser has finished reading Fred.pm, the source stream associated with it will be destroyed. The source stream for `cpp_test` then becomes active again and the parser reads line 4 and subsequent lines from `cpp_test`.
You can use more than one source filter on a single file. Similarly, you can reuse the same filter in as many files as you like.
For example, if you have a uuencoded and compressed source file, it is possible to stack a uudecode filter and an uncompression filter like this:
```
use Filter::uudecode; use Filter::uncompress;
M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
...
```
Once the first line has been processed, the flow will look like this:
```
file ---> uudecode ---> uncompress ---> parser
filter filter
```
Data flows through filters in the same order they appear in the source file. The uudecode filter appeared before the uncompress filter, so the source file will be uudecoded before it's uncompressed.
WRITING A SOURCE FILTER
------------------------
There are three ways to write your own source filter. You can write it in C, use an external program as a filter, or write the filter in Perl. I won't cover the first two in any great detail, so I'll get them out of the way first. Writing the filter in Perl is most convenient, so I'll devote the most space to it.
WRITING A SOURCE FILTER IN C
-----------------------------
The first of the three available techniques is to write the filter completely in C. The external module you create interfaces directly with the source filter hooks provided by Perl.
The advantage of this technique is that you have complete control over the implementation of your filter. The big disadvantage is the increased complexity required to write the filter - not only do you need to understand the source filter hooks, but you also need a reasonable knowledge of Perl guts. One of the few times it is worth going to this trouble is when writing a source scrambler. The `decrypt` filter (which unscrambles the source before Perl parses it) included with the source filter distribution is an example of a C source filter (see Decryption Filters, below).
**Decryption Filters**
All decryption filters work on the principle of "security through obscurity." Regardless of how well you write a decryption filter and how strong your encryption algorithm is, anyone determined enough can retrieve the original source code. The reason is quite simple - once the decryption filter has decrypted the source back to its original form, fragments of it will be stored in the computer's memory as Perl parses it. The source might only be in memory for a short period of time, but anyone possessing a debugger, skill, and lots of patience can eventually reconstruct your program.
That said, there are a number of steps that can be taken to make life difficult for the potential cracker. The most important: Write your decryption filter in C and statically link the decryption module into the Perl binary. For further tips to make life difficult for the potential cracker, see the file *decrypt.pm* in the source filters distribution.
CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE
--------------------------------------------------
An alternative to writing the filter in C is to create a separate executable in the language of your choice. The separate executable reads from standard input, does whatever processing is necessary, and writes the filtered data to standard output. `Filter::cpp` is an example of a source filter implemented as a separate executable - the executable is the C preprocessor bundled with your C compiler.
The source filter distribution includes two modules that simplify this task: `Filter::exec` and `Filter::sh`. Both allow you to run any external executable. Both use a coprocess to control the flow of data into and out of the external executable. (For details on coprocesses, see Stephens, W.R., "Advanced Programming in the UNIX Environment." Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference between them is that `Filter::exec` spawns the external command directly, while `Filter::sh` spawns a shell to execute the external command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning a shell allows you to make use of the shell metacharacters and redirection facilities.
Here is an example script that uses `Filter::sh`:
```
use Filter::sh 'tr XYZ PQR';
$a = 1;
print "XYZ a = $a\n";
```
The output you'll get when the script is executed:
```
PQR a = 1
```
Writing a source filter as a separate executable works fine, but a small performance penalty is incurred. For example, if you execute the small example above, a separate subprocess will be created to run the Unix `tr` command. Each use of the filter requires its own subprocess. If creating subprocesses is expensive on your system, you might want to consider one of the other options for creating source filters.
WRITING A SOURCE FILTER IN PERL
--------------------------------
The easiest and most portable option available for creating your own source filter is to write it completely in Perl. To distinguish this from the previous two techniques, I'll call it a Perl source filter.
To help understand how to write a Perl source filter we need an example to study. Here is a complete source filter that performs rot13 decoding. (Rot13 is a very simple encryption scheme used in Usenet postings to hide the contents of offensive posts. It moves every letter forward thirteen places, so that A becomes N, B becomes O, and Z becomes M.)
```
package Rot13;
use Filter::Util::Call;
sub import {
my ($type) = @_;
my ($ref) = [];
filter_add(bless $ref);
}
sub filter {
my ($self) = @_;
my ($status);
tr/n-za-mN-ZA-M/a-zA-Z/
if ($status = filter_read()) > 0;
$status;
}
1;
```
All Perl source filters are implemented as Perl classes and have the same basic structure as the example above.
First, we include the `Filter::Util::Call` module, which exports a number of functions into your filter's namespace. The filter shown above uses two of these functions, `filter_add()` and `filter_read()`.
Next, we create the filter object and associate it with the source stream by defining the `import` function. If you know Perl well enough, you know that `import` is called automatically every time a module is included with a use statement. This makes `import` the ideal place to both create and install a filter object.
In the example filter, the object (`$ref`) is blessed just like any other Perl object. Our example uses an anonymous array, but this isn't a requirement. Because this example doesn't need to store any context information, we could have used a scalar or hash reference just as well. The next section demonstrates context data.
The association between the filter object and the source stream is made with the `filter_add()` function. This takes a filter object as a parameter (`$ref` in this case) and installs it in the source stream.
Finally, there is the code that actually does the filtering. For this type of Perl source filter, all the filtering is done in a method called `filter()`. (It is also possible to write a Perl source filter using a closure. See the `Filter::Util::Call` manual page for more details.) It's called every time the Perl parser needs another line of source to process. The `filter()` method, in turn, reads lines from the source stream using the `filter_read()` function.
If a line was available from the source stream, `filter_read()` returns a status value greater than zero and appends the line to `$_`. A status value of zero indicates end-of-file, less than zero means an error. The filter function itself is expected to return its status in the same way, and put the filtered line it wants written to the source stream in `$_`. The use of `$_` accounts for the brevity of most Perl source filters.
In order to make use of the rot13 filter we need some way of encoding the source file in rot13 format. The script below, `mkrot13`, does just that.
```
die "usage mkrot13 filename\n" unless @ARGV;
my $in = $ARGV[0];
my $out = "$in.tmp";
open(IN, "<$in") or die "Cannot open file $in: $!\n";
open(OUT, ">$out") or die "Cannot open file $out: $!\n";
print OUT "use Rot13;\n";
while (<IN>) {
tr/a-zA-Z/n-za-mN-ZA-M/;
print OUT;
}
close IN;
close OUT;
unlink $in;
rename $out, $in;
```
If we encrypt this with `mkrot13`:
```
print " hello fred \n";
```
the result will be this:
```
use Rot13;
cevag "uryyb serq\a";
```
Running it produces this output:
```
hello fred
```
USING CONTEXT: THE DEBUG FILTER
--------------------------------
The rot13 example was a trivial example. Here's another demonstration that shows off a few more features.
Say you wanted to include a lot of debugging code in your Perl script during development, but you didn't want it available in the released product. Source filters offer a solution. In order to keep the example simple, let's say you wanted the debugging output to be controlled by an environment variable, `DEBUG`. Debugging code is enabled if the variable exists, otherwise it is disabled.
Two special marker lines will bracket debugging code, like this:
```
## DEBUG_BEGIN
if ($year > 1999) {
warn "Debug: millennium bug in year $year\n";
}
## DEBUG_END
```
The filter ensures that Perl parses the code between the <DEBUG\_BEGIN> and `DEBUG_END` markers only when the `DEBUG` environment variable exists. That means that when `DEBUG` does exist, the code above should be passed through the filter unchanged. The marker lines can also be passed through as-is, because the Perl parser will see them as comment lines. When `DEBUG` isn't set, we need a way to disable the debug code. A simple way to achieve that is to convert the lines between the two markers into comments:
```
## DEBUG_BEGIN
#if ($year > 1999) {
# warn "Debug: millennium bug in year $year\n";
#}
## DEBUG_END
```
Here is the complete Debug filter:
```
package Debug;
use v5.36;
use Filter::Util::Call;
use constant TRUE => 1;
use constant FALSE => 0;
sub import {
my ($type) = @_;
my (%context) = (
Enabled => defined $ENV{DEBUG},
InTraceBlock => FALSE,
Filename => (caller)[1],
LineNo => 0,
LastBegin => 0,
);
filter_add(bless \%context);
}
sub Die {
my ($self) = shift;
my ($message) = shift;
my ($line_no) = shift || $self->{LastBegin};
die "$message at $self->{Filename} line $line_no.\n"
}
sub filter {
my ($self) = @_;
my ($status);
$status = filter_read();
++ $self->{LineNo};
# deal with EOF/error first
if ($status <= 0) {
$self->Die("DEBUG_BEGIN has no DEBUG_END")
if $self->{InTraceBlock};
return $status;
}
if ($self->{InTraceBlock}) {
if (/^\s*##\s*DEBUG_BEGIN/ ) {
$self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
} elsif (/^\s*##\s*DEBUG_END/) {
$self->{InTraceBlock} = FALSE;
}
# comment out the debug lines when the filter is disabled
s/^/#/ if ! $self->{Enabled};
} elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
$self->{InTraceBlock} = TRUE;
$self->{LastBegin} = $self->{LineNo};
} elsif ( /^\s*##\s*DEBUG_END/ ) {
$self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
}
return $status;
}
1;
```
The big difference between this filter and the previous example is the use of context data in the filter object. The filter object is based on a hash reference, and is used to keep various pieces of context information between calls to the filter function. All but two of the hash fields are used for error reporting. The first of those two, Enabled, is used by the filter to determine whether the debugging code should be given to the Perl parser. The second, InTraceBlock, is true when the filter has encountered a `DEBUG_BEGIN` line, but has not yet encountered the following `DEBUG_END` line.
If you ignore all the error checking that most of the code does, the essence of the filter is as follows:
```
sub filter {
my ($self) = @_;
my ($status);
$status = filter_read();
# deal with EOF/error first
return $status if $status <= 0;
if ($self->{InTraceBlock}) {
if (/^\s*##\s*DEBUG_END/) {
$self->{InTraceBlock} = FALSE
}
# comment out debug lines when the filter is disabled
s/^/#/ if ! $self->{Enabled};
} elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
$self->{InTraceBlock} = TRUE;
}
return $status;
}
```
Be warned: just as the C-preprocessor doesn't know C, the Debug filter doesn't know Perl. It can be fooled quite easily:
```
print <<EOM;
##DEBUG_BEGIN
EOM
```
Such things aside, you can see that a lot can be achieved with a modest amount of code.
CONCLUSION
----------
You now have better understanding of what a source filter is, and you might even have a possible use for them. If you feel like playing with source filters but need a bit of inspiration, here are some extra features you could add to the Debug filter.
First, an easy one. Rather than having debugging code that is all-or-nothing, it would be much more useful to be able to control which specific blocks of debugging code get included. Try extending the syntax for debug blocks to allow each to be identified. The contents of the `DEBUG` environment variable can then be used to control which blocks get included.
Once you can identify individual blocks, try allowing them to be nested. That isn't difficult either.
Here is an interesting idea that doesn't involve the Debug filter. Currently Perl subroutines have fairly limited support for formal parameter lists. You can specify the number of parameters and their type, but you still have to manually take them out of the `@_` array yourself. Write a source filter that allows you to have a named parameter list. Such a filter would turn this:
```
sub MySub ($first, $second, @rest) { ... }
```
into this:
```
sub MySub($$@) {
my ($first) = shift;
my ($second) = shift;
my (@rest) = @_;
...
}
```
Finally, if you feel like a real challenge, have a go at writing a full-blown Perl macro preprocessor as a source filter. Borrow the useful features from the C preprocessor and any other macro processors you know. The tricky bit will be choosing how much knowledge of Perl's syntax you want your filter to have.
LIMITATIONS
-----------
Source filters only work on the string level, thus are highly limited in its ability to change source code on the fly. It cannot detect comments, quoted strings, heredocs, it is no replacement for a real parser. The only stable usage for source filters are encryption, compression, or the byteloader, to translate binary code back to source code.
See for example the limitations in [Switch](switch), which uses source filters, and thus is does not work inside a string eval, the presence of regexes with embedded newlines that are specified with raw `/.../` delimiters and don't have a modifier `//x` are indistinguishable from code chunks beginning with the division operator `/`. As a workaround you must use `m/.../` or `m?...?` for such patterns. Also, the presence of regexes specified with raw `?...?` delimiters may cause mysterious errors. The workaround is to use `m?...?` instead. See <https://metacpan.org/pod/Switch#LIMITATIONS>.
Currently the content of the `__DATA__` block is not filtered.
Currently internal buffer lengths are limited to 32-bit only.
THINGS TO LOOK OUT FOR
-----------------------
Some Filters Clobber the `DATA` Handle Some source filters use the `DATA` handle to read the calling program. When using these source filters you cannot rely on this handle, nor expect any particular kind of behavior when operating on it. Filters based on Filter::Util::Call (and therefore Filter::Simple) do not alter the `DATA` filehandle, but on the other hand totally ignore the text after `__DATA__`.
REQUIREMENTS
------------
The Source Filters distribution is available on CPAN, in
```
CPAN/modules/by-module/Filter
```
Starting from Perl 5.8 Filter::Util::Call (the core part of the Source Filters distribution) is part of the standard Perl distribution. Also included is a friendlier interface called Filter::Simple, by Damian Conway.
AUTHOR
------
Paul Marquess <[email protected]>
Reini Urban <[email protected]>
Copyrights
----------
The first version of this article originally appeared in The Perl Journal #11, 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 zipdetails zipdetails
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Default Behaviour](#Default-Behaviour)
+ [Scan-Mode](#Scan-Mode)
+ [OPTIONS](#OPTIONS)
+ [Default Output](#Default-Output)
+ [Verbose Output](#Verbose-Output)
* [LIMITATIONS](#LIMITATIONS)
* [TODO](#TODO)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
zipdetails - display the internal structure of zip files
SYNOPSIS
--------
```
zipdetails [-v][--scan][--redact][--utc] zipfile.zip
zipdetails -h
zipdetails --version
```
DESCRIPTION
-----------
This program creates a detailed report on the internal structure of zip files. For each item of metadata within a zip file the program will output
the offset into the zip file where the item is located.
a textual representation for the item.
an optional hex dump of the item. The program assumes a prior understanding of the internal structure of Zip files. You should have a copy of the Zip [APPNOTE.TXT](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) file at hand to help understand the output from this program.
###
Default Behaviour
By default the program expects to be given a well-formed zip file. It will navigate the Zip file by first parsing the zip central directory at the end of the file. If that is found, it will then walk through the zip records starting at the beginning of the file. Any badly formed zip data structures encountered are likely to terminate the program.
If the program finds any structural problems with the zip file it will print a summary at the end of the output report. The set of error cases reported is very much a work in progress, so don't rely on this feature to find all the possible errors in a zip file. If you have suggestions for use-cases where this could be enhanced please consider creating an enhancement request (see ["SUPPORT"](#SUPPORT)).
Date/time fields are found in zip files are displayed in local time. Use the `--utc` option to display these fields in Coordinated Universal Time (UTC).
###
Scan-Mode
If you do have a potentially corrupt zip file, particulatly where the central directory at the end of the file is absent/incomplete, you can try usng the `--scan` option to search for zip records that are still present.
When Scan-mode is enabled, the program will walk the zip file from the start, blindly looking for the 4-byte signatures that preceed each of the zip data structures. If it finds any of the recognised signatures it will attempt to dump the associated zip record. For very large zip files, this operation can take a long time to run.
Note that the 4-byte signatures used in zip files can sometimes match with random data stored in the zip file, so care is needed interpreting the results.
### OPTIONS
-h Display help
--redact Obscure filenames in the output. Handy for the use case where the zip files contains sensitive data that cannot be shared.
--scan Walk the zip file loking for possible zip records. Can be error-prone. See ["Scan-Mode"](#Scan-Mode)
--utc By default, date/time fields are displayed in local time. Use this option to display them in in Coordinated Universal Time (UTC).
-v Enable Verbose mode. See ["Verbose Output"](#Verbose-Output).
--version Display version number of the program and exit.
###
Default Output
By default zipdetails will output the details of the zip file in three columns.
Column 1 This contains the offset from the start of the file in hex.
Column 2 This contains a textual description of the field.
Column 3 If the field contains a numeric value it will be displayed in hex. Zip stores most numbers in little-endian format - the value displayed will have the little-endian encoding removed.
Next, is an optional description of what the value means.
For example, assuming you have a zip file with two entries, like this
```
$ unzip -l test.zip
Archive: setup/test.zip
Length Date Time Name
--------- ---------- ----- ----
6 2021-03-23 18:52 latters.txt
6 2021-03-23 18:52 numbers.txt
--------- -------
12 2 files
```
Running `zipdetails` will gives this output
```
$ zipdetails test.zip
0000 LOCAL HEADER #1 04034B50
0004 Extract Zip Spec 0A '1.0'
0005 Extract OS 00 'MS-DOS'
0006 General Purpose Flag 0000
0008 Compression Method 0000 'Stored'
000A Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
000E CRC 0F8A149C
0012 Compressed Length 00000006
0016 Uncompressed Length 00000006
001A Filename Length 000B
001C Extra Length 0000
001E Filename 'letters.txt'
0029 PAYLOAD abcde.
002F LOCAL HEADER #2 04034B50
0033 Extract Zip Spec 0A '1.0'
0034 Extract OS 00 'MS-DOS'
0035 General Purpose Flag 0000
0037 Compression Method 0000 'Stored'
0039 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
003D CRC 261DAFE6
0041 Compressed Length 00000006
0045 Uncompressed Length 00000006
0049 Filename Length 000B
004B Extra Length 0000
004D Filename 'numbers.txt'
0058 PAYLOAD 12345.
005E CENTRAL HEADER #1 02014B50
0062 Created Zip Spec 1E '3.0'
0063 Created OS 03 'Unix'
0064 Extract Zip Spec 0A '1.0'
0065 Extract OS 00 'MS-DOS'
0066 General Purpose Flag 0000
0068 Compression Method 0000 'Stored'
006A Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
006E CRC 0F8A149C
0072 Compressed Length 00000006
0076 Uncompressed Length 00000006
007A Filename Length 000B
007C Extra Length 0000
007E Comment Length 0000
0080 Disk Start 0000
0082 Int File Attributes 0001
[Bit 0] 1 Text Data
0084 Ext File Attributes 81B40000
0088 Local Header Offset 00000000
008C Filename 'letters.txt'
0097 CENTRAL HEADER #2 02014B50
009B Created Zip Spec 1E '3.0'
009C Created OS 03 'Unix'
009D Extract Zip Spec 0A '1.0'
009E Extract OS 00 'MS-DOS'
009F General Purpose Flag 0000
00A1 Compression Method 0000 'Stored'
00A3 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
00A7 CRC 261DAFE6
00AB Compressed Length 00000006
00AF Uncompressed Length 00000006
00B3 Filename Length 000B
00B5 Extra Length 0000
00B7 Comment Length 0000
00B9 Disk Start 0000
00BB Int File Attributes 0001
[Bit 0] 1 Text Data
00BD Ext File Attributes 81B40000
00C1 Local Header Offset 0000002F
00C5 Filename 'numbers.txt'
00D0 END CENTRAL HEADER 06054B50
00D4 Number of this disk 0000
00D6 Central Dir Disk no 0000
00D8 Entries in this disk 0002
00DA Total Entries 0002
00DC Size of Central Dir 00000072
00E0 Offset to Central Dir 0000005E
00E4 Comment Length 0000
Done
```
###
Verbose Output
If the `-v` option is present, column 1 is expanded to include
* The offset from the start of the file in hex.
* The length of the field in hex.
* A hex dump of the bytes in field in the order they are stored in the zip file.
Here is the same zip file dumped using the `zipdetails` `-v` option:
```
$ zipdetails -v test.zip
0000 0004 50 4B 03 04 LOCAL HEADER #1 04034B50
0004 0001 0A Extract Zip Spec 0A '1.0'
0005 0001 00 Extract OS 00 'MS-DOS'
0006 0002 00 00 General Purpose Flag 0000
0008 0002 00 00 Compression Method 0000 'Stored'
000A 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
000E 0004 9C 14 8A 0F CRC 0F8A149C
0012 0004 06 00 00 00 Compressed Length 00000006
0016 0004 06 00 00 00 Uncompressed Length 00000006
001A 0002 0B 00 Filename Length 000B
001C 0002 00 00 Extra Length 0000
001E 000B 6C 65 74 74 Filename 'letters.txt'
65 72 73 2E
74 78 74
0029 0006 61 62 63 64 PAYLOAD abcde.
65 0A
002F 0004 50 4B 03 04 LOCAL HEADER #2 04034B50
0033 0001 0A Extract Zip Spec 0A '1.0'
0034 0001 00 Extract OS 00 'MS-DOS'
0035 0002 00 00 General Purpose Flag 0000
0037 0002 00 00 Compression Method 0000 'Stored'
0039 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
003D 0004 E6 AF 1D 26 CRC 261DAFE6
0041 0004 06 00 00 00 Compressed Length 00000006
0045 0004 06 00 00 00 Uncompressed Length 00000006
0049 0002 0B 00 Filename Length 000B
004B 0002 00 00 Extra Length 0000
004D 000B 6E 75 6D 62 Filename 'numbers.txt'
65 72 73 2E
74 78 74
0058 0006 31 32 33 34 PAYLOAD 12345.
35 0A
005E 0004 50 4B 01 02 CENTRAL HEADER #1 02014B50
0062 0001 1E Created Zip Spec 1E '3.0'
0063 0001 03 Created OS 03 'Unix'
0064 0001 0A Extract Zip Spec 0A '1.0'
0065 0001 00 Extract OS 00 'MS-DOS'
0066 0002 00 00 General Purpose Flag 0000
0068 0002 00 00 Compression Method 0000 'Stored'
006A 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
006E 0004 9C 14 8A 0F CRC 0F8A149C
0072 0004 06 00 00 00 Compressed Length 00000006
0076 0004 06 00 00 00 Uncompressed Length 00000006
007A 0002 0B 00 Filename Length 000B
007C 0002 00 00 Extra Length 0000
007E 0002 00 00 Comment Length 0000
0080 0002 00 00 Disk Start 0000
0082 0002 01 00 Int File Attributes 0001
[Bit 0] 1 Text Data
0084 0004 00 00 B4 81 Ext File Attributes 81B40000
0088 0004 00 00 00 00 Local Header Offset 00000000
008C 000B 6C 65 74 74 Filename 'letters.txt'
65 72 73 2E
74 78 74
0097 0004 50 4B 01 02 CENTRAL HEADER #2 02014B50
009B 0001 1E Created Zip Spec 1E '3.0'
009C 0001 03 Created OS 03 'Unix'
009D 0001 0A Extract Zip Spec 0A '1.0'
009E 0001 00 Extract OS 00 'MS-DOS'
009F 0002 00 00 General Purpose Flag 0000
00A1 0002 00 00 Compression Method 0000 'Stored'
00A3 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021'
00A7 0004 E6 AF 1D 26 CRC 261DAFE6
00AB 0004 06 00 00 00 Compressed Length 00000006
00AF 0004 06 00 00 00 Uncompressed Length 00000006
00B3 0002 0B 00 Filename Length 000B
00B5 0002 00 00 Extra Length 0000
00B7 0002 00 00 Comment Length 0000
00B9 0002 00 00 Disk Start 0000
00BB 0002 01 00 Int File Attributes 0001
[Bit 0] 1 Text Data
00BD 0004 00 00 B4 81 Ext File Attributes 81B40000
00C1 0004 2F 00 00 00 Local Header Offset 0000002F
00C5 000B 6E 75 6D 62 Filename 'numbers.txt'
65 72 73 2E
74 78 74
00D0 0004 50 4B 05 06 END CENTRAL HEADER 06054B50
00D4 0002 00 00 Number of this disk 0000
00D6 0002 00 00 Central Dir Disk no 0000
00D8 0002 02 00 Entries in this disk 0002
00DA 0002 02 00 Total Entries 0002
00DC 0004 72 00 00 00 Size of Central Dir 00000072
00E0 0004 5E 00 00 00 Offset to Central Dir 0000005E
00E4 0002 00 00 Comment Length 0000
Done
```
LIMITATIONS
-----------
The following zip file features are not supported by this program:
* Multi-part archives.
* The strong encryption features defined in the [APPNOTE.TXT](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) document.
TODO
----
Error handling is a work in progress. If the program encounters a problem reading a zip file it is likely to terminate with an unhelpful error message.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/zipdetails/issues>.
SEE ALSO
---------
The primary reference for Zip files is [APPNOTE.TXT](http://www.pkware.com/documents/casestudies/APPNOTE.TXT).
An alternative reference is the Info-Zip appnote. This is available from <ftp://ftp.info-zip.org/pub/infozip/doc/>
For details of WinZip AES encryption see [AES Encryption Information: Encryption Specification AE-1 and AE-2](https://www.winzip.com/win/es/aes_info.html).
The `zipinfo` program that comes with the info-zip distribution (<http://www.info-zip.org/>) can also display details of the structure of a zip file.
AUTHOR
------
Paul Marquess *[email protected]*.
COPYRIGHT
---------
Copyright (c) 2011-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 Symbol Symbol
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
NAME
----
Symbol - manipulate Perl symbols and their names
SYNOPSIS
--------
```
use Symbol;
$sym = gensym;
open($sym, '<', "filename");
$_ = <$sym>;
# etc.
ungensym $sym; # no effect
# replace *FOO{IO} handle but not $FOO, %FOO, etc.
*FOO = geniosym;
print qualify("x"), "\n"; # "main::x"
print qualify("x", "FOO"), "\n"; # "FOO::x"
print qualify("BAR::x"), "\n"; # "BAR::x"
print qualify("BAR::x", "FOO"), "\n"; # "BAR::x"
print qualify("STDOUT", "FOO"), "\n"; # "main::STDOUT" (global)
print qualify(\*x), "\n"; # returns \*x
print qualify(\*x, "FOO"), "\n"; # returns \*x
use strict refs;
print { qualify_to_ref $fh } "foo!\n";
$ref = qualify_to_ref $name, $pkg;
use Symbol qw(delete_package);
delete_package('Foo::Bar');
print "deleted\n" unless exists $Foo::{'Bar::'};
```
DESCRIPTION
-----------
`Symbol::gensym` creates an anonymous glob and returns a reference to it. Such a glob reference can be used as a file or directory handle.
For backward compatibility with older implementations that didn't support anonymous globs, `Symbol::ungensym` is also provided. But it doesn't do anything.
`Symbol::geniosym` creates an anonymous IO handle. This can be assigned into an existing glob without affecting the non-IO portions of the glob.
`Symbol::qualify` turns unqualified symbol names into qualified variable names (e.g. "myvar" -> "MyPackage::myvar"). If it is given a second parameter, `qualify` uses it as the default package; otherwise, it uses the package of its caller. Regardless, global variable names (e.g. "STDOUT", "ENV", "SIG") are always qualified with "main::".
Qualification applies only to symbol names (strings). References are left unchanged under the assumption that they are glob references, which are qualified by their nature.
`Symbol::qualify_to_ref` is just like `Symbol::qualify` except that it returns a glob ref rather than a symbol name, so you can use the result even if `use strict 'refs'` is in effect.
`Symbol::delete_package` wipes out a whole package namespace. Note this routine is not exported by default--you may want to import it explicitly.
BUGS
----
`Symbol::delete_package` is a bit too powerful. It undefines every symbol that lives in the specified package. Since perl, for performance reasons, does not perform a symbol table lookup each time a function is called or a global variable is accessed, some code that has already been loaded and that makes use of symbols in package `Foo` may stop working after you delete `Foo`, even if you reload the `Foo` module afterwards.
perl File::stat File::stat
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [ERRORS](#ERRORS)
* [WARNINGS](#WARNINGS)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
File::stat - by-name interface to Perl's built-in stat() functions
SYNOPSIS
--------
```
use File::stat;
$st = stat($file) or die "No $file: $!";
if ( ($st->mode & 0111) && ($st->nlink > 1) ) {
print "$file is executable with lotsa links\n";
}
if ( -x $st ) {
print "$file is executable\n";
}
use Fcntl "S_IRUSR";
if ( $st->cando(S_IRUSR, 1) ) {
print "My effective uid can read $file\n";
}
use File::stat qw(:FIELDS);
stat($file) or die "No $file: $!";
if ( ($st_mode & 0111) && ($st_nlink > 1) ) {
print "$file is executable with lotsa links\n";
}
```
DESCRIPTION
-----------
This module's default exports override the core stat() and lstat() functions, replacing them with versions that return "File::stat" objects. This object has methods that return the similarly named structure field name from the stat(2) function; namely, dev, ino, mode, nlink, uid, gid, rdev, size, atime, mtime, ctime, blksize, and blocks.
As of version 1.02 (provided with perl 5.12) the object provides `"-X"` overloading, so you can call filetest operators (`-f`, `-x`, and so on) on it. It also provides a `->cando` method, called like
```
$st->cando( ACCESS, EFFECTIVE )
```
where *ACCESS* is one of `S_IRUSR`, `S_IWUSR` or `S_IXUSR` from the [Fcntl](fcntl) module, and *EFFECTIVE* indicates whether to use effective (true) or real (false) ids. The method interprets the `mode`, `uid` and `gid` fields, and returns whether or not the current process would be allowed the specified access.
If you don't want to use the objects, you may import the `->cando` method into your namespace as a regular function called `stat_cando`. This takes an arrayref containing the return values of `stat` or `lstat` as its first argument, and interprets it for you.
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 stat() and lstat() functions.) Access these fields as variables named with a preceding `st_` in front their method names. Thus, `$stat_obj->dev()` corresponds to $st\_dev if you import the fields.
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.
BUGS
----
As of Perl 5.8.0 after using this module you cannot use the implicit `$_` or the special filehandle `_` with stat() or lstat(), trying to do so leads into strange errors. The workaround is for `$_` to be explicit
```
my $stat_obj = stat $_;
```
and for `_` to explicitly populate the object using the unexported and undocumented populate() function with CORE::stat():
```
my $stat_obj = File::stat::populate(CORE::stat(_));
```
ERRORS
------
-%s is not implemented on a File::stat object The filetest operators `-t`, `-T` and `-B` are not implemented, as they require more information than just a stat buffer.
WARNINGS
--------
These can all be disabled with
```
no warnings "File::stat";
```
File::stat ignores use filetest 'access' You have tried to use one of the `-rwxRWX` filetests with `use filetest 'access'` in effect. `File::stat` will ignore the pragma, and just use the information in the `mode` member as usual.
File::stat ignores VMS ACLs VMS systems have a permissions structure that cannot be completely represented in a stat buffer, and unlike on other systems the builtin filetest operators respect this. The `File::stat` overloads, however, do not, since the information required is not available.
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 File::Spec::Mac File::Spec::Mac
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::Mac - File::Spec for Mac OS (Classic)
SYNOPSIS
--------
```
require File::Spec::Mac; # Done internally by File::Spec if needed
```
DESCRIPTION
-----------
Methods for manipulating file specifications.
METHODS
-------
canonpath On Mac OS, there's nothing to be done. Returns what it's given.
catdir() Concatenate two or more directory names to form a path separated by colons (":") ending with a directory. Resulting paths are **relative** by default, but can be forced to be absolute (but avoid this, see below). Automatically puts a trailing ":" on the end of the complete path, because that's what's done in MacPerl's environment and helps to distinguish a file path from a directory path.
**IMPORTANT NOTE:** Beginning with version 1.3 of this module, the resulting path is relative by default and *not* absolute. This decision was made due to portability reasons. Since `File::Spec->catdir()` returns relative paths on all other operating systems, it will now also follow this convention on Mac OS. Note that this may break some existing scripts.
The intended purpose of this routine is to concatenate *directory names*. But because of the nature of Macintosh paths, some additional possibilities are allowed to make using this routine give reasonable results for some common situations. In other words, you are also allowed to concatenate *paths* instead of directory names (strictly speaking, a string like ":a" is a path, but not a name, since it contains a punctuation character ":").
So, beside calls like
```
catdir("a") = ":a:"
catdir("a","b") = ":a:b:"
catdir() = "" (special case)
```
calls like the following
```
catdir(":a:") = ":a:"
catdir(":a","b") = ":a:b:"
catdir(":a:","b") = ":a:b:"
catdir(":a:",":b:") = ":a:b:"
catdir(":") = ":"
```
are allowed.
Here are the rules that are used in `catdir()`; note that we try to be as compatible as possible to Unix:
1. The resulting path is relative by default, i.e. the resulting path will have a leading colon.
2. A trailing colon is added automatically to the resulting path, to denote a directory.
3. Generally, each argument has one leading ":" and one trailing ":" removed (if any). They are then joined together by a ":". Special treatment applies for arguments denoting updir paths like "::lib:", see (4), or arguments consisting solely of colons ("colon paths"), see (5).
4. When an updir path like ":::lib::" is passed as argument, the number of directories to climb up is handled correctly, not removing leading or trailing colons when necessary. E.g.
```
catdir(":::a","::b","c") = ":::a::b:c:"
catdir(":::a::","::b","c") = ":::a:::b:c:"
```
5. Adding a colon ":" or empty string "" to a path at *any* position doesn't alter the path, i.e. these arguments are ignored. (When a "" is passed as the first argument, it has a special meaning, see (6)). This way, a colon ":" is handled like a "." (curdir) on Unix, while an empty string "" is generally ignored (see ["canonpath()" in File::Spec::Unix](File::Spec::Unix#canonpath%28%29) ). Likewise, a "::" is handled like a ".." (updir), and a ":::" is handled like a "../.." etc. E.g.
```
catdir("a",":",":","b") = ":a:b:"
catdir("a",":","::",":b") = ":a::b:"
```
6. If the first argument is an empty string "" or is a volume name, i.e. matches the pattern /^[^:]+:/, the resulting path is **absolute**.
7. Passing an empty string "" as the first argument to `catdir()` is like passing`File::Spec->rootdir()` as the first argument, i.e.
```
catdir("","a","b") is the same as
catdir(rootdir(),"a","b").
```
This is true on Unix, where `catdir("","a","b")` yields "/a/b" and `rootdir()` is "/". Note that `rootdir()` on Mac OS is the startup volume, which is the closest in concept to Unix' "/". This should help to run existing scripts originally written for Unix.
8. For absolute paths, some cleanup is done, to ensure that the volume name isn't immediately followed by updirs. This is invalid, because this would go beyond "root". Generally, these cases are handled like their Unix counterparts:
```
Unix:
Unix->catdir("","") = "/"
Unix->catdir("",".") = "/"
Unix->catdir("","..") = "/" # can't go
# beyond root
Unix->catdir("",".","..","..","a") = "/a"
Mac:
Mac->catdir("","") = rootdir() # (e.g. "HD:")
Mac->catdir("",":") = rootdir()
Mac->catdir("","::") = rootdir() # can't go
# beyond root
Mac->catdir("",":","::","::","a") = rootdir() . "a:"
# (e.g. "HD:a:")
```
However, this approach is limited to the first arguments following "root" (again, see ["canonpath()" in File::Spec::Unix](File::Spec::Unix#canonpath%28%29). If there are more arguments that move up the directory tree, an invalid path going beyond root can be created.
As you've seen, you can force `catdir()` to create an absolute path by passing either an empty string or a path that begins with a volume name as the first argument. However, you are strongly encouraged not to do so, since this is done only for backward compatibility. Newer versions of File::Spec come with a method called `catpath()` (see below), that is designed to offer a portable solution for the creation of absolute paths. It takes volume, directory and file portions and returns an entire path. While `catdir()` is still suitable for the concatenation of *directory names*, you are encouraged to use `catpath()` to concatenate *volume names* and *directory paths*. E.g.
```
$dir = File::Spec->catdir("tmp","sources");
$abs_path = File::Spec->catpath("MacintoshHD:", $dir,"");
```
yields
```
"MacintoshHD:tmp:sources:" .
```
catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename. Resulting paths are **relative** by default, but can be forced to be absolute (but avoid this).
**IMPORTANT NOTE:** Beginning with version 1.3 of this module, the resulting path is relative by default and *not* absolute. This decision was made due to portability reasons. Since `File::Spec->catfile()` returns relative paths on all other operating systems, it will now also follow this convention on Mac OS. Note that this may break some existing scripts.
The last argument is always considered to be the file portion. Since `catfile()` uses `catdir()` (see above) for the concatenation of the directory portions (if any), the following with regard to relative and absolute paths is true:
```
catfile("") = ""
catfile("file") = "file"
```
but
```
catfile("","") = rootdir() # (e.g. "HD:")
catfile("","file") = rootdir() . file # (e.g. "HD:file")
catfile("HD:","file") = "HD:file"
```
This means that `catdir()` is called only when there are two or more arguments, as one might expect.
Note that the leading ":" is removed from the filename, so that
```
catfile("a","b","file") = ":a:b:file" and
catfile("a","b",":file") = ":a:b:file"
```
give the same answer.
To concatenate *volume names*, *directory paths* and *filenames*, you are encouraged to use `catpath()` (see below).
curdir Returns a string representing the current directory. On Mac OS, this is ":".
devnull Returns a string representing the null device. On Mac OS, this is "Dev:Null".
rootdir Returns the empty string. Mac OS has no real root directory.
tmpdir Returns the contents of $ENV{TMPDIR}, if that directory exits or the current working directory otherwise. Under MacPerl, $ENV{TMPDIR} will contain a path like "MacintoshHD:Temporary Items:", which is a hidden directory on your startup volume.
updir Returns a string representing the parent directory. On Mac OS, this is "::".
file\_name\_is\_absolute Takes as argument a path and returns true, if it is an absolute path. If the path has a leading ":", it's a relative path. Otherwise, it's an absolute path, unless the path doesn't contain any colons, i.e. it's a name like "a". In this particular case, the path is considered to be relative (i.e. it is considered to be a filename). Use ":" in the appropriate place in the path if you want to distinguish unambiguously. As a special case, the filename '' is always considered to be absolute. Note that with version 1.2 of File::Spec::Mac, this does no longer consult the local filesystem.
E.g.
```
File::Spec->file_name_is_absolute("a"); # false (relative)
File::Spec->file_name_is_absolute(":a:b:"); # false (relative)
File::Spec->file_name_is_absolute("MacintoshHD:");
# true (absolute)
File::Spec->file_name_is_absolute(""); # true (absolute)
```
path Returns the null list for the MacPerl application, since the concept is usually meaningless under Mac OS. But if you're using the MacPerl tool under MPW, it gives back $ENV{Commands} suitably split, as is done in :lib:ExtUtils:MM\_Mac.pm.
splitpath
```
($volume,$directories,$file) = File::Spec->splitpath( $path );
($volume,$directories,$file) = File::Spec->splitpath( $path,
$no_file );
```
Splits a path into volume, directory, and filename portions.
On Mac OS, assumes that the last part of the path is a filename unless $no\_file is true or a trailing separator ":" is present.
The volume portion is always returned with a trailing ":". The directory portion is always returned with a leading (to denote a relative path) and a trailing ":" (to denote a directory). The file portion is always returned *without* a leading ":". Empty portions are returned as empty string ''.
The results can be passed to `catpath()` to get back a path equivalent to (usually identical to) the original path.
splitdir The opposite of `catdir()`.
```
@dirs = File::Spec->splitdir( $directories );
```
$directories should 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. Consider using `splitpath()` otherwise.
Unlike just splitting the directories on the separator, empty directory names (`""`) can be returned. Since `catdir()` on Mac OS always appends a trailing colon to distinguish a directory path from a file path, a single trailing colon will be ignored, i.e. there's no empty directory name after it.
Hence, on Mac OS, both
```
File::Spec->splitdir( ":a:b::c:" ); and
File::Spec->splitdir( ":a:b::c" );
```
yield:
```
( "a", "b", "::", "c")
```
while
```
File::Spec->splitdir( ":a:b::c::" );
```
yields:
```
( "a", "b", "::", "c", "::")
```
catpath
```
$path = File::Spec->catpath($volume,$directory,$file);
```
Takes volume, directory and file portions and returns an entire path. On Mac OS, $volume, $directory and $file are concatenated. A ':' is inserted if need be. You may pass an empty string for each portion. If all portions are empty, the empty string is returned. If $volume is empty, the result will be a relative path, beginning with a ':'. If $volume and $directory are empty, a leading ":" (if any) is removed form $file and the remainder is returned. If $file is empty, the resulting path will have a trailing ':'.
abs2rel Takes a destination path and an optional base path and 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 ) ;
```
Note that both paths are assumed to have a notation that distinguishes a directory path (with trailing ':') from a file path (without trailing ':').
If $base is not present or '', then the current working directory is used. If $base is relative, then it is converted to absolute form using `rel2abs()`. This means that it is taken to be relative to the current working directory.
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.
If $base doesn't have a trailing colon, the last element of $base is assumed to be a filename. This filename is ignored. Otherwise all path components are assumed to be directories.
If $path is relative, it is converted to absolute form using `rel2abs()`. This means that it is taken to be relative to the current working directory.
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 ) ;
```
Note that both paths are assumed to have a notation that distinguishes a directory path (with trailing ':') from a file path (without trailing ':').
If $base is not present or '', then $base is set to the current working directory. If $base is relative, then it is converted to absolute form using `rel2abs()`. This means that it is taken to be relative to the current working directory.
If $base doesn't have a trailing colon, the last element of $base is assumed to be a filename. This filename is ignored. Otherwise all path components are assumed to be directories.
If $path is already absolute, it is returned and $base is ignored.
Based on code written by Shigio Yamaguchi.
AUTHORS
-------
See the authors list in *File::Spec*. Mac OS support by Paul Schinder <[email protected]> and Thomas Wegner <wegner\[email protected]>.
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.
SEE ALSO
---------
See <File::Spec> and <File::Spec::Unix>. This package overrides the implementation of these methods, not the semantics.
| programming_docs |
perl vars vars
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
vars - Perl pragma to predeclare global variable names
SYNOPSIS
--------
```
use vars qw($frob @mung %seen);
```
DESCRIPTION
-----------
NOTE: For use with variables in the current package for a single scope, the functionality provided by this pragma has been superseded by `our` declarations, available in Perl v5.6.0 or later, and use of this pragma is discouraged. See ["our" in perlfunc](perlfunc#our).
This pragma will predeclare all the variables whose names are in the list, allowing you to use them under `use strict`, and disabling any typo warnings for them.
Unlike pragmas that affect the `$^H` hints variable, the `use vars` and `use subs` declarations are not lexically scoped to the block they appear in: they affect the entire package in which they appear. It is not possible to rescind these declarations with `no vars` or `no subs`.
Packages such as the **AutoLoader** and **SelfLoader** that delay loading of subroutines within packages can create problems with package lexicals defined using `my()`. While the **vars** pragma cannot duplicate the effect of package lexicals (total transparency outside of the package), it can act as an acceptable substitute by pre-declaring global symbols, ensuring their availability to the later-loaded routines.
See ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules).
perl autodie::exception autodie::exception
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Common Methods](#Common-Methods)
- [args](#args)
- [function](#function)
- [file](#file)
- [package](#package)
- [caller](#caller)
- [line](#line)
- [context](#context)
- [return](#return)
- [errno](#errno)
- [eval\_error](#eval_error)
- [matches](#matches)
+ [Advanced methods](#Advanced-methods)
- [register](#register)
- [add\_file\_and\_line](#add_file_and_line)
- [stringify](#stringify)
- [format\_default](#format_default)
- [new](#new)
* [SEE ALSO](#SEE-ALSO)
* [LICENSE](#LICENSE)
* [AUTHOR](#AUTHOR)
NAME
----
autodie::exception - Exceptions from autodying functions.
SYNOPSIS
--------
```
eval {
use autodie;
open(my $fh, '<', 'some_file.txt');
...
};
if (my $E = $@) {
say "Ooops! ",$E->caller," had problems: $@";
}
```
DESCRIPTION
-----------
When an <autodie> enabled function fails, it generates an `autodie::exception` object. This can be interrogated to determine further information about the error that occurred.
This document is broken into two sections; those methods that are most useful to the end-developer, and those methods for anyone wishing to subclass or get very familiar with `autodie::exception`.
###
Common Methods
These methods are intended to be used in the everyday dealing of exceptions.
The following assume that the error has been copied into a separate scalar:
```
if ($E = $@) {
...
}
```
This is not required, but is recommended in case any code is called which may reset or alter `$@`.
#### args
```
my $array_ref = $E->args;
```
Provides a reference to the arguments passed to the subroutine that died.
#### function
```
my $sub = $E->function;
```
The subroutine (including package) that threw the exception.
#### file
```
my $file = $E->file;
```
The file in which the error occurred (eg, `myscript.pl` or `MyTest.pm`).
#### package
```
my $package = $E->package;
```
The package from which the exceptional subroutine was called.
#### caller
```
my $caller = $E->caller;
```
The subroutine that *called* the exceptional code.
#### line
```
my $line = $E->line;
```
The line in `$E->file` where the exceptional code was called.
#### context
```
my $context = $E->context;
```
The context in which the subroutine was called by autodie; usually the same as the context in which you called the autodying subroutine. This can be 'list', 'scalar', or undefined (unknown). It will never be 'void', as `autodie` always captures the return value in one way or another.
For some core functions that always return a scalar value regardless of their context (eg, `chown`), this may be 'scalar', even if you used a list context.
#### return
```
my $return_value = $E->return;
```
The value(s) returned by the failed subroutine. When the subroutine was called in a list context, this will always be a reference to an array containing the results. When the subroutine was called in a scalar context, this will be the actual scalar returned.
#### errno
```
my $errno = $E->errno;
```
The value of `$!` at the time when the exception occurred.
**NOTE**: This method will leave the main `autodie::exception` class and become part of a role in the future. You should only call `errno` for exceptions where `$!` would reasonably have been set on failure.
#### eval\_error
```
my $old_eval_error = $E->eval_error;
```
The contents of `$@` immediately after autodie triggered an exception. This may be useful when dealing with modules such as <Text::Balanced> that set (but do not throw) `$@` on error.
#### matches
```
if ( $e->matches('open') ) { ... }
if ( 'open' ~~ $e ) { ... }
```
`matches` is used to determine whether a given exception matches a particular role.
An exception is considered to match a string if:
* For a string not starting with a colon, the string exactly matches the package and subroutine that threw the exception. For example, `MyModule::log`. If the string does not contain a package name, `CORE::` is assumed.
* For a string that does start with a colon, if the subroutine throwing the exception *does* that behaviour. For example, the `CORE::open` subroutine does `:file`, `:io` and `:all`.
See ["CATEGORIES" in autodie](autodie#CATEGORIES) for further information.
On Perl 5.10 and above, using smart-match (`~~`) with an `autodie::exception` object will use `matches` underneath. This module used to recommend using smart-match with the exception object on the left hand side, but in future Perls that is likely to stop working. The smart-match facility of this class should only be used with the exception object on the right hand side. Having the exception object on the right is both future-proof and portable to older Perls, back to 5.10. Beware that this facility can only be relied upon when it is certain that the exception object actually is an `autodie::exception` object; it is no more capable than an explicit call to the `matches` method.
###
Advanced methods
The following methods, while usable from anywhere, are primarily intended for developers wishing to subclass `autodie::exception`, write code that registers custom error messages, or otherwise work closely with the `autodie::exception` model.
#### register
```
autodie::exception->register( 'CORE::open' => \&mysub );
```
The `register` method allows for the registration of a message handler for a given subroutine. The full subroutine name including the package should be used.
Registered message handlers will receive the `autodie::exception` object as the first parameter.
#### add\_file\_and\_line
```
say "Problem occurred",$@->add_file_and_line;
```
Returns the string `at %s line %d`, where `%s` is replaced with the filename, and `%d` is replaced with the line number.
Primarily intended for use by format handlers.
#### stringify
```
say "The error was: ",$@->stringify;
```
Formats the error as a human readable string. Usually there's no reason to call this directly, as it is used automatically if an `autodie::exception` object is ever used as a string.
Child classes can override this method to change how they're stringified.
#### format\_default
```
my $error_string = $E->format_default;
```
This produces the default error string for the given exception, *without using any registered message handlers*. It is primarily intended to be called from a message handler when they have been passed an exception they don't want to format.
Child classes can override this method to change how default messages are formatted.
#### new
```
my $error = autodie::exception->new(
args => \@_,
function => "CORE::open",
errno => $!,
context => 'scalar',
return => undef,
);
```
Creates a new `autodie::exception` object. Normally called directly from an autodying function. The `function` argument is required, its the function we were trying to call that generated the exception. The `args` parameter is optional.
The `errno` value is optional. In versions of `autodie::exception` 1.99 and earlier the code would try to automatically use the current value of `$!`, but this was unreliable and is no longer supported.
Atrributes such as package, file, and caller are determined automatically, and cannot be specified.
SEE ALSO
---------
<autodie>, <autodie::exception::system>
LICENSE
-------
Copyright (C)2008 Paul Fenwick
This is free software. You may modify and/or redistribute this code under the same terms as Perl 5.10 itself, or, at your option, any later version of Perl 5.
AUTHOR
------
Paul Fenwick <[email protected]>
perl Test2::EventFacet::Assert Test2::EventFacet::Assert
=========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Assert - Facet representing an assertion.
DESCRIPTION
-----------
The assertion facet is provided by any event representing an assertion that was made.
FIELDS
------
$string = $assert->{details}
$string = $assert->details() Human readable description of the assertion.
$bool = $assert->{pass}
$bool = $assert->pass() True if the assertion passed.
$bool = $assert->{no\_debug}
$bool = $assert->no\_debug() Set this to true if you have provided custom diagnostics and do not want the defaults to be displayed.
$int = $assert->{number}
$int = $assert->number() (Optional) assertion number. This may be omitted or ignored. This is usually only useful when parsing/processing TAP.
**Note**: This is not set by the Test2 system, assertion number is not known until AFTER the assertion has been processed. This attribute is part of the spec only for harnesses.
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 Net::FTP::dataconn Net::FTP::dataconn
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::FTP::dataconn - FTP Client data connection class
SYNOPSIS
--------
```
# Perform IO operations on an FTP client data connection object:
$num_bytes_read = $obj->read($buffer, $size);
$num_bytes_read = $obj->read($buffer, $size, $timeout);
$num_bytes_written = $obj->write($buffer, $size);
$num_bytes_written = $obj->write($buffer, $size, $timeout);
$num_bytes_read_so_far = $obj->bytes_read();
$obj->abort();
$closed_successfully = $obj->close();
```
DESCRIPTION
-----------
Some of the methods defined in `Net::FTP` return an object which will be derived from this class. The dataconn class itself is derived from the `IO::Socket::INET` class, so any normal IO operations can be performed. However the following methods are defined in the dataconn class and IO should be performed using these.
`read($buffer, $size[, $timeout])`
Read `$size` bytes of data from the server and place it into `$buffer`, also performing any <CRLF> translation necessary. `$timeout` is optional, if not given, the timeout value from the command connection will be used.
Returns the number of bytes read before any <CRLF> translation.
`write($buffer, $size[, $timeout])`
Write `$size` bytes of data from `$buffer` to the server, also performing any <CRLF> translation necessary. `$timeout` is optional, if not given, the timeout value from the command connection will be used.
Returns the number of bytes written before any <CRLF> translation.
`bytes_read()`
Returns the number of bytes read so far.
`abort()`
Abort the current data transfer.
`close()`
Close the data connection and get a response from the FTP server. Returns *true* if the connection was closed successfully and the first digit of the response from the server was a '2'.
EXPORTS
-------
*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) 1997-2010 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 ExtUtils::MM_AIX ExtUtils::MM\_AIX
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overridden methods](#Overridden-methods)
- [dlsyms](#dlsyms)
- [xs\_dlsyms\_ext](#xs_dlsyms_ext)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MM\_AIX - AIX 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 AIX.
Unless otherwise stated it works just like ExtUtils::MM\_Unix.
###
Overridden methods
#### dlsyms
Define DL\_FUNCS and DL\_VARS and write the \*.exp files.
#### xs\_dlsyms\_ext
On AIX, is `.exp`.
AUTHOR
------
Michael G Schwern <[email protected]> with code from ExtUtils::MM\_Unix
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl File::Temp File::Temp
==========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OBJECT-ORIENTED INTERFACE](#OBJECT-ORIENTED-INTERFACE)
* [FUNCTIONS](#FUNCTIONS)
* [MKTEMP FUNCTIONS](#MKTEMP-FUNCTIONS)
* [POSIX FUNCTIONS](#POSIX-FUNCTIONS)
* [ADDITIONAL FUNCTIONS](#ADDITIONAL-FUNCTIONS)
* [UTILITY FUNCTIONS](#UTILITY-FUNCTIONS)
* [PACKAGE VARIABLES](#PACKAGE-VARIABLES)
* [WARNING](#WARNING)
+ [Temporary files and NFS](#Temporary-files-and-NFS)
+ [Forking](#Forking)
+ [Directory removal](#Directory-removal)
+ [Taint mode](#Taint-mode)
+ [BINMODE](#BINMODE)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [AUTHOR](#AUTHOR)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
File::Temp - return name and handle of a temporary file safely
VERSION
-------
version 0.2311
SYNOPSIS
--------
```
use File::Temp qw/ tempfile tempdir /;
$fh = tempfile();
($fh, $filename) = tempfile();
($fh, $filename) = tempfile( $template, DIR => $dir);
($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
($fh, $filename) = tempfile( $template, TMPDIR => 1 );
binmode( $fh, ":utf8" );
$dir = tempdir( CLEANUP => 1 );
($fh, $filename) = tempfile( DIR => $dir );
```
Object interface:
```
require File::Temp;
use File::Temp ();
use File::Temp qw/ :seekable /;
$fh = File::Temp->new();
$fname = $fh->filename;
$fh = File::Temp->new(TEMPLATE => $template);
$fname = $fh->filename;
$tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' );
print $tmp "Some data\n";
print "Filename is $tmp\n";
$tmp->seek( 0, SEEK_END );
$dir = File::Temp->newdir(); # CLEANUP => 1 by default
```
The following interfaces are provided for compatibility with existing APIs. They should not be used in new code.
MkTemp family:
```
use File::Temp qw/ :mktemp /;
($fh, $file) = mkstemp( "tmpfileXXXXX" );
($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
$tmpdir = mkdtemp( $template );
$unopened_file = mktemp( $template );
```
POSIX functions:
```
use File::Temp qw/ :POSIX /;
$file = tmpnam();
$fh = tmpfile();
($fh, $file) = tmpnam();
```
Compatibility functions:
```
$unopened_file = File::Temp::tempnam( $dir, $pfx );
```
DESCRIPTION
-----------
`File::Temp` can be used to create and open temporary files in a safe way. There is both a function interface and an object-oriented interface. The File::Temp constructor or the tempfile() function can be used to return the name and the open filehandle of a temporary file. The tempdir() function can be used to create a temporary directory.
The security aspect of temporary file creation is emphasized such that a filehandle and filename are returned together. This helps guarantee that a race condition can not occur where the temporary file is created by another process between checking for the existence of the file and its opening. Additional security levels are provided to check, for example, that the sticky bit is set on world writable directories. See ["safe\_level"](#safe_level) for more information.
For compatibility with popular C library functions, Perl implementations of the mkstemp() family of functions are provided. These are, mkstemp(), mkstemps(), mkdtemp() and mktemp().
Additionally, implementations of the standard [POSIX](posix) tmpnam() and tmpfile() functions are provided if required.
Implementations of mktemp(), tmpnam(), and tempnam() are provided, but should be used with caution since they return only a filename that was valid when function was called, so cannot guarantee that the file will not exist by the time the caller opens the filename.
Filehandles returned by these functions support the seekable methods.
OBJECT-ORIENTED INTERFACE
--------------------------
This is the primary interface for interacting with `File::Temp`. Using the OO interface a temporary file can be created when the object is constructed and the file can be removed when the object is no longer required.
Note that there is no method to obtain the filehandle from the `File::Temp` object. The object itself acts as a filehandle. The object isa `IO::Handle` and isa `IO::Seekable` so all those methods are available.
Also, the object is configured such that it stringifies to the name of the temporary file and so can be compared to a filename directly. It numifies to the `refaddr` the same as other handles and so can be compared to other handles with `==`.
```
$fh eq $filename # as a string
$fh != \*STDOUT # as a number
```
Available since 0.14.
**new** Create a temporary file object.
```
my $tmp = File::Temp->new();
```
by default the object is constructed as if `tempfile` was called without options, but with the additional behaviour that the temporary file is removed by the object destructor if UNLINK is set to true (the default).
Supported arguments are the same as for `tempfile`: UNLINK (defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. Additionally, the filename template is specified using the TEMPLATE option. The OPEN option is not supported (the file is always opened).
```
$tmp = File::Temp->new( TEMPLATE => 'tempXXXXX',
DIR => 'mydir',
SUFFIX => '.dat');
```
Arguments are case insensitive.
Can call croak() if an error occurs.
Available since 0.14.
TEMPLATE available since 0.23
**newdir** Create a temporary directory using an object oriented interface.
```
$dir = File::Temp->newdir();
```
By default the directory is deleted when the object goes out of scope.
Supports the same options as the `tempdir` function. Note that directories created with this method default to CLEANUP => 1.
```
$dir = File::Temp->newdir( $template, %options );
```
A template may be specified either with a leading template or with a TEMPLATE argument.
Available since 0.19.
TEMPLATE available since 0.23.
**filename** Return the name of the temporary file associated with this object (if the object was created using the "new" constructor).
```
$filename = $tmp->filename;
```
This method is called automatically when the object is used as a string.
Current API available since 0.14
**dirname** Return the name of the temporary directory associated with this object (if the object was created using the "newdir" constructor).
```
$dirname = $tmpdir->dirname;
```
This method is called automatically when the object is used in string context.
**unlink\_on\_destroy** Control whether the file is unlinked when the object goes out of scope. The file is removed if this value is true and $KEEP\_ALL is not.
```
$fh->unlink_on_destroy( 1 );
```
Default is for the file to be removed.
Current API available since 0.15
**DESTROY** When the object goes out of scope, the destructor is called. This destructor will attempt to unlink the file (using [unlink1](#unlink1)) if the constructor was called with UNLINK set to 1 (the default state if UNLINK is not specified).
No error is given if the unlink fails.
If the object has been passed to a child process during a fork, the file will be deleted when the object goes out of scope in the parent.
For a temporary directory object the directory will be removed unless the CLEANUP argument was used in the constructor (and set to false) or `unlink_on_destroy` was modified after creation. Note that if a temp directory is your current directory, it cannot be removed - a warning will be given in this case. `chdir()` out of the directory before letting the object go out of scope.
If the global variable $KEEP\_ALL is true, the file or directory will not be removed.
FUNCTIONS
---------
This section describes the recommended interface for generating temporary files and directories.
**tempfile** This is the basic function to generate temporary files. The behaviour of the file can be changed using various options:
```
$fh = tempfile();
($fh, $filename) = tempfile();
```
Create a temporary file in the directory specified for temporary files, as specified by the tmpdir() function in <File::Spec>.
```
($fh, $filename) = tempfile($template);
```
Create a temporary file in the current directory using the supplied template. Trailing `X' characters are replaced with random letters to generate the filename. At least four `X' characters must be present at the end of the template.
```
($fh, $filename) = tempfile($template, SUFFIX => $suffix)
```
Same as previously, except that a suffix is added to the template after the `X' translation. Useful for ensuring that a temporary filename has a particular extension when needed by other applications. But see the WARNING at the end.
```
($fh, $filename) = tempfile($template, DIR => $dir);
```
Translates the template as before except that a directory name is specified.
```
($fh, $filename) = tempfile($template, TMPDIR => 1);
```
Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file into the same temporary directory as would be used if no template was specified at all.
```
($fh, $filename) = tempfile($template, UNLINK => 1);
```
Return the filename and filehandle as before except that the file is automatically removed when the program exits (dependent on $KEEP\_ALL). Default is for the file to be removed if a file handle is requested and to be kept if the filename is requested. In a scalar context (where no filename is returned) the file is always deleted either (depending on the operating system) on exit or when it is closed (unless $KEEP\_ALL is true when the temp file is created).
Use the object-oriented interface if fine-grained control of when a file is removed is required.
If the template is not specified, a template is always automatically generated. This temporary file is placed in tmpdir() (<File::Spec>) unless a directory is specified explicitly with the DIR option.
```
$fh = tempfile( DIR => $dir );
```
If called in scalar context, only the filehandle is returned and the file will automatically be deleted when closed on operating systems that support this (see the description of tmpfile() elsewhere in this document). This is the preferred mode of operation, as if you only have a filehandle, you can never create a race condition by fumbling with the filename. On systems that can not unlink an open file or can not mark a file as temporary when it is opened (for example, Windows NT uses the `O_TEMPORARY` flag) the file is marked for deletion when the program ends (equivalent to setting UNLINK to 1). The `UNLINK` flag is ignored if present.
```
(undef, $filename) = tempfile($template, OPEN => 0);
```
This will return the filename based on the template but will not open this file. Cannot be used in conjunction with UNLINK set to true. Default is to always open the file to protect from possible race conditions. A warning is issued if warnings are turned on. Consider using the tmpnam() and mktemp() functions described elsewhere in this document if opening the file is not required.
To open the temporary filehandle with O\_EXLOCK (open with exclusive file lock) use `EXLOCK=>1`. This is supported only by some operating systems (most notably BSD derived systems). By default EXLOCK will be false. Former `File::Temp` versions set EXLOCK to true, so to be sure to get an unlocked filehandle also with older versions, explicitly set `EXLOCK=>0`.
```
($fh, $filename) = tempfile($template, EXLOCK => 1);
```
By default, the temp file is created with 0600 file permissions. Use `PERMS` to change this:
```
($fh, $filename) = tempfile($template, PERMS => 0666);
```
Options can be combined as required.
Will croak() if there is an error.
Available since 0.05.
UNLINK flag available since 0.10.
TMPDIR flag available since 0.19.
EXLOCK flag available since 0.19.
PERMS flag available since 0.2310.
**tempdir** This is the recommended interface for creation of temporary directories. By default the directory will not be removed on exit (that is, it won't be temporary; this behaviour can not be changed because of issues with backwards compatibility). To enable removal either use the CLEANUP option which will trigger removal on program exit, or consider using the "newdir" method in the object interface which will allow the directory to be cleaned up when the object goes out of scope.
The behaviour of the function depends on the arguments:
```
$tempdir = tempdir();
```
Create a directory in tmpdir() (see <File::Spec>).
```
$tempdir = tempdir( $template );
```
Create a directory from the supplied template. This template is similar to that described for tempfile(). `X' characters at the end of the template are replaced with random letters to construct the directory name. At least four `X' characters must be in the template.
```
$tempdir = tempdir ( DIR => $dir );
```
Specifies the directory to use for the temporary directory. The temporary directory name is derived from an internal template.
```
$tempdir = tempdir ( $template, DIR => $dir );
```
Prepend the supplied directory name to the template. The template should not include parent directory specifications itself. Any parent directory specifications are removed from the template before prepending the supplied directory.
```
$tempdir = tempdir ( $template, TMPDIR => 1 );
```
Using the supplied template, create the temporary directory in a standard location for temporary files. Equivalent to doing
```
$tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
```
but shorter. Parent directory specifications are stripped from the template itself. The `TMPDIR` option is ignored if `DIR` is set explicitly. Additionally, `TMPDIR` is implied if neither a template nor a directory are supplied.
```
$tempdir = tempdir( $template, CLEANUP => 1);
```
Create a temporary directory using the supplied template, but attempt to remove it (and all files inside it) when the program exits. Note that an attempt will be made to remove all files from the directory even if they were not created by this module (otherwise why ask to clean it up?). The directory removal is made with the rmtree() function from the <File::Path> module. Of course, if the template is not specified, the temporary directory will be created in tmpdir() and will also be removed at program exit.
Will croak() if there is an error.
Current API available since 0.05.
MKTEMP FUNCTIONS
-----------------
The following functions are Perl implementations of the mktemp() family of temp file generation system calls.
**mkstemp** Given a template, returns a filehandle to the temporary file and the name of the file.
```
($fh, $name) = mkstemp( $template );
```
In scalar context, just the filehandle is returned.
The template may be any filename with some number of X's appended to it, for example */tmp/temp.XXXX*. The trailing X's are replaced with unique alphanumeric combinations.
Will croak() if there is an error.
Current API available since 0.05.
**mkstemps** Similar to mkstemp(), except that an extra argument can be supplied with a suffix to be appended to the template.
```
($fh, $name) = mkstemps( $template, $suffix );
```
For example a template of `testXXXXXX` and suffix of `.dat` would generate a file similar to *testhGji\_w.dat*.
Returns just the filehandle alone when called in scalar context.
Will croak() if there is an error.
Current API available since 0.05.
**mkdtemp** Create a directory from a template. The template must end in X's that are replaced by the routine.
```
$tmpdir_name = mkdtemp($template);
```
Returns the name of the temporary directory created.
Directory must be removed by the caller.
Will croak() if there is an error.
Current API available since 0.05.
**mktemp** Returns a valid temporary filename but does not guarantee that the file will not be opened by someone else.
```
$unopened_file = mktemp($template);
```
Template is the same as that required by mkstemp().
Will croak() if there is an error.
Current API available since 0.05.
POSIX FUNCTIONS
----------------
This section describes the re-implementation of the tmpnam() and tmpfile() functions described in [POSIX](posix) using the mkstemp() from this module.
Unlike the [POSIX](posix) implementations, the directory used for the temporary file is not specified in a system include file (`P_tmpdir`) but simply depends on the choice of tmpdir() returned by <File::Spec>. On some implementations this location can be set using the `TMPDIR` environment variable, which may not be secure. If this is a problem, simply use mkstemp() and specify a template.
**tmpnam** When called in scalar context, returns the full name (including path) of a temporary file (uses mktemp()). The only check is that the file does not already exist, but there is no guarantee that that condition will continue to apply.
```
$file = tmpnam();
```
When called in list context, a filehandle to the open file and a filename are returned. This is achieved by calling mkstemp() after constructing a suitable template.
```
($fh, $file) = tmpnam();
```
If possible, this form should be used to prevent possible race conditions.
See ["tmpdir" in File::Spec](File::Spec#tmpdir) for information on the choice of temporary directory for a particular operating system.
Will croak() if there is an error.
Current API available since 0.05.
**tmpfile** Returns the filehandle of a temporary file.
```
$fh = tmpfile();
```
The file is removed when the filehandle is closed or when the program exits. No access to the filename is provided.
If the temporary file can not be created undef is returned. Currently this command will probably not work when the temporary directory is on an NFS file system.
Will croak() if there is an error.
Available since 0.05.
Returning undef if unable to create file added in 0.12.
ADDITIONAL FUNCTIONS
---------------------
These functions are provided for backwards compatibility with common tempfile generation C library functions.
They are not exported and must be addressed using the full package name.
**tempnam** Return the name of a temporary file in the specified directory using a prefix. The file is guaranteed not to exist at the time the function was called, but such guarantees are good for one clock tick only. Always use the proper form of `sysopen` with `O_CREAT | O_EXCL` if you must open such a filename.
```
$filename = File::Temp::tempnam( $dir, $prefix );
```
Equivalent to running mktemp() with $dir/$prefixXXXXXXXX (using unix file convention as an example)
Because this function uses mktemp(), it can suffer from race conditions.
Will croak() if there is an error.
Current API available since 0.05.
UTILITY FUNCTIONS
------------------
Useful functions for dealing with the filehandle and filename.
**unlink0** Given an open filehandle and the associated filename, make a safe unlink. This is achieved by first checking that the filename and filehandle initially point to the same file and that the number of links to the file is 1 (all fields returned by stat() are compared). Then the filename is unlinked and the filehandle checked once again to verify that the number of links on that file is now 0. This is the closest you can come to making sure that the filename unlinked was the same as the file whose descriptor you hold.
```
unlink0($fh, $path)
or die "Error unlinking file $path safely";
```
Returns false on error but croaks() if there is a security anomaly. The filehandle is not closed since on some occasions this is not required.
On some platforms, for example Windows NT, it is not possible to unlink an open file (the file must be closed first). On those platforms, the actual unlinking is deferred until the program ends and good status is returned. A check is still performed to make sure that the filehandle and filename are pointing to the same thing (but not at the time the end block is executed since the deferred removal may not have access to the filehandle).
Additionally, on Windows NT not all the fields returned by stat() can be compared. For example, the `dev` and `rdev` fields seem to be different. Also, it seems that the size of the file returned by stat() does not always agree, with `stat(FH)` being more accurate than `stat(filename)`, presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to `unlink0` it).
Finally, on NFS file systems the link count of the file handle does not always go to zero immediately after unlinking. Currently, this command is expected to fail on NFS disks.
This function is disabled if the global variable $KEEP\_ALL is true and an unlink on open file is supported. If the unlink is to be deferred to the END block, the file is still registered for removal.
This function should not be called if you are using the object oriented interface since the it will interfere with the object destructor deleting the file.
Available Since 0.05.
If can not unlink open file, defer removal until later available since 0.06.
**cmpstat** Compare `stat` of filehandle with `stat` of provided filename. This can be used to check that the filename and filehandle initially point to the same file and that the number of links to the file is 1 (all fields returned by stat() are compared).
```
cmpstat($fh, $path)
or die "Error comparing handle with file";
```
Returns false if the stat information differs or if the link count is greater than 1. Calls croak if there is a security anomaly.
On certain platforms, for example Windows, not all the fields returned by stat() can be compared. For example, the `dev` and `rdev` fields seem to be different in Windows. Also, it seems that the size of the file returned by stat() does not always agree, with `stat(FH)` being more accurate than `stat(filename)`, presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to `unlink0` it).
Not exported by default.
Current API available since 0.14.
**unlink1** Similar to `unlink0` except after file comparison using cmpstat, the filehandle is closed prior to attempting to unlink the file. This allows the file to be removed without using an END block, but does mean that the post-unlink comparison of the filehandle state provided by `unlink0` is not available.
```
unlink1($fh, $path)
or die "Error closing and unlinking file";
```
Usually called from the object destructor when using the OO interface.
Not exported by default.
This function is disabled if the global variable $KEEP\_ALL is true.
Can call croak() if there is a security anomaly during the stat() comparison.
Current API available since 0.14.
**cleanup** Calling this function will cause any temp files or temp directories that are registered for removal to be removed. This happens automatically when the process exits but can be triggered manually if the caller is sure that none of the temp files are required. This method can be registered as an Apache callback.
Note that if a temp directory is your current directory, it cannot be removed. `chdir()` out of the directory first before calling `cleanup()`. (For the cleanup at program exit when the CLEANUP flag is set, this happens automatically.)
On OSes where temp files are automatically removed when the temp file is closed, calling this function will have no effect other than to remove temporary directories (which may include temporary files).
```
File::Temp::cleanup();
```
Not exported by default.
Current API available since 0.15.
PACKAGE VARIABLES
------------------
These functions control the global state of the package.
**safe\_level** Controls the lengths to which the module will go to check the safety of the temporary file or directory before proceeding. Options are:
STANDARD Do the basic security measures to ensure the directory exists and is writable, that temporary files are opened only if they do not already exist, and that possible race conditions are avoided. Finally the [unlink0](#unlink0) function is used to remove files safely.
MEDIUM In addition to the STANDARD security, the output directory is checked to make sure that it is owned either by root or the user running the program. If the directory is writable by group or by other, it is then checked to make sure that the sticky bit is set.
Will not work on platforms that do not support the `-k` test for sticky bit.
HIGH In addition to the MEDIUM security checks, also check for the possibility of ``chown() giveaway'' using the [POSIX](posix) sysconf() function. If this is a possibility, each directory in the path is checked in turn for safeness, recursively walking back to the root directory.
For platforms that do not support the [POSIX](posix) `_PC_CHOWN_RESTRICTED` symbol (for example, Windows NT) it is assumed that ``chown() giveaway'' is possible and the recursive test is performed.
The level can be changed as follows:
```
File::Temp->safe_level( File::Temp::HIGH );
```
The level constants are not exported by the module.
Currently, you must be running at least perl v5.6.0 in order to run with MEDIUM or HIGH security. This is simply because the safety tests use functions from [Fcntl](fcntl) that are not available in older versions of perl. The problem is that the version number for Fcntl is the same in perl 5.6.0 and in 5.005\_03 even though they are different versions.
On systems that do not support the HIGH or MEDIUM safety levels (for example Win NT or OS/2) any attempt to change the level will be ignored. The decision to ignore rather than raise an exception allows portable programs to be written with high security in mind for the systems that can support this without those programs failing on systems where the extra tests are irrelevant.
If you really need to see whether the change has been accepted simply examine the return value of `safe_level`.
```
$newlevel = File::Temp->safe_level( File::Temp::HIGH );
die "Could not change to high security"
if $newlevel != File::Temp::HIGH;
```
Available since 0.05.
TopSystemUID This is the highest UID on the current system that refers to a root UID. This is used to make sure that the temporary directory is owned by a system UID (`root`, `bin`, `sys` etc) rather than simply by root.
This is required since on many unix systems `/tmp` is not owned by root.
Default is to assume that any UID less than or equal to 10 is a root UID.
```
File::Temp->top_system_uid(10);
my $topid = File::Temp->top_system_uid;
```
This value can be adjusted to reduce security checking if required. The value is only relevant when `safe_level` is set to MEDIUM or higher.
Available since 0.05.
**$KEEP\_ALL**
Controls whether temporary files and directories should be retained regardless of any instructions in the program to remove them automatically. This is useful for debugging but should not be used in production code.
```
$File::Temp::KEEP_ALL = 1;
```
Default is for files to be removed as requested by the caller.
In some cases, files will only be retained if this variable is true when the file is created. This means that you can not create a temporary file, set this variable and expect the temp file to still be around when the program exits.
**$DEBUG**
Controls whether debugging messages should be enabled.
```
$File::Temp::DEBUG = 1;
```
Default is for debugging mode to be disabled.
Available since 0.15.
WARNING
-------
For maximum security, endeavour always to avoid ever looking at, touching, or even imputing the existence of the filename. You do not know that that filename is connected to the same file as the handle you have, and attempts to check this can only trigger more race conditions. It's far more secure to use the filehandle alone and dispense with the filename altogether.
If you need to pass the handle to something that expects a filename then on a unix system you can use `"/dev/fd/" . fileno($fh)` for arbitrary programs. Perl code that uses the 2-argument version of `open` can be passed `"+<=&" . fileno($fh)`. Otherwise you will need to pass the filename. You will have to clear the close-on-exec bit on that file descriptor before passing it to another process.
```
use Fcntl qw/F_SETFD F_GETFD/;
fcntl($tmpfh, F_SETFD, 0)
or die "Can't clear close-on-exec flag on temp fh: $!\n";
```
###
Temporary files and NFS
Some problems are associated with using temporary files that reside on NFS file systems and it is recommended that a local filesystem is used whenever possible. Some of the security tests will most probably fail when the temp file is not local. Additionally, be aware that the performance of I/O operations over NFS will not be as good as for a local disk.
### Forking
In some cases files created by File::Temp are removed from within an END block. Since END blocks are triggered when a child process exits (unless `POSIX::_exit()` is used by the child) File::Temp takes care to only remove those temp files created by a particular process ID. This means that a child will not attempt to remove temp files created by the parent process.
If you are forking many processes in parallel that are all creating temporary files, you may need to reset the random number seed using srand(EXPR) in each child else all the children will attempt to walk through the same set of random file names and may well cause themselves to give up if they exceed the number of retry attempts.
###
Directory removal
Note that if you have chdir'ed into the temporary directory and it is subsequently cleaned up (either in the END block or as part of object destruction), then you will get a warning from File::Path::rmtree().
###
Taint mode
If you need to run code under taint mode, updating to the latest <File::Spec> is highly recommended. On Windows, if the directory given by <File::Spec::tmpdir> isn't writable, File::Temp will attempt to fallback to the user's local application data directory or croak with an error.
### BINMODE
The file returned by File::Temp will have been opened in binary mode if such a mode is available. If that is not correct, use the `binmode()` function to change the mode of the filehandle.
Note that you can modify the encoding of a file opened by File::Temp also by using `binmode()`.
HISTORY
-------
Originally began life in May 1999 as an XS interface to the system mkstemp() function. In March 2000, the OpenBSD mkstemp() code was translated to Perl for total control of the code's security checking, to ensure the presence of the function regardless of operating system and to help with portability. The module was shipped as a standard part of perl from v5.6.1.
Thanks to Tom Christiansen for suggesting that this module should be written and providing ideas for code improvements and security enhancements.
SEE ALSO
---------
["tmpnam" in POSIX](posix#tmpnam), ["tmpfile" in POSIX](posix#tmpfile), <File::Spec>, <File::Path>
See <IO::File> and <File::MkTemp>, <Apache::TempFile> for different implementations of temporary file handling.
See <File::Tempdir> for an alternative object-oriented wrapper for the `tempdir` function.
SUPPORT
-------
Bugs may be submitted through [the RT bug tracker](https://rt.cpan.org/Public/Dist/Display.html?Name=File-Temp) (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
------
Tim Jenness <[email protected]>
CONTRIBUTORS
------------
* Tim Jenness <[email protected]>
* Karen Etheridge <[email protected]>
* David Golden <[email protected]>
* Slaven Rezic <[email protected]>
* mohawk2 <[email protected]>
* Roy Ivy III <[email protected]>
* Peter Rabbitson <[email protected]>
* Olivier Menguรฉ <[email protected]>
* Peter John Acklam <[email protected]>
* Tim Gim Yee <[email protected]>
* Nicolas R <[email protected]>
* Brian Mowrey <[email protected]>
* Dagfinn Ilmari Mannsรฅker <[email protected]>
* David Steinbrunner <[email protected]>
* Ed Avis <[email protected]>
* Guillem Jover <[email protected]>
* James E. Keenan <[email protected]>
* Kevin Ryde <[email protected]>
* Ben Tilly <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2020 by Tim Jenness and the UK Particle Physics and Astronomy Research Council.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
| programming_docs |
perl Test2::Event::Waiting Test2::Event::Waiting
=====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Waiting - Tell all procs/threads it is time to be done
DESCRIPTION
-----------
This event has no data of its own. This event is sent out by the IPC system when the main process/thread is ready to end.
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 NEXT NEXT
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Enforcing redispatch](#Enforcing-redispatch)
+ [Avoiding repetitions](#Avoiding-repetitions)
+ [Invoking all versions of a method with a single call](#Invoking-all-versions-of-a-method-with-a-single-call)
+ [Using EVERY methods](#Using-EVERY-methods)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [BUGS AND IRRITATIONS](#BUGS-AND-IRRITATIONS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
NEXT - Provide a pseudo-class NEXT (et al) that allows method redispatch
SYNOPSIS
--------
```
use NEXT;
package P;
sub P::method { print "$_[0]: P method\n"; $_[0]->NEXT::method() }
sub P::DESTROY { print "$_[0]: P dtor\n"; $_[0]->NEXT::DESTROY() }
package Q;
use base qw( P );
sub Q::AUTOLOAD { print "$_[0]: Q AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
sub Q::DESTROY { print "$_[0]: Q dtor\n"; $_[0]->NEXT::DESTROY() }
package R;
sub R::method { print "$_[0]: R method\n"; $_[0]->NEXT::method() }
sub R::AUTOLOAD { print "$_[0]: R AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
sub R::DESTROY { print "$_[0]: R dtor\n"; $_[0]->NEXT::DESTROY() }
package S;
use base qw( Q R );
sub S::method { print "$_[0]: S method\n"; $_[0]->NEXT::method() }
sub S::AUTOLOAD { print "$_[0]: S AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
sub S::DESTROY { print "$_[0]: S dtor\n"; $_[0]->NEXT::DESTROY() }
package main;
my $obj = bless {}, "S";
$obj->method(); # Calls S::method, P::method, R::method
$obj->missing_method(); # Calls S::AUTOLOAD, Q::AUTOLOAD, R::AUTOLOAD
# Clean-up calls S::DESTROY, Q::DESTROY, P::DESTROY, R::DESTROY
```
DESCRIPTION
-----------
The `NEXT` module adds a pseudoclass named `NEXT` to any program that uses it. If a method `m` calls `$self->NEXT::m()`, the call to `m` is redispatched as if the calling method had not originally been found.
**Note:** before using this module, you should look at [next::method](https://metacpan.org/pod/mro#next::method) in the core <mro> module. `mro` has been a core module since Perl 5.9.5.
In other words, a call to `$self->NEXT::m()` resumes the depth-first, left-to-right search of `$self`'s class hierarchy that resulted in the original call to `m`.
Note that this is not the same thing as `$self->SUPER::m()`, which begins a new dispatch that is restricted to searching the ancestors of the current class. `$self->NEXT::m()` can backtrack past the current class -- to look for a suitable method in other ancestors of `$self` -- whereas `$self->SUPER::m()` cannot.
A typical use would be in the destructors of a class hierarchy, as illustrated in the SYNOPSIS above. Each class in the hierarchy has a DESTROY method that performs some class-specific action and then redispatches the call up the hierarchy. As a result, when an object of class S is destroyed, the destructors of *all* its parent classes are called (in depth-first, left-to-right order).
Another typical use of redispatch would be in `AUTOLOAD`'ed methods. If such a method determined that it was not able to handle a particular call, it might choose to redispatch that call, in the hope that some other `AUTOLOAD` (above it, or to its left) might do better.
By default, if a redispatch attempt fails to find another method elsewhere in the objects class hierarchy, it quietly gives up and does nothing (but see ["Enforcing redispatch"](#Enforcing-redispatch)). This gracious acquiescence is also unlike the (generally annoying) behaviour of `SUPER`, which throws an exception if it cannot redispatch.
Note that it is a fatal error for any method (including `AUTOLOAD`) to attempt to redispatch any method that does not have the same name. For example:
```
sub S::oops { print "oops!\n"; $_[0]->NEXT::other_method() }
```
###
Enforcing redispatch
It is possible to make `NEXT` redispatch more demandingly (i.e. like `SUPER` does), so that the redispatch throws an exception if it cannot find a "next" method to call.
To do this, simple invoke the redispatch as:
```
$self->NEXT::ACTUAL::method();
```
rather than:
```
$self->NEXT::method();
```
The `ACTUAL` tells `NEXT` that there must actually be a next method to call, or it should throw an exception.
`NEXT::ACTUAL` is most commonly used in `AUTOLOAD` methods, as a means to decline an `AUTOLOAD` request, but preserve the normal exception-on-failure semantics:
```
sub AUTOLOAD {
if ($AUTOLOAD =~ /foo|bar/) {
# handle here
}
else { # try elsewhere
shift()->NEXT::ACTUAL::AUTOLOAD(@_);
}
}
```
By using `NEXT::ACTUAL`, if there is no other `AUTOLOAD` to handle the method call, an exception will be thrown (as usually happens in the absence of a suitable `AUTOLOAD`).
###
Avoiding repetitions
If `NEXT` redispatching is used in the methods of a "diamond" class hierarchy:
```
# A B
# / \ /
# C D
# \ /
# E
use NEXT;
package A;
sub foo { print "called A::foo\n"; shift->NEXT::foo() }
package B;
sub foo { print "called B::foo\n"; shift->NEXT::foo() }
package C; @ISA = qw( A );
sub foo { print "called C::foo\n"; shift->NEXT::foo() }
package D; @ISA = qw(A B);
sub foo { print "called D::foo\n"; shift->NEXT::foo() }
package E; @ISA = qw(C D);
sub foo { print "called E::foo\n"; shift->NEXT::foo() }
E->foo();
```
then derived classes may (re-)inherit base-class methods through two or more distinct paths (e.g. in the way `E` inherits `A::foo` twice -- through `C` and `D`). In such cases, a sequence of `NEXT` redispatches will invoke the multiply inherited method as many times as it is inherited. For example, the above code prints:
```
called E::foo
called C::foo
called A::foo
called D::foo
called A::foo
called B::foo
```
(i.e. `A::foo` is called twice).
In some cases this *may* be the desired effect within a diamond hierarchy, but in others (e.g. for destructors) it may be more appropriate to call each method only once during a sequence of redispatches.
To cover such cases, you can redispatch methods via:
```
$self->NEXT::DISTINCT::method();
```
rather than:
```
$self->NEXT::method();
```
This causes the redispatcher to only visit each distinct `method` method once. That is, to skip any classes in the hierarchy that it has already visited during redispatch. So, for example, if the previous example were rewritten:
```
package A;
sub foo { print "called A::foo\n"; shift->NEXT::DISTINCT::foo() }
package B;
sub foo { print "called B::foo\n"; shift->NEXT::DISTINCT::foo() }
package C; @ISA = qw( A );
sub foo { print "called C::foo\n"; shift->NEXT::DISTINCT::foo() }
package D; @ISA = qw(A B);
sub foo { print "called D::foo\n"; shift->NEXT::DISTINCT::foo() }
package E; @ISA = qw(C D);
sub foo { print "called E::foo\n"; shift->NEXT::DISTINCT::foo() }
E->foo();
```
then it would print:
```
called E::foo
called C::foo
called A::foo
called D::foo
called B::foo
```
and omit the second call to `A::foo` (since it would not be distinct from the first call to `A::foo`).
Note that you can also use:
```
$self->NEXT::DISTINCT::ACTUAL::method();
```
or:
```
$self->NEXT::ACTUAL::DISTINCT::method();
```
to get both unique invocation *and* exception-on-failure.
Note that, for historical compatibility, you can also use `NEXT::UNSEEN` instead of `NEXT::DISTINCT`.
###
Invoking all versions of a method with a single call
Yet another pseudo-class that `NEXT` provides is `EVERY`. Its behaviour is considerably simpler than that of the `NEXT` family. A call to:
```
$obj->EVERY::foo();
```
calls *every* method named `foo` that the object in `$obj` has inherited. That is:
```
use NEXT;
package A; @ISA = qw(B D X);
sub foo { print "A::foo " }
package B; @ISA = qw(D X);
sub foo { print "B::foo " }
package X; @ISA = qw(D);
sub foo { print "X::foo " }
package D;
sub foo { print "D::foo " }
package main;
my $obj = bless {}, 'A';
$obj->EVERY::foo(); # prints" A::foo B::foo X::foo D::foo
```
Prefixing a method call with `EVERY::` causes every method in the object's hierarchy with that name to be invoked. As the above example illustrates, they are not called in Perl's usual "left-most-depth-first" order. Instead, they are called "breadth-first-dependency-wise".
That means that the inheritance tree of the object is traversed breadth-first and the resulting order of classes is used as the sequence in which methods are called. However, that sequence is modified by imposing a rule that the appropriate method of a derived class must be called before the same method of any ancestral class. That's why, in the above example, `X::foo` is called before `D::foo`, even though `D` comes before `X` in `@B::ISA`.
In general, there's no need to worry about the order of calls. They will be left-to-right, breadth-first, most-derived-first. This works perfectly for most inherited methods (including destructors), but is inappropriate for some kinds of methods (such as constructors, cloners, debuggers, and initializers) where it's more appropriate that the least-derived methods be called first (as more-derived methods may rely on the behaviour of their "ancestors"). In that case, instead of using the `EVERY` pseudo-class:
```
$obj->EVERY::foo(); # prints" A::foo B::foo X::foo D::foo
```
you can use the `EVERY::LAST` pseudo-class:
```
$obj->EVERY::LAST::foo(); # prints" D::foo X::foo B::foo A::foo
```
which reverses the order of method call.
Whichever version is used, the actual methods are called in the same context (list, scalar, or void) as the original call via `EVERY`, and return:
* A hash of array references in list context. Each entry of the hash has the fully qualified method name as its key and a reference to an array containing the method's list-context return values as its value.
* A reference to a hash of scalar values in scalar context. Each entry of the hash has the fully qualified method name as its key and the method's scalar-context return values as its value.
* Nothing in void context (obviously).
###
Using `EVERY` methods
The typical way to use an `EVERY` call is to wrap it in another base method, that all classes inherit. For example, to ensure that every destructor an object inherits is actually called (as opposed to just the left-most-depth-first-est one):
```
package Base;
sub DESTROY { $_[0]->EVERY::Destroy }
package Derived1;
use base 'Base';
sub Destroy {...}
package Derived2;
use base 'Base', 'Derived1';
sub Destroy {...}
```
et cetera. Every derived class than needs its own clean-up behaviour simply adds its own `Destroy` method (*not* a `DESTROY` method), which the call to `EVERY::LAST::Destroy` in the inherited destructor then correctly picks up.
Likewise, to create a class hierarchy in which every initializer inherited by a new object is invoked:
```
package Base;
sub new {
my ($class, %args) = @_;
my $obj = bless {}, $class;
$obj->EVERY::LAST::Init(\%args);
}
package Derived1;
use base 'Base';
sub Init {
my ($argsref) = @_;
...
}
package Derived2;
use base 'Base', 'Derived1';
sub Init {
my ($argsref) = @_;
...
}
```
et cetera. Every derived class than needs some additional initialization behaviour simply adds its own `Init` method (*not* a `new` method), which the call to `EVERY::LAST::Init` in the inherited constructor then correctly picks up.
SEE ALSO
---------
<mro> (in particular [next::method](https://metacpan.org/pod/mro#next::method)), which has been a core module since Perl 5.9.5.
AUTHOR
------
Damian Conway ([email protected])
BUGS AND IRRITATIONS
---------------------
Because it's a module, not an integral part of the interpreter, `NEXT` has to guess where the surrounding call was found in the method look-up sequence. In the presence of diamond inheritance patterns it occasionally guesses wrong.
It's also too slow (despite caching).
Comment, suggestions, and patches welcome.
COPYRIGHT
---------
```
Copyright (c) 2000-2001, Damian Conway. All Rights Reserved.
This module is free software. It may be used, redistributed
and/or modified under the same terms as Perl itself.
```
perl perlpolicy perlpolicy
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [GOVERNANCE](#GOVERNANCE)
+ [Perl 5 Porters](#Perl-5-Porters)
* [MAINTENANCE AND SUPPORT](#MAINTENANCE-AND-SUPPORT)
* [BACKWARD COMPATIBILITY AND DEPRECATION](#BACKWARD-COMPATIBILITY-AND-DEPRECATION)
+ [Terminology](#Terminology)
* [MAINTENANCE BRANCHES](#MAINTENANCE-BRANCHES)
+ [Getting changes into a maint branch](#Getting-changes-into-a-maint-branch)
* [CONTRIBUTED MODULES](#CONTRIBUTED-MODULES)
+ [A Social Contract about Artistic Control](#A-Social-Contract-about-Artistic-Control)
* [DOCUMENTATION](#DOCUMENTATION)
* [STANDARDS OF CONDUCT](#STANDARDS-OF-CONDUCT)
* [CREDITS](#CREDITS)
NAME
----
perlpolicy - Various and sundry policies and commitments related to the Perl core
DESCRIPTION
-----------
This document is the master document which records all written policies about how the Perl 5 Porters collectively develop and maintain the Perl core.
GOVERNANCE
----------
###
Perl 5 Porters
Subscribers to perl5-porters (the porters themselves) come in several flavours. Some are quiet curious lurkers, who rarely pitch in and instead watch the ongoing development to ensure they're forewarned of new changes or features in Perl. Some are representatives of vendors, who are there to make sure that Perl continues to compile and work on their platforms. Some patch any reported bug that they know how to fix, some are actively patching their pet area (threads, Win32, the regexp -engine), while others seem to do nothing but complain. In other words, it's your usual mix of technical people.
Among these people are the core Perl team. These are trusted volunteers involved in the ongoing development of the Perl language and interpreter. They are not required to be language developers or committers.
Over this group of porters presides Larry Wall. He has the final word in what does and does not change in any of the Perl programming languages. These days, Larry spends most of his time on Raku, while Perl 5 is shepherded by a steering council of porters responsible for deciding what goes into each release and ensuring that releases happen on a regular basis.
Larry sees Perl development along the lines of the US government: there's the Legislature (the porters, represented by the core team), the Executive branch (the steering council), and the Supreme Court (Larry). The legislature can discuss and submit patches to the executive branch all they like, but the executive branch is free to veto them. Rarely, the Supreme Court will side with the executive branch over the legislature, or the legislature over the executive branch. Mostly, however, the legislature and the executive branch are supposed to get along and work out their differences without impeachment or court cases.
You might sometimes see reference to Rule 1 and Rule 2. Larry's power as Supreme Court is expressed in The Rules:
1. Larry is always by definition right about how Perl should behave. This means he has final veto power on the core functionality.
2. Larry is allowed to change his mind about any matter at a later date, regardless of whether he previously invoked Rule 1.
Got that? Larry is always right, even when he was wrong. It's rare to see either Rule exercised, but they are often alluded to.
For the specifics on how the members of the core team and steering council are elected or rotated, consult <perlgov>, which spells it all out in detail.
MAINTENANCE AND SUPPORT
------------------------
Perl 5 is developed by a community, not a corporate entity. Every change contributed to the Perl core is the result of a donation. Typically, these donations are contributions of code or time by individual members of our community. On occasion, these donations come in the form of corporate or organizational sponsorship of a particular individual or project.
As a volunteer organization, the commitments we make are heavily dependent on the goodwill and hard work of individuals who have no obligation to contribute to Perl.
That being said, we value Perl's stability and security and have long had an unwritten covenant with the broader Perl community to support and maintain releases of Perl.
This document codifies the support and maintenance commitments that the Perl community should expect from Perl's developers:
* We "officially" support the two most recent stable release series. 5.30.x and earlier are now out of support. As of the release of 5.36.0, we will "officially" end support for Perl 5.32.x, other than providing security updates as described below.
* To the best of our ability, we will attempt to fix critical issues in the two most recent stable 5.x release series. Fixes for the current release series take precedence over fixes for the previous release series.
* To the best of our ability, we will provide "critical" security patches / releases for any major version of Perl whose 5.x.0 release was within the past three years. We can only commit to providing these for the most recent .y release in any 5.x.y series.
* We will not provide security updates or bug fixes for development releases of Perl.
* We encourage vendors to ship the most recent supported release of Perl at the time of their code freeze.
* As a vendor, you may have a requirement to backport security fixes beyond our 3 year support commitment. We can provide limited support and advice to you as you do so and, where possible will try to apply those patches to the relevant -maint branches in git, though we may or may not choose to make numbered releases or "official" patches available. See ["SECURITY VULNERABILITY CONTACT INFORMATION" in perlsec](perlsec#SECURITY-VULNERABILITY-CONTACT-INFORMATION) for details on how to begin that process.
BACKWARD COMPATIBILITY AND DEPRECATION
---------------------------------------
Our community has a long-held belief that backward-compatibility is a virtue, even when the functionality in question is a design flaw.
We would all love to unmake some mistakes we've made over the past decades. Living with every design error we've ever made can lead to painful stagnation. Unwinding our mistakes is very, very difficult. Doing so without actively harming our users is nearly impossible.
Lately, ignoring or actively opposing compatibility with earlier versions of Perl has come into vogue. Sometimes, a change is proposed which wants to usurp syntax which previously had another meaning. Sometimes, a change wants to improve previously-crazy semantics.
Down this road lies madness.
Requiring end-user programmers to change just a few language constructs, even language constructs which no well-educated developer would ever intentionally use is tantamount to saying "you should not upgrade to a new release of Perl unless you have 100% test coverage and can do a full manual audit of your codebase." If we were to have tools capable of reliably upgrading Perl source code from one version of Perl to another, this concern could be significantly mitigated.
We want to ensure that Perl continues to grow and flourish in the coming years and decades, but not at the expense of our user community.
Existing syntax and semantics should only be marked for destruction in very limited circumstances. If they are believed to be very rarely used, stand in the way of actual improvement to the Perl language or perl interpreter, and if affected code can be easily updated to continue working, they may be considered for removal. When in doubt, caution dictates that we will favor backward compatibility. When a feature is deprecated, a statement of reasoning describing the decision process will be posted, and a link to it will be provided in the relevant perldelta documents.
Using a lexical pragma to enable or disable legacy behavior should be considered when appropriate, and in the absence of any pragma legacy behavior should be enabled. Which backward-incompatible changes are controlled implicitly by a 'use v5.x.y' is a decision which should be made by the steering council in consultation with the community.
Historically, we've held ourselves to a far higher standard than backward-compatibility -- bugward-compatibility. Any accident of implementation or unintentional side-effect of running some bit of code has been considered to be a feature of the language to be defended with the same zeal as any other feature or functionality. No matter how frustrating these unintentional features may be to us as we continue to improve Perl, these unintentional features often deserve our protection. It is very important that existing software written in Perl continue to work correctly. If end-user developers have adopted a bug as a feature, we need to treat it as such.
New syntax and semantics which don't break existing language constructs and syntax have a much lower bar. They merely need to prove themselves to be useful, elegant, well designed, and well tested. In most cases, these additions will be marked as *experimental* for some time. See below for more on that.
### Terminology
To make sure we're talking about the same thing when we discuss the removal of features or functionality from the Perl core, we have specific definitions for a few words and phrases.
experimental If something in the Perl core is marked as **experimental**, we may change its behaviour, deprecate or remove it without notice. While we'll always do our best to smooth the transition path for users of experimental features, you should contact the perl5-porters mailinglist if you find an experimental feature useful and want to help shape its future.
Experimental features must be experimental in two stable releases before being marked non-experimental. Experimental features will only have their experimental status revoked when they no longer have any design-changing bugs open against them and when they have remained unchanged in behavior for the entire length of a development cycle. In other words, a feature present in v5.20.0 may be marked no longer experimental in v5.22.0 if and only if its behavior is unchanged throughout all of v5.21.
deprecated If something in the Perl core is marked as **deprecated**, we may remove it from the core in the future, though we might not. Generally, backward incompatible changes will have deprecation warnings for two release cycles before being removed, but may be removed after just one cycle if the risk seems quite low or the benefits quite high.
As of Perl 5.12, deprecated features and modules warn the user as they're used. When a module is deprecated, it will also be made available on CPAN. Installing it from CPAN will silence deprecation warnings for that module.
If you use a deprecated feature or module and believe that its removal from the Perl core would be a mistake, please contact the perl5-porters mailinglist and plead your case. We don't deprecate things without a good reason, but sometimes there's a counterargument we haven't considered. Historically, we did not distinguish between "deprecated" and "discouraged" features.
discouraged From time to time, we may mark language constructs and features which we consider to have been mistakes as **discouraged**. Discouraged features aren't currently candidates for removal, but we may later deprecate them if they're found to stand in the way of a significant improvement to the Perl core.
removed Once a feature, construct or module has been marked as deprecated, we may remove it from the Perl core. Unsurprisingly, we say we've **removed** these things. When a module is removed, it will no longer ship with Perl, but will continue to be available on CPAN.
MAINTENANCE BRANCHES
---------------------
New releases of maintenance branches should only contain changes that fall into one of the "acceptable" categories set out below, but must not contain any changes that fall into one of the "unacceptable" categories. (For example, a fix for a crashing bug must not be included if it breaks binary compatibility.)
It is not necessary to include every change meeting these criteria, and in general the focus should be on addressing security issues, crashing bugs, regressions and serious installation issues. The temptation to include a plethora of minor changes that don't affect the installation or execution of perl (e.g. spelling corrections in documentation) should be resisted in order to reduce the overall risk of overlooking something. The intention is to create maintenance releases which are both worthwhile and which users can have full confidence in the stability of. (A secondary concern is to avoid burning out the maint-release manager or overwhelming other committers voting on changes to be included (see ["Getting changes into a maint branch"](#Getting-changes-into-a-maint-branch) below).)
The following types of change may be considered acceptable, as long as they do not also fall into any of the "unacceptable" categories set out below:
* Patches that fix CVEs or security issues. These changes should be passed using the security reporting mechanism rather than applied directly; see ["SECURITY VULNERABILITY CONTACT INFORMATION" in perlsec](perlsec#SECURITY-VULNERABILITY-CONTACT-INFORMATION).
* Patches that fix crashing bugs, assertion failures and memory corruption but which do not otherwise change perl's functionality or negatively impact performance.
* Patches that fix regressions in perl's behavior relative to previous releases, no matter how old the regression, since some people may upgrade from very old versions of perl to the latest version.
* Patches that fix bugs in features that were new in the corresponding 5.x.0 stable release.
* Patches that fix anything which prevents or seriously impacts the build or installation of perl.
* Portability fixes, such as changes to Configure and the files in the hints/ folder.
* Minimal patches that fix platform-specific test failures.
* Documentation updates that correct factual errors, explain significant bugs or deficiencies in the current implementation, or fix broken markup.
* Updates to dual-life modules should consist of minimal patches to fix crashing bugs or security issues (as above). Any changes made to dual-life modules for which CPAN is canonical should be coordinated with the upstream author.
The following types of change are NOT acceptable:
* Patches that break binary compatibility. (Please talk to the steering council.)
* Patches that add or remove features.
* Patches that add new warnings or errors or deprecate features.
* Ports of Perl to a new platform, architecture or OS release that involve changes to the implementation.
* New versions of dual-life modules should NOT be imported into maint. Those belong in the next stable series.
If there is any question about whether a given patch might merit inclusion in a maint release, then it almost certainly should not be included.
###
Getting changes into a maint branch
Historically, only the single-person project manager cherry-picked changes from bleadperl into maintperl. This has scaling problems. At the same time, maintenance branches of stable versions of Perl need to be treated with great care. To that end, as of Perl 5.12, we have a new process for maint branches.
Any committer may cherry-pick any commit from blead to a maint branch by first adding an entry to the relevant voting file in the maint-votes branch announcing the commit as a candidate for back-porting, and then waiting for at least two other committers to add their votes in support of this (i.e. a total of at least three votes is required before a commit may be back-ported).
Most of the work involved in both rounding up a suitable set of candidate commits and cherry-picking those for which three votes have been cast will be done by the maint branch release manager, but anyone else is free to add other proposals if they're keen to ensure certain fixes don't get overlooked or fear they already have been.
Other voting mechanisms may also be used instead (e.g. sending mail to perl5-porters and at least two other committers responding to the list giving their assent), as long as the same number of votes is gathered in a transparent manner. Specifically, proposals of which changes to cherry-pick must be visible to everyone on perl5-porters so that the views of everyone interested may be heard.
It is not necessary for voting to be held on cherry-picking perldelta entries associated with changes that have already been cherry-picked, nor for the maint-release manager to obtain votes on changes required by the *Porting/release\_managers\_guide.pod* where such changes can be applied by the means of cherry-picking from blead.
CONTRIBUTED MODULES
--------------------
###
A Social Contract about Artistic Control
What follows is a statement about artistic control, defined as the ability of authors of packages to guide the future of their code and maintain control over their work. It is a recognition that authors should have control over their work, and that it is a responsibility of the rest of the Perl community to ensure that they retain this control. It is an attempt to document the standards to which we, as Perl developers, intend to hold ourselves. It is an attempt to write down rough guidelines about the respect we owe each other as Perl developers.
This statement is not a legal contract. This statement is not a legal document in any way, shape, or form. Perl is distributed under the GNU Public License and under the Artistic License; those are the precise legal terms. This statement isn't about the law or licenses. It's about community, mutual respect, trust, and good-faith cooperation.
We recognize that the Perl core, defined as the software distributed with the heart of Perl itself, is a joint project on the part of all of us. From time to time, a script, module, or set of modules (hereafter referred to simply as a "module") will prove so widely useful and/or so integral to the correct functioning of Perl itself that it should be distributed with the Perl core. This should never be done without the author's explicit consent, and a clear recognition on all parts that this means the module is being distributed under the same terms as Perl itself. A module author should realize that inclusion of a module into the Perl core will necessarily mean some loss of control over it, since changes may occasionally have to be made on short notice or for consistency with the rest of Perl.
Once a module has been included in the Perl core, however, everyone involved in maintaining Perl should be aware that the module is still the property of the original author unless the original author explicitly gives up their ownership of it. In particular:
* The version of the module in the Perl core should still be considered the work of the original author. All patches, bug reports, and so forth should be fed back to them. Their development directions should be respected whenever possible.
* Patches may be applied by the steering council without the explicit cooperation of the module author if and only if they are very minor, time-critical in some fashion (such as urgent security fixes), or if the module author cannot be reached. Those patches must still be given back to the author when possible, and if the author decides on an alternate fix in their version, that fix should be strongly preferred unless there is a serious problem with it. Any changes not endorsed by the author should be marked as such, and the contributor of the change acknowledged.
* The version of the module distributed with Perl should, whenever possible, be the latest version of the module as distributed by the author (the latest non-beta version in the case of public Perl releases), although the steering council may hold off on upgrading the version of the module distributed with Perl to the latest version until the latest version has had sufficient testing.
In other words, the author of a module should be considered to have final say on modifications to their module whenever possible (bearing in mind that it's expected that everyone involved will work together and arrive at reasonable compromises when there are disagreements).
As a last resort, however:
If the author's vision of the future of their module is sufficiently different from the vision of the steering council and perl5-porters as a whole so as to cause serious problems for Perl, the steering council may choose to formally fork the version of the module in the Perl core from the one maintained by the author. This should not be done lightly and should **always** if at all possible be done only after direct input from Larry. If this is done, it must then be made explicit in the module as distributed with the Perl core that it is a forked version and that while it is based on the original author's work, it is no longer maintained by them. This must be noted in both the documentation and in the comments in the source of the module.
Again, this should be a last resort only. Ideally, this should never happen, and every possible effort at cooperation and compromise should be made before doing this. If it does prove necessary to fork a module for the overall health of Perl, proper credit must be given to the original author in perpetuity and the decision should be constantly re-evaluated to see if a remerging of the two branches is possible down the road.
In all dealings with contributed modules, everyone maintaining Perl should keep in mind that the code belongs to the original author, that they may not be on perl5-porters at any given time, and that a patch is not official unless it has been integrated into the author's copy of the module. To aid with this, and with points #1, #2, and #3 above, contact information for the authors of all contributed modules should be kept with the Perl distribution.
Finally, the Perl community as a whole recognizes that respect for ownership of code, respect for artistic control, proper credit, and active effort to prevent unintentional code skew or communication gaps is vital to the health of the community and Perl itself. Members of a community should not normally have to resort to rules and laws to deal with each other, and this document, although it contains rules so as to be clear, is about an attitude and general approach. The first step in any dispute should be open communication, respect for opposing views, and an attempt at a compromise. In nearly every circumstance nothing more will be necessary, and certainly no more drastic measure should be used until every avenue of communication and discussion has failed.
DOCUMENTATION
-------------
Perl's documentation is an important resource for our users. It's incredibly important for Perl's documentation to be reasonably coherent and to accurately reflect the current implementation.
Just as P5P collectively maintains the codebase, we collectively maintain the documentation. Writing a particular bit of documentation doesn't give an author control of the future of that documentation. At the same time, just as source code changes should match the style of their surrounding blocks, so should documentation changes.
Examples in documentation should be illustrative of the concept they're explaining. Sometimes, the best way to show how a language feature works is with a small program the reader can run without modification. More often, examples will consist of a snippet of code containing only the "important" bits. The definition of "important" varies from snippet to snippet. Sometimes it's important to declare `use strict` and `use warnings`, initialize all variables and fully catch every error condition. More often than not, though, those things obscure the lesson the example was intended to teach.
As Perl is developed by a global team of volunteers, our documentation often contains spellings which look funny to *somebody*. Choice of American/British/Other spellings is left as an exercise for the author of each bit of documentation. When patching documentation, try to emulate the documentation around you, rather than changing the existing prose.
In general, documentation should describe what Perl does "now" rather than what it used to do. It's perfectly reasonable to include notes in documentation about how behaviour has changed from previous releases, but, with very few exceptions, documentation isn't "dual-life" -- it doesn't need to fully describe how all old versions used to work.
STANDARDS OF CONDUCT
---------------------
The official forum for the development of perl is the perl5-porters mailing list, mentioned above, and its bugtracker at GitHub. Posting to the list and the bugtracker is not a right: all participants in discussion are expected to adhere to a standard of conduct.
* Always be civil.
* Heed the moderators.
Civility is simple: stick to the facts while avoiding demeaning remarks, belittling other individuals, sarcasm, or a presumption of bad faith. It is not enough to be factual. You must also be civil. Responding in kind to incivility is not acceptable. If you relay otherwise-unposted comments to the list from a third party, you take responsibility for the content of those comments, and you must therefore ensure that they are civil.
While civility is required, kindness is encouraged; if you have any doubt about whether you are being civil, simply ask yourself, "Am I being kind?" and aspire to that.
If the list moderators tell you that you are not being civil, carefully consider how your words have appeared before responding in any way. Were they kind? You may protest, but repeated protest in the face of a repeatedly reaffirmed decision is not acceptable. Repeatedly protesting about the moderators' decisions regarding a third party is also unacceptable, as is continuing to initiate off-list contact with the moderators about their decisions.
Unacceptable behavior will result in a public and clearly identified warning. A second instance of unacceptable behavior from the same individual will result in removal from the mailing list and GitHub issue tracker, for a period of one calendar month. The rationale for this is to provide an opportunity for the person to change the way they act.
After the time-limited ban has been lifted, a third instance of unacceptable behavior will result in a further public warning. A fourth or subsequent instance will result in an indefinite ban. The rationale is that, in the face of an apparent refusal to change behavior, we must protect other community members from future unacceptable actions. The moderators may choose to lift an indefinite ban if the person in question affirms they will not transgress again.
Removals, like warnings, are public.
The list of moderators will be public knowledge. At present, it is: Karen Etheridge, Neil Bowers, Nicholas Clark, Ricardo Signes, Todd Rinaldo.
CREDITS
-------
"Social Contract about Contributed Modules" originally by Russ Allbery <[email protected]> and the perl5-porters.
| programming_docs |
perl Tie::Hash::NamedCapture Tie::Hash::NamedCapture
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Tie::Hash::NamedCapture - Named regexp capture buffers
SYNOPSIS
--------
```
tie my %hash, "Tie::Hash::NamedCapture";
# %hash now behaves like %+
tie my %hash, "Tie::Hash::NamedCapture", all => 1;
# %hash now access buffers from regexp in $qr like %-
```
DESCRIPTION
-----------
This module is used to implement the special hashes `%+` and `%-`, but it can be used to tie other variables as you choose.
When the `all` parameter is provided, then the tied hash elements will be array refs listing the contents of each capture buffer whose name is the same as the associated hash key. If none of these buffers were involved in the match, the contents of that array ref will be as many `undef` values as there are capture buffers with that name. In other words, the tied hash will behave as `%-`.
When the `all` parameter is omitted or false, then the tied hash elements will be the contents of the leftmost defined buffer with the name of the associated hash key. In other words, the tied hash will behave as `%+`.
The keys of `%-`-like hashes correspond to all buffer names found in the regular expression; the keys of `%+`-like hashes list only the names of buffers that have captured (and that are thus associated to defined values).
This implementation has been moved into the core executable, but you can still load this module for backward compatibility.
SEE ALSO
---------
<perlreapi>, <re>, ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules), ["%+" in perlvar](perlvar#%25%2B), ["%-" in perlvar](perlvar#%25-).
perl Encode::Symbol Encode::Symbol
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Symbol - Symbol Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$symbol = encode("symbol", $utf8); # loads Encode::Symbol implicitly
$utf8 = decode("", $symbol); # ditto
```
ABSTRACT
--------
This module implements symbol and dingbats encodings. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
symbol
dingbats
AdobeZDingbat
AdobeSymbol
MacDingbats
```
DESCRIPTION
-----------
To find out how to use this module in detail, see [Encode](encode).
SEE ALSO
---------
[Encode](encode)
perl libnetcfg libnetcfg
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
libnetcfg - configure libnet
DESCRIPTION
-----------
The libnetcfg utility can be used to configure the libnet. Starting from perl 5.8 libnet is part of the standard Perl distribution, but the libnetcfg can be used for any libnet installation.
USAGE
-----
Without arguments libnetcfg displays the current configuration.
```
$ libnetcfg
# old config ./libnet.cfg
daytime_hosts ntp1.none.such
ftp_int_passive 0
ftp_testhost ftp.funet.fi
inet_domain none.such
nntp_hosts nntp.none.such
ph_hosts
pop3_hosts pop.none.such
smtp_hosts smtp.none.such
snpp_hosts
test_exist 1
test_hosts 1
time_hosts ntp.none.such
# libnetcfg -h for help
$
```
It tells where the old configuration file was found (if found).
The `-h` option will show a usage message.
To change the configuration you will need to use either the `-c` or the `-d` options.
The default name of the old configuration file is by default "libnet.cfg", unless otherwise specified using the -i option, `-i oldfile`, and it is searched first from the current directory, and then from your module path.
The default name of the new configuration file is "libnet.cfg", and by default it is written to the current directory, unless otherwise specified using the -o option, `-o newfile`.
SEE ALSO
---------
<Net::Config>, [libnetFAQ](libnetfaq)
AUTHORS
-------
Graham Barr, the original Configure script of libnet.
Jarkko Hietaniemi, conversion into libnetcfg for inclusion into Perl 5.8.
perl ExtUtils::MM_UWIN ExtUtils::MM\_UWIN
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overridden methods](#Overridden-methods)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MM\_UWIN - U/WIN 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 the AT&T U/WIN UNIX on Windows environment.
Unless otherwise stated it works just like ExtUtils::MM\_Unix.
###
Overridden methods
os\_flavor In addition to being Unix, we're U/WIN.
**replace\_manpage\_separator** AUTHOR
------
Michael G Schwern <[email protected]> with code from ExtUtils::MM\_Unix
SEE ALSO
---------
<ExtUtils::MM_Win32>, <ExtUtils::MakeMaker>
perl autodie::hints autodie::hints
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Introduction](#Introduction)
+ [What are hints?](#What-are-hints?)
+ [Example hints](#Example-hints)
* [Manually setting hints from within your program](#Manually-setting-hints-from-within-your-program)
* [Adding hints to your module](#Adding-hints-to-your-module)
* [Insisting on hints](#Insisting-on-hints)
* [Diagnostics](#Diagnostics)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
autodie::hints - Provide hints about user subroutines to autodie
SYNOPSIS
--------
```
package Your::Module;
our %DOES = ( 'autodie::hints::provider' => 1 );
sub AUTODIE_HINTS {
return {
foo => { scalar => HINTS, list => SOME_HINTS },
bar => { scalar => HINTS, list => MORE_HINTS },
}
}
# Later, in your main program...
use Your::Module qw(foo bar);
use autodie qw(:default foo bar);
foo(); # succeeds or dies based on scalar hints
# Alternatively, hints can be set on subroutines we've
# imported.
use autodie::hints;
use Some::Module qw(think_positive);
BEGIN {
autodie::hints->set_hints_for(
\&think_positive,
{
fail => sub { $_[0] <= 0 }
}
)
}
use autodie qw(think_positive);
think_positive(...); # Returns positive or dies.
```
DESCRIPTION
-----------
### Introduction
The <autodie> pragma is very smart when it comes to working with Perl's built-in functions. The behaviour for these functions are fixed, and `autodie` knows exactly how they try to signal failure.
But what about user-defined subroutines from modules? If you use `autodie` on a user-defined subroutine then it assumes the following behaviour to demonstrate failure:
* A false value, in scalar context
* An empty list, in list context
* A list containing a single undef, in list context
All other return values (including the list of the single zero, and the list containing a single empty string) are considered successful. However, real-world code isn't always that easy. Perhaps the code you're working with returns a string containing the word "FAIL" upon failure, or a two element list containing `(undef, "human error message")`. To make autodie work with these sorts of subroutines, we have the *hinting interface*.
The hinting interface allows *hints* to be provided to `autodie` on how it should detect failure from user-defined subroutines. While these *can* be provided by the end-user of `autodie`, they are ideally written into the module itself, or into a helper module or sub-class of `autodie` itself.
###
What are hints?
A *hint* is a subroutine or value that is checked against the return value of an autodying subroutine. If the match returns true, `autodie` considers the subroutine to have failed.
If the hint provided is a subroutine, then `autodie` will pass the complete return value to that subroutine. If the hint is any other value, then `autodie` will smart-match against the value provided. In Perl 5.8.x there is no smart-match operator, and as such only subroutine hints are supported in these versions.
Hints can be provided for both scalar and list contexts. Note that an autodying subroutine will never see a void context, as `autodie` always needs to capture the return value for examination. Autodying subroutines called in void context act as if they're called in a scalar context, but their return value is discarded after it has been checked.
###
Example hints
Hints may consist of subroutine references, objects overloading smart-match, regular expressions, and depending on Perl version possibly other things. You can specify different hints for how failure should be identified in scalar and list contexts.
These examples apply for use in the `AUTODIE_HINTS` subroutine and when calling `autodie::hints->set_hints_for()`.
The most common context-specific hints are:
```
# Scalar failures always return undef:
{ scalar => sub { !defined($_[0]) } }
# Scalar failures return any false value [default expectation]:
{ scalar => sub { ! $_[0] } }
# Scalar failures always return zero explicitly:
{ scalar => sub { defined($_[0]) && $_[0] eq '0' } }
# List failures always return an empty list:
{ list => sub { !@_ } }
# List failures return () or (undef) [default expectation]:
{ list => sub { ! @_ || @_ == 1 && !defined $_[0] } }
# List failures return () or a single false value:
{ list => sub { ! @_ || @_ == 1 && !$_[0] } }
# List failures return (undef, "some string")
{ list => sub { @_ == 2 && !defined $_[0] } }
# Unsuccessful foo() returns 'FAIL' or '_FAIL' in scalar context,
# returns (-1) in list context...
autodie::hints->set_hints_for(
\&foo,
{
scalar => qr/^ _? FAIL $/xms,
list => sub { @_ == 1 && $_[0] eq -1 },
}
);
# Unsuccessful foo() returns 0 in all contexts...
autodie::hints->set_hints_for(
\&foo,
{
scalar => sub { defined($_[0]) && $_[0] == 0 },
list => sub { @_ == 1 && defined($_[0]) && $_[0] == 0 },
}
);
```
This "in all contexts" construction is very common, and can be abbreviated, using the 'fail' key. This sets both the `scalar` and `list` hints to the same value:
```
# Unsuccessful foo() returns 0 in all contexts...
autodie::hints->set_hints_for(
\&foo,
{
fail => sub { @_ == 1 and defined $_[0] and $_[0] == 0 }
}
);
# Unsuccessful think_positive() returns negative number on failure...
autodie::hints->set_hints_for(
\&think_positive,
{
fail => sub { $_[0] < 0 }
}
);
# Unsuccessful my_system() returns non-zero on failure...
autodie::hints->set_hints_for(
\&my_system,
{
fail => sub { $_[0] != 0 }
}
);
```
Manually setting hints from within your program
------------------------------------------------
If you are using a module which returns something special on failure, then you can manually create hints for each of the desired subroutines. Once the hints are specified, they are available for all files and modules loaded thereafter, thus you can move this work into a module and it will still work.
```
use Some::Module qw(foo bar);
use autodie::hints;
autodie::hints->set_hints_for(
\&foo,
{
scalar => SCALAR_HINT,
list => LIST_HINT,
}
);
autodie::hints->set_hints_for(
\&bar,
{ fail => SOME_HINT, }
);
```
It is possible to pass either a subroutine reference (recommended) or a fully qualified subroutine name as the first argument. This means you can set hints on modules that *might* get loaded:
```
use autodie::hints;
autodie::hints->set_hints_for(
'Some::Module:bar', { fail => SCALAR_HINT, }
);
```
This technique is most useful when you have a project that uses a lot of third-party modules. You can define all your possible hints in one-place. This can even be in a sub-class of autodie. For example:
```
package my::autodie;
use parent qw(autodie);
use autodie::hints;
autodie::hints->set_hints_for(...);
1;
```
You can now `use my::autodie`, which will work just like the standard `autodie`, but is now aware of any hints that you've set.
Adding hints to your module
----------------------------
`autodie` provides a passive interface to allow you to declare hints for your module. These hints will be found and used by `autodie` if it is loaded, but otherwise have no effect (or dependencies) without autodie. To set these, your module needs to declare that it *does* the `autodie::hints::provider` role. This can be done by writing your own `DOES` method, using a system such as `Class::DOES` to handle the heavy-lifting for you, or declaring a `%DOES` package variable with a `autodie::hints::provider` key and a corresponding true value.
Note that checking for a `%DOES` hash is an `autodie`-only short-cut. Other modules do not use this mechanism for checking roles, although you can use the `Class::DOES` module from the CPAN to allow it.
In addition, you must define a `AUTODIE_HINTS` subroutine that returns a hash-reference containing the hints for your subroutines:
```
package Your::Module;
# We can use the Class::DOES from the CPAN to declare adherence
# to a role.
use Class::DOES 'autodie::hints::provider' => 1;
# Alternatively, we can declare the role in %DOES. Note that
# this is an autodie specific optimisation, although Class::DOES
# can be used to promote this to a true role declaration.
our %DOES = ( 'autodie::hints::provider' => 1 );
# Finally, we must define the hints themselves.
sub AUTODIE_HINTS {
return {
foo => { scalar => HINTS, list => SOME_HINTS },
bar => { scalar => HINTS, list => MORE_HINTS },
baz => { fail => HINTS },
}
}
```
This allows your code to set hints without relying on `autodie` and `autodie::hints` being loaded, or even installed. In this way your code can do the right thing when `autodie` is installed, but does not need to depend upon it to function.
Insisting on hints
-------------------
When a user-defined subroutine is wrapped by `autodie`, it will use hints if they are available, and otherwise reverts to the *default behaviour* described in the introduction of this document. This can be problematic if we expect a hint to exist, but (for whatever reason) it has not been loaded.
We can ask autodie to *insist* that a hint be used by prefixing an exclamation mark to the start of the subroutine name. A lone exclamation mark indicates that *all* subroutines after it must have hints declared.
```
# foo() and bar() must have their hints defined
use autodie qw( !foo !bar baz );
# Everything must have hints (recommended).
use autodie qw( ! foo bar baz );
# bar() and baz() must have their hints defined
use autodie qw( foo ! bar baz );
# Enable autodie for all of Perl's supported built-ins,
# as well as for foo(), bar() and baz(). Everything must
# have hints.
use autodie qw( ! :all foo bar baz );
```
If hints are not available for the specified subroutines, this will cause a compile-time error. Insisting on hints for Perl's built-in functions (eg, `open` and `close`) is always successful.
Insisting on hints is *strongly* recommended.
Diagnostics
-----------
Attempts to set\_hints\_for unidentifiable subroutine You've called `autodie::hints->set_hints_for()` using a subroutine reference, but that reference could not be resolved back to a subroutine name. It may be an anonymous subroutine (which can't be made autodying), or may lack a name for other reasons.
If you receive this error with a subroutine that has a real name, then you may have found a bug in autodie. See ["BUGS" in autodie](autodie#BUGS) for how to report this.
fail hints cannot be provided with either scalar or list hints for %s When defining hints, you can either supply both `list` and `scalar` keywords, *or* you can provide a single `fail` keyword. You can't mix and match them.
%s hint missing for %s You've provided either a `scalar` hint without supplying a `list` hint, or vice-versa. You *must* supply both `scalar` and `list` hints, *or* a single `fail` hint.
ACKNOWLEDGEMENTS
----------------
* Dr Damian Conway for suggesting the hinting interface and providing the example usage.
* Jacinta Richardson for translating much of my ideas into this documentation.
AUTHOR
------
Copyright 2009, Paul Fenwick <[email protected]>
LICENSE
-------
This module is free software. You may distribute it under the same terms as Perl itself.
SEE ALSO
---------
<autodie>, <Class::DOES>
perl Unicode::Collate Unicode::Collate
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Constructor and Tailoring](#Constructor-and-Tailoring)
+ [Methods for Collation](#Methods-for-Collation)
+ [Methods for Searching](#Methods-for-Searching)
+ [Other Methods](#Other-Methods)
* [EXPORT](#EXPORT)
* [INSTALL](#INSTALL)
* [CAVEATS](#CAVEATS)
* [AUTHOR, COPYRIGHT AND LICENSE](#AUTHOR,-COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate - Unicode Collation Algorithm
SYNOPSIS
--------
```
use Unicode::Collate;
#construct
$Collator = Unicode::Collate->new(%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` or should decode them before.
DESCRIPTION
-----------
This module is an implementation of Unicode Technical Standard #10 (a.k.a. UTS #10) - Unicode Collation Algorithm (a.k.a. UCA).
###
Constructor and Tailoring
The `new` method returns a collator object. If new() is called with no parameters, the collator should do the default collation.
```
$Collator = Unicode::Collate->new(
UCA_Version => $UCA_Version,
alternate => $alternate, # alias for 'variable'
backwards => $levelNumber, # or \@levelNumbers
entry => $element,
hangul_terminator => $term_primary_weight,
highestFFFF => $bool,
identical => $bool,
ignoreName => qr/$ignoreName/,
ignoreChar => qr/$ignoreChar/,
ignore_level2 => $bool,
katakana_before_hiragana => $bool,
level => $collationLevel,
long_contraction => $bool,
minimalFFFE => $bool,
normalization => $normalization_form,
overrideCJK => \&overrideCJK,
overrideHangul => \&overrideHangul,
preprocess => \&preprocess,
rearrange => \@charList,
rewrite => \&rewrite,
suppress => \@charList,
table => $filename,
undefName => qr/$undefName/,
undefChar => qr/$undefChar/,
upper_before_lower => $bool,
variable => $variable,
);
```
UCA\_Version If the revision (previously "tracking version") number of UCA is given, behavior of that revision is emulated on collating. If omitted, the return value of `UCA_Version()` is used.
The following revisions are supported. The default is 43.
```
UCA Unicode Standard DUCET (@version)
-------------------------------------------------------
8 3.1 3.0.1 (3.0.1d9)
9 3.1 with Corrigendum 3 3.1.1
11 4.0.0
14 4.1.0
16 5.0.0
18 5.1.0
20 5.2.0
22 6.0.0
24 6.1.0
26 6.2.0
28 6.3.0
30 7.0.0
32 8.0.0
34 9.0.0
36 10.0.0
38 11.0.0
40 12.0.0
41 12.1.0
43 13.0.0
```
\* See below for `long_contraction` with `UCA_Version` 22 and 24.
\* Noncharacters (e.g. U+FFFF) are not ignored, and can be overridden since `UCA_Version` 22.
\* Out-of-range codepoints (greater than U+10FFFF) are not ignored, and can be overridden since `UCA_Version` 22.
\* Fully ignorable characters were ignored, and would not interrupt contractions with `UCA_Version` 9 and 11.
\* Treatment of ignorables after variables and some behaviors were changed at `UCA_Version` 9.
\* Characters regarded as CJK unified ideographs (cf. `overrideCJK`) depend on `UCA_Version`.
\* Many hangul jamo are assigned at `UCA_Version` 20, that will affect `hangul_terminator`.
alternate -- see 3.2.2 Alternate Weighting, version 8 of UTS #10
For backward compatibility, `alternate` (old name) can be used as an alias for `variable`.
backwards -- see 3.4 Backward Accents, UTS #10.
```
backwards => $levelNumber or \@levelNumbers
```
Weights in reverse order; ex. level 2 (diacritic ordering) in French. If omitted (or `$levelNumber` is `undef` or `\@levelNumbers` is `[]`), forwards at all the levels.
entry -- see 5 Tailoring; 9.1 Allkeys File Format, UTS #10.
If the same character (or a sequence of characters) exists in the collation element table through `table`, mapping to collation elements is overridden. If it does not exist, the mapping is defined additionally.
```
entry => <<'ENTRY', # for DUCET v4.0.0 (allkeys-4.0.0.txt)
0063 0068 ; [.0E6A.0020.0002.0063] # ch
0043 0068 ; [.0E6A.0020.0007.0043] # Ch
0043 0048 ; [.0E6A.0020.0008.0043] # CH
006C 006C ; [.0F4C.0020.0002.006C] # ll
004C 006C ; [.0F4C.0020.0007.004C] # Ll
004C 004C ; [.0F4C.0020.0008.004C] # LL
00F1 ; [.0F7B.0020.0002.00F1] # n-tilde
006E 0303 ; [.0F7B.0020.0002.00F1] # n-tilde
00D1 ; [.0F7B.0020.0008.00D1] # N-tilde
004E 0303 ; [.0F7B.0020.0008.00D1] # N-tilde
ENTRY
entry => <<'ENTRY', # for DUCET v4.0.0 (allkeys-4.0.0.txt)
00E6 ; [.0E33.0020.0002.00E6][.0E8B.0020.0002.00E6] # ae ligature as <a><e>
00C6 ; [.0E33.0020.0008.00C6][.0E8B.0020.0008.00C6] # AE ligature as <A><E>
ENTRY
```
**NOTE:** The code point in the UCA file format (before `';'`) **must** be a Unicode code point (defined as hexadecimal), but not a native code point. So `0063` must always denote `U+0063`, but not a character of `"\x63"`.
Weighting may vary depending on collation element table. So ensure the weights defined in `entry` will be consistent with those in the collation element table loaded via `table`.
In DUCET v4.0.0, primary weight of `C` is `0E60` and that of `D` is `0E6D`. So setting primary weight of `CH` to `0E6A` (as a value between `0E60` and `0E6D`) makes ordering as `C < CH < D`. Exactly speaking DUCET already has some characters between `C` and `D`: `small capital C` (`U+1D04`) with primary weight `0E64`, `c-hook/C-hook` (`U+0188/U+0187`) with `0E65`, and `c-curl` (`U+0255`) with `0E69`. Then primary weight `0E6A` for `CH` makes `CH` ordered between `c-curl` and `D`.
hangul\_terminator -- see 7.1.4 Trailing Weights, UTS #10.
If a true value is given (non-zero but should be positive), it will be added as a terminator primary weight to the end of every standard Hangul syllable. Secondary and any higher weights for terminator are set to zero. If the value is false or `hangul_terminator` key does not exist, insertion of terminator weights will not be performed.
Boundaries of Hangul syllables are determined according to conjoining Jamo behavior in *the Unicode Standard* and *HangulSyllableType.txt*.
**Implementation Note:** (1) For expansion mapping (Unicode character mapped to a sequence of collation elements), a terminator will not be added between collation elements, even if Hangul syllable boundary exists there. Addition of terminator is restricted to the next position to the last collation element.
(2) Non-conjoining Hangul letters (Compatibility Jamo, halfwidth Jamo, and enclosed letters) are not automatically terminated with a terminator primary weight. These characters may need terminator included in a collation element table beforehand.
highestFFFF -- see 2.4 Tailored noncharacter weights, UTS #35 (LDML) Part 5: Collation.
If the parameter is made true, `U+FFFF` has a highest primary weight. When a boolean of `$coll->ge($str, "abc")` and `$coll->le($str, "abc\x{FFFF}")` is true, it is expected that `$str` begins with `"abc"`, or another primary equivalent. `$str` may be `"abcd"`, `"abc012"`, but should not include `U+FFFF` such as `"abc\x{FFFF}xyz"`.
`$coll->le($str, "abc\x{FFFF}")` works like `$coll->lt($str, "abd")` almost, but the latter has a problem that you should know which letter is next to `c`. For a certain language where `ch` as the next letter, `"abch"` is greater than `"abc\x{FFFF}"`, but less than `"abd"`.
Note: This is equivalent to `(entry => 'FFFF ; [.FFFE.0020.0005.FFFF]')`. Any other character than `U+FFFF` can be tailored by `entry`.
identical -- see A.3 Deterministic Comparison, UTS #10.
By default, strings whose weights are equal should be equal, even though their code points are not equal. Completely ignorable characters are ignored.
If the parameter is made true, a final, tie-breaking level is used. If no difference of weights is found after the comparison through all the level specified by `level`, the comparison with code points will be performed. For the tie-breaking comparison, the sort key has code points of the original string appended. Completely ignorable characters are not ignored.
If `preprocess` and/or `normalization` is applied, the code points of the string after them (in NFD by default) are used.
ignoreChar ignoreName -- see 3.6 Variable Weighting, UTS #10.
Makes the entry in the table completely ignorable; i.e. as if the weights were zero at all level.
Through `ignoreChar`, any character matching `qr/$ignoreChar/` will be ignored. Through `ignoreName`, any character whose name (given in the `table` file as a comment) matches `qr/$ignoreName/` will be ignored.
E.g. when 'a' and 'e' are ignorable, 'element' is equal to 'lament' (or 'lmnt').
ignore\_level2 -- see 5.1 Parametric Tailoring, UTS #10.
By default, case-sensitive comparison (that is level 3 difference) won't ignore accents (that is level 2 difference).
If the parameter is made true, accents (and other primary ignorable characters) are ignored, even though cases are taken into account.
**NOTE**: `level` should be 3 or greater.
katakana\_before\_hiragana -- see 7.2 Tertiary Weight Table, UTS #10.
By default, hiragana is before katakana. If the parameter is made true, this is reversed.
**NOTE**: This parameter simplemindedly assumes that any hiragana/katakana distinctions must occur in level 3, and their weights at level 3 must be same as those mentioned in 7.3.1, UTS #10. If you define your collation elements which violate this requirement, this parameter does not work validly.
level -- see 4.3 Form Sort Key, UTS #10.
Set the maximum level. Any higher levels than the specified one are ignored.
```
Level 1: alphabetic ordering
Level 2: diacritic ordering
Level 3: case ordering
Level 4: tie-breaking (e.g. in the case when variable is 'shifted')
ex.level => 2,
```
If omitted, the maximum is the 4th.
**NOTE:** The DUCET includes weights over 0xFFFF at the 4th level. But this module only uses weights within 0xFFFF. When `variable` is 'blanked' or 'non-ignorable' (other than 'shifted' and 'shift-trimmed'), the level 4 may be unreliable.
See also `identical`.
long\_contraction -- see 3.8.2 Well-Formedness of the DUCET, 4.2 Produce Array, UTS #10.
If the parameter is made true, for a contraction with three or more characters (here nicknamed "long contraction"), initial substrings will be handled. For example, a contraction ABC, where A is a starter, and B and C are non-starters (character with non-zero combining character class), will be detected even if there is not AB as a contraction.
**Default:** Usually false. If `UCA_Version` is 22 or 24, and the value of `long_contraction` is not specified in `new()`, a true value is set implicitly. This is a workaround to pass Conformance Tests for Unicode 6.0.0 and 6.1.0.
`change()` handles `long_contraction` explicitly only. If `long_contraction` is not specified in `change()`, even though `UCA_Version` is changed, `long_contraction` will not be changed.
**Limitation:** Scanning non-starters is one-way (no back tracking). If AB is found but not ABC is not found, other long contraction where the first character is A and the second is not B may not be found.
Under `(normalization => undef)`, detection step of discontiguous contractions will be skipped.
**Note:** The following contractions in DUCET are not considered in steps S2.1.1 to S2.1.3, where they are discontiguous.
```
0FB2 0F71 0F80 (TIBETAN VOWEL SIGN VOCALIC RR)
0FB3 0F71 0F80 (TIBETAN VOWEL SIGN VOCALIC LL)
```
For example `TIBETAN VOWEL SIGN VOCALIC RR` with `COMBINING TILDE OVERLAY` (`U+0344`) is `0FB2 0344 0F71 0F80` in NFD. In this case `0FB2 0F80` (`TIBETAN VOWEL SIGN VOCALIC R`) is detected, instead of `0FB2 0F71 0F80`. Inserted `0344` makes `0FB2 0F71 0F80` discontiguous and lack of contraction `0FB2 0F71` prohibits `0FB2 0F71 0F80` from being detected.
minimalFFFE -- see 1.1.1 U+FFFE, UTS #35 (LDML) Part 5: Collation.
If the parameter is made true, `U+FFFE` has a minimal primary weight. The comparison between `"$a1\x{FFFE}$a2"` and `"$b1\x{FFFE}$b2"` first compares `$a1` and `$b1` at level 1, and then `$a2` and `$b2` at level 1, as followed.
```
"ab\x{FFFE}a"
"Ab\x{FFFE}a"
"ab\x{FFFE}c"
"Ab\x{FFFE}c"
"ab\x{FFFE}xyz"
"abc\x{FFFE}def"
"abc\x{FFFE}xYz"
"aBc\x{FFFE}xyz"
"abcX\x{FFFE}def"
"abcx\x{FFFE}xyz"
"b\x{FFFE}aaa"
"bbb\x{FFFE}a"
```
Note: This is equivalent to `(entry => 'FFFE ; [.0001.0020.0005.FFFE]')`. Any other character than `U+FFFE` can be tailored by `entry`.
normalization -- see 4.1 Normalize, UTS #10.
If specified, strings are normalized before preparation of sort keys (the normalization is executed after preprocess).
A form name `Unicode::Normalize::normalize()` accepts will be applied as `$normalization_form`. Acceptable names include `'NFD'`, `'NFC'`, `'NFKD'`, and `'NFKC'`. See `Unicode::Normalize::normalize()` for detail. If omitted, `'NFD'` is used.
`normalization` is performed after `preprocess` (if defined).
Furthermore, special values, `undef` and `"prenormalized"`, can be used, though they are not concerned with `Unicode::Normalize::normalize()`.
If `undef` (not a string `"undef"`) is passed explicitly as the value for this key, any normalization is not carried out (this may make tailoring easier if any normalization is not desired). Under `(normalization => undef)`, only contiguous contractions are resolved; e.g. even if `A-ring` (and `A-ring-cedilla`) is ordered after `Z`, `A-cedilla-ring` would be primary equal to `A`. In this point, `(normalization => undef, preprocess => sub { NFD(shift) })` **is not** equivalent to `(normalization => 'NFD')`.
In the case of `(normalization => "prenormalized")`, any normalization is not performed, but discontiguous contractions with combining characters are performed. Therefore `(normalization => 'prenormalized', preprocess => sub { NFD(shift) })` **is** equivalent to `(normalization => 'NFD')`. If source strings are finely prenormalized, `(normalization => 'prenormalized')` may save time for normalization.
Except `(normalization => undef)`, **Unicode::Normalize** is required (see also **CAVEAT**).
overrideCJK -- see 7.1 Derived Collation Elements, UTS #10.
By default, CJK unified ideographs are ordered in Unicode codepoint order, but those in the CJK Unified Ideographs block are less than those in the CJK Unified Ideographs Extension A etc.
```
In the CJK Unified Ideographs block:
U+4E00..U+9FA5 if UCA_Version is 8, 9 or 11.
U+4E00..U+9FBB if UCA_Version is 14 or 16.
U+4E00..U+9FC3 if UCA_Version is 18.
U+4E00..U+9FCB if UCA_Version is 20 or 22.
U+4E00..U+9FCC if UCA_Version is 24 to 30.
U+4E00..U+9FD5 if UCA_Version is 32 or 34.
U+4E00..U+9FEA if UCA_Version is 36.
U+4E00..U+9FEF if UCA_Version is 38, 40 or 41.
U+4E00..U+9FFC if UCA_Version is 43.
In the CJK Unified Ideographs Extension blocks:
Ext.A (U+3400..U+4DB5) if UCA_Version is 8 to 41.
Ext.A (U+3400..U+4DBF) if UCA_Version is 43.
Ext.B (U+20000..U+2A6D6) if UCA_Version is 8 to 41.
Ext.B (U+20000..U+2A6DD) if UCA_Version is 43.
Ext.C (U+2A700..U+2B734) if UCA_Version is 20 or later.
Ext.D (U+2B740..U+2B81D) if UCA_Version is 22 or later.
Ext.E (U+2B820..U+2CEA1) if UCA_Version is 32 or later.
Ext.F (U+2CEB0..U+2EBE0) if UCA_Version is 36 or later.
Ext.G (U+30000..U+3134A) if UCA_Version is 43.
```
Through `overrideCJK`, ordering of CJK unified ideographs (including extensions) can be overridden.
ex. CJK unified ideographs in the JIS code point order.
```
overrideCJK => sub {
my $u = shift; # get a Unicode codepoint
my $b = pack('n', $u); # to UTF-16BE
my $s = your_unicode_to_sjis_converter($b); # convert
my $n = unpack('n', $s); # convert sjis to short
[ $n, 0x20, 0x2, $u ]; # return the collation element
},
```
The return value may be an arrayref of 1st to 4th weights as shown above. The return value may be an integer as the primary weight as shown below. If `undef` is returned, the default derived collation element will be used.
```
overrideCJK => sub {
my $u = shift; # get a Unicode codepoint
my $b = pack('n', $u); # to UTF-16BE
my $s = your_unicode_to_sjis_converter($b); # convert
my $n = unpack('n', $s); # convert sjis to short
return $n; # return the primary weight
},
```
The return value may be a list containing zero or more of an arrayref, an integer, or `undef`.
ex. ignores all CJK unified ideographs.
```
overrideCJK => sub {()}, # CODEREF returning empty list
# where ->eq("Pe\x{4E00}rl", "Perl") is true
# as U+4E00 is a CJK unified ideograph and to be ignorable.
```
If a false value (including `undef`) is passed, `overrideCJK` has no effect. `$Collator->change(overrideCJK => 0)` resets the old one.
But assignment of weight for CJK unified ideographs in `table` or `entry` is still valid. If `undef` is passed explicitly as the value for this key, weights for CJK unified ideographs are treated as undefined. However when `UCA_Version` > 8, `(overrideCJK => undef)` has no special meaning.
**Note:** In addition to them, 12 CJK compatibility ideographs (`U+FA0E`, `U+FA0F`, `U+FA11`, `U+FA13`, `U+FA14`, `U+FA1F`, `U+FA21`, `U+FA23`, `U+FA24`, `U+FA27`, `U+FA28`, `U+FA29`) are also treated as CJK unified ideographs. But they can't be overridden via `overrideCJK` when you use DUCET, as the table includes weights for them. `table` or `entry` has priority over `overrideCJK`.
overrideHangul -- see 7.1 Derived Collation Elements, UTS #10.
By default, Hangul syllables are decomposed into Hangul Jamo, even if `(normalization => undef)`. But the mapping of Hangul syllables may be overridden.
This parameter works like `overrideCJK`, so see there for examples.
If you want to override the mapping of Hangul syllables, NFD and NFKD are not appropriate, since NFD and NFKD will decompose Hangul syllables before overriding. FCD may decompose Hangul syllables as the case may be.
If a false value (but not `undef`) is passed, `overrideHangul` has no effect. `$Collator->change(overrideHangul => 0)` resets the old one.
If `undef` is passed explicitly as the value for this key, weight for Hangul syllables is treated as undefined without decomposition into Hangul Jamo. But definition of weight for Hangul syllables in `table` or `entry` is still valid.
overrideOut -- see 7.1.1 Handling Ill-Formed Code Unit Sequences, UTS #10.
Perl seems to allow out-of-range values (greater than 0x10FFFF). By default, out-of-range values are replaced with `U+FFFD` (REPLACEMENT CHARACTER) when `UCA_Version` >= 22, or ignored when `UCA_Version` <= 20.
When `UCA_Version` >= 22, the weights of out-of-range values can be overridden. Though `table` or `entry` are available for them, out-of-range values are too many.
`overrideOut` can perform it algorithmically. This parameter works like `overrideCJK`, so see there for examples.
ex. ignores all out-of-range values.
```
overrideOut => sub {()}, # CODEREF returning empty list
```
If a false value (including `undef`) is passed, `overrideOut` has no effect. `$Collator->change(overrideOut => 0)` resets the old one.
**NOTE ABOUT U+FFFD:**
UCA recommends that out-of-range values should not be ignored for security reasons. Say, `"pe\x{110000}rl"` should not be equal to `"perl"`. However, `U+FFFD` is wrongly mapped to a variable collation element in DUCET for Unicode 6.0.0 to 6.2.0, that means out-of-range values will be ignored when `variable` isn't `Non-ignorable`.
The mapping of `U+FFFD` is corrected in Unicode 6.3.0. see <http://www.unicode.org/reports/tr10/tr10-28.html#Trailing_Weights> (7.1.4 Trailing Weights). Such a correction is reproduced by this.
```
overrideOut => sub { 0xFFFD }, # CODEREF returning a very large integer
```
This workaround is unnecessary since Unicode 6.3.0.
preprocess -- see 5.4 Preprocessing, UTS #10.
If specified, the coderef is used to preprocess each string before the formation of sort keys.
ex. dropping English articles, such as "a" or "the". Then, "the pen" is before "a pencil".
```
preprocess => sub {
my $str = shift;
$str =~ s/\b(?:an?|the)\s+//gi;
return $str;
},
```
`preprocess` is performed before `normalization` (if defined).
ex. decoding strings in a legacy encoding such as shift-jis:
```
$sjis_collator = Unicode::Collate->new(
preprocess => \&your_shiftjis_to_unicode_decoder,
);
@result = $sjis_collator->sort(@shiftjis_strings);
```
**Note:** Strings returned from the coderef will be interpreted according to Perl's Unicode support. See <perlunicode>, <perluniintro>, <perlunitut>, <perlunifaq>, <utf8>.
rearrange -- see 3.5 Rearrangement, UTS #10.
Characters that are not coded in logical order and to be rearranged. If `UCA_Version` is equal to or less than 11, default is:
```
rearrange => [ 0x0E40..0x0E44, 0x0EC0..0x0EC4 ],
```
If you want to disallow any rearrangement, pass `undef` or `[]` (a reference to empty list) as the value for this key.
If `UCA_Version` is equal to or greater than 14, default is `[]` (i.e. no rearrangement).
**According to the version 9 of UCA, this parameter shall not be used; but it is not warned at present.**
rewrite If specified, the coderef is used to rewrite lines in `table` or `entry`. The coderef will get each line, and then should return a rewritten line according to the UCA file format. If the coderef returns an empty line, the line will be skipped.
e.g. any primary ignorable characters into tertiary ignorable:
```
rewrite => sub {
my $line = shift;
$line =~ s/\[\.0000\..{4}\..{4}\./[.0000.0000.0000./g;
return $line;
},
```
This example shows rewriting weights. `rewrite` is allowed to affect code points, weights, and the name.
**NOTE**: `table` is available to use another table file; preparing a modified table once would be more efficient than rewriting lines on reading an unmodified table every time.
suppress -- see 3.12 Special-Purpose Commands, UTS #35 (LDML) Part 5: Collation.
Contractions beginning with the specified characters are suppressed, even if those contractions are defined in `table`.
An example for Russian and some languages using the Cyrillic script:
```
suppress => [0x0400..0x0417, 0x041A..0x0437, 0x043A..0x045F],
```
where 0x0400 stands for `U+0400`, CYRILLIC CAPITAL LETTER IE WITH GRAVE.
**NOTE**: Contractions via `entry` will not be suppressed.
table -- see 3.8 Default Unicode Collation Element Table, UTS #10.
You can use another collation element table if desired.
The table file should locate in the *Unicode/Collate* directory on `@INC`. Say, if the filename is *Foo.txt*, the table file is searched as *Unicode/Collate/Foo.txt* in `@INC`.
By default, *allkeys.txt* (as the filename of DUCET) is used. If you will prepare your own table file, any name other than *allkeys.txt* may be better to avoid namespace conflict.
**NOTE**: When XSUB is used, the DUCET is compiled on building this module, and it may save time at the run time. Explicit saying `(table => 'allkeys.txt')`, or using another table, or using `ignoreChar`, `ignoreName`, `undefChar`, `undefName` or `rewrite` will prevent this module from using the compiled DUCET.
If `undef` is passed explicitly as the value for this key, no file is read (but you can define collation elements via `entry`).
A typical way to define a collation element table without any file of table:
```
$onlyABC = Unicode::Collate->new(
table => undef,
entry => << 'ENTRIES',
0061 ; [.0101.0020.0002.0061] # LATIN SMALL LETTER A
0041 ; [.0101.0020.0008.0041] # LATIN CAPITAL LETTER A
0062 ; [.0102.0020.0002.0062] # LATIN SMALL LETTER B
0042 ; [.0102.0020.0008.0042] # LATIN CAPITAL LETTER B
0063 ; [.0103.0020.0002.0063] # LATIN SMALL LETTER C
0043 ; [.0103.0020.0008.0043] # LATIN CAPITAL LETTER C
ENTRIES
);
```
If `ignoreName` or `undefName` is used, character names should be specified as a comment (following `#`) on each line.
undefChar undefName -- see 6.3.3 Reducing the Repertoire, UTS #10.
Undefines the collation element as if it were unassigned in the `table`. This reduces the size of the table. If an unassigned character appears in the string to be collated, the sort key is made from its codepoint as a single-character collation element, as it is greater than any other assigned collation elements (in the codepoint order among the unassigned characters). But, it'd be better to ignore characters unfamiliar to you and maybe never used.
Through `undefChar`, any character matching `qr/$undefChar/` will be undefined. Through `undefName`, any character whose name (given in the `table` file as a comment) matches `qr/$undefName/` will be undefined.
ex. Collation weights for beyond-BMP characters are not stored in object:
```
undefChar => qr/[^\0-\x{fffd}]/,
```
upper\_before\_lower -- see 6.6 Case Comparisons, UTS #10.
By default, lowercase is before uppercase. If the parameter is made true, this is reversed.
**NOTE**: This parameter simplemindedly assumes that any lowercase/uppercase distinctions must occur in level 3, and their weights at level 3 must be same as those mentioned in 7.3.1, UTS #10. If you define your collation elements which differs from this requirement, this parameter doesn't work validly.
variable -- see 3.6 Variable Weighting, UTS #10.
This key allows for variable weighting of variable collation elements, which are marked with an ASTERISK in the table (NOTE: Many punctuation marks and symbols are variable in *allkeys.txt*).
```
variable => 'blanked', 'non-ignorable', 'shifted', or 'shift-trimmed'.
```
These names are case-insensitive. By default (if specification is omitted), 'shifted' is adopted.
```
'Blanked' Variable elements are made ignorable at levels 1 through 3;
considered at the 4th level.
'Non-Ignorable' Variable elements are not reset to ignorable.
'Shifted' Variable elements are made ignorable at levels 1 through 3
their level 4 weight is replaced by the old level 1 weight.
Level 4 weight for Non-Variable elements is 0xFFFF.
'Shift-Trimmed' Same as 'shifted', but all FFFF's at the 4th level
are trimmed.
```
###
Methods for Collation
`@sorted = $Collator->sort(@not_sorted)`
Sorts a list of strings.
`$result = $Collator->cmp($a, $b)`
Returns 1 (when `$a` is greater than `$b`) or 0 (when `$a` is equal to `$b`) or -1 (when `$a` is less than `$b`).
`$result = $Collator->eq($a, $b)`
`$result = $Collator->ne($a, $b)`
`$result = $Collator->lt($a, $b)`
`$result = $Collator->le($a, $b)`
`$result = $Collator->gt($a, $b)`
`$result = $Collator->ge($a, $b)`
They works like the same name operators as theirs.
```
eq : whether $a is equal to $b.
ne : whether $a is not equal to $b.
lt : whether $a is less than $b.
le : whether $a is less than $b or equal to $b.
gt : whether $a is greater than $b.
ge : whether $a is greater than $b or equal to $b.
```
`$sortKey = $Collator->getSortKey($string)`
-- see 4.3 Form Sort Key, UTS #10.
Returns a sort key.
You compare the sort keys using a binary comparison and get the result of the comparison of the strings using UCA.
```
$Collator->getSortKey($a) cmp $Collator->getSortKey($b)
is equivalent to
$Collator->cmp($a, $b)
```
`$sortKeyForm = $Collator->viewSortKey($string)`
Converts a sorting key into its representation form. If `UCA_Version` is 8, the output is slightly different.
```
use Unicode::Collate;
my $c = Unicode::Collate->new();
print $c->viewSortKey("Perl"),"\n";
# output:
# [0B67 0A65 0B7F 0B03 | 0020 0020 0020 0020 | 0008 0002 0002 0002 | FFFF FFFF FFFF FFFF]
# Level 1 Level 2 Level 3 Level 4
```
###
Methods for Searching
The `match`, `gmatch`, `subst`, `gsubst` methods work like `m//`, `m//g`, `s///`, `s///g`, respectively, but they are not aware of any pattern, but only a literal substring.
**DISCLAIMER:** If `preprocess` or `normalization` parameter is true for `$Collator`, calling these methods (`index`, `match`, `gmatch`, `subst`, `gsubst`) is croaked, as the position and the length might differ from those on the specified string.
`rearrange` and `hangul_terminator` parameters are neglected. `katakana_before_hiragana` and `upper_before_lower` don't affect matching and searching, as it doesn't matter whether greater or less.
`$position = $Collator->index($string, $substring[, $position])`
`($position, $length) = $Collator->index($string, $substring[, $position])`
If `$substring` matches a part of `$string`, returns the position of the first occurrence of the matching part in scalar context; in list context, returns a two-element list of the position and the length of the matching part.
If `$substring` does not match any part of `$string`, returns `-1` in scalar context and an empty list in list context.
e.g. when the content of `$str` is `"Ich mu`ร `studieren Perl."`, you say the following where `$sub` is `"M`รผ`SS"`,
```
my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
# (normalization => undef) is REQUIRED.
my $match;
if (my($pos,$len) = $Collator->index($str, $sub)) {
$match = substr($str, $pos, $len);
}
```
and get `"mu`ร`"` in `$match`, since `"mu`ร`"` is primary equal to `"M`รผ`SS"`.
`$match_ref = $Collator->match($string, $substring)`
`($match) = $Collator->match($string, $substring)`
If `$substring` matches a part of `$string`, in scalar context, returns **a reference to** the first occurrence of the matching part (`$match_ref` is always true if matches, since every reference is **true**); in list context, returns the first occurrence of the matching part.
If `$substring` does not match any part of `$string`, returns `undef` in scalar context and an empty list in list context.
e.g.
```
if ($match_ref = $Collator->match($str, $sub)) { # scalar context
print "matches [$$match_ref].\n";
} else {
print "doesn't match.\n";
}
or
if (($match) = $Collator->match($str, $sub)) { # list context
print "matches [$match].\n";
} else {
print "doesn't match.\n";
}
```
`@match = $Collator->gmatch($string, $substring)`
If `$substring` matches a part of `$string`, returns all the matching parts (or matching count in scalar context).
If `$substring` does not match any part of `$string`, returns an empty list.
`$count = $Collator->subst($string, $substring, $replacement)`
If `$substring` matches a part of `$string`, the first occurrence of the matching part is replaced by `$replacement` (`$string` is modified) and `$count` (always equals to `1`) is returned.
`$replacement` can be a `CODEREF`, taking the matching part as an argument, and returning a string to replace the matching part (a bit similar to `s/(..)/$coderef->($1)/e`).
`$count = $Collator->gsubst($string, $substring, $replacement)`
If `$substring` matches a part of `$string`, all the occurrences of the matching part are replaced by `$replacement` (`$string` is modified) and `$count` is returned.
`$replacement` can be a `CODEREF`, taking the matching part as an argument, and returning a string to replace the matching part (a bit similar to `s/(..)/$coderef->($1)/eg`).
e.g.
```
my $Collator = Unicode::Collate->new( normalization => undef, level => 1 );
# (normalization => undef) is REQUIRED.
my $str = "Camel donkey zebra came\x{301}l CAMEL horse cam\0e\0l...";
$Collator->gsubst($str, "camel", sub { "<b>$_[0]</b>" });
# now $str is "<b>Camel</b> donkey zebra <b>came\x{301}l</b> <b>CAMEL</b> horse <b>cam\0e\0l</b>...";
# i.e., all the camels are made bold-faced.
Examples: levels and ignore_level2 - what does camel match?
---------------------------------------------------------------------------
level ignore_level2 | camel Camel came\x{301}l c-a-m-e-l cam\0e\0l
-----------------------|---------------------------------------------------
1 false | yes yes yes yes yes
2 false | yes yes no yes yes
3 false | yes no no yes yes
4 false | yes no no no yes
-----------------------|---------------------------------------------------
1 true | yes yes yes yes yes
2 true | yes yes yes yes yes
3 true | yes no yes yes yes
4 true | yes no yes no yes
---------------------------------------------------------------------------
note: if variable => non-ignorable, camel doesn't match c-a-m-e-l
at any level.
```
###
Other Methods
`%old_tailoring = $Collator->change(%new_tailoring)`
`$modified_collator = $Collator->change(%new_tailoring)`
Changes the value of specified keys and returns the changed part.
```
$Collator = Unicode::Collate->new(level => 4);
$Collator->eq("perl", "PERL"); # false
%old = $Collator->change(level => 2); # returns (level => 4).
$Collator->eq("perl", "PERL"); # true
$Collator->change(%old); # returns (level => 2).
$Collator->eq("perl", "PERL"); # false
```
Not all `(key,value)`s are allowed to be changed. See also `@Unicode::Collate::ChangeOK` and `@Unicode::Collate::ChangeNG`.
In the scalar context, returns the modified collator (but it is **not** a clone from the original).
```
$Collator->change(level => 2)->eq("perl", "PERL"); # true
$Collator->eq("perl", "PERL"); # true; now max level is 2nd.
$Collator->change(level => 4)->eq("perl", "PERL"); # false
```
`$version = $Collator->version()`
Returns the version number (a string) of the Unicode Standard which the `table` file used by the collator object is based on. If the table does not include a version line (starting with `@version`), returns `"unknown"`.
`UCA_Version()`
Returns the revision number of UTS #10 this module consults, that should correspond with the DUCET incorporated.
`Base_Unicode_Version()`
Returns the version number of UTS #10 this module consults, that should correspond with the DUCET incorporated.
EXPORT
------
No method will be exported.
INSTALL
-------
Though this module can be used without any `table` file, to use this module easily, it is recommended to install a table file in the UCA format, by copying it under the directory <a place in @INC>/Unicode/Collate.
The most preferable one is "The Default Unicode Collation Element Table" (aka DUCET), available from the Unicode Consortium's website:
```
http://www.unicode.org/Public/UCA/
http://www.unicode.org/Public/UCA/latest/allkeys.txt
(latest version)
```
If DUCET is not installed, it is recommended to copy the file from http://www.unicode.org/Public/UCA/latest/allkeys.txt to <a place in @INC>/Unicode/Collate/allkeys.txt manually.
CAVEATS
-------
Normalization Use of the `normalization` parameter requires the **Unicode::Normalize** module (see <Unicode::Normalize>).
If you need not it (say, in the case when you need not handle any combining characters), assign `(normalization => undef)` explicitly.
-- see 6.5 Avoiding Normalization, UTS #10.
Conformance Test The Conformance Test for the UCA is available under <http://www.unicode.org/Public/UCA/>.
For *CollationTest\_SHIFTED.txt*, a collator via `Unicode::Collate->new( )` should be used; for *CollationTest\_NON\_IGNORABLE.txt*, a collator via `Unicode::Collate->new(variable => "non-ignorable", level => 3)`.
If `UCA_Version` is 26 or later, the `identical` level is preferred; `Unicode::Collate->new(identical => 1)` and `Unicode::Collate->new(identical => 1,` `variable => "non-ignorable", level => 3)` should be used.
**Unicode::Normalize is required to try The Conformance Test.**
**EBCDIC-SUPPORT IS EXPERIMENTAL.**
AUTHOR, COPYRIGHT AND LICENSE
------------------------------
The Unicode::Collate module for perl was written by SADAHIRO Tomoyuki, <[email protected]>. This module is Copyright(C) 2001-2021, 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.
The file Unicode/Collate/allkeys.txt was copied verbatim from <http://www.unicode.org/Public/UCA/13.0.0/allkeys.txt>. For this file, Copyright (c) 2020 Unicode, Inc.; distributed under the Terms of Use in <http://www.unicode.org/terms_of_use.html>
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>
The conformance test for the UCA <http://www.unicode.org/Public/UCA/latest/CollationTest.html>
<http://www.unicode.org/Public/UCA/latest/CollationTest.zip>
Hangul Syllable Type <http://www.unicode.org/Public/UNIDATA/HangulSyllableType.txt>
Unicode Normalization Forms - UAX #15 <http://www.unicode.org/reports/tr15/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
| programming_docs |
perl TAP::Parser::Result::Pragma TAP::Parser::Result::Pragma
===========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDDEN METHODS](#OVERRIDDEN-METHODS)
+ [Instance Methods](#Instance-Methods)
- [pragmas](#pragmas)
NAME
----
TAP::Parser::Result::Pragma - TAP pragma token.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This is a subclass of <TAP::Parser::Result>. A token of this class will be returned if a pragma is encountered.
```
TAP version 13
pragma +strict, -foo
```
Pragmas are only supported from TAP version 13 onwards.
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
#### `pragmas`
if ( $result->is\_pragma ) { @pragmas = $result->pragmas; }
perl Encode::Alias Encode::Alias
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Changes in code reference aliasing](#Changes-in-code-reference-aliasing)
+ [Alias overloading](#Alias-overloading)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Alias - alias definitions to encodings
SYNOPSIS
--------
```
use Encode;
use Encode::Alias;
define_alias( "newName" => ENCODING);
define_alias( qr/.../ => ENCODING);
define_alias( sub { return ENCODING if ...; } );
```
DESCRIPTION
-----------
Allows newName to be used as an alias for ENCODING. ENCODING may be either the name of an encoding or an encoding object (as described in [Encode](encode)).
Currently the first argument to define\_alias() can be specified in the following ways:
As a simple string.
As a qr// compiled regular expression, e.g.:
```
define_alias( qr/^iso8859-(\d+)$/i => '"iso-8859-$1"' );
```
In this case, if *ENCODING* is not a reference, it is `eval`-ed in order to allow `$1` etc. to be substituted. The example is one way to alias names as used in X11 fonts to the MIME names for the iso-8859-\* family. Note the double quotes inside the single quotes.
(or, you don't have to do this yourself because this example is predefined)
If you are using a regex here, you have to use the quotes as shown or it won't work. Also note that regex handling is tricky even for the experienced. Use this feature with caution.
As a code reference, e.g.:
```
define_alias( sub {shift =~ /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } );
```
The same effect as the example above in a different way. The coderef takes the alias name as an argument and returns a canonical name on success or undef if not. Note the second argument is ignored if provided. Use this with even more caution than the regex version.
####
Changes in code reference aliasing
As of Encode 1.87, the older form
```
define_alias( sub { return /^iso8859-(\d+)$/i ? "iso-8859-$1" : undef } );
```
no longer works.
Encode up to 1.86 internally used "local $\_" to implement this older form. But consider the code below;
```
use Encode;
$_ = "eeeee" ;
while (/(e)/g) {
my $utf = decode('aliased-encoding-name', $1);
print "position:",pos,"\n";
}
```
Prior to Encode 1.86 this fails because of "local $\_".
###
Alias overloading
You can override predefined aliases by simply applying define\_alias(). The new alias is always evaluated first, and when necessary, define\_alias() flushes the internal cache to make the new definition available.
```
# redirect SHIFT_JIS to MS/IBM Code Page 932, which is a
# superset of SHIFT_JIS
define_alias( qr/shift.*jis$/i => '"cp932"' );
define_alias( qr/sjis$/i => '"cp932"' );
```
If you want to zap all predefined aliases, you can use
```
Encode::Alias->undef_aliases;
```
to do so. And
```
Encode::Alias->init_aliases;
```
gets the factory settings back.
Note that define\_alias() will not be able to override the canonical name of encodings. Encodings are first looked up by canonical name before potential aliases are tried.
SEE ALSO
---------
[Encode](encode), <Encode::Supported>
perl CPAN::Meta::History::Meta_1_0 CPAN::Meta::History::Meta\_1\_0
===============================
CONTENTS
--------
* [NAME](#NAME)
* [PREFACE](#PREFACE)
* [DESCRIPTION](#DESCRIPTION)
* [Format](#Format)
* [Fields](#Fields)
* [Related Projects](#Related-Projects)
* [History](#History)
NAME
----
CPAN::Meta::History::Meta\_1\_0 - Version 1.0 metadata specification for META.yml
PREFACE
-------
This is a historical copy of the version 1.0 specification for *META.yml* files, copyright by Ken Williams and licensed under the same terms as Perl itself.
Modifications from the original:
* Conversion from the original HTML to POD format
* Include list of valid licenses from <Module::Build> 0.17 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.
DESCRIPTION
-----------
This document describes version 1.0 of the *META.yml* specification.
The META.yml file describes important properties of contributed Perl distributions such as the ones found on [CPAN](http://www.cpan.org). It is typically created by tools like <Module::Build> and <ExtUtils::MakeMaker>.
The fields in the *META.yml* file are meant to be helpful to people maintaining module collections (like CPAN), for people writing installation tools (like [CPAN](cpan) or [CPANPLUS](cpanplus)), or just people who want to know some stuff about a distribution before downloading it and starting to install it.
Format
------
*META.yml* files are written in the [YAML](http://www.yaml.org/) format. The reasons we chose YAML instead of, say, XML or Data::Dumper are discussed in [this thread](http://www.nntp.perl.org/group/perl.makemaker/2002/04/msg406.html) on the MakeMaker mailing list.
The first line of a *META.yml* file should be a valid [YAML document header](http://yaml.org/spec/history/2002-10-31.html#syntax-document) like `"--- #YAML:1.0"`
Fields
------
The rest of the META.yml file is one big YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping), whose keys are described here.
name Example: `Module-Build`
The name of the distribution. 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](http://search.cpan.org/author/GAAS/libwww-perl/) distribution.
version Example: `0.16`
The version of the distribution to which the META.yml file refers.
license Example: `perl`
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: `module`
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.
requires Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-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 the [documentation for Module::Build's "requires" parameter](Module::Build::API#requires).
*Note: the exact nature of the fancy specifications like `">= 1.2, != 1.5, < 2.0"` is subject to change. Advance notice will be given here. The simple specifications like `"1.2"` will not change in format.*
recommends Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping) indicating the Perl modules this distribution recommends for enhanced operation.
build\_requires Example:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-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:
```
Data::Dumper: 0
File::Find: 1.03
```
A YAML [mapping](http://yaml.org/spec/history/2002-10-31.html#syntax-mapping) indicating the Perl modules that cannot be installed while this distribution is installed. This is a pretty uncommon situation.
dynamic\_config Example: `0`
A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed, or whether this module 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.pm](cpan) to do something useful with it. It can potentially bring lots of security, packaging, and convenience improvements.
generated\_by Example: `Module::Build version 0.16`
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.
Related Projects
-----------------
DOAP An RDF vocabulary to describe software projects. <http://usefulinc.com/doap>.
History
-------
* **March 14, 2003** (Pi day) - created version 1.0 of this document.
* **May 8, 2003** - added the "dynamic\_config" field, which was missing from the initial version.
perl Locale::Maketext::Simple Locale::Maketext::Simple
========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
+ [Class](#Class)
+ [Path](#Path)
+ [Style](#Style)
+ [Export](#Export)
+ [Subclass](#Subclass)
+ [Decode](#Decode)
+ [Encoding](#Encoding)
* [ACKNOWLEDGMENTS](#ACKNOWLEDGMENTS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
+ [The "MIT" License](#The-%22MIT%22-License)
NAME
----
Locale::Maketext::Simple - Simple interface to Locale::Maketext::Lexicon
VERSION
-------
This document describes version 0.18 of Locale::Maketext::Simple, released Septermber 8, 2006.
SYNOPSIS
--------
Minimal setup (looks for *auto/Foo/\*.po* and *auto/Foo/\*.mo*):
```
package Foo;
use Locale::Maketext::Simple; # exports 'loc'
loc_lang('fr'); # set language to French
sub hello {
print loc("Hello, [_1]!", "World");
}
```
More sophisticated example:
```
package Foo::Bar;
use Locale::Maketext::Simple (
Class => 'Foo', # search in auto/Foo/
Style => 'gettext', # %1 instead of [_1]
Export => 'maketext', # maketext() instead of loc()
Subclass => 'L10N', # Foo::L10N instead of Foo::I18N
Decode => 1, # decode entries to unicode-strings
Encoding => 'locale', # but encode lexicons in current locale
# (needs Locale::Maketext::Lexicon 0.36)
);
sub japh {
print maketext("Just another %1 hacker", "Perl");
}
```
DESCRIPTION
-----------
This module is a simple wrapper around **Locale::Maketext::Lexicon**, designed to alleviate the need of creating *Language Classes* for module authors.
The language used is chosen from the loc\_lang call. If a lookup is not possible, the i-default language will be used. If the lookup is not in the i-default language, then the key will be returned.
If **Locale::Maketext::Lexicon** is not present, it implements a minimal localization function by simply interpolating `[_1]` with the first argument, `[_2]` with the second, etc. Interpolated function like `[quant,_1]` are treated as `[_1]`, with the sole exception of `[tense,_1,X]`, which will append `ing` to `_1` when X is `present`, or appending `ed` to <\_1> otherwise.
OPTIONS
-------
All options are passed either via the `use` statement, or via an explicit `import`.
### Class
By default, **Locale::Maketext::Simple** draws its source from the calling package's *auto/* directory; you can override this behaviour by explicitly specifying another package as `Class`.
### Path
If your PO and MO files are under a path elsewhere than `auto/`, you may specify it using the `Path` option.
### Style
By default, this module uses the `maketext` style of `[_1]` and `[quant,_1]` for interpolation. Alternatively, you can specify the `gettext` style, which uses `%1` and `%quant(%1)` for interpolation.
This option is case-insensitive.
### Export
By default, this module exports a single function, `loc`, into its caller's namespace. You can set it to another name, or set it to an empty string to disable exporting.
### Subclass
By default, this module creates an `::I18N` subclass under the caller's package (or the package specified by `Class`), and stores lexicon data in its subclasses. You can assign a name other than `I18N` via this option.
### Decode
If set to a true value, source entries will be converted into utf8-strings (available in Perl 5.6.1 or later). This feature needs the **Encode** or **Encode::compat** module.
### Encoding
Specifies an encoding to store lexicon entries, instead of utf8-strings. If set to `locale`, the encoding from the current locale setting is used. Implies a true value for `Decode`.
ACKNOWLEDGMENTS
---------------
Thanks to Jos I. Boumans for suggesting this module to be written.
Thanks to Chia-Liang Kao for suggesting `Path` and `loc_lang`.
SEE ALSO
---------
<Locale::Maketext>, <Locale::Maketext::Lexicon>
AUTHORS
-------
Audrey Tang <[email protected]>
COPYRIGHT
---------
Copyright 2003, 2004, 2005, 2006 by Audrey Tang <[email protected]>.
This software is released under the MIT license cited below. Additionally, when this software is distributed with **Perl Kit, Version 5**, you may also redistribute it and/or modify it under the same terms as Perl itself.
###
The "MIT" License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
perl Tie::SubstrHash Tie::SubstrHash
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
NAME
----
Tie::SubstrHash - Fixed-table-size, fixed-key-length hashing
SYNOPSIS
--------
```
require Tie::SubstrHash;
tie %myhash, 'Tie::SubstrHash', $key_len, $value_len, $table_size;
```
DESCRIPTION
-----------
The **Tie::SubstrHash** package provides a hash-table-like interface to an array of determinate size, with constant key size and record size.
Upon tying a new hash to this package, the developer must specify the size of the keys that will be used, the size of the value fields that the keys will index, and the size of the overall table (in terms of key-value pairs, not size in hard memory). *These values will not change for the duration of the tied hash*. The newly-allocated hash table may now have data stored and retrieved. Efforts to store more than `$table_size` elements will result in a fatal error, as will efforts to store a value not exactly `$value_len` characters in length, or reference through a key not exactly `$key_len` characters in length. While these constraints may seem excessive, the result is a hash table using much less internal memory than an equivalent freely-allocated hash table.
CAVEATS
-------
Because the current implementation uses the table and key sizes for the hashing algorithm, there is no means by which to dynamically change the value of any of the initialization parameters.
The hash does not support exists().
perl encguess encguess
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
+ [SWITCHES](#SWITCHES)
+ [EXAMPLES:](#EXAMPLES:)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [LICENSE AND COPYRIGHT](#LICENSE-AND-COPYRIGHT)
NAME
----
encguess - guess character encodings of files
VERSION
-------
$Id: encguess,v 0.3 2020/12/02 01:28:17 dankogai Exp $
SYNOPSIS
--------
```
encguess [switches] filename...
```
### SWITCHES
-h show this message and exit.
-s specify a list of "suspect encoding types" to test, separated by either `:` or `,`
-S output a list of all acceptable encoding types that can be used with the -s param
-u suppress display of unidentified types
###
EXAMPLES:
* Guess encoding of a file named `test.txt`, using only the default suspect types.
```
encguess test.txt
```
* Guess the encoding type of a file named `test.txt`, using the suspect types `euc-jp,shiftjis,7bit-jis`.
```
encguess -s euc-jp,shiftjis,7bit-jis test.txt
encguess -s euc-jp:shiftjis:7bit-jis test.txt
```
* Guess the encoding type of several files, do not display results for unidentified files.
```
encguess -us euc-jp,shiftjis,7bit-jis test*.txt
```
DESCRIPTION
-----------
The encoding identification is done by checking one encoding type at a time until all but the right type are eliminated. The set of encoding types to try is defined by the -s parameter and defaults to ascii, utf8 and UTF-16/32 with BOM. This can be overridden by passing one or more encoding types via the -s parameter. If you need to pass in multiple suspect encoding types, use a quoted string with the a space separating each value.
SEE ALSO
---------
<Encode::Guess>, <Encode::Detect>
LICENSE AND COPYRIGHT
----------------------
Copyright 2015 Michael LaGrasta and Dan Kogai.
This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:
<http://www.perlfoundation.org/artistic_license_2_0>
| programming_docs |
perl PerlIO::via PerlIO::via
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPECTED METHODS](#EXPECTED-METHODS)
* [EXAMPLES](#EXAMPLES)
+ [Example - a Hexadecimal Handle](#Example-a-Hexadecimal-Handle)
NAME
----
PerlIO::via - Helper class for PerlIO layers implemented in perl
SYNOPSIS
--------
```
use PerlIO::via::Layer;
open($fh,"<:via(Layer)",...);
use Some::Other::Package;
open($fh,">:via(Some::Other::Package)",...);
```
DESCRIPTION
-----------
The PerlIO::via module allows you to develop PerlIO layers in Perl, without having to go into the nitty gritty of programming C with XS as the interface to Perl.
One example module, <PerlIO::via::QuotedPrint>, is included with Perl 5.8.0, and more example modules are available from CPAN, such as <PerlIO::via::StripHTML> and <PerlIO::via::Base64>. The PerlIO::via::StripHTML module for instance, allows you to say:
```
use PerlIO::via::StripHTML;
open( my $fh, "<:via(StripHTML)", "index.html" );
my @line = <$fh>;
```
to obtain the text of an HTML-file in an array with all the HTML-tags automagically removed.
Please note that if the layer is created in the PerlIO::via:: namespace, it does **not** have to be fully qualified. The PerlIO::via module will prefix the PerlIO::via:: namespace if the specified modulename does not exist as a fully qualified module name.
EXPECTED METHODS
-----------------
To create a Perl module that implements a PerlIO layer in Perl (as opposed to in C using XS as the interface to Perl), you need to supply some of the following subroutines. It is recommended to create these Perl modules in the PerlIO::via:: namespace, so that they can easily be located on CPAN and use the default namespace feature of the PerlIO::via module itself.
Please note that this is an area of recent development in Perl and that the interface described here is therefore still subject to change (and hopefully will have better documentation and more examples).
In the method descriptions below *$fh* will be a reference to a glob which can be treated as a perl file handle. It refers to the layer below. *$fh* is not passed if the layer is at the bottom of the stack, for this reason and to maintain some level of "compatibility" with TIEHANDLE classes it is passed last.
$class->PUSHED([$mode,[$fh]]) Should return an object or the class, or -1 on failure. (Compare TIEHANDLE.) The arguments are an optional mode string ("r", "w", "w+", ...) and a filehandle for the PerlIO layer below. Mandatory.
When the layer is pushed as part of an `open` call, `PUSHED` will be called *before* the actual open occurs, whether that be via `OPEN`, `SYSOPEN`, `FDOPEN` or by letting a lower layer do the open.
$obj->POPPED([$fh]) Optional - called when the layer is about to be removed.
$obj->UTF8($belowFlag,[$fh]) Optional - if present it will be called immediately after PUSHED has returned. It should return a true value if the layer expects data to be UTF-8 encoded. If it returns true, the result is as if the caller had done
```
":via(YourClass):utf8"
```
If not present or if it returns false, then the stream is left with the UTF-8 flag clear. The *$belowFlag* argument will be true if there is a layer below and that layer was expecting UTF-8.
$obj->OPEN($path,$mode,[$fh]) Optional - if not present a lower layer does the open. If present, called for normal opens after the layer is pushed. This function is subject to change as there is no easy way to get a lower layer to do the open and then regain control.
$obj->BINMODE([$fh]) Optional - if not present the layer is popped on binmode($fh) or when `:raw` is pushed. If present it should return 0 on success, -1 on error, or undef to pop the layer.
$obj->FDOPEN($fd,[$fh]) Optional - if not present a lower layer does the open. If present, called after the layer is pushed for opens which pass a numeric file descriptor. This function is subject to change as there is no easy way to get a lower layer to do the open and then regain control.
$obj->SYSOPEN($path,$imode,$perm,[$fh]) Optional - if not present a lower layer does the open. If present, called after the layer is pushed for sysopen style opens which pass a numeric mode and permissions. This function is subject to change as there is no easy way to get a lower layer to do the open and then regain control.
$obj->FILENO($fh) Returns a numeric value for a Unix-like file descriptor. Returns -1 if there isn't one. Optional. Default is fileno($fh).
$obj->READ($buffer,$len,$fh) Returns the number of octets placed in $buffer (must be less than or equal to $len). Optional. Default is to use FILL instead.
$obj->WRITE($buffer,$fh) Returns the number of octets from $buffer that have been successfully written.
$obj->FILL($fh) Should return a string to be placed in the buffer. Optional. If not provided, must provide READ or reject handles open for reading in PUSHED.
$obj->CLOSE($fh) Should return 0 on success, -1 on error. Optional.
$obj->SEEK($posn,$whence,$fh) Should return 0 on success, -1 on error. Optional. Default is to fail, but that is likely to be changed in future.
$obj->TELL($fh) Returns file position. Optional. Default to be determined.
$obj->UNREAD($buffer,$fh) Returns the number of octets from $buffer that have been successfully saved to be returned on future FILL/READ calls. Optional. Default is to push data into a temporary layer above this one.
$obj->FLUSH($fh) Flush any buffered write data. May possibly be called on readable handles too. Should return 0 on success, -1 on error.
$obj->SETLINEBUF($fh) Optional. No return.
$obj->CLEARERR($fh) Optional. No return.
$obj->ERROR($fh) Optional. Returns error state. Default is no error until a mechanism to signal error (die?) is worked out.
$obj->EOF($fh) Optional. Returns end-of-file state. Default is a function of the return value of FILL or READ.
EXAMPLES
--------
Check the PerlIO::via:: namespace on CPAN for examples of PerlIO layers implemented in Perl. To give you an idea how simple the implementation of a PerlIO layer can look, a simple example is included here.
###
Example - a Hexadecimal Handle
Given the following module, PerlIO::via::Hex :
```
package PerlIO::via::Hex;
sub PUSHED
{
my ($class,$mode,$fh) = @_;
# When writing we buffer the data
my $buf = '';
return bless \$buf,$class;
}
sub FILL
{
my ($obj,$fh) = @_;
my $line = <$fh>;
return (defined $line) ? pack("H*", $line) : undef;
}
sub WRITE
{
my ($obj,$buf,$fh) = @_;
$$obj .= unpack("H*", $buf);
return length($buf);
}
sub FLUSH
{
my ($obj,$fh) = @_;
print $fh $$obj or return -1;
$$obj = '';
return 0;
}
1;
```
The following code opens up an output handle that will convert any output to a hexadecimal dump of the output bytes: for example "A" will be converted to "41" (on ASCII-based machines, on EBCDIC platforms the "A" will become "c1")
```
use PerlIO::via::Hex;
open(my $fh, ">:via(Hex)", "foo.hex");
```
and the following code will read the hexdump in and convert it on the fly back into bytes:
```
open(my $fh, "<:via(Hex)", "foo.hex");
```
perl App::Cpan App::Cpan
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Options](#Options)
+ [Examples](#Examples)
+ [Environment variables](#Environment-variables)
+ [Methods](#Methods)
* [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
----
App::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.
If the file does not exist, `cpan` dies.
-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`.
### Methods
run( ARGS ) Just do it.
The `run` method returns 0 on success and a positive number on failure. See the section on EXIT CODES for details on the values.
CPAN.pm sends all the good stuff either to STDOUT, or to a temp file if $CPAN::Be\_Silent is set. I have to intercept that output so I can find out what happened.
Stolen from File::Path::Expand
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
------
\* There is initial support for Log4perl if it is available, but I haven't gone through everything to make the NullLogger work out correctly if Log4perl is not installed.
\* When I capture CPAN.pm output, I need to check for errors and report them to the user.
\* Warnings switch
\* Check then exit
BUGS
----
\* none noted
SEE ALSO
---------
[CPAN](cpan), <App::cpanminus>
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 suggested 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
David Golden helps integrate this into the `CPAN.pm` repos.
Jim Keenan fixed up various issues with \_download
AUTHOR
------
brian d foy, `<[email protected]>`
COPYRIGHT
---------
Copyright (c) 2001-2021, brian d foy, All Rights Reserved.
You may redistribute this under the same terms as Perl itself.
perl Encode::JP Encode::JP
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [Note on ISO-2022-JP(-1)?](#Note-on-ISO-2022-JP(-1)?)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::JP - Japanese Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$euc_jp = encode("euc-jp", $utf8); # loads Encode::JP implicitly
$utf8 = decode("euc-jp", $euc_jp); # ditto
```
ABSTRACT
--------
This module implements Japanese charset encodings. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
euc-jp /\beuc.*jp$/i EUC (Extended Unix Character)
/\bjp.*euc/i
/\bujis$/i
shiftjis /\bshift.*jis$/i Shift JIS (aka MS Kanji)
/\bsjis$/i
7bit-jis /\bjis$/i 7bit JIS
iso-2022-jp ISO-2022-JP [RFC1468]
= 7bit JIS with all Halfwidth Kana
converted to Fullwidth
iso-2022-jp-1 ISO-2022-JP-1 [RFC2237]
= ISO-2022-JP with JIS X 0212-1990
support. See below
MacJapanese Shift JIS + Apple vendor mappings
cp932 /\bwindows-31j$/i Code Page 932
= Shift JIS + MS/IBM vendor mappings
jis0201-raw JIS0201, raw format
jis0208-raw JIS0208, raw format
jis0212-raw JIS0212, raw format
--------------------------------------------------------------------
```
DESCRIPTION
-----------
To find out how to use this module in detail, see [Encode](encode).
Note on ISO-2022-JP(-1)?
-------------------------
ISO-2022-JP-1 (RFC2237) is a superset of ISO-2022-JP (RFC1468) which adds support for JIS X 0212-1990. That means you can use the same code to decode to utf8 but not vice versa.
```
$utf8 = decode('iso-2022-jp-1', $stream);
```
and
```
$utf8 = decode('iso-2022-jp', $stream);
```
yield the same result but
```
$with_0212 = encode('iso-2022-jp-1', $utf8);
```
is now different from
```
$without_0212 = encode('iso-2022-jp', $utf8 );
```
In the latter case, characters that map to 0212 are first converted to U+3013 (0xA2AE in EUC-JP; a white square also known as 'Tofu' or 'geta mark') then fed to the decoding engine. U+FFFD is not used, in order to preserve text layout as much as possible.
BUGS
----
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 ExtUtils::MM_QNX ExtUtils::MM\_QNX
=================
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\_QNX - QNX 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 QNX.
Unless otherwise stated it works just like ExtUtils::MM\_Unix.
###
Overridden methods
#### extra\_clean\_files
Add .err files corresponding to each .c file.
AUTHOR
------
Michael G Schwern <[email protected]> with code from ExtUtils::MM\_Unix
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl Pod::Checker Pod::Checker
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS/ARGUMENTS](#OPTIONS/ARGUMENTS)
+ [podchecker()](#podchecker())
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
+ [Errors](#Errors)
+ [Warnings](#Warnings)
+ [Hyperlinks](#Hyperlinks)
* [RETURN VALUE](#RETURN-VALUE)
* [EXAMPLES](#EXAMPLES)
* [SCRIPTS](#SCRIPTS)
* [INTERFACE](#INTERFACE)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Checker - check pod documents for syntax errors
SYNOPSIS
--------
```
use Pod::Checker;
$syntax_okay = podchecker($filepath, $outputpath, %options);
my $checker = Pod::Checker->new(%options);
$checker->parse_from_file($filepath, \*STDERR);
```
OPTIONS/ARGUMENTS
------------------
`$filepath` is the input POD to read and `$outputpath` is where to write POD syntax error messages. Either argument may be a scalar indicating a file-path, or else a reference to an open filehandle. If unspecified, the input-file it defaults to `\*STDIN`, and the output-file defaults to `\*STDERR`.
###
podchecker()
This function can take a hash of options:
**-warnings** => *val*
Turn warnings on/off. *val* is usually 1 for on, but higher values trigger additional warnings. See ["Warnings"](#Warnings).
**-quiet** => *val*
If `val` is true, do not print any errors/warnings.
DESCRIPTION
-----------
**podchecker** will perform syntax checking of Perl5 POD format documentation.
Curious/ambitious users are welcome to propose additional features they wish to see in **Pod::Checker** and **podchecker** and verify that the checks are consistent with <perlpod>.
The following checks are currently performed:
* Unknown '=xxxx' commands, unknown 'X<...>' interior-sequences, and unterminated interior sequences.
* Check for proper balancing of `=begin` and `=end`. The contents of such a block are generally ignored, i.e. no syntax checks are performed.
* Check for proper nesting and balancing of `=over`, `=item` and `=back`.
* Check for same nested interior-sequences (e.g. `L<...L<...>...>`).
* Check for malformed or non-existing entities `E<...>`.
* Check for correct syntax of hyperlinks `L<...>`. See <perlpod> for details.
* Check for unresolved document-internal links. This check may also reveal misspelled links that seem to be internal links but should be links to something else.
DIAGNOSTICS
-----------
### Errors
* empty =headn
A heading (`=head1` or `=head2`) without any text? That ain't no heading!
* =over on line *N* without closing =back
* You forgot a '=back' before '=head*N*'
* =over is the last thing in the document?!
The `=over` command does not have a corresponding `=back` before the next heading (`=head1` or `=head2`) or the end of the file.
* '=item' outside of any '=over'
* =back without =over
An `=item` or `=back` command has been found outside a `=over`/`=back` block.
* Can't have a 0 in =over *N*
You need to indent a strictly positive number of spaces, not 0.
* =over should be: '=over' or '=over positive\_number'
Either have an argumentless =over, or have its argument a strictly positive number.
* =begin *TARGET* without matching =end *TARGET*
A `=begin` command was found that has no matching =end command.
* =begin without a target?
A `=begin` command was found that is not followed by the formatter specification.
* =end *TARGET* without matching =begin.
A standalone `=end` command was found.
* '=end' without a target?
'=end' directives need to have a target, just like =begin directives.
* '=end *TARGET*' is invalid.
*TARGET* needs to be one word
* =end *CONTENT* doesn't match =begin *TARGET*
*CONTENT* needs to match =begin's *TARGET*.
* =for without a target?
There is no specification of the formatter after the `=for` command.
* unresolved internal link *NAME*
The given link to *NAME* does not have a matching node in the current POD. This also happened when a single word node name is not enclosed in `""`.
* Unknown directive: *CMD*
An invalid POD command has been found. Valid are `=head1`, `=head2`, `=head3`, `=head4`, `=over`, `=item`, `=back`, `=begin`, `=end`, `=for`, `=pod`, `=cut`
* Deleting unknown formatting code *SEQ*
An invalid markup command has been encountered. Valid are: `B<>`, `C<>`, `E<>`, `F<>`, `I<>`, `L<>`, `S<>`, `X<>`, `Z<>`
* Unterminated *SEQ*<> sequence
An unclosed formatting code
* An E<...> surrounding strange content
The *STRING* found cannot be interpreted as a character entity.
* An empty E<>
* An empty `L<>`
* An empty X<>
There needs to be content inside E, L, and X formatting codes.
* Spurious text after =pod / =cut
The commands `=pod` and `=cut` do not take any arguments.
* =back doesn't take any parameters, but you said =back *ARGUMENT*
The `=back` command does not take any arguments.
* =pod directives shouldn't be over one line long! Ignoring all *N* lines of content
Self explanatory
* =cut found outside a pod block.
A '=cut' directive found in the middle of non-POD
* Invalid =encoding syntax: *CONTENT*
Syntax error in =encoding directive
### Warnings
These may not necessarily cause trouble, but indicate mediocre style.
* nested commands *CMD*<...*CMD*<...>...>
Two nested identical markup commands have been found. Generally this does not make sense.
* multiple occurrences (*N*) of link target *name*
The POD file has some `=item` and/or `=head` commands that have the same text. Potential hyperlinks to such a text cannot be unique then. This warning is printed only with warning level greater than one.
* line containing nothing but whitespace in paragraph
There is some whitespace on a seemingly empty line. POD is very sensitive to such things, so this is flagged. **vi** users switch on the **list** option to avoid this problem.
* =item has no contents
There is a list `=item` that has no text contents. You probably want to delete empty items.
* You can't have =items (as at line *N*) unless the first thing after the =over is an =item
A list introduced by `=over` starts with a text or verbatim paragraph, but continues with `=item`s. Move the non-item paragraph out of the `=over`/`=back` block.
* Expected '=item *EXPECTED VALUE*'
* Expected '=item \*'
* Possible =item type mismatch: '*x*' found leading a supposed definition =item
A list started with e.g. a bullet-like `=item` and continued with a numbered one. This is obviously inconsistent. For most translators the type of the *first* `=item` determines the type of the list.
* You have '=item x' instead of the expected '=item *N*'
Erroneous numbering of =item numbers; they need to ascend consecutively.
* Unknown E content in E<*CONTENT*>
A character entity was found that does not belong to the standard ISO set or the POD specials `verbar` and `sol`. *Currently, this warning only appears if a character entity was found that does not have a Unicode character. This should be fixed to adhere to the original warning.*
* empty =over/=back block
The list opened with `=over` does not contain anything.
* empty section in previous paragraph
The previous section (introduced by a `=head` command) does not contain any valid content. This usually indicates that something is missing. Note: A `=head1` followed immediately by `=head2` does not trigger this warning.
* Verbatim paragraph in NAME section
The NAME section (`=head1 NAME`) should consist of a single paragraph with the script/module name, followed by a dash `-' and a very short description of what the thing is good for.
* =head*n* without preceding higher level
For example if there is a `=head2` in the POD file prior to a `=head1`.
* A non-empty Z<>
The `Z<>` sequence is supposed to be empty. Caveat: this issue is detected in <Pod::Simple> and will be flagged as an *ERROR* by any client code; any contents of `Z<...>` will be disregarded, anyway.
### Hyperlinks
There are some warnings with respect to malformed hyperlinks:
* ignoring leading/trailing whitespace in link
There is whitespace at the beginning or the end of the contents of L<...>.
* alternative text/node '%s' contains non-escaped | or /
The characters `|` and `/` are special in the L<...> context. Although the hyperlink parser does its best to determine which "/" is text and which is a delimiter in case of doubt, one ought to escape these literal characters like this:
```
/ E<sol>
| E<verbar>
```
Note that the line number of the error/warning may refer to the line number of the start of the paragraph in which the error/warning exists, not the line number that the error/warning is on. This bug is present in errors/warnings related to formatting codes. *This should be fixed.*
RETURN VALUE
-------------
**podchecker** returns the number of POD syntax errors found or -1 if there were no POD commands at all found in the file.
EXAMPLES
--------
See ["SYNOPSIS"](#SYNOPSIS)
SCRIPTS
-------
The **podchecker** script that comes with this distribution is a lean wrapper around this module. See the online manual with
```
podchecker -help
podchecker -man
```
INTERFACE
---------
While checking, this module collects document properties, e.g. the nodes for hyperlinks (`=headX`, `=item`) and index entries (`X<>`). POD translators can use this feature to syntax-check and get the nodes in a first pass before actually starting to convert. This is expensive in terms of execution time, but allows for very robust conversions.
Since v1.24 the **Pod::Checker** module uses only the **poderror** method to print errors and warnings. The summary output (e.g. "Pod syntax OK") has been dropped from the module and has been included in **podchecker** (the script). This allows users of **Pod::Checker** to control completely the output behavior. Users of **podchecker** (the script) get the well-known behavior.
v1.45 inherits from <Pod::Simple> as opposed to all previous versions inheriting from Pod::Parser. Do **not** use Pod::Simple's interface when using Pod::Checker unless it is documented somewhere on this page. I repeat, DO **NOT** USE POD::SIMPLE'S INTERFACE.
The following list documents the overrides to Pod::Simple, primarily to make <Pod::Coverage> happy:
end\_B end\_C end\_Document end\_F end\_I end\_L end\_Para end\_S end\_X end\_fcode end\_for end\_head end\_head1 end\_head2 end\_head3 end\_head4 end\_item end\_item\_bullet end\_item\_number end\_item\_text handle\_pod\_and\_cut handle\_text handle\_whiteline hyperlink scream start\_B start\_C start\_Data start\_F start\_I start\_L start\_Para start\_S start\_Verbatim start\_X start\_fcode start\_for start\_head start\_head1 start\_head2 start\_head3 start\_head4 start\_item\_bullet start\_item\_number start\_item\_text start\_over start\_over\_block start\_over\_bullet start\_over\_empty start\_over\_number start\_over\_text whine
`Pod::Checker->new( %options )`
Return a reference to a new Pod::Checker object that inherits from Pod::Simple and is used for calling the required methods later. The following options are recognized:
`-warnings => num` Print warnings if `num` is true. The higher the value of `num`, the more warnings are printed. Currently there are only levels 1 and 2.
`-quiet => num` If `num` is true, do not print any errors/warnings. This is useful when Pod::Checker is used to munge POD code into plain text from within POD formatters.
`$checker->poderror( @args )`
`$checker->poderror( {%opts}, @args )`
Internal method for printing errors and warnings. If no options are given, simply prints "@\_". The following options are recognized and used to form the output:
```
-msg
```
A message to print prior to `@args`.
```
-line
```
The line number the error occurred in.
```
-file
```
The file (name) the error occurred in. Defaults to the name of the current file being processed.
```
-severity
```
The error level, should be 'WARNING' or 'ERROR'.
`$checker->num_errors()`
Set (if argument specified) and retrieve the number of errors found.
`$checker->num_warnings()`
Set (if argument specified) and retrieve the number of warnings found.
`$checker->name()`
Set (if argument specified) and retrieve the canonical name of POD as found in the `=head1 NAME` section.
`$checker->node()`
Add (if argument specified) and retrieve the nodes (as defined by `=headX` and `=item`) of the current POD. The nodes are returned in the order of their occurrence. They consist of plain text, each piece of whitespace is collapsed to a single blank.
`$checker->idx()`
Add (if argument specified) and retrieve the index entries (as defined by `X<>`) of the current POD. They consist of plain text, each piece of whitespace is collapsed to a single blank.
`$checker->hyperlinks()`
Retrieve an array containing the hyperlinks to things outside the current POD (as defined by `L<>`).
Each is an instance of a class with the following methods:
line() Returns the approximate line number in which the link was encountered
type() Returns the type of the link; one of: `"url"` for things like `http://www.foo`, `"man"` for man pages, or `"pod"`.
page() Returns the linked-to page or url.
node() Returns the anchor or node within the linked-to page, or an empty string (`""`) if none appears in the link.
AUTHOR
------
Please report bugs using <http://rt.cpan.org>.
Brad Appleton <[email protected]> (initial version), Marek Rouchal <[email protected]>, Marc Green <[email protected]> (port to Pod::Simple) Ricardo Signes <[email protected]> (more porting to Pod::Simple) Karl Williamson <[email protected]> (more porting to Pod::Simple)
Based on code for **Pod::Text::pod2text()** written by Tom Christiansen <[email protected]>
| programming_docs |
perl Archive::Tar Archive::Tar
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Object Methods](#Object-Methods)
+ [Archive::Tar->new( [$file, $compressed] )](#Archive::Tar-%3Enew(-%5B%24file,-%24compressed%5D-))
+ [$tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] )](#%24tar-%3Eread-(-%24filename%7C%24handle,-%5B%24compressed,-%7Bopt-=%3E-'val'%7D%5D-))
+ [$tar->contains\_file( $filename )](#%24tar-%3Econtains_file(-%24filename-))
+ [$tar->extract( [@filenames] )](#%24tar-%3Eextract(-%5B@filenames%5D-))
+ [$tar->extract\_file( $file, [$extract\_path] )](#%24tar-%3Eextract_file(-%24file,-%5B%24extract_path%5D-))
+ [$tar->list\_files( [\@properties] )](#%24tar-%3Elist_files(-%5B%5C@properties%5D-))
+ [$tar->get\_files( [@filenames] )](#%24tar-%3Eget_files(-%5B@filenames%5D-))
+ [$tar->get\_content( $file )](#%24tar-%3Eget_content(-%24file-))
+ [$tar->replace\_content( $file, $content )](#%24tar-%3Ereplace_content(-%24file,-%24content-))
+ [$tar->rename( $file, $new\_name )](#%24tar-%3Erename(-%24file,-%24new_name-))
+ [$tar->chmod( $file, $mode )](#%24tar-%3Echmod(-%24file,-%24mode-))
+ [$tar->chown( $file, $uname [, $gname] )](#%24tar-%3Echown(-%24file,-%24uname-%5B,-%24gname%5D-))
+ [$tar->remove (@filenamelist)](#%24tar-%3Eremove-(@filenamelist))
+ [$tar->clear](#%24tar-%3Eclear)
+ [$tar->write ( [$file, $compressed, $prefix] )](#%24tar-%3Ewrite-(-%5B%24file,-%24compressed,-%24prefix%5D-))
+ [$tar->add\_files( @filenamelist )](#%24tar-%3Eadd_files(-@filenamelist-))
+ [$tar->add\_data ( $filename, $data, [$opthashref] )](#%24tar-%3Eadd_data-(-%24filename,-%24data,-%5B%24opthashref%5D-))
+ [$tar->error( [$BOOL] )](#%24tar-%3Eerror(-%5B%24BOOL%5D-))
+ [$tar->setcwd( $cwd );](#%24tar-%3Esetcwd(-%24cwd-);)
* [Class Methods](#Class-Methods)
+ [Archive::Tar->create\_archive($file, $compressed, @filelist)](#Archive::Tar-%3Ecreate_archive(%24file,-%24compressed,-@filelist))
+ [Archive::Tar->iter( $filename, [ $compressed, {opt => $val} ] )](#Archive::Tar-%3Eiter(-%24filename,-%5B-%24compressed,-%7Bopt-=%3E-%24val%7D-%5D-))
+ [Archive::Tar->list\_archive($file, $compressed, [\@properties])](#Archive::Tar-%3Elist_archive(%24file,-%24compressed,-%5B%5C@properties%5D))
+ [Archive::Tar->extract\_archive($file, $compressed)](#Archive::Tar-%3Eextract_archive(%24file,-%24compressed))
+ [$bool = Archive::Tar->has\_io\_string](#%24bool-=-Archive::Tar-%3Ehas_io_string)
+ [$bool = Archive::Tar->has\_perlio](#%24bool-=-Archive::Tar-%3Ehas_perlio)
+ [$bool = Archive::Tar->has\_zlib\_support](#%24bool-=-Archive::Tar-%3Ehas_zlib_support)
+ [$bool = Archive::Tar->has\_bzip2\_support](#%24bool-=-Archive::Tar-%3Ehas_bzip2_support)
+ [$bool = Archive::Tar->has\_xz\_support](#%24bool-=-Archive::Tar-%3Ehas_xz_support)
+ [Archive::Tar->can\_handle\_compressed\_files](#Archive::Tar-%3Ecan_handle_compressed_files)
* [GLOBAL VARIABLES](#GLOBAL-VARIABLES)
+ [$Archive::Tar::FOLLOW\_SYMLINK](#%24Archive::Tar::FOLLOW_SYMLINK)
+ [$Archive::Tar::CHOWN](#%24Archive::Tar::CHOWN)
+ [$Archive::Tar::CHMOD](#%24Archive::Tar::CHMOD)
+ [$Archive::Tar::SAME\_PERMISSIONS](#%24Archive::Tar::SAME_PERMISSIONS)
+ [$Archive::Tar::DO\_NOT\_USE\_PREFIX](#%24Archive::Tar::DO_NOT_USE_PREFIX)
+ [$Archive::Tar::DEBUG](#%24Archive::Tar::DEBUG)
+ [$Archive::Tar::WARN](#%24Archive::Tar::WARN)
+ [$Archive::Tar::error](#%24Archive::Tar::error)
+ [$Archive::Tar::INSECURE\_EXTRACT\_MODE](#%24Archive::Tar::INSECURE_EXTRACT_MODE)
+ [$Archive::Tar::HAS\_PERLIO](#%24Archive::Tar::HAS_PERLIO)
+ [$Archive::Tar::HAS\_IO\_STRING](#%24Archive::Tar::HAS_IO_STRING)
+ [$Archive::Tar::ZERO\_PAD\_NUMBERS](#%24Archive::Tar::ZERO_PAD_NUMBERS)
+ [Tuning the way RESOLVE\_SYMLINK will works](#Tuning-the-way-RESOLVE_SYMLINK-will-works)
* [FAQ](#FAQ)
* [CAVEATS](#CAVEATS)
* [TODO](#TODO)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Archive::Tar - module for manipulations of tar archives
SYNOPSIS
--------
```
use Archive::Tar;
my $tar = Archive::Tar->new;
$tar->read('origin.tgz');
$tar->extract();
$tar->add_files('file/foo.pl', 'docs/README');
$tar->add_data('file/baz.txt', 'This is the contents now');
$tar->rename('oldname', 'new/file/name');
$tar->chown('/', 'root');
$tar->chown('/', 'root:root');
$tar->chmod('/tmp', '1777');
$tar->write('files.tar'); # plain tar
$tar->write('files.tgz', COMPRESS_GZIP); # gzip compressed
$tar->write('files.tbz', COMPRESS_BZIP); # bzip2 compressed
$tar->write('files.txz', COMPRESS_XZ); # xz compressed
```
DESCRIPTION
-----------
Archive::Tar provides an object oriented mechanism for handling tar files. It provides class methods for quick and easy files handling while also allowing for the creation of tar file objects for custom manipulation. If you have the IO::Zlib module installed, Archive::Tar will also support compressed or gzipped tar files.
An object of class Archive::Tar represents a .tar(.gz) archive full of files and things.
Object Methods
---------------
###
Archive::Tar->new( [$file, $compressed] )
Returns a new Tar object. If given any arguments, `new()` calls the `read()` method automatically, passing on the arguments provided to the `read()` method.
If `new()` is invoked with arguments and the `read()` method fails for any reason, `new()` returns undef.
###
$tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] )
Read the given tar file into memory. The first argument can either be the name of a file or a reference to an already open filehandle (or an IO::Zlib object if it's compressed)
The `read` will *replace* any previous content in `$tar`!
The second argument may be considered optional, but remains for backwards compatibility. Archive::Tar now looks at the file magic to determine what class should be used to open the file and will transparently Do The Right Thing.
Archive::Tar will warn if you try to pass a bzip2 / xz compressed file and the IO::Uncompress::Bunzip2 / IO::Uncompress::UnXz are not available and simply return.
Note that you can currently **not** pass a `gzip` compressed filehandle, which is not opened with `IO::Zlib`, a `bzip2` compressed filehandle, which is not opened with `IO::Uncompress::Bunzip2`, a `xz` compressed filehandle, which is not opened with `IO::Uncompress::UnXz`, nor a string containing the full archive information (either compressed or uncompressed). These are worth while features, but not currently implemented. See the `TODO` section.
The third argument can be a hash reference with options. Note that all options are case-sensitive.
limit Do not read more than `limit` files. This is useful if you have very big archives, and are only interested in the first few files.
filter Can be set to a regular expression. Only files with names that match the expression will be read.
md5 Set to 1 and the md5sum of files will be returned (instead of file data) my $iter = Archive::Tar->iter( $file, 1, {md5 => 1} ); while( my $f = $iter->() ) { print $f->data . "\t" . $f->full\_path . $/; }
extract If set to true, immediately extract entries when reading them. This gives you the same memory break as the `extract_archive` function. Note however that entries will not be read into memory, but written straight to disk. This means no `Archive::Tar::File` objects are created for you to inspect.
All files are stored internally as `Archive::Tar::File` objects. Please consult the <Archive::Tar::File> documentation for details.
Returns the number of files read in scalar context, and a list of `Archive::Tar::File` objects in list context.
###
$tar->contains\_file( $filename )
Check if the archive contains a certain file. It will return true if the file is in the archive, false otherwise.
Note however, that this function does an exact match using `eq` on the full path. So it cannot compensate for case-insensitive file- systems or compare 2 paths to see if they would point to the same underlying file.
###
$tar->extract( [@filenames] )
Write files whose names are equivalent to any of the names in `@filenames` to disk, creating subdirectories as necessary. This might not work too well under VMS. Under MacPerl, the file's modification time will be converted to the MacOS zero of time, and appropriate conversions will be done to the path. However, the length of each element of the path is not inspected to see whether it's longer than MacOS currently allows (32 characters).
If `extract` is called without a list of file names, the entire contents of the archive are extracted.
Returns a list of filenames extracted.
###
$tar->extract\_file( $file, [$extract\_path] )
Write an entry, whose name is equivalent to the file name provided to disk. Optionally takes a second parameter, which is the full native path (including filename) the entry will be written to.
For example:
```
$tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
$tar->extract_file( $at_file_object, 'name/i/want/to/give/it' );
```
Returns true on success, false on failure.
###
$tar->list\_files( [\@properties] )
Returns a list of the names of all the files in the archive.
If `list_files()` is passed an array reference as its first argument it returns a list of hash references containing the requested properties of each file. The following list of properties is supported: name, size, mtime (last modified date), mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix.
Passing an array reference containing only one element, 'name', is special cased to return a list of names rather than a list of hash references, making it equivalent to calling `list_files` without arguments.
###
$tar->get\_files( [@filenames] )
Returns the `Archive::Tar::File` objects matching the filenames provided. If no filename list was passed, all `Archive::Tar::File` objects in the current Tar object are returned.
Please refer to the `Archive::Tar::File` documentation on how to handle these objects.
###
$tar->get\_content( $file )
Return the content of the named file.
###
$tar->replace\_content( $file, $content )
Make the string $content be the content for the file named $file.
###
$tar->rename( $file, $new\_name )
Rename the file of the in-memory archive to $new\_name.
Note that you must specify a Unix path for $new\_name, since per tar standard, all files in the archive must be Unix paths.
Returns true on success and false on failure.
###
$tar->chmod( $file, $mode )
Change mode of $file to $mode.
Returns true on success and false on failure.
###
$tar->chown( $file, $uname [, $gname] )
Change owner $file to $uname and $gname.
Returns true on success and false on failure.
###
$tar->remove (@filenamelist)
Removes any entries with names matching any of the given filenames from the in-memory archive. Returns a list of `Archive::Tar::File` objects that remain.
###
$tar->clear
`clear` clears the current in-memory archive. This effectively gives you a 'blank' object, ready to be filled again. Note that `clear` only has effect on the object, not the underlying tarfile.
###
$tar->write ( [$file, $compressed, $prefix] )
Write the in-memory archive to disk. The first argument can either be the name of a file or a reference to an already open filehandle (a GLOB reference).
The second argument is used to indicate compression. You can compress using `gzip`, `bzip2` or `xz`. If you pass a digit, it's assumed to be the `gzip` compression level (between 1 and 9), but the use of constants is preferred:
```
# write a gzip compressed file
$tar->write( 'out.tgz', COMPRESS_GZIP );
# write a bzip compressed file
$tar->write( 'out.tbz', COMPRESS_BZIP );
# write a xz compressed file
$tar->write( 'out.txz', COMPRESS_XZ );
```
Note that when you pass in a filehandle, the compression argument is ignored, as all files are printed verbatim to your filehandle. If you wish to enable compression with filehandles, use an `IO::Zlib`, `IO::Compress::Bzip2` or `IO::Compress::Xz` filehandle instead.
The third argument is an optional prefix. All files will be tucked away in the directory you specify as prefix. So if you have files 'a' and 'b' in your archive, and you specify 'foo' as prefix, they will be written to the archive as 'foo/a' and 'foo/b'.
If no arguments are given, `write` returns the entire formatted archive as a string, which could be useful if you'd like to stuff the archive into a socket or a pipe to gzip or something.
###
$tar->add\_files( @filenamelist )
Takes a list of filenames and adds them to the in-memory archive.
The path to the file is automatically converted to a Unix like equivalent for use in the archive, and, if on MacOS, the file's modification time is converted from the MacOS epoch to the Unix epoch. So tar archives created on MacOS with **Archive::Tar** can be read both with *tar* on Unix and applications like *suntar* or *Stuffit Expander* on MacOS.
Be aware that the file's type/creator and resource fork will be lost, which is usually what you want in cross-platform archives.
Instead of a filename, you can also pass it an existing `Archive::Tar::File` object from, for example, another archive. The object will be clone, and effectively be a copy of the original, not an alias.
Returns a list of `Archive::Tar::File` objects that were just added.
###
$tar->add\_data ( $filename, $data, [$opthashref] )
Takes a filename, a scalar full of data and optionally a reference to a hash with specific options.
Will add a file to the in-memory archive, with name `$filename` and content `$data`. Specific properties can be set using `$opthashref`. The following list of properties is supported: name, size, mtime (last modified date), mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix, type. (On MacOS, the file's path and modification times are converted to Unix equivalents.)
Valid values for the file type are the following constants defined by Archive::Tar::Constant:
FILE Regular file.
HARDLINK SYMLINK Hard and symbolic ("soft") links; linkname should specify target.
CHARDEV BLOCKDEV Character and block devices. devmajor and devminor should specify the major and minor device numbers.
DIR Directory.
FIFO FIFO (named pipe).
SOCKET Socket.
Returns the `Archive::Tar::File` object that was just added, or `undef` on failure.
###
$tar->error( [$BOOL] )
Returns the current error string (usually, the last error reported). If a true value was specified, it will give the `Carp::longmess` equivalent of the error, in effect giving you a stacktrace.
For backwards compatibility, this error is also available as `$Archive::Tar::error` although it is much recommended you use the method call instead.
###
$tar->setcwd( $cwd );
`Archive::Tar` needs to know the current directory, and it will run `Cwd::cwd()` *every* time it extracts a *relative* entry from the tarfile and saves it in the file system. (As of version 1.30, however, `Archive::Tar` will use the speed optimization described below automatically, so it's only relevant if you're using `extract_file()`).
Since `Archive::Tar` doesn't change the current directory internally while it is extracting the items in a tarball, all calls to `Cwd::cwd()` can be avoided if we can guarantee that the current directory doesn't get changed externally.
To use this performance boost, set the current directory via
```
use Cwd;
$tar->setcwd( cwd() );
```
once before calling a function like `extract_file` and `Archive::Tar` will use the current directory setting from then on and won't call `Cwd::cwd()` internally.
To switch back to the default behaviour, use
```
$tar->setcwd( undef );
```
and `Archive::Tar` will call `Cwd::cwd()` internally again.
If you're using `Archive::Tar`'s `extract()` method, `setcwd()` will be called for you.
Class Methods
--------------
###
Archive::Tar->create\_archive($file, $compressed, @filelist)
Creates a tar file from the list of files provided. The first argument can either be the name of the tar file to create or a reference to an open file handle (e.g. a GLOB reference).
The second argument is used to indicate compression. You can compress using `gzip`, `bzip2` or `xz`. If you pass a digit, it's assumed to be the `gzip` compression level (between 1 and 9), but the use of constants is preferred:
```
# write a gzip compressed file
Archive::Tar->create_archive( 'out.tgz', COMPRESS_GZIP, @filelist );
# write a bzip compressed file
Archive::Tar->create_archive( 'out.tbz', COMPRESS_BZIP, @filelist );
# write a xz compressed file
Archive::Tar->create_archive( 'out.txz', COMPRESS_XZ, @filelist );
```
Note that when you pass in a filehandle, the compression argument is ignored, as all files are printed verbatim to your filehandle. If you wish to enable compression with filehandles, use an `IO::Zlib`, `IO::Compress::Bzip2` or `IO::Compress::Xz` filehandle instead.
The remaining arguments list the files to be included in the tar file. These files must all exist. Any files which don't exist or can't be read are silently ignored.
If the archive creation fails for any reason, `create_archive` will return false. Please use the `error` method to find the cause of the failure.
Note that this method does not write `on the fly` as it were; it still reads all the files into memory before writing out the archive. Consult the FAQ below if this is a problem.
###
Archive::Tar->iter( $filename, [ $compressed, {opt => $val} ] )
Returns an iterator function that reads the tar file without loading it all in memory. Each time the function is called it will return the next file in the tarball. The files are returned as `Archive::Tar::File` objects. The iterator function returns the empty list once it has exhausted the files contained.
The second argument can be a hash reference with options, which are identical to the arguments passed to `read()`.
Example usage:
```
my $next = Archive::Tar->iter( "example.tar.gz", 1, {filter => qr/\.pm$/} );
while( my $f = $next->() ) {
print $f->name, "\n";
$f->extract or warn "Extraction failed";
# ....
}
```
###
Archive::Tar->list\_archive($file, $compressed, [\@properties])
Returns a list of the names of all the files in the archive. The first argument can either be the name of the tar file to list or a reference to an open file handle (e.g. a GLOB reference).
If `list_archive()` is passed an array reference as its third argument it returns a list of hash references containing the requested properties of each file. The following list of properties is supported: full\_path, name, size, mtime (last modified date), mode, uid, gid, linkname, uname, gname, devmajor, devminor, prefix, type.
See `Archive::Tar::File` for details about supported properties.
Passing an array reference containing only one element, 'name', is special cased to return a list of names rather than a list of hash references.
###
Archive::Tar->extract\_archive($file, $compressed)
Extracts the contents of the tar file. The first argument can either be the name of the tar file to create or a reference to an open file handle (e.g. a GLOB reference). All relative paths in the tar file will be created underneath the current working directory.
`extract_archive` will return a list of files it extracted. If the archive extraction fails for any reason, `extract_archive` will return false. Please use the `error` method to find the cause of the failure.
###
$bool = Archive::Tar->has\_io\_string
Returns true if we currently have `IO::String` support loaded.
Either `IO::String` or `perlio` support is needed to support writing stringified archives. Currently, `perlio` is the preferred method, if available.
See the `GLOBAL VARIABLES` section to see how to change this preference.
###
$bool = Archive::Tar->has\_perlio
Returns true if we currently have `perlio` support loaded.
This requires `perl-5.8` or higher, compiled with `perlio`
Either `IO::String` or `perlio` support is needed to support writing stringified archives. Currently, `perlio` is the preferred method, if available.
See the `GLOBAL VARIABLES` section to see how to change this preference.
###
$bool = Archive::Tar->has\_zlib\_support
Returns true if `Archive::Tar` can extract `zlib` compressed archives
###
$bool = Archive::Tar->has\_bzip2\_support
Returns true if `Archive::Tar` can extract `bzip2` compressed archives
###
$bool = Archive::Tar->has\_xz\_support
Returns true if `Archive::Tar` can extract `xz` compressed archives
###
Archive::Tar->can\_handle\_compressed\_files
A simple checking routine, which will return true if `Archive::Tar` is able to uncompress compressed archives on the fly with `IO::Zlib`, `IO::Compress::Bzip2` and `IO::Compress::Xz` or false if not both are installed.
You can use this as a shortcut to determine whether `Archive::Tar` will do what you think before passing compressed archives to its `read` method.
GLOBAL VARIABLES
-----------------
###
$Archive::Tar::FOLLOW\_SYMLINK
Set this variable to `1` to make `Archive::Tar` effectively make a copy of the file when extracting. Default is `0`, which means the symlink stays intact. Of course, you will have to pack the file linked to as well.
This option is checked when you write out the tarfile using `write` or `create_archive`.
This works just like `/bin/tar`'s `-h` option.
###
$Archive::Tar::CHOWN
By default, `Archive::Tar` will try to `chown` your files if it is able to. In some cases, this may not be desired. In that case, set this variable to `0` to disable `chown`-ing, even if it were possible.
The default is `1`.
###
$Archive::Tar::CHMOD
By default, `Archive::Tar` will try to `chmod` your files to whatever mode was specified for the particular file in the archive. In some cases, this may not be desired. In that case, set this variable to `0` to disable `chmod`-ing.
The default is `1`.
###
$Archive::Tar::SAME\_PERMISSIONS
When, `$Archive::Tar::CHMOD` is enabled, this setting controls whether the permissions on files from the archive are used without modification of if they are filtered by removing any setid bits and applying the current umask.
The default is `1` for the root user and `0` for normal users.
###
$Archive::Tar::DO\_NOT\_USE\_PREFIX
By default, `Archive::Tar` will try to put paths that are over 100 characters in the `prefix` field of your tar header, as defined per POSIX-standard. However, some (older) tar programs do not implement this spec. To retain compatibility with these older or non-POSIX compliant versions, you can set the `$DO_NOT_USE_PREFIX` variable to a true value, and `Archive::Tar` will use an alternate way of dealing with paths over 100 characters by using the `GNU Extended Header` feature.
Note that clients who do not support the `GNU Extended Header` feature will not be able to read these archives. Such clients include tars on `Solaris`, `Irix` and `AIX`.
The default is `0`.
###
$Archive::Tar::DEBUG
Set this variable to `1` to always get the `Carp::longmess` output of the warnings, instead of the regular `carp`. This is the same message you would get by doing:
```
$tar->error(1);
```
Defaults to `0`.
###
$Archive::Tar::WARN
Set this variable to `0` if you do not want any warnings printed. Personally I recommend against doing this, but people asked for the option. Also, be advised that this is of course not threadsafe.
Defaults to `1`.
###
$Archive::Tar::error
Holds the last reported error. Kept for historical reasons, but its use is very much discouraged. Use the `error()` method instead:
```
warn $tar->error unless $tar->extract;
```
Note that in older versions of this module, the `error()` method would return an effectively global value even when called an instance method as above. This has since been fixed, and multiple instances of `Archive::Tar` now have separate error strings.
###
$Archive::Tar::INSECURE\_EXTRACT\_MODE
This variable indicates whether `Archive::Tar` should allow files to be extracted outside their current working directory.
Allowing this could have security implications, as a malicious tar archive could alter or replace any file the extracting user has permissions to. Therefor, the default is to not allow insecure extractions.
If you trust the archive, or have other reasons to allow the archive to write files outside your current working directory, set this variable to `true`.
Note that this is a backwards incompatible change from version `1.36` and before.
###
$Archive::Tar::HAS\_PERLIO
This variable holds a boolean indicating if we currently have `perlio` support loaded. This will be enabled for any perl greater than `5.8` compiled with `perlio`.
If you feel strongly about disabling it, set this variable to `false`. Note that you will then need `IO::String` installed to support writing stringified archives.
Don't change this variable unless you **really** know what you're doing.
###
$Archive::Tar::HAS\_IO\_STRING
This variable holds a boolean indicating if we currently have `IO::String` support loaded. This will be enabled for any perl that has a loadable `IO::String` module.
If you feel strongly about disabling it, set this variable to `false`. Note that you will then need `perlio` support from your perl to be able to write stringified archives.
Don't change this variable unless you **really** know what you're doing.
###
$Archive::Tar::ZERO\_PAD\_NUMBERS
This variable holds a boolean indicating if we will create zero padded numbers for `size`, `mtime` and `checksum`. The default is `0`, indicating that we will create space padded numbers. Added for compatibility with `busybox` implementations.
###
Tuning the way RESOLVE\_SYMLINK will works
```
You can tune the behaviour by setting the $Archive::Tar::RESOLVE_SYMLINK variable,
or $ENV{PERL5_AT_RESOLVE_SYMLINK} before loading the module Archive::Tar.
Values can be one of the following:
none
Disable this mechanism and failed as it was in previous version (<1.88)
speed (default)
If you prefer speed
this will read again the whole archive using read() so all entries
will be available
memory
If you prefer memory
Limitation
It won't work for terminal, pipe or sockets or every non seekable source.
```
FAQ
---
What's the minimum perl version required to run Archive::Tar? You will need perl version 5.005\_03 or newer.
Isn't Archive::Tar slow? Yes it is. It's pure perl, so it's a lot slower then your `/bin/tar` However, it's very portable. If speed is an issue, consider using `/bin/tar` instead.
Isn't Archive::Tar heavier on memory than /bin/tar? Yes it is, see previous answer. Since `Compress::Zlib` and therefore `IO::Zlib` doesn't support `seek` on their filehandles, there is little choice but to read the archive into memory. This is ok if you want to do in-memory manipulation of the archive.
If you just want to extract, use the `extract_archive` class method instead. It will optimize and write to disk immediately.
Another option is to use the `iter` class method to iterate over the files in the tarball without reading them all in memory at once.
Can you lazy-load data instead? In some cases, yes. You can use the `iter` class method to iterate over the files in the tarball without reading them all in memory at once.
How much memory will an X kb tar file need? Probably more than X kb, since it will all be read into memory. If this is a problem, and you don't need to do in memory manipulation of the archive, consider using the `iter` class method, or `/bin/tar` instead.
What do you do with unsupported filetypes in an archive? `Unix` has a few filetypes that aren't supported on other platforms, like `Win32`. If we encounter a `hardlink` or `symlink` we'll just try to make a copy of the original file, rather than throwing an error.
This does require you to read the entire archive in to memory first, since otherwise we wouldn't know what data to fill the copy with. (This means that you cannot use the class methods, including `iter` on archives that have incompatible filetypes and still expect things to work).
For other filetypes, like `chardevs` and `blockdevs` we'll warn that the extraction of this particular item didn't work.
I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly! By default, `Archive::Tar` is in a completely POSIX-compatible mode, which uses the POSIX-specification of `tar` to store files. For paths greater than 100 characters, this is done using the `POSIX header prefix`. Non-POSIX-compatible clients may not support this part of the specification, and may only support the `GNU Extended Header` functionality. To facilitate those clients, you can set the `$Archive::Tar::DO_NOT_USE_PREFIX` variable to `true`. See the `GLOBAL VARIABLES` section for details on this variable.
Note that GNU tar earlier than version 1.14 does not cope well with the `POSIX header prefix`. If you use such a version, consider setting the `$Archive::Tar::DO_NOT_USE_PREFIX` variable to `true`.
How do I extract only files that have property X from an archive? Sometimes, you might not wish to extract a complete archive, just the files that are relevant to you, based on some criteria.
You can do this by filtering a list of `Archive::Tar::File` objects based on your criteria. For example, to extract only files that have the string `foo` in their title, you would use:
```
$tar->extract(
grep { $_->full_path =~ /foo/ } $tar->get_files
);
```
This way, you can filter on any attribute of the files in the archive. Consult the `Archive::Tar::File` documentation on how to use these objects.
How do I access .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 accesses 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 Archive::Tar;
open F, "uncompress -c $filename |";
my $tar = Archive::Tar->new(*F);
...
```
and this with `gunzip`
```
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 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 handle Unicode strings? `Archive::Tar` uses byte semantics for any files it reads from or writes to disk. This is not a problem if you only deal with files and never look at their content or work solely with byte strings. But if you use Unicode strings with character semantics, some additional steps need to be taken.
For example, if you add a Unicode string like
```
# Problem
$tar->add_data('file.txt', "Euro: \x{20AC}");
```
then there will be a problem later when the tarfile gets written out to disk via `$tar->write()`:
```
Wide character in print at .../Archive/Tar.pm line 1014.
```
The data was added as a Unicode string and when writing it out to disk, the `:utf8` line discipline wasn't set by `Archive::Tar`, so Perl tried to convert the string to ISO-8859 and failed. The written file now contains garbage.
For this reason, Unicode strings need to be converted to UTF-8-encoded bytestrings before they are handed off to `add_data()`:
```
use Encode;
my $data = "Accented character: \x{20AC}";
$data = encode('utf8', $data);
$tar->add_data('file.txt', $data);
```
A opposite problem occurs if you extract a UTF8-encoded file from a tarball. Using `get_content()` on the `Archive::Tar::File` object will return its content as a bytestring, not as a Unicode string.
If you want it to be a Unicode string (because you want character semantics with operations like regular expression matching), you need to decode the UTF8-encoded content and have Perl convert it into a Unicode string:
```
use Encode;
my $data = $tar->get_content();
# Make it a Unicode string
$data = decode('utf8', $data);
```
There is no easy way to provide this functionality in `Archive::Tar`, because a tarball can contain many files, and each of which could be encoded in a different way.
CAVEATS
-------
The AIX tar does not fill all unused space in the tar archive with 0x00. This sometimes leads to warning messages from `Archive::Tar`.
```
Invalid header block at offset nnn
```
A fix for that problem is scheduled to be released in the following levels of AIX, all of which should be coming out in the 4th quarter of 2009:
```
AIX 5.3 TL7 SP10
AIX 5.3 TL8 SP8
AIX 5.3 TL9 SP5
AIX 5.3 TL10 SP2
AIX 6.1 TL0 SP11
AIX 6.1 TL1 SP7
AIX 6.1 TL2 SP6
AIX 6.1 TL3 SP3
```
The IBM APAR number for this problem is IZ50240 (Reported component ID: 5765G0300 / AIX 5.3). It is possible to get an ifix for that problem. If you need an ifix please contact your local IBM AIX support.
TODO
----
Check if passed in handles are open for read/write Currently I don't know of any portable pure perl way to do this. Suggestions welcome.
Allow archives to be passed in as string Currently, we only allow opened filehandles or filenames, but not strings. The internals would need some reworking to facilitate stringified archives.
Facilitate processing an opened filehandle of a compressed archive Currently, we only support this if the filehandle is an IO::Zlib object. Environments, like apache, will present you with an opened filehandle to an uploaded file, which might be a compressed archive.
SEE ALSO
---------
The GNU tar specification `http://www.gnu.org/software/tar/manual/tar.html`
The PAX format specification The specification which tar derives from; `http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html`
A comparison of GNU and POSIX tar standards; `http://www.delorie.com/gnu/docs/tar/tar_114.html`
GNU tar intends to switch to POSIX compatibility GNU Tar authors have expressed their intention to become completely POSIX-compatible; `http://www.gnu.org/software/tar/manual/html_node/Formats.html`
A Comparison between various tar implementations Lists known issues and incompatibilities; `http://gd.tuwien.ac.at/utils/archivers/star/README.otherbugs`
AUTHOR
------
This module by Jos Boumans <[email protected]>.
Please reports bugs to <[email protected]>.
ACKNOWLEDGEMENTS
----------------
Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney, Gisle Aas, Rainer Tammer and especially Andrew Savige for their help and suggestions.
COPYRIGHT
---------
This module is copyright (c) 2002 - 2009 Jos Boumans <[email protected]>. All rights reserved.
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Pod::Simple::PullParserStartToken Pod::Simple::PullParserStartToken
=================================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SEE ALSO](#SEE-ALSO1)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::PullParserStartToken -- start-tokens from Pod::Simple::PullParser
SYNOPSIS
--------
(See <Pod::Simple::PullParser>)
DESCRIPTION
-----------
When you do $parser->get\_token on a <Pod::Simple::PullParser> object, 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 start-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 start-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*`
$token->attr(*attrname*) This returns the value of the *attrname* attribute for this start-token object, or undef.
For example, parsing a L<Foo/"Bar"> link will produce a start-token with a "to" attribute with the value "Foo", a "type" attribute with the value "pod", and a "section" attribute with the value "Bar".
$token->attr(*attrname*, *newvalue*) This sets the *attrname* attribute for this start-token object to *newvalue*. You probably won't need to do this.
$token->attr\_hash This returns the hashref that is the attribute set for this start-token. This is useful if (for example) you want to ask what all the attributes are -- you can just do `keys %{$token->attr_hash}`
You're unlikely to ever need to construct an object of this class for yourself, but if you want to, call `Pod::Simple::PullParserStartToken->new( *tagname*, *attrhash* )`
SEE ALSO
---------
<Pod::Simple::PullParserToken>, <Pod::Simple>, <Pod::Simple::Subclassing>
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 Encode::TW Encode::TW
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::TW - Taiwan-based Chinese Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$big5 = encode("big5", $utf8); # loads Encode::TW implicitly
$utf8 = decode("big5", $big5); # ditto
```
DESCRIPTION
-----------
This module implements tradition Chinese charset encodings as used in Taiwan and Hong Kong. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
big5-eten /\bbig-?5$/i Big5 encoding (with ETen extensions)
/\bbig5-?et(en)?$/i
/\btca-?big5$/i
big5-hkscs /\bbig5-?hk(scs)?$/i
/\bhk(scs)?-?big5$/i
Big5 + Cantonese characters in Hong Kong
MacChineseTrad Big5 + Apple Vendor Mappings
cp950 Code Page 950
= Big5 + Microsoft vendor mappings
--------------------------------------------------------------------
```
To find out how to use this module in detail, see [Encode](encode).
NOTES
-----
Due to size concerns, `EUC-TW` (Extended Unix Character), `CCCII` (Chinese Character Code for Information Interchange), `BIG5PLUS` (CMEX's Big5+) and `BIG5EXT` (CMEX's Big5e) are distributed separately on CPAN, under the name <Encode::HanExtra>. That module also contains extra China-based encodings.
BUGS
----
Since the original `big5` encoding (1984) is not supported anywhere (glibc and DOS-based systems uses `big5` to mean `big5-eten`; Microsoft uses `big5` to mean `cp950`), a conscious decision was made to alias `big5` to `big5-eten`, which is the de facto superset of the original big5.
The `CNS11643` encoding files are not complete. For common `CNS11643` manipulation, please use `EUC-TW` in <Encode::HanExtra>, which contains planes 1-7.
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 Time::gmtime Time::gmtime
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
Time::gmtime - by-name interface to Perl's built-in gmtime() function
SYNOPSIS
--------
```
use Time::gmtime;
$gm = gmtime();
printf "The day in Greenwich is %s\n",
(qw(Sun Mon Tue Wed Thu Fri Sat Sun))[ $gm->wday() ];
use Time::gmtime qw(:FIELDS);
gmtime();
printf "The day in Greenwich is %s\n",
(qw(Sun Mon Tue Wed Thu Fri Sat Sun))[ $tm_wday ];
$now = gmctime();
use Time::gmtime;
use File::stat;
$date_string = gmctime(stat($file)->mtime);
```
DESCRIPTION
-----------
This module's default exports override the core gmtime() function, replacing it with a version that returns "Time::tm" objects. This object has methods that return the similarly named structure field name from the C's tm structure from *time.h*; namely sec, min, hour, mday, mon, year, wday, yday, and isdst.
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 `tm_` in front their method names. Thus, `$tm_obj->mday()` corresponds to $tm\_mday if you import the fields.
The gmctime() function provides a way of getting at the scalar sense of the original CORE::gmtime() function.
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 perlfaq3 perlfaq3
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [How do I do (anything)?](#How-do-I-do-(anything)?)
+ [How can I use Perl interactively?](#How-can-I-use-Perl-interactively?)
+ [How do I find which modules are installed on my system?](#How-do-I-find-which-modules-are-installed-on-my-system?)
+ [How do I debug my Perl programs?](#How-do-I-debug-my-Perl-programs?)
+ [How do I profile my Perl programs?](#How-do-I-profile-my-Perl-programs?)
+ [How do I cross-reference my Perl programs?](#How-do-I-cross-reference-my-Perl-programs?)
+ [Is there a pretty-printer (formatter) for Perl?](#Is-there-a-pretty-printer-(formatter)-for-Perl?)
+ [Is there an IDE or Windows Perl Editor?](#Is-there-an-IDE-or-Windows-Perl-Editor?)
+ [Where can I get Perl macros for vi?](#Where-can-I-get-Perl-macros-for-vi?)
+ [Where can I get perl-mode or cperl-mode for emacs?](#Where-can-I-get-perl-mode-or-cperl-mode-for-emacs?)
+ [How can I use curses with Perl?](#How-can-I-use-curses-with-Perl?)
+ [How can I write a GUI (X, Tk, Gtk, etc.) in 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-run-faster?)
+ [How can I make my Perl program take less memory?](#How-can-I-make-my-Perl-program-take-less-memory?)
+ [Is it safe to return a reference to local or lexical data?](#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-free-an-array-or-hash-so-my-program-shrinks?)
+ [How can I make my CGI script more efficient?](#How-can-I-make-my-CGI-script-more-efficient?)
+ [How can I hide the source for my Perl program?](#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-compile-my-Perl-program-into-byte-code-or-C?)
+ [How can I get #!perl to work on [MS-DOS,NT,...]?](#How-can-I-get-%23!perl-to-work-on-%5BMS-DOS,NT,...%5D?)
+ [Can I write useful Perl programs on the command line?](#Can-I-write-useful-Perl-programs-on-the-command-line?)
+ [Why don't Perl one-liners work on my DOS/Mac/VMS system?](#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-CGI-or-Web-programming-in-Perl?)
+ [Where can I learn about object-oriented Perl programming?](#Where-can-I-learn-about-object-oriented-Perl-programming?)
+ [Where can I learn about linking C with Perl?](#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?](#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?](#When-I-tried-to-run-my-script,-I-got-this-message.-What-does-it-mean?)
+ [What's MakeMaker?](#What's-MakeMaker?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq3 - Programming Tools
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
This section of the FAQ answers questions related to programmer tools and programming support.
###
How do I do (anything)?
Have you looked at CPAN (see <perlfaq2>)? The chances are that someone has already written a module that can solve your problem. Have you read the appropriate manpages? Here's a brief index:
Basics
<perldata> - Perl data types
<perlvar> - Perl pre-defined variables
<perlsyn> - Perl syntax
<perlop> - Perl operators and precedence
<perlsub> - Perl subroutines Execution
<perlrun> - how to execute the Perl interpreter
<perldebug> - Perl debugging Functions
<perlfunc> - Perl builtin functions Objects
<perlref> - Perl references and nested data structures
<perlmod> - Perl modules (packages and symbol tables)
<perlobj> - Perl objects
<perltie> - how to hide an object class in a simple variable
Data Structures
<perlref> - Perl references and nested data structures
<perllol> - Manipulating arrays of arrays in Perl
<perldsc> - Perl Data Structures Cookbook Modules
<perlmod> - Perl modules (packages and symbol tables)
<perlmodlib> - constructing new Perl modules and finding existing ones Regexes
<perlre> - Perl regular expressions
<perlfunc> - Perl builtin functions>
<perlop> - Perl operators and precedence
<perllocale> - Perl locale handling (internationalization and localization)
Moving to perl5
<perltrap> - Perl traps for the unwary <perl>
Linking with C
<perlxstut> - Tutorial for writing XSUBs
<perlxs> - XS language reference manual
<perlcall> - Perl calling conventions from C
<perlguts> - Introduction to the Perl API
<perlembed> - how to embed perl in your C program Various <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> (not a man-page but still useful, a collection of various essays on Perl techniques)
A crude table of contents for the Perl manpage set is found in <perltoc>.
###
How can I use Perl interactively?
The typical approach uses the Perl debugger, described in the [perldebug(1)](http://man.he.net/man1/perldebug) manpage, on an "empty" program, like this:
```
perl -de 42
```
Now just type in any legal Perl code, and it will be immediately evaluated. You can also examine the symbol table, get stack backtraces, check variable values, set breakpoints, and other operations typically found in symbolic debuggers.
You can also use <Devel::REPL> which is an interactive shell for Perl, commonly known as a REPL - Read, Evaluate, Print, Loop. It provides various handy features.
###
How do I find which modules are installed on my system?
From the command line, you can use the `cpan` command's `-l` switch:
```
$ cpan -l
```
You can also use `cpan`'s `-a` switch to create an autobundle file that `CPAN.pm` understands and can use to re-install every module:
```
$ cpan -a
```
Inside a Perl program, you can use the <ExtUtils::Installed> module to show all installed distributions, although it can take awhile to do its magic. The standard library which comes with Perl just shows up as "Perl" (although you can get those with <Module::CoreList>).
```
use ExtUtils::Installed;
my $inst = ExtUtils::Installed->new();
my @modules = $inst->modules();
```
If you want a list of all of the Perl module filenames, you can use <File::Find::Rule>:
```
use File::Find::Rule;
my @files = File::Find::Rule->
extras({follow => 1})->
file()->
name( '*.pm' )->
in( @INC )
;
```
If you do not have that module, you can do the same thing with <File::Find> which is part of the standard library:
```
use File::Find;
my @files;
find(
{
wanted => sub {
push @files, $File::Find::fullname
if -f $File::Find::fullname && /\.pm$/
},
follow => 1,
follow_skip => 2,
},
@INC
);
print join "\n", @files;
```
If you simply need to check quickly to see if a module is available, you can check for its documentation. If you can read the documentation the module is most likely installed. If you cannot read the documentation, the module might not have any (in rare cases):
```
$ perldoc Module::Name
```
You can also try to include the module in a one-liner to see if perl finds it:
```
$ perl -MModule::Name -e1
```
(If you don't receive a "Can't locate ... in @INC" error message, then Perl found the module name you asked for.)
###
How do I debug my Perl programs?
(contributed by brian d foy)
Before you do anything else, you can help yourself by ensuring that you let Perl tell you about problem areas in your code. By turning on warnings and strictures, you can head off many problems before they get too big. You can find out more about these in <strict> and <warnings>.
```
#!/usr/bin/perl
use strict;
use warnings;
```
Beyond that, the simplest debugger is the `print` function. Use it to look at values as you run your program:
```
print STDERR "The value is [$value]\n";
```
The <Data::Dumper> module can pretty-print Perl data structures:
```
use Data::Dumper qw( Dumper );
print STDERR "The hash is " . Dumper( \%hash ) . "\n";
```
Perl comes with an interactive debugger, which you can start with the `-d` switch. It's fully explained in <perldebug>.
If you'd like a graphical user interface and you have [Tk](tk), you can use `ptkdb`. It's on CPAN and available for free.
If you need something much more sophisticated and controllable, Leon Brocard's <Devel::ebug> (which you can call with the `-D` switch as `-Debug`) gives you the programmatic hooks into everything you need to write your own (without too much pain and suffering).
You can also use a commercial debugger such as Affrus (Mac OS X), Komodo from Activestate (Windows and Mac OS X), or EPIC (most platforms).
###
How do I profile my Perl programs?
(contributed by brian d foy, updated Fri Jul 25 12:22:26 PDT 2008)
The `Devel` namespace has several modules which you can use to profile your Perl programs.
The <Devel::NYTProf> (New York Times Profiler) does both statement and subroutine profiling. It's available from CPAN and you also invoke it with the `-d` switch:
```
perl -d:NYTProf some_perl.pl
```
It creates a database of the profile information that you can turn into reports. The `nytprofhtml` command turns the data into an HTML report similar to the <Devel::Cover> report:
```
nytprofhtml
```
You might also be interested in using the [Benchmark](benchmark) to measure and compare code snippets.
You can read more about profiling in *Programming Perl*, chapter 20, or *Mastering Perl*, chapter 5.
<perldebguts> documents creating a custom debugger if you need to create a special sort of profiler. brian d foy describes the process in *The Perl Journal*, "Creating a Perl Debugger", <http://www.ddj.com/184404522> , and "Profiling in Perl" <http://www.ddj.com/184404580> .
Perl.com has two interesting articles on profiling: "Profiling Perl", by Simon Cozens, <https://www.perl.com/pub/2004/06/25/profiling.html/> and "Debugging and Profiling mod\_perl Applications", by Frank Wiles, <http://www.perl.com/pub/a/2006/02/09/debug_mod_perl.html> .
Randal L. Schwartz writes about profiling in "Speeding up Your Perl Programs" for *Unix Review*, <http://www.stonehenge.com/merlyn/UnixReview/col49.html> , and "Profiling in Template Toolkit via Overriding" for *Linux Magazine*, <http://www.stonehenge.com/merlyn/LinuxMag/col75.html> .
###
How do I cross-reference my Perl programs?
The <B::Xref> module can be used to generate cross-reference reports for Perl programs.
```
perl -MO=Xref[,OPTIONS] scriptname.plx
```
###
Is there a pretty-printer (formatter) for Perl?
<Perl::Tidy> comes with a perl script <perltidy> which indents and reformats Perl scripts to make them easier to read by trying to follow the rules of the <perlstyle>. If you write Perl, or spend much time reading Perl, you will probably find it useful.
Of course, if you simply follow the guidelines in <perlstyle>, you shouldn't need to reformat. The habit of formatting your code as you write it will help prevent bugs. Your editor can and should help you with this. The perl-mode or newer cperl-mode for emacs can provide remarkable amounts of help with most (but not all) code, and even less programmable editors can provide significant assistance. Tom Christiansen and many other VI users swear by the following settings in vi and its clones:
```
set ai sw=4
map! ^O {^M}^[O^T
```
Put that in your *.exrc* file (replacing the caret characters with control characters) and away you go. In insert mode, ^T is for indenting, ^D is for undenting, and ^O is for blockdenting--as it were. A more complete example, with comments, can be found at <http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz>
###
Is there an IDE or Windows Perl Editor?
Perl programs are just plain text, so any editor will do.
If you're on Unix, you already have an IDE--Unix itself. The Unix philosophy is the philosophy of several small tools that each do one thing and do it well. It's like a carpenter's toolbox.
If you want an IDE, check the following (in alphabetical order, not order of preference):
Eclipse <http://e-p-i-c.sf.net/>
The Eclipse Perl Integration Project integrates Perl editing/debugging with Eclipse.
Enginsite <http://www.enginsite.com/>
Perl Editor by EngInSite is a complete integrated development environment (IDE) for creating, testing, and debugging Perl scripts; the tool runs on Windows 9x/NT/2000/XP or later.
IntelliJ IDEA <https://plugins.jetbrains.com/plugin/7796>
Camelcade plugin provides Perl5 support in IntelliJ IDEA and other JetBrains IDEs.
Kephra <http://kephra.sf.net>
GUI editor written in Perl using wxWidgets and Scintilla with lots of smaller features. Aims for a UI based on Perl principles like TIMTOWTDI and "easy things should be easy, hard things should be possible".
Komodo <http://www.ActiveState.com/Products/Komodo/>
ActiveState's cross-platform (as of October 2004, that's Windows, Linux, and Solaris), multi-language IDE has Perl support, including a regular expression debugger and remote debugging.
Notepad++ <http://notepad-plus.sourceforge.net/>
Open Perl IDE <http://open-perl-ide.sourceforge.net/>
Open Perl IDE is an integrated development environment for writing and debugging Perl scripts with ActiveState's ActivePerl distribution under Windows 95/98/NT/2000.
OptiPerl <http://www.optiperl.com/>
OptiPerl is a Windows IDE with simulated CGI environment, including debugger and syntax-highlighting editor.
Padre <http://padre.perlide.org/>
Padre is cross-platform IDE for Perl written in Perl using wxWidgets to provide a native look and feel. It's open source under the Artistic License. It is one of the newer Perl IDEs.
PerlBuilder <http://www.solutionsoft.com/perl.htm>
PerlBuilder is an integrated development environment for Windows that supports Perl development.
visiPerl+ <http://helpconsulting.net/visiperl/index.html>
From Help Consulting, for Windows.
Visual Perl <http://www.activestate.com/Products/Visual_Perl/>
Visual Perl is a Visual Studio.NET plug-in from ActiveState.
Zeus <http://www.zeusedit.com/lookmain.html>
Zeus for Windows is another Win32 multi-language editor/IDE that comes with support for Perl.
For editors: if you're on Unix you probably have vi or a vi clone already, and possibly an emacs too, so you may not need to download anything. In any emacs the cperl-mode (M-x cperl-mode) gives you perhaps the best available Perl editing mode in any editor.
If you are using Windows, you can use any editor that lets you work with plain text, such as NotePad or WordPad. Word processors, such as Microsoft Word or WordPerfect, typically do not work since they insert all sorts of behind-the-scenes information, although some allow you to save files as "Text Only". You can also download text editors designed specifically for programming, such as Textpad ( <http://www.textpad.com/> ) and UltraEdit ( <http://www.ultraedit.com/> ), among others.
If you are using MacOS, the same concerns apply. MacPerl (for Classic environments) comes with a simple editor. Popular external editors are BBEdit ( <http://www.barebones.com/products/bbedit/> ) or Alpha ( <http://www.his.com/~jguyer/Alpha/Alpha8.html> ). MacOS X users can use Unix editors as well.
GNU Emacs <http://www.gnu.org/software/emacs/windows/ntemacs.html>
MicroEMACS <http://www.microemacs.de/>
XEmacs <http://www.xemacs.org/Download/index.html>
Jed <http://space.mit.edu/~davis/jed/>
or a vi clone such as
Vim <http://www.vim.org/>
Vile <http://invisible-island.net/vile/vile.html>
The following are Win32 multilanguage editor/IDEs that support Perl:
MultiEdit <http://www.MultiEdit.com/>
SlickEdit <http://www.slickedit.com/>
ConTEXT <http://www.contexteditor.org/>
There is also a toyedit Text widget based editor written in Perl that is distributed with the Tk module on CPAN. The ptkdb ( <http://ptkdb.sourceforge.net/> ) is a Perl/Tk-based debugger that acts as a development environment of sorts. Perl Composer ( <http://perlcomposer.sourceforge.net/> ) is an IDE for Perl/Tk GUI creation.
In addition to an editor/IDE you might be interested in a more powerful shell environment for Win32. Your options include
bash from the Cygwin package ( <http://cygwin.com/> )
zsh <http://www.zsh.org/>
Cygwin is covered by the GNU General Public License (but that shouldn't matter for Perl use). Cygwin contains (in addition to the shell) a comprehensive set of standard Unix toolkit utilities.
BBEdit and TextWrangler are text editors for OS X that have a Perl sensitivity mode ( <http://www.barebones.com/> ).
###
Where can I get Perl macros for vi?
For a complete version of Tom Christiansen's vi configuration file, see <http://www.cpan.org/authors/id/T/TO/TOMC/scripts/toms.exrc.gz> , the standard benchmark file for vi emulators. The file runs best with nvi, the current version of vi out of Berkeley, which incidentally can be built with an embedded Perl interpreter--see <http://www.cpan.org/src/misc/> .
###
Where can I get perl-mode or cperl-mode for emacs?
Since Emacs version 19 patchlevel 22 or so, there have been both a perl-mode.el and support for the Perl debugger built in. These should come with the standard Emacs 19 distribution.
Note that the perl-mode of emacs will have fits with `"main'foo"` (single quote), and mess up the indentation and highlighting. You are probably using `"main::foo"` in new Perl code anyway, so this shouldn't be an issue.
For CPerlMode, see <http://www.emacswiki.org/cgi-bin/wiki/CPerlMode>
###
How can I use curses with Perl?
The Curses module from CPAN provides a dynamically loadable object module interface to a curses library. A small demo can be found at the directory <http://www.cpan.org/authors/id/T/TO/TOMC/scripts/rep.gz> ; this program repeats a command and updates the screen as needed, rendering **rep ps axu** similar to **top**.
###
How can I write a GUI (X, Tk, Gtk, etc.) in Perl?
(contributed by Ben Morrow)
There are a number of modules which let you write GUIs in Perl. Most GUI toolkits have a perl interface: an incomplete list follows.
Tk This works under Unix and Windows, and the current version doesn't look half as bad under Windows as it used to. Some of the gui elements still don't 'feel' quite right, though. The interface is very natural and 'perlish', making it easy to use in small scripts that just need a simple gui. It hasn't been updated in a while.
Wx This is a Perl binding for the cross-platform wxWidgets toolkit ( <http://www.wxwidgets.org> ). It works under Unix, Win32 and Mac OS X, using native widgets (Gtk under Unix). The interface follows the C++ interface closely, but the documentation is a little sparse for someone who doesn't know the library, mostly just referring you to the C++ documentation.
Gtk and Gtk2 These are Perl bindings for the Gtk toolkit ( <http://www.gtk.org> ). The interface changed significantly between versions 1 and 2 so they have separate Perl modules. It runs under Unix, Win32 and Mac OS X (currently it requires an X server on Mac OS, but a 'native' port is underway), and the widgets look the same on every platform: i.e., they don't match the native widgets. As with Wx, the Perl bindings follow the C API closely, and the documentation requires you to read the C documentation to understand it.
Win32::GUI This provides access to most of the Win32 GUI widgets from Perl. Obviously, it only runs under Win32, and uses native widgets. The Perl interface doesn't really follow the C interface: it's been made more Perlish, and the documentation is pretty good. More advanced stuff may require familiarity with the C Win32 APIs, or reference to MSDN.
CamelBones CamelBones ( <http://camelbones.sourceforge.net> ) is a Perl interface to Mac OS X's Cocoa GUI toolkit, and as such can be used to produce native GUIs on Mac OS X. It's not on CPAN, as it requires frameworks that CPAN.pm doesn't know how to install, but installation is via the standard OSX package installer. The Perl API is, again, very close to the ObjC API it's wrapping, and the documentation just tells you how to translate from one to the other.
Qt There is a Perl interface to TrollTech's Qt toolkit, but it does not appear to be maintained.
Athena Sx is an interface to the Athena widget set which comes with X, but again it appears not to be much used nowadays.
###
How can I make my Perl program run faster?
The best way to do this is to come up with a better algorithm. This can often make a dramatic difference. Jon Bentley's book *Programming Pearls* (that's not a misspelling!) has some good tips on optimization, too. Advice on benchmarking boils down to: benchmark and profile to make sure you're optimizing the right part, look for better algorithms instead of microtuning your code, and when all else fails consider just buying faster hardware. You will probably want to read the answer to the earlier question "How do I profile my Perl programs?" if you haven't done so already.
A different approach is to autoload seldom-used Perl code. See the AutoSplit and AutoLoader modules in the standard distribution for that. Or you could locate the bottleneck and think about writing just that part in C, the way we used to take bottlenecks in C code and write them in assembler. Similar to rewriting in C, modules that have critical sections can be written in C (for instance, the PDL module from CPAN).
If you're currently linking your perl executable to a shared *libc.so*, you can often gain a 10-25% performance benefit by rebuilding it to link with a static libc.a instead. This will make a bigger perl executable, but your Perl programs (and programmers) may thank you for it. See the *INSTALL* file in the source distribution for more information.
The undump program was an ancient attempt to speed up Perl program by storing the already-compiled form to disk. This is no longer a viable option, as it only worked on a few architectures, and wasn't a good solution anyway.
###
How can I make my Perl program take less memory?
When it comes to time-space tradeoffs, Perl nearly always prefers to throw memory at a problem. Scalars in Perl use more memory than strings in C, arrays take more than that, and hashes use even more. While there's still a lot to be done, recent releases have been addressing these issues. For example, as of 5.004, duplicate hash keys are shared amongst all hashes using them, so require no reallocation.
In some cases, using substr() or vec() to simulate arrays can be highly beneficial. For example, an array of a thousand booleans will take at least 20,000 bytes of space, but it can be turned into one 125-byte bit vector--a considerable memory savings. The standard Tie::SubstrHash module can also help for certain types of data structure. If you're working with specialist data structures (matrices, for instance) modules that implement these in C may use less memory than equivalent Perl modules.
Another thing to try is learning whether your Perl was compiled with the system malloc or with Perl's builtin malloc. Whichever one it is, try using the other one and see whether this makes a difference. Information about malloc is in the *INSTALL* file in the source distribution. You can find out whether you are using perl's malloc by typing `perl -V:usemymalloc`.
Of course, the best way to save memory is to not do anything to waste it in the first place. Good programming practices can go a long way toward this:
Don't slurp! Don't read an entire file into memory if you can process it line by line. Or more concretely, use a loop like this:
```
#
# Good Idea
#
while (my $line = <$file_handle>) {
# ...
}
```
instead of this:
```
#
# Bad Idea
#
my @data = <$file_handle>;
foreach (@data) {
# ...
}
```
When the files you're processing are small, it doesn't much matter which way you do it, but it makes a huge difference when they start getting larger.
Use map and grep selectively Remember that both map and grep expect a LIST argument, so doing this:
```
@wanted = grep {/pattern/} <$file_handle>;
```
will cause the entire file to be slurped. For large files, it's better to loop:
```
while (<$file_handle>) {
push(@wanted, $_) if /pattern/;
}
```
Avoid unnecessary quotes and stringification Don't quote large strings unless absolutely necessary:
```
my $copy = "$large_string";
```
makes 2 copies of $large\_string (one for $copy and another for the quotes), whereas
```
my $copy = $large_string;
```
only makes one copy.
Ditto for stringifying large arrays:
```
{
local $, = "\n";
print @big_array;
}
```
is much more memory-efficient than either
```
print join "\n", @big_array;
```
or
```
{
local $" = "\n";
print "@big_array";
}
```
Pass by reference Pass arrays and hashes by reference, not by value. For one thing, it's the only way to pass multiple lists or hashes (or both) in a single call/return. It also avoids creating a copy of all the contents. This requires some judgement, however, because any changes will be propagated back to the original data. If you really want to mangle (er, modify) a copy, you'll have to sacrifice the memory needed to make one.
Tie large variables to disk For "big" data stores (i.e. ones that exceed available memory) consider using one of the DB modules to store it on disk instead of in RAM. This will incur a penalty in access time, but that's probably better than causing your hard disk to thrash due to massive swapping.
###
Is it safe to return a reference to local or lexical data?
Yes. Perl's garbage collection system takes care of this so everything works out right.
```
sub makeone {
my @a = ( 1 .. 10 );
return \@a;
}
for ( 1 .. 10 ) {
push @many, makeone();
}
print $many[4][5], "\n";
print "@many\n";
```
###
How can I free an array or hash so my program shrinks?
(contributed by Michael Carman)
You usually can't. Memory allocated to lexicals (i.e. my() variables) cannot be reclaimed or reused even if they go out of scope. It is reserved in case the variables come back into scope. Memory allocated to global variables can be reused (within your program) by using undef() and/or delete().
On most operating systems, memory allocated to a program can never be returned to the system. That's why long-running programs sometimes re- exec themselves. Some operating systems (notably, systems that use mmap(2) for allocating large chunks of memory) can reclaim memory that is no longer used, but on such systems, perl must be configured and compiled to use the OS's malloc, not perl's.
In general, memory allocation and de-allocation isn't something you can or should be worrying about much in Perl.
See also "How can I make my Perl program take less memory?"
###
How can I make my CGI script more efficient?
Beyond the normal measures described to make general Perl programs faster or smaller, a CGI program has additional issues. It may be run several times per second. Given that each time it runs it will need to be re-compiled and will often allocate a megabyte or more of system memory, this can be a killer. Compiling into C **isn't going to help you** because the process start-up overhead is where the bottleneck is.
There are three popular ways to avoid this overhead. One solution involves running the Apache HTTP server (available from <http://www.apache.org/> ) with either of the mod\_perl or mod\_fastcgi plugin modules.
With mod\_perl and the Apache::Registry module (distributed with mod\_perl), httpd will run with an embedded Perl interpreter which pre-compiles your script and then executes it within the same address space without forking. The Apache extension also gives Perl access to the internal server API, so modules written in Perl can do just about anything a module written in C can. For more on mod\_perl, see <http://perl.apache.org/>
With the FCGI module (from CPAN) and the mod\_fastcgi module (available from <http://www.fastcgi.com/> ) each of your Perl programs becomes a permanent CGI daemon process.
Finally, [Plack](plack) is a Perl module and toolkit that contains PSGI middleware, helpers and adapters to web servers, allowing you to easily deploy scripts which can continue running, and provides flexibility with regards to which web server you use. It can allow existing CGI scripts to enjoy this flexibility and performance with minimal changes, or can be used along with modern Perl web frameworks to make writing and deploying web services with Perl a breeze.
These solutions can have far-reaching effects on your system and on the way you write your CGI programs, so investigate them with care.
See also <http://www.cpan.org/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/> .
###
How can I hide the source for my Perl program?
Delete it. :-) Seriously, there are a number of (mostly unsatisfactory) solutions with varying levels of "security".
First of all, however, you *can't* take away read permission, because the source code has to be readable in order to be compiled and interpreted. (That doesn't mean that a CGI script's source is readable by people on the web, though--only by people with access to the filesystem.) So you have to leave the permissions at the socially friendly 0755 level.
Some people regard this as a security problem. If your program does insecure things and relies on people not knowing how to exploit those insecurities, it is not secure. It is often possible for someone to determine the insecure things and exploit them without viewing the source. Security through obscurity, the name for hiding your bugs instead of fixing them, is little security indeed.
You can try using encryption via source filters (Starting from Perl 5.8 the Filter::Simple and Filter::Util::Call modules are included in the standard distribution), but any decent programmer will be able to decrypt it. You can try using the byte code compiler and interpreter described later in <perlfaq3>, but the curious might still be able to de-compile it. You can try using the native-code compiler described later, but crackers might be able to disassemble it. These pose varying degrees of difficulty to people wanting to get at your code, but none can definitively conceal it (true of every language, not just Perl).
It is very easy to recover the source of Perl programs. You simply feed the program to the perl interpreter and use the modules in the B:: hierarchy. The B::Deparse module should be able to defeat most attempts to hide source. Again, this is not unique to Perl.
If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive license will give you legal security. License your software and pepper it with threatening statements like "This is unpublished proprietary software of XYZ Corp. Your access to it does not give you permission to use it blah blah blah." We are not lawyers, of course, so you should see a lawyer if you want to be sure your license's wording will stand up in court.
###
How can I compile my Perl program into byte code or C?
(contributed by brian d foy)
In general, you can't do this. There are some things that may work for your situation though. People usually ask this question because they want to distribute their works without giving away the source code, and most solutions trade disk space for convenience. You probably won't see much of a speed increase either, since most solutions simply bundle a Perl interpreter in the final product (but see ["How can I make my Perl program run faster?"](#How-can-I-make-my-Perl-program-run-faster%3F)).
The Perl Archive Toolkit is Perl's analog to Java's JAR. It's freely available and on CPAN ( <https://metacpan.org/pod/PAR> ).
There are also some commercial products that may work for you, although you have to buy a license for them.
The Perl Dev Kit ( <http://www.activestate.com/Products/Perl_Dev_Kit/> ) from ActiveState can "Turn your Perl programs into ready-to-run executables for HP-UX, Linux, Solaris and Windows."
Perl2Exe ( <http://www.indigostar.com/perl2exe.htm> ) is a command line program for converting perl scripts to executable files. It targets both Windows and Unix platforms.
###
How can I get `#!perl` to work on [MS-DOS,NT,...]?
For OS/2 just use
```
extproc perl -S -your_switches
```
as the first line in `*.cmd` file (`-S` due to a bug in cmd.exe's "extproc" handling). For DOS one should first invent a corresponding batch file and codify it in `ALTERNATE_SHEBANG` (see the *dosish.h* file in the source distribution for more information).
The Win95/NT installation, when using the ActiveState port of Perl, will modify the Registry to associate the `.pl` extension with the perl interpreter. If you install another port, perhaps even building your own Win95/NT Perl from the standard sources by using a Windows port of gcc (e.g., with cygwin or mingw32), then you'll have to modify the Registry yourself. In addition to associating `.pl` with the interpreter, NT people can use: `SET PATHEXT=%PATHEXT%;.PL` to let them run the program `install-linux.pl` merely by typing `install-linux`.
Under "Classic" MacOS, a perl program will have the appropriate Creator and Type, so that double-clicking them will invoke the MacPerl application. Under Mac OS X, clickable apps can be made from any `#!` script using Wil Sanchez' DropScript utility: <http://www.wsanchez.net/software/> .
*IMPORTANT!*: Whatever you do, PLEASE don't get frustrated, and just throw the perl interpreter into your cgi-bin directory, in order to get your programs working for a web server. This is an EXTREMELY big security risk. Take the time to figure out how to do it correctly.
###
Can I write useful Perl programs on the command line?
Yes. Read <perlrun> for more information. Some examples follow. (These assume standard Unix shell quoting rules.)
```
# sum first and last fields
perl -lane 'print $F[0] + $F[-1]' *
# identify text files
perl -le 'for(@ARGV) {print if -f && -T _}' *
# remove (most) comments from C program
perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
# make file a month younger than today, defeating reaper daemons
perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
# find first unused uid
perl -le '$i++ while getpwuid($i); print $i'
# display reasonable manpath
echo $PATH | perl -nl -072 -e '
s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
```
OK, the last one was actually an Obfuscated Perl Contest entry. :-)
###
Why don't Perl one-liners work on my DOS/Mac/VMS system?
The problem is usually that the command interpreters on those systems have rather different ideas about quoting than the Unix shells under which the one-liners were created. On some systems, you may have to change single-quotes to double ones, which you must *NOT* do on Unix or Plan9 systems. You might also have to change a single % to a %%.
For example:
```
# Unix (including Mac OS X)
perl -e 'print "Hello world\n"'
# DOS, etc.
perl -e "print \"Hello world\n\""
# Mac Classic
print "Hello world\n"
(then Run "Myscript" or Shift-Command-R)
# MPW
perl -e 'print "Hello world\n"'
# VMS
perl -e "print ""Hello world\n"""
```
The problem is that none of these examples are reliable: they depend on the command interpreter. Under Unix, the first two often work. Under DOS, it's entirely possible that neither works. If 4DOS was the command shell, you'd probably have better luck like this:
```
perl -e "print <Ctrl-x>"Hello world\n<Ctrl-x>""
```
Under the Mac, it depends which environment you are using. The MacPerl shell, or MPW, is much like Unix shells in its support for several quoting variants, except that it makes free use of the Mac's non-ASCII characters as control characters.
Using qq(), q(), and qx(), instead of "double quotes", 'single quotes', and `backticks`, may make one-liners easier to write.
There is no general solution to all of this. It is a mess.
[Some of this answer was contributed by Kenneth Albanowski.]
###
Where can I learn about CGI or Web programming in Perl?
For modules, get the CGI or LWP modules from CPAN. For textbooks, see the two especially dedicated to web stuff in the question on books. For problems and questions related to the web, like "Why do I get 500 Errors" or "Why doesn't it run from the browser right when it runs fine on the command line", see the troubleshooting guides and references in <perlfaq9> or in the CGI MetaFAQ:
```
L<http://www.perl.org/CGI_MetaFAQ.html>
```
Looking into <https://plackperl.org> and modern Perl web frameworks is highly recommended, though; web programming in Perl has evolved a long way from the old days of simple CGI scripts.
###
Where can I learn about object-oriented Perl programming?
A good place to start is <perlootut>, and you can use <perlobj> for reference.
A good book on OO on Perl is the "Object-Oriented Perl" by Damian Conway from Manning Publications, or "Intermediate Perl" by Randal Schwartz, brian d foy, and Tom Phoenix from O'Reilly Media.
###
Where can I learn about linking C with Perl?
If you want to call C from Perl, start with <perlxstut>, moving on to <perlxs>, <xsubpp>, and <perlguts>. If you want to call Perl from C, then read <perlembed>, <perlcall>, and <perlguts>. Don't forget that you can learn a lot from looking at how the authors of existing extension modules wrote their code and solved their problems.
You might not need all the power of XS. The Inline::C module lets you put C code directly in your Perl source. It handles all the magic to make it work. You still have to learn at least some of the perl API but you won't have to deal with the complexity of the XS support files.
###
I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?
Download the ExtUtils::Embed kit from CPAN and run `make test'. If the tests pass, read the pods again and again and again. If they fail, submit a bug report to <https://github.com/Perl/perl5/issues> with the output of `make test TEST_VERBOSE=1` along with `perl -V`.
###
When I tried to run my script, I got this message. What does it mean?
A complete list of Perl's error messages and warnings with explanatory text can be found in <perldiag>. You can also use the splain program (distributed with Perl) to explain the error messages:
```
perl program 2>diag.out
splain [-v] [-p] diag.out
```
or change your program to explain the messages for you:
```
use diagnostics;
```
or
```
use diagnostics -verbose;
```
###
What's MakeMaker?
(contributed by brian d foy)
The <ExtUtils::MakeMaker> module, better known simply as "MakeMaker", turns a Perl script, typically called `Makefile.PL`, into a Makefile. The Unix tool `make` uses this file to manage dependencies and actions to process and install a Perl distribution.
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 ExtUtils::MM_Win95 ExtUtils::MM\_Win95
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overridden methods](#Overridden-methods)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::MM\_Win95 - method to customize MakeMaker for Win9X
SYNOPSIS
--------
```
You should not be using this module directly.
```
DESCRIPTION
-----------
This is a subclass of <ExtUtils::MM_Win32> containing changes necessary to get MakeMaker playing nice with command.com and other Win9Xisms.
###
Overridden methods
Most of these make up for limitations in the Win9x/nmake command shell.
max\_exec\_len Win98 chokes on things like Encode if we set the max length to nmake's max of 2K. So we go for a more conservative value of 1K.
os\_flavor Win95 and Win98 and WinME are collectively Win9x and Win32
AUTHOR
------
Code originally inside MM\_Win32. Original author unknown.
Currently maintained by Michael G Schwern `[email protected]`.
Send patches and ideas to `[email protected]`.
See https://metacpan.org/release/ExtUtils-MakeMaker.
perl CPAN::Nox CPAN::Nox
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
CPAN::Nox - Wrapper around CPAN.pm without using any XS module
SYNOPSIS
--------
Interactive mode:
```
perl -MCPAN::Nox -e shell;
```
DESCRIPTION
-----------
This package has the same functionality as CPAN.pm, but tries to prevent the usage of compiled extensions during its own execution. Its primary purpose is a rescue in case you upgraded perl and broke binary compatibility somehow.
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
[CPAN](cpan)
perl IO::Socket::UNIX IO::Socket::UNIX
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Socket::UNIX - Object interface for AF\_UNIX domain sockets
SYNOPSIS
--------
```
use IO::Socket::UNIX;
my $SOCK_PATH = "$ENV{HOME}/unix-domain-socket-test.sock";
# Server:
my $server = IO::Socket::UNIX->new(
Type => SOCK_STREAM(),
Local => $SOCK_PATH,
Listen => 1,
);
my $count = 1;
while (my $conn = $server->accept()) {
$conn->print("Hello " . ($count++) . "\n");
}
# Client:
my $client = IO::Socket::UNIX->new(
Type => SOCK_STREAM(),
Peer => $SOCK_PATH,
);
# Now read and write from $client
```
DESCRIPTION
-----------
`IO::Socket::UNIX` provides an object interface to creating and using sockets in the AF\_UNIX 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::UNIX` 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::UNIX` provides.
```
Type Type of socket (eg SOCK_STREAM or SOCK_DGRAM)
Local Path to local fifo
Peer Path to peer fifo
Listen Queue size for listen
```
If the constructor is only passed a single argument, it is assumed to be a `Peer` specification.
If the `Listen` argument is given, but false, the queue size will be set to 5.
If the constructor fails it will return `undef` and set the `$IO::Socket::errstr` package variable to contain an error message.
```
$sock = IO::Socket::UNIX->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::UNIX->new(...)
or die "Cannot create socket - $@\n";
```
METHODS
-------
hostpath() Returns the pathname to the fifo at the local end
peerpath() Returns the pathanme to the fifo at the peer end
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 Net::Time Net::Time
=========
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::Time - time and daytime network client interface
SYNOPSIS
--------
```
use Net::Time qw(inet_time inet_daytime);
print inet_time(); # use default host from Net::Config
print inet_time('localhost');
print inet_time('localhost', 'tcp');
print inet_daytime(); # use default host from Net::Config
print inet_daytime('localhost');
print inet_daytime('localhost', 'tcp');
```
DESCRIPTION
-----------
`Net::Time` provides subroutines that obtain the time on a remote machine.
### Functions
`inet_time([$host[, $protocol[, $timeout]]])`
Obtain the time on `$host`, or some default host if `$host` is not given or not defined, using the protocol as defined in RFC868. The optional argument `$protocol` should define the protocol to use, either `tcp` or `udp`. The result will be a time value in the same units as returned by time() or *undef* upon failure.
`inet_daytime([$host[, $protocol[, $timeout]]])`
Obtain the time on `$host`, or some default host if `$host` is not given or not defined, using the protocol as defined in RFC867. The optional argument `$protocol` should define the protocol to use, either `tcp` or `udp`. The result will be an ASCII string or *undef* upon failure.
EXPORTS
-------
The following symbols are, or can be, exported by this module:
Default Exports *None*.
Optional Exports `inet_time`, `inet_daytime`.
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) 1995-2004 Graham Barr. All rights reserved.
Copyright (C) 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 Config Config
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE](#EXAMPLE)
* [WARNING](#WARNING)
* [GLOSSARY](#GLOSSARY)
+ [\_](#_)
+ [a](#a1)
+ [b](#b)
+ [c](#c)
+ [d](#d)
+ [e](#e)
+ [f](#f)
+ [g](#g)
+ [h](#h)
+ [i](#i)
+ [k](#k)
+ [l](#l)
+ [m](#m)
+ [n](#n)
+ [o](#o1)
+ [p](#p)
+ [P](#P)
+ [q](#q)
+ [r](#r)
+ [s](#s)
+ [t](#t)
+ [u](#u)
+ [v](#v)
+ [x](#x)
+ [y](#y)
+ [z](#z)
* [GIT DATA](#GIT-DATA)
* [NOTE](#NOTE)
NAME
----
Config - access Perl configuration information
SYNOPSIS
--------
```
use Config;
if ($Config{usethreads}) {
print "has thread support\n"
}
use Config qw(myconfig config_sh config_vars config_re);
print myconfig();
print config_sh();
print config_re();
config_vars(qw(osname archname));
```
DESCRIPTION
-----------
The Config module contains all the information that was available to the `Configure` program at Perl build time (over 900 values).
Shell variables from the *config.sh* file (written by Configure) are stored in the readonly-variable `%Config`, indexed by their names.
Values stored in config.sh as 'undef' are returned as undefined values. The perl `exists` function can be used to check if a named variable exists.
For a description of the variables, please have a look at the Glossary file, as written in the Porting folder, or use the url: https://github.com/Perl/perl5/blob/blead/Porting/Glossary
myconfig() Returns a textual summary of the major perl configuration values. See also `-V` in ["Command Switches" in perlrun](perlrun#Command-Switches).
config\_sh() Returns the entire perl configuration information in the form of the original config.sh shell variable assignment script.
config\_re($regex) Like config\_sh() but returns, as a list, only the config entries who's names match the $regex.
config\_vars(@names) Prints to STDOUT the values of the named configuration variable. Each is printed on a separate line in the form:
```
name='value';
```
Names which are unknown are output as `name='UNKNOWN';`. See also `-V:name` in ["Command Switches" in perlrun](perlrun#Command-Switches).
bincompat\_options() Returns a list of C pre-processor options used when compiling this *perl* binary, which affect its binary compatibility with extensions. `bincompat_options()` and `non_bincompat_options()` are shown together in the output of `perl -V` as *Compile-time options*.
non\_bincompat\_options() Returns a list of C pre-processor options used when compiling this *perl* binary, which do not affect binary compatibility with extensions.
compile\_date() Returns the compile date (as a string), equivalent to what is shown by `perl -V`
local\_patches() Returns a list of the names of locally applied patches, equivalent to what is shown by `perl -V`.
header\_files() Returns a list of the header files that should be used as dependencies for XS code, for this version of Perl on this platform.
EXAMPLE
-------
Here's a more sophisticated example of using %Config:
```
use Config;
use strict;
my %sig_num;
my @sig_name;
unless($Config{sig_name} && $Config{sig_num}) {
die "No sigs?";
} else {
my @names = split ' ', $Config{sig_name};
@sig_num{@names} = split ' ', $Config{sig_num};
foreach (@names) {
$sig_name[$sig_num{$_}] ||= $_;
}
}
print "signal #17 = $sig_name[17]\n";
if ($sig_num{ALRM}) {
print "SIGALRM is $sig_num{ALRM}\n";
}
```
WARNING
-------
Because this information is not stored within the perl executable itself it is possible (but unlikely) that the information does not relate to the actual perl binary which is being used to access it.
The Config module is installed into the architecture and version specific library directory ($Config{installarchlib}) and it checks the perl version number when loaded.
The values stored in config.sh may be either single-quoted or double-quoted. Double-quoted strings are handy for those cases where you need to include escape sequences in the strings. To avoid runtime variable interpolation, any `$` and `@` characters are replaced by `\$` and `\@`, respectively. This isn't foolproof, of course, so don't embed `\$` or `\@` in double-quoted strings unless you're willing to deal with the consequences. (The slashes will end up escaped and the `$` or `@` will trigger variable interpolation)
GLOSSARY
--------
Most `Config` variables are determined by the `Configure` script on platforms supported by it (which is most UNIX platforms). Some platforms have custom-made `Config` variables, and may thus not have some of the variables described below, or may have extraneous variables specific to that particular port. See the port specific documentation in such cases.
###
\_
`_a`
From *Unix.U*:
This variable defines the extension used for ordinary library files. For unix, it is *.a*. The *.* is included. Other possible values include *.lib*.
`_exe`
From *Unix.U*:
This variable defines the extension used for executable files. `DJGPP`, Cygwin and *OS/2* use *.exe*. Stratus `VOS` uses *.pm*. On operating systems which do not require a specific extension for executable files, this variable is empty.
`_o`
From *Unix.U*:
This variable defines the extension used for object files. For unix, it is *.o*. The *.* is included. Other possible values include *.obj*.
### a
`afs` From *afs.U*:
This variable is set to `true` if `AFS` (Andrew File System) is used on the system, `false` otherwise. It is possible to override this with a hint value or command line option, but you'd better know what you are doing.
`afsroot` From *afs.U*:
This variable is by default set to */afs*. In the unlikely case this is not the correct root, it is possible to override this with a hint value or command line option. This will be used in subsequent tests for AFSness in the configure and test process.
`alignbytes` From *alignbytes.U*:
This variable holds 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.
`aphostname` From *d\_gethname.U*:
This variable contains the command which can be used to compute the host name. The command is fully qualified by its absolute path, to make it safe when used by a process with super-user privileges.
`api_revision` From *patchlevel.U*:
The three variables, api\_revision, api\_version, and api\_subversion, specify the version of the oldest perl binary compatible with the present perl. In a full version string such as *5.6.1*, api\_revision is the `5`. Prior to 5.5.640, the format was a floating point number, like 5.00563.
*perl.c*:incpush() and *lib/lib.pm* will automatically search in *$sitelib/.*. for older directories back to the limit specified by these api\_ variables. This is only useful if you have a perl library directory tree structured like the default one. See `INSTALL` for how this works. The versioned site\_perl directory was introduced in 5.005, so that is the lowest possible value. The version list appropriate for the current system is determined in *inc\_version\_list.U*.
`XXX` To do: Since compatibility can depend on compile time options (such as bincompat, longlong, etc.) it should (perhaps) be set by Configure, but currently it isn't. Currently, we read a hard-wired value from *patchlevel.h*. Perhaps what we ought to do is take the hard-wired value from *patchlevel.h* but then modify it if the current Configure options warrant. *patchlevel.h* then would use an #ifdef guard.
`api_subversion` From *patchlevel.U*:
The three variables, api\_revision, api\_version, and api\_subversion, specify the version of the oldest perl binary compatible with the present perl. In a full version string such as *5.6.1*, api\_subversion is the `1`. See api\_revision for full details.
`api_version` From *patchlevel.U*:
The three variables, api\_revision, api\_version, and api\_subversion, specify the version of the oldest perl binary compatible with the present perl. In a full version string such as *5.6.1*, api\_version is the `6`. See api\_revision for full details. As a special case, 5.5.0 is rendered in the old-style as 5.005. (In the 5.005\_0x maintenance series, this was the only versioned directory in $sitelib.)
`api_versionstring` From *patchlevel.U*:
This variable combines api\_revision, api\_version, and api\_subversion in a format such as 5.6.1 (or 5\_6\_1) suitable for use as a directory name. This is filesystem dependent.
`ar` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the ar program. After Configure runs, the value is reset to a plain `ar` and is not useful.
`archlib` From *archlib.U*:
This variable holds the name of the directory in which the user wants to put architecture-dependent public library files for $package. It is most often a local directory such as */usr/local/lib*. Programs using this variable must be prepared to deal with filename expansion.
`archlibexp` From *archlib.U*:
This variable is the same as the archlib variable, but is filename expanded at configuration time, for convenient use.
`archname` From *archname.U*:
This variable is a short name to characterize the current architecture. It is used mainly to construct the default archlib.
`archname64` From *use64bits.U*:
This variable is used for the 64-bitness part of $archname.
`archobjs` From *Unix.U*:
This variable defines any additional objects that must be linked in with the program on this architecture. On unix, it is usually empty. It is typically used to include emulations of unix calls or other facilities. For perl on *OS/2*, for example, this would include *os2/os2.obj*.
`asctime_r_proto` From *d\_asctime\_r.U*:
This variable 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.
`awk` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the awk program. After Configure runs, the value is reset to a plain `awk` and is not useful.
### b
`baserev` From *baserev.U*:
The base revision level of this package, from the *.package* file.
`bash` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`bin` From *bin.U*:
This variable holds the name of the directory in which the user wants to put publicly executable images for the package in question. It is most often a local directory such as */usr/local/bin*. Programs using this variable must be prepared to deal with *~name* substitution.
`bin_ELF` From *dlsrc.U*:
This variable saves the result from configure if generated binaries are in `ELF` format. Only set to defined when the test has actually been performed, and the result was positive.
`binexp` From *bin.U*:
This is the same as the bin variable, but is filename expanded at configuration time, for use in your makefiles.
`bison` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the bison program. After Configure runs, the value is reset to a plain `bison` and is not useful.
`byacc` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the byacc program. After Configure runs, the value is reset to a plain `byacc` and is not useful.
`byteorder` From *byteorder.U*:
This variable holds the byte order in a `UV`. In the following, larger digits indicate more significance. The variable byteorder is either 4321 on a big-endian machine, or 1234 on a little-endian, or 87654321 on a Cray ... or 3412 with weird order !
### c
`c` From *n.U*:
This variable contains the \c string if that is what causes the echo command to suppress newline. Otherwise it is null. Correct usage is $echo $n "prompt for a question: $c".
`castflags` From *d\_castneg.U*:
This variable contains a flag that precise 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
`cat` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the cat program. After Configure runs, the value is reset to a plain `cat` and is not useful.
`cc` From *cc.U*:
This variable holds the name of a command to execute a C compiler which can resolve multiple global references that happen to have the same name. Usual values are `cc` and `gcc`. Fervent `ANSI` compilers may be called `c89`. `AIX` has xlc.
`cccdlflags` From *dlsrc.U*:
This variable contains any special flags that might need to be passed with `cc -c` to compile modules to be used to create a shared library that will be used for dynamic loading. For hpux, this should be +z. It is up to the makefile to use it.
`ccdlflags` From *dlsrc.U*:
This variable contains any special flags that might need to be passed to cc to link with a shared library for dynamic loading. It is up to the makefile to use it. For sunos 4.1, it should be empty.
`ccflags` From *ccflags.U*:
This variable contains any additional C compiler flags desired by the user. It is up to the Makefile to use this.
`ccflags_uselargefiles` From *uselfs.U*:
This variable contains the compiler flags needed by large file builds and added to ccflags by hints files.
`ccname` From *Checkcc.U*:
This can set either by hints files or by Configure. If using gcc, this is gcc, and if not, usually equal to cc, unimpressive, no? Some platforms, however, make good use of this by storing the flavor of the C compiler being used here. For example if using the Sun WorkShop suite, ccname will be `workshop`.
`ccsymbols` From *Cppsym.U*:
The variable contains the symbols defined by the C compiler alone. The symbols defined by cpp or by cc when it calls cpp are not in this list, see cppsymbols and cppccsymbols. The list is a space-separated list of symbol=value tokens.
`ccversion` From *Checkcc.U*:
This can set either by hints files or by Configure. If using a (non-gcc) vendor cc, this variable may contain a version for the compiler.
`cf_by` From *cf\_who.U*:
Login name of the person who ran the Configure script and answered the questions. This is used to tag both *config.sh* and *config\_h.SH*.
`cf_email` From *cf\_email.U*:
Electronic mail address of the person who ran Configure. This can be used by units that require the user's e-mail, like *MailList.U*.
`cf_time` From *cf\_who.U*:
Holds the output of the `date` command when the configuration file was produced. This is used to tag both *config.sh* and *config\_h.SH*.
`charbits` From *charsize.U*:
This variable contains the value of the `CHARBITS` symbol, which indicates to the C program how many bits there are in a character.
`charsize` From *charsize.U*:
This variable contains the value of the `CHARSIZE` symbol, which indicates to the C program how many bytes there are in a character.
`chgrp` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`chmod` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the chmod program. After Configure runs, the value is reset to a plain `chmod` and is not useful.
`chown` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`clocktype` From *d\_times.U*:
This variable holds the type returned by times(). It can be long, or clock\_t on `BSD` sites (in which case <sys/types.h> should be included).
`comm` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the comm program. After Configure runs, the value is reset to a plain `comm` and is not useful.
`compiler_warning` From *compiler\_warning.U*:
This variable holds the command to check if the file specified as a parameter contains a compiler warning
`compress` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`config_arg0` From *Options.U*:
This variable contains the string used to invoke the Configure command, as reported by the shell in the $0 variable.
`config_argc` From *Options.U*:
This variable contains the number of command-line arguments passed to Configure, as reported by the shell in the $# variable. The individual arguments are stored as variables config\_arg1, config\_arg2, etc.
`config_args` From *Options.U*:
This variable contains a single string giving the command-line arguments passed to Configure. Spaces within arguments, quotes, and escaped characters are not correctly preserved. To reconstruct the command line, you must assemble the individual command line pieces, given in config\_arg[0-9]\*.
`contains` From *contains.U*:
This variable holds the command to do a grep with a proper return status. On most sane systems it is simply `grep`. On insane systems it is a grep followed by a cat followed by a test. This variable is primarily for the use of other Configure units.
`cp` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the cp program. After Configure runs, the value is reset to a plain `cp` and is not useful.
`cpio` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`cpp` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the cpp program. After Configure runs, the value is reset to a plain `cpp` and is not useful.
`cpp_stuff` From *cpp\_stuff.U*:
This variable contains an identification of the concatenation mechanism used by the C preprocessor.
`cppccsymbols` From *Cppsym.U*:
The variable contains the symbols defined by the C compiler when it calls cpp. The symbols defined by the cc alone or cpp alone are not in this list, see ccsymbols and cppsymbols. The list is a space-separated list of symbol=value tokens.
`cppflags` From *ccflags.U*:
This variable holds the flags that will be passed to the C pre- processor. It is up to the Makefile to use it.
`cpplast` From *cppstdin.U*:
This variable has the same functionality as cppminus, only it applies to cpprun and not cppstdin.
`cppminus` From *cppstdin.U*:
This variable contains the second part of the string which will invoke the C preprocessor on the standard input and produce to standard output. This variable will have the value `-` if cppstdin needs a minus to specify standard input, otherwise the value is "".
`cpprun` From *cppstdin.U*:
This variable contains the command which will invoke a C preprocessor on standard input and put the output to stdout. It is guaranteed not to be a wrapper and may be a null string if no preprocessor can be made directly available. This preprocessor might be different from the one used by the C compiler. Don't forget to append cpplast after the preprocessor options.
`cppstdin` From *cppstdin.U*:
This variable contains the command which will invoke the C preprocessor on standard input and put the output to stdout. It is primarily used by other Configure units that ask about preprocessor symbols.
`cppsymbols` From *Cppsym.U*:
The variable contains the symbols defined by the C preprocessor alone. The symbols defined by cc or by cc when it calls cpp are not in this list, see ccsymbols and cppccsymbols. The list is a space-separated list of symbol=value tokens.
`crypt_r_proto` From *d\_crypt\_r.U*:
This variable 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.
`cryptlib` From *d\_crypt.U*:
This variable holds -lcrypt or the path to a *libcrypt.a* archive if the crypt() function is not defined in the standard C library. It is up to the Makefile to use this.
`csh` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the csh program. After Configure runs, the value is reset to a plain `csh` and is not useful.
`ctermid_r_proto` From *d\_ctermid\_r.U*:
This variable 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.
`ctime_r_proto` From *d\_ctime\_r.U*:
This variable 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.
### d
`d__fwalk` From *d\_\_fwalk.U*:
This variable conditionally defines `HAS__FWALK` if \_fwalk() is available to apply a function to all the file handles.
`d_accept4` From *d\_accept4.U*:
This variable conditionally defines HAS\_ACCEPT4 if accept4() is available to accept socket connections.
`d_access` From *d\_access.U*:
This variable conditionally defines `HAS_ACCESS` if the access() system call is available to check for access permissions using real IDs.
`d_accessx` From *d\_accessx.U*:
This variable conditionally defines the `HAS_ACCESSX` symbol, which indicates to the C program that the accessx() routine is available.
`d_acosh` From *d\_acosh.U*:
This variable conditionally defines the `HAS_ACOSH` symbol, which indicates to the C program that the acosh() routine is available.
`d_aintl` From *d\_aintl.U*:
This variable conditionally defines the `HAS_AINTL` symbol, which indicates to the C program that the aintl() routine is available. If copysignl is also present we can emulate modfl.
`d_alarm` From *d\_alarm.U*:
This variable conditionally defines the `HAS_ALARM` symbol, which indicates to the C program that the alarm() routine is available.
`d_archlib` From *archlib.U*:
This variable conditionally defines `ARCHLIB` to hold the pathname of architecture-dependent library files for $package. If $archlib is the same as $privlib, then this is set to undef.
`d_asctime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_ASCTIME64 symbol, which indicates to the C program that the asctime64 () routine is available.
`d_asctime_r` From *d\_asctime\_r.U*:
This variable conditionally defines the `HAS_ASCTIME_R` symbol, which indicates to the C program that the asctime\_r() routine is available.
`d_asinh` From *d\_asinh.U*:
This variable conditionally defines the `HAS_ASINH` symbol, which indicates to the C program that the asinh() routine is available.
`d_atanh` From *d\_atanh.U*:
This variable conditionally defines the `HAS_ATANH` symbol, which indicates to the C program that the atanh() routine is available.
`d_atolf` From *atolf.U*:
This variable conditionally defines the `HAS_ATOLF` symbol, which indicates to the C program that the atolf() routine is available.
`d_atoll` From *atoll.U*:
This variable conditionally defines the `HAS_ATOLL` symbol, which indicates to the C program that the atoll() routine is available.
`d_attribute_always_inline` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_ALWAYS_INLINE`, which indicates that the C compiler can know that certain functions should always be inlined.
`d_attribute_deprecated` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_DEPRECATED`, which indicates that `GCC` can handle the attribute for marking deprecated APIs
`d_attribute_format` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_FORMAT`, which indicates the C compiler can check for printf-like formats.
`d_attribute_malloc` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_MALLOC`, which indicates the C compiler can understand functions as having malloc-like semantics.
`d_attribute_nonnull` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_NONNULL`, which indicates that the C compiler can know that certain arguments must not be `NULL`, and will check accordingly at compile time.
`d_attribute_noreturn` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_NORETURN`, which indicates that the C compiler can know that certain functions are guaranteed never to return.
`d_attribute_pure` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_PURE`, which indicates that the C compiler can know that certain functions are `pure` functions, meaning that they have no side effects, and only rely on function input *and/or* global data for their results.
`d_attribute_unused` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_UNUSED`, which indicates that the C compiler can know that certain variables and arguments may not always be used, and to not throw warnings if they don't get used.
`d_attribute_warn_unused_result` From *d\_attribut.U*:
This variable conditionally defines `HASATTRIBUTE_WARN_UNUSED_RESULT`, which indicates that the C compiler can know that certain functions have a return values that must not be ignored, such as malloc() or open().
`d_backtrace` From *d\_backtrace.U*:
This variable conditionally defines the `HAS_BACKTRACE` symbol, which indicates to the C program that the backtrace() routine is available to get a stack trace.
`d_bsd` From *Guess.U*:
This symbol conditionally defines the symbol `BSD` when running on a `BSD` system.
`d_bsdgetpgrp` From *d\_getpgrp.U*:
This variable conditionally defines `USE_BSD_GETPGRP` if getpgrp needs one arguments whereas `USG` one needs none.
`d_bsdsetpgrp` From *d\_setpgrp.U*:
This variable conditionally defines `USE_BSD_SETPGRP` if setpgrp needs two arguments whereas `USG` one needs none. See also d\_setpgid for a `POSIX` interface.
`d_builtin_add_overflow` From *d\_builtin\_overflow.U*:
This variable conditionally defines `HAS_BUILTIN_ADD_OVERFLOW`, which indicates that the compiler supports \_\_builtin\_add\_overflow(x,y,&z) for safely adding x and y into z while checking for overflow.
`d_builtin_choose_expr` From *d\_builtin.U*:
This conditionally defines `HAS_BUILTIN_CHOOSE_EXPR`, which indicates that the compiler supports \_\_builtin\_choose\_expr(x,y,z). This built-in function is analogous to the `x?y:z` operator in C, except that the expression returned has its type unaltered by promotion rules. Also, the built-in function does not evaluate the expression that was not chosen.
`d_builtin_expect` From *d\_builtin.U*:
This conditionally defines `HAS_BUILTIN_EXPECT`, which indicates that the compiler supports \_\_builtin\_expect(exp,c). You may use \_\_builtin\_expect to provide the compiler with branch prediction information.
`d_builtin_mul_overflow` From *d\_builtin\_overflow.U*:
This variable conditionally defines `HAS_BUILTIN_MUL_OVERFLOW`, which indicates that the compiler supports \_\_builtin\_mul\_overflow(x,y,&z) for safely multiplying x and y into z while checking for overflow.
`d_builtin_sub_overflow` From *d\_builtin\_overflow.U*:
This variable conditionally defines `HAS_BUILTIN_SUB_OVERFLOW`, which indicates that the compiler supports \_\_builtin\_sub\_overflow(x,y,&z) for safely subtracting y from x into z while checking for overflow.
`d_c99_variadic_macros` From *d\_c99\_variadic.U*:
This variable conditionally defines the HAS\_C99\_VARIADIC\_MACROS symbol, which indicates to the C program that C99 variadic macros are available.
`d_casti32` From *d\_casti32.U*:
This variable conditionally defines CASTI32, which indicates whether the C compiler can cast large floats to 32-bit ints.
`d_castneg` From *d\_castneg.U*:
This variable conditionally defines `CASTNEG`, which indicates whether the C compiler can cast negative float to unsigned.
`d_cbrt` From *d\_cbrt.U*:
This variable conditionally defines the `HAS_CBRT` symbol, which indicates to the C program that the cbrt() (cube root) function is available.
`d_chown` From *d\_chown.U*:
This variable conditionally defines the `HAS_CHOWN` symbol, which indicates to the C program that the chown() routine is available.
`d_chroot` From *d\_chroot.U*:
This variable conditionally defines the `HAS_CHROOT` symbol, which indicates to the C program that the chroot() routine is available.
`d_chsize` From *d\_chsize.U*:
This variable conditionally defines the `CHSIZE` symbol, which indicates to the C program that the chsize() routine is available to truncate files. You might need a -lx to get this routine.
`d_class` From *d\_class.U*:
This variable conditionally defines the `HAS_CLASS` symbol, which indicates to the C program that the class() routine is available.
`d_clearenv` From *d\_clearenv.U*:
This variable conditionally defines the `HAS_CLEARENV` symbol, which indicates to the C program that the clearenv () routine is available.
`d_closedir` From *d\_closedir.U*:
This variable conditionally defines `HAS_CLOSEDIR` if closedir() is available.
`d_cmsghdr_s` From *d\_cmsghdr\_s.U*:
This variable conditionally defines the `HAS_STRUCT_CMSGHDR` symbol, which indicates that the struct cmsghdr is supported.
`d_copysign` From *d\_copysign.U*:
This variable conditionally defines the `HAS_COPYSIGN` symbol, which indicates to the C program that the copysign() routine is available.
`d_copysignl` From *d\_copysignl.U*:
This variable conditionally defines the `HAS_COPYSIGNL` symbol, which indicates to the C program that the copysignl() routine is available. If aintl is also present we can emulate modfl.
`d_cplusplus` From *d\_cplusplus.U*:
This variable conditionally defines the `USE_CPLUSPLUS` symbol, which indicates that a C++ compiler was used to compiled Perl and will be used to compile extensions.
`d_crypt` From *d\_crypt.U*:
This variable conditionally defines the `CRYPT` symbol, which indicates to the C program that the crypt() routine is available to encrypt passwords and the like.
`d_crypt_r` From *d\_crypt\_r.U*:
This variable conditionally defines the `HAS_CRYPT_R` symbol, which indicates to the C program that the crypt\_r() routine is available.
`d_csh` From *d\_csh.U*:
This variable conditionally defines the `CSH` symbol, which indicates to the C program that the C-shell exists.
`d_ctermid` From *d\_ctermid.U*:
This variable conditionally defines `CTERMID` if ctermid() is available to generate filename for terminal.
`d_ctermid_r` From *d\_ctermid\_r.U*:
This variable conditionally defines the `HAS_CTERMID_R` symbol, which indicates to the C program that the ctermid\_r() routine is available.
`d_ctime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_CTIME64 symbol, which indicates to the C program that the ctime64 () routine is available.
`d_ctime_r` From *d\_ctime\_r.U*:
This variable conditionally defines the `HAS_CTIME_R` symbol, which indicates to the C program that the ctime\_r() routine is available.
`d_cuserid` From *d\_cuserid.U*:
This variable conditionally defines the `HAS_CUSERID` symbol, which indicates to the C program that the cuserid() routine is available to get character login names.
`d_dbminitproto` From *d\_dbminitproto.U*:
This variable conditionally defines the `HAS_DBMINIT_PROTO` symbol, which indicates to the C program that the system provides a prototype for the dbminit() function. Otherwise, it is up to the program to supply one.
`d_difftime` From *d\_difftime.U*:
This variable conditionally defines the `HAS_DIFFTIME` symbol, which indicates to the C program that the difftime() routine is available.
`d_difftime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_DIFFTIME64 symbol, which indicates to the C program that the difftime64 () routine is available.
`d_dir_dd_fd` From *d\_dir\_dd\_fd.U*:
This variable conditionally defines the `HAS_DIR_DD_FD` symbol, which indicates that the `DIR` directory stream type contains a member variable called dd\_fd.
`d_dirfd` From *d\_dirfd.U*:
This variable conditionally defines the `HAS_DIRFD` constant, which indicates to the C program that dirfd() is available to return the file descriptor of a directory stream.
`d_dirnamlen` From *i\_dirent.U*:
This variable conditionally defines `DIRNAMLEN`, which indicates to the C program that the length of directory entry names is provided by a d\_namelen field.
`d_dladdr` From *d\_dladdr.U*:
This variable conditionally defines the `HAS_DLADDR` symbol, which indicates to the C program that the dladdr() routine is available to get a stack trace.
`d_dlerror` From *d\_dlerror.U*:
This variable conditionally defines the `HAS_DLERROR` symbol, which indicates to the C program that the dlerror() routine is available.
`d_dlopen` From *d\_dlopen.U*:
This variable conditionally defines the `HAS_DLOPEN` symbol, which indicates to the C program that the dlopen() routine is available.
`d_dlsymun` From *d\_dlsymun.U*:
This variable conditionally defines `DLSYM_NEEDS_UNDERSCORE`, which indicates that we need to prepend an underscore to the symbol name before calling dlsym().
`d_dosuid` From *d\_dosuid.U*:
This variable conditionally defines the symbol `DOSUID`, which tells the C program that it should insert setuid emulation code on hosts which have setuid #! scripts disabled.
`d_double_has_inf` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_HAS_INF` which indicates that the double type has an infinity.
`d_double_has_nan` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_HAS_NAN` which indicates that the double type has a not-a-number.
`d_double_has_negative_zero` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_HAS_NEGATIVE_ZERO` which indicates that the double type has a negative zero.
`d_double_has_subnormals` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_HAS_SUBNORMALS` which indicates that the double type has subnormals (denormals).
`d_double_style_cray` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_STYLE_CRAY` which indicates that the double is the 64-bit `CRAY` mainframe format.
`d_double_style_ibm` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_STYLE_IBM`, which indicates that the double is the 64-bit `IBM` mainframe format.
`d_double_style_ieee` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_STYLE_IEEE`, which indicates that the double is the 64-bit `IEEE` 754.
`d_double_style_vax` From *longdblfio.U*:
This variable conditionally defines the symbol `DOUBLE_STYLE_VAX`, which indicates that the double is the 64-bit `VAX` format D or G.
`d_drand48_r` From *d\_drand48\_r.U*:
This variable conditionally defines the HAS\_DRAND48\_R symbol, which indicates to the C program that the drand48\_r() routine is available.
`d_drand48proto` From *d\_drand48proto.U*:
This variable conditionally defines the HAS\_DRAND48\_PROTO symbol, which indicates to the C program that the system provides a prototype for the drand48() function. Otherwise, it is up to the program to supply one.
`d_dup2` From *d\_dup2.U*:
This variable conditionally defines HAS\_DUP2 if dup2() is available to duplicate file descriptors.
`d_dup3` From *d\_dup3.U*:
This variable conditionally defines HAS\_DUP3 if dup3() is available to duplicate file descriptors.
`d_duplocale` From *d\_newlocale.U*:
This variable conditionally defines the `HAS_DUPLOCALE` symbol, which indicates to the C program that the duplocale() routine is available to duplicate a locale object.
`d_eaccess` From *d\_eaccess.U*:
This variable conditionally defines the `HAS_EACCESS` symbol, which indicates to the C program that the eaccess() routine is available.
`d_endgrent` From *d\_endgrent.U*:
This variable conditionally defines the `HAS_ENDGRENT` symbol, which indicates to the C program that the endgrent() routine is available for sequential access of the group database.
`d_endgrent_r` From *d\_endgrent\_r.U*:
This variable conditionally defines the `HAS_ENDGRENT_R` symbol, which indicates to the C program that the endgrent\_r() routine is available.
`d_endhent` From *d\_endhent.U*:
This variable conditionally defines `HAS_ENDHOSTENT` if endhostent() is available to close whatever was being used for host queries.
`d_endhostent_r` From *d\_endhostent\_r.U*:
This variable conditionally defines the `HAS_ENDHOSTENT_R` symbol, which indicates to the C program that the endhostent\_r() routine is available.
`d_endnent` From *d\_endnent.U*:
This variable conditionally defines `HAS_ENDNETENT` if endnetent() is available to close whatever was being used for network queries.
`d_endnetent_r` From *d\_endnetent\_r.U*:
This variable conditionally defines the `HAS_ENDNETENT_R` symbol, which indicates to the C program that the endnetent\_r() routine is available.
`d_endpent` From *d\_endpent.U*:
This variable conditionally defines `HAS_ENDPROTOENT` if endprotoent() is available to close whatever was being used for protocol queries.
`d_endprotoent_r` From *d\_endprotoent\_r.U*:
This variable conditionally defines the `HAS_ENDPROTOENT_R` symbol, which indicates to the C program that the endprotoent\_r() routine is available.
`d_endpwent` From *d\_endpwent.U*:
This variable conditionally defines the `HAS_ENDPWENT` symbol, which indicates to the C program that the endpwent() routine is available for sequential access of the passwd database.
`d_endpwent_r` From *d\_endpwent\_r.U*:
This variable conditionally defines the `HAS_ENDPWENT_R` symbol, which indicates to the C program that the endpwent\_r() routine is available.
`d_endsent` From *d\_endsent.U*:
This variable conditionally defines `HAS_ENDSERVENT` if endservent() is available to close whatever was being used for service queries.
`d_endservent_r` From *d\_endservent\_r.U*:
This variable conditionally defines the `HAS_ENDSERVENT_R` symbol, which indicates to the C program that the endservent\_r() routine is available.
`d_eofnblk` From *nblock\_io.U*:
This variable conditionally defines `EOF_NONBLOCK` if `EOF` can be seen when reading from a non-blocking I/O source.
`d_erf` From *d\_erf.U*:
This variable conditionally defines the `HAS_ERF` symbol, which indicates to the C program that the erf() routine is available.
`d_erfc` From *d\_erfc.U*:
This variable conditionally defines the `HAS_ERFC` symbol, which indicates to the C program that the erfc() routine is available.
`d_eunice` From *Guess.U*:
This variable conditionally defines the symbols `EUNICE` and `VAX`, which alerts the C program that it must deal with idiosyncrasies of `VMS`.
`d_exp2` From *d\_exp2.U*:
This variable conditionally defines the HAS\_EXP2 symbol, which indicates to the C program that the exp2() routine is available.
`d_expm1` From *d\_expm1.U*:
This variable conditionally defines the HAS\_EXPM1 symbol, which indicates to the C program that the expm1() routine is available.
`d_faststdio` From *d\_faststdio.U*:
This variable conditionally defines the `HAS_FAST_STDIO` symbol, which indicates to the C program that the "fast stdio" is available to manipulate the stdio buffers directly.
`d_fchdir` From *d\_fchdir.U*:
This variable conditionally defines the `HAS_FCHDIR` symbol, which indicates to the C program that the fchdir() routine is available.
`d_fchmod` From *d\_fchmod.U*:
This variable conditionally defines the `HAS_FCHMOD` symbol, which indicates to the C program that the fchmod() routine is available to change mode of opened files.
`d_fchmodat` From *d\_fsat.U*:
This variable conditionally defines the `HAS_FCHMODAT` symbol, which indicates the `POSIX` fchmodat() function is available.
`d_fchown` From *d\_fchown.U*:
This variable conditionally defines the `HAS_FCHOWN` symbol, which indicates to the C program that the fchown() routine is available to change ownership of opened files.
`d_fcntl` From *d\_fcntl.U*:
This variable conditionally defines the `HAS_FCNTL` symbol, and indicates whether the fcntl() function exists
`d_fcntl_can_lock` From *d\_fcntl\_can\_lock.U*:
This variable conditionally defines the `FCNTL_CAN_LOCK` symbol and indicates whether file locking with fcntl() works.
`d_fd_macros` From *d\_fd\_set.U*:
This variable contains the eventual value of the `HAS_FD_MACROS` symbol, which indicates if your C compiler knows about the macros which manipulate an fd\_set.
`d_fd_set` From *d\_fd\_set.U*:
This variable contains the eventual value of the `HAS_FD_SET` symbol, which indicates if your C compiler knows about the fd\_set typedef.
`d_fdclose` From *d\_fdclose.U*:
This variable conditionally defines the `HAS_FDCLOSE` symbol, which indicates to the C program that the fdclose() routine is available.
`d_fdim` From *d\_fdim.U*:
This variable conditionally defines the `HAS_FDIM` symbol, which indicates to the C program that the fdim() routine is available.
`d_fds_bits` From *d\_fd\_set.U*:
This variable contains the eventual value of the `HAS_FDS_BITS` symbol, which indicates if your fd\_set typedef contains the fds\_bits member. If you have an fd\_set typedef, but the dweebs who installed it did a half-fast job and neglected to provide the macros to manipulate an fd\_set, `HAS_FDS_BITS` will let us know how to fix the gaffe.
`d_fegetround` From *d\_fegetround.U*:
This variable conditionally defines `HAS_FEGETROUND` if fegetround() is available to get the floating point rounding mode.
`d_ffs` From *d\_ffs.U*:
This variable conditionally defines the `HAS_FFS` symbol, which indicates to the C program that the ffs() routine is available to find the first bit which is set in its integer argument.
`d_ffsl` From *d\_ffs.U*:
This variable conditionally defines the `HAS_FFSL` symbol, which indicates to the C program that the ffsl() routine is available to find the first bit which is set in its long integer argument.
`d_fgetpos` From *d\_fgetpos.U*:
This variable conditionally defines `HAS_FGETPOS` if fgetpos() is available to get the file position indicator.
`d_finite` From *d\_finite.U*:
This variable conditionally defines the `HAS_FINITE` symbol, which indicates to the C program that the finite() routine is available.
`d_finitel` From *d\_finitel.U*:
This variable conditionally defines the `HAS_FINITEL` symbol, which indicates to the C program that the finitel() routine is available.
`d_flexfnam` From *d\_flexfnam.U*:
This variable conditionally defines the `FLEXFILENAMES` symbol, which indicates that the system supports filenames longer than 14 characters.
`d_flock` From *d\_flock.U*:
This variable conditionally defines `HAS_FLOCK` if flock() is available to do file locking.
`d_flockproto` From *d\_flockproto.U*:
This variable conditionally defines the `HAS_FLOCK_PROTO` symbol, which indicates to the C program that the system provides a prototype for the flock() function. Otherwise, it is up to the program to supply one.
`d_fma` From *d\_fma.U*:
This variable conditionally defines the `HAS_FMA` symbol, which indicates to the C program that the fma() routine is available.
`d_fmax` From *d\_fmax.U*:
This variable conditionally defines the `HAS_FMAX` symbol, which indicates to the C program that the fmax() routine is available.
`d_fmin` From *d\_fmin.U*:
This variable conditionally defines the `HAS_FMIN` symbol, which indicates to the C program that the fmin() routine is available.
`d_fork` From *d\_fork.U*:
This variable conditionally defines the `HAS_FORK` symbol, which indicates to the C program that the fork() routine is available.
`d_fp_class` From *d\_fp\_class.U*:
This variable conditionally defines the `HAS_FP_CLASS` symbol, which indicates to the C program that the fp\_class() routine is available.
`d_fp_classify` From *d\_fpclassify.U*:
This variable conditionally defines the `HAS_FP_CLASSIFY` symbol, which indicates to the C program that the fp\_classify() routine is available.
`d_fp_classl` From *d\_fp\_classl.U*:
This variable conditionally defines the `HAS_FP_CLASSL` symbol, which indicates to the C program that the fp\_classl() routine is available.
`d_fpathconf` From *d\_pathconf.U*:
This variable conditionally defines the `HAS_FPATHCONF` symbol, which indicates to the C program that the pathconf() routine is available to determine file-system related limits and options associated with a given open file descriptor.
`d_fpclass` From *d\_fpclass.U*:
This variable conditionally defines the `HAS_FPCLASS` symbol, which indicates to the C program that the fpclass() routine is available.
`d_fpclassify` From *d\_fpclassify.U*:
This variable conditionally defines the `HAS_FPCLASSIFY` symbol, which indicates to the C program that the fpclassify() routine is available.
`d_fpclassl` From *d\_fpclassl.U*:
This variable conditionally defines the `HAS_FPCLASSL` symbol, which indicates to the C program that the fpclassl() routine is available.
`d_fpgetround` From *d\_fpgetround.U*:
This variable conditionally defines `HAS_FPGETROUND` if fpgetround() is available to get the floating point rounding mode.
`d_fpos64_t` From *d\_fpos64\_t.U*:
This symbol will be defined if the C compiler supports fpos64\_t.
`d_freelocale` From *d\_newlocale.U*:
This variable conditionally defines the `HAS_FREELOCALE` symbol, which indicates to the C program that the freelocale() routine is available to deallocates the resources associated with a locale object.
`d_frexpl` From *d\_frexpl.U*:
This variable conditionally defines the `HAS_FREXPL` symbol, which indicates to the C program that the frexpl() routine is available.
`d_fs_data_s` From *d\_fs\_data\_s.U*:
This variable conditionally defines the `HAS_STRUCT_FS_DATA` symbol, which indicates that the struct fs\_data is supported.
`d_fseeko` From *d\_fseeko.U*:
This variable conditionally defines the `HAS_FSEEKO` symbol, which indicates to the C program that the fseeko() routine is available.
`d_fsetpos` From *d\_fsetpos.U*:
This variable conditionally defines `HAS_FSETPOS` if fsetpos() is available to set the file position indicator.
`d_fstatfs` From *d\_fstatfs.U*:
This variable conditionally defines the `HAS_FSTATFS` symbol, which indicates to the C program that the fstatfs() routine is available.
`d_fstatvfs` From *d\_statvfs.U*:
This variable conditionally defines the `HAS_FSTATVFS` symbol, which indicates to the C program that the fstatvfs() routine is available.
`d_fsync` From *d\_fsync.U*:
This variable conditionally defines the `HAS_FSYNC` symbol, which indicates to the C program that the fsync() routine is available.
`d_ftello` From *d\_ftello.U*:
This variable conditionally defines the `HAS_FTELLO` symbol, which indicates to the C program that the ftello() routine is available.
`d_ftime` From *d\_ftime.U*:
This variable conditionally defines the `HAS_FTIME` symbol, which indicates that the ftime() routine exists. The ftime() routine is basically a sub-second accuracy clock.
`d_futimes` From *d\_futimes.U*:
This variable conditionally defines the `HAS_FUTIMES` symbol, which indicates to the C program that the futimes() routine is available.
`d_gai_strerror` From *d\_gai\_strerror.U*:
This variable conditionally defines the `HAS_GAI_STRERROR` symbol if the gai\_strerror() routine is available and can be used to translate error codes returned by getaddrinfo() into human readable strings.
`d_Gconvert` From *d\_gconvert.U*:
This variable holds what Gconvert is defined as to convert floating point numbers into strings. By default, Configure sets `this` macro to use the first of gconvert, gcvt, or sprintf that pass sprintf-%g-like behavior tests. If perl is using long doubles, the macro uses the first of the following functions that pass Configure's tests: qgcvt, sprintf (if Configure knows how to make sprintf format long doubles--see sPRIgldbl), gconvert, gcvt, and sprintf (casting to double). The gconvert\_preference and gconvert\_ld\_preference variables can be used to alter Configure's preferences, for doubles and long doubles, respectively. If present, they contain a space-separated list of one or more of the above function names in the order they should be tried.
d\_Gconvert may be set to override Configure with a platform- specific function. If this function expects a double, a different value may need to be set by the *uselongdouble.cbu* call-back unit so that long doubles can be formatted without loss of precision.
`d_gdbm_ndbm_h_uses_prototypes` From *i\_ndbm.U*:
This variable conditionally defines the `NDBM_H_USES_PROTOTYPES` symbol, which indicates that the gdbm-*ndbm.h* include file uses real `ANSI` C prototypes instead of K&R style function declarations. K&R style declarations are unsupported in C++, so the include file requires special handling when using a C++ compiler and this variable is undefined. Consult the different d\_\*ndbm\_h\_uses\_prototypes variables to get the same information for alternative *ndbm.h* include files.
`d_gdbmndbm_h_uses_prototypes` From *i\_ndbm.U*:
This variable conditionally defines the `NDBM_H_USES_PROTOTYPES` symbol, which indicates that the *gdbm/ndbm.h* include file uses real `ANSI` C prototypes instead of K&R style function declarations. K&R style declarations are unsupported in C++, so the include file requires special handling when using a C++ compiler and this variable is undefined. Consult the different d\_\*ndbm\_h\_uses\_prototypes variables to get the same information for alternative *ndbm.h* include files.
`d_getaddrinfo` From *d\_getaddrinfo.U*:
This variable conditionally defines the `HAS_GETADDRINFO` symbol, which indicates to the C program that the getaddrinfo() function is available.
`d_getcwd` From *d\_getcwd.U*:
This variable conditionally defines the `HAS_GETCWD` symbol, which indicates to the C program that the getcwd() routine is available to get the current working directory.
`d_getenv_preserves_other_thread` From *d\_getenv\_thread.U*:
This variable conditionally defines the `GETENV_PRESERVES_OTHER_THREAD` symbol, which indicates to the C program that the getenv() system call does not zap the static buffer in a different thread.
`d_getespwnam` From *d\_getespwnam.U*:
This variable conditionally defines `HAS_GETESPWNAM` if getespwnam() is available to retrieve enhanced (shadow) password entries by name.
`d_getfsstat` From *d\_getfsstat.U*:
This variable conditionally defines the `HAS_GETFSSTAT` symbol, which indicates to the C program that the getfsstat() routine is available.
`d_getgrent` From *d\_getgrent.U*:
This variable conditionally defines the `HAS_GETGRENT` symbol, which indicates to the C program that the getgrent() routine is available for sequential access of the group database.
`d_getgrent_r` From *d\_getgrent\_r.U*:
This variable conditionally defines the `HAS_GETGRENT_R` symbol, which indicates to the C program that the getgrent\_r() routine is available.
`d_getgrgid_r` From *d\_getgrgid\_r.U*:
This variable conditionally defines the `HAS_GETGRGID_R` symbol, which indicates to the C program that the getgrgid\_r() routine is available.
`d_getgrnam_r` From *d\_getgrnam\_r.U*:
This variable conditionally defines the `HAS_GETGRNAM_R` symbol, which indicates to the C program that the getgrnam\_r() routine is available.
`d_getgrps` From *d\_getgrps.U*:
This variable conditionally defines the `HAS_GETGROUPS` symbol, which indicates to the C program that the getgroups() routine is available to get the list of process groups.
`d_gethbyaddr` From *d\_gethbyad.U*:
This variable conditionally defines the `HAS_GETHOSTBYADDR` symbol, which indicates to the C program that the gethostbyaddr() routine is available to look up hosts by their `IP` addresses.
`d_gethbyname` From *d\_gethbynm.U*:
This variable conditionally defines the `HAS_GETHOSTBYNAME` symbol, which indicates to the C program that the gethostbyname() routine is available to look up host names in some data base or other.
`d_gethent` From *d\_gethent.U*:
This variable conditionally defines `HAS_GETHOSTENT` if gethostent() is available to look up host names in some data base or another.
`d_gethname` From *d\_gethname.U*:
This variable conditionally defines the `HAS_GETHOSTNAME` symbol, which indicates to the C program that the gethostname() routine may be used to derive the host name.
`d_gethostbyaddr_r` From *d\_gethostbyaddr\_r.U*:
This variable conditionally defines the `HAS_GETHOSTBYADDR_R` symbol, which indicates to the C program that the gethostbyaddr\_r() routine is available.
`d_gethostbyname_r` From *d\_gethostbyname\_r.U*:
This variable conditionally defines the `HAS_GETHOSTBYNAME_R` symbol, which indicates to the C program that the gethostbyname\_r() routine is available.
`d_gethostent_r` From *d\_gethostent\_r.U*:
This variable conditionally defines the `HAS_GETHOSTENT_R` symbol, which indicates to the C program that the gethostent\_r() routine is available.
`d_gethostprotos` From *d\_gethostprotos.U*:
This variable conditionally defines the `HAS_GETHOST_PROTOS` symbol, which indicates to the C program that <netdb.h> supplies prototypes for the various gethost\*() functions. See also *netdbtype.U* for probing for various netdb types.
`d_getitimer` From *d\_getitimer.U*:
This variable conditionally defines the `HAS_GETITIMER` symbol, which indicates to the C program that the getitimer() routine is available.
`d_getlogin` From *d\_getlogin.U*:
This variable conditionally defines the `HAS_GETLOGIN` symbol, which indicates to the C program that the getlogin() routine is available to get the login name.
`d_getlogin_r` From *d\_getlogin\_r.U*:
This variable conditionally defines the `HAS_GETLOGIN_R` symbol, which indicates to the C program that the getlogin\_r() routine is available.
`d_getmnt` From *d\_getmnt.U*:
This variable conditionally defines the `HAS_GETMNT` symbol, which indicates to the C program that the getmnt() routine is available to retrieve one or more mount info blocks by filename.
`d_getmntent` From *d\_getmntent.U*:
This variable conditionally defines the `HAS_GETMNTENT` symbol, which indicates to the C program that the getmntent() routine is available to iterate through mounted files to get their mount info.
`d_getnameinfo` From *d\_getnameinfo.U*:
This variable conditionally defines the `HAS_GETNAMEINFO` symbol, which indicates to the C program that the getnameinfo() function is available.
`d_getnbyaddr` From *d\_getnbyad.U*:
This variable conditionally defines the `HAS_GETNETBYADDR` symbol, which indicates to the C program that the getnetbyaddr() routine is available to look up networks by their `IP` addresses.
`d_getnbyname` From *d\_getnbynm.U*:
This variable conditionally defines the `HAS_GETNETBYNAME` symbol, which indicates to the C program that the getnetbyname() routine is available to look up networks by their names.
`d_getnent` From *d\_getnent.U*:
This variable conditionally defines `HAS_GETNETENT` if getnetent() is available to look up network names in some data base or another.
`d_getnetbyaddr_r` From *d\_getnetbyaddr\_r.U*:
This variable conditionally defines the `HAS_GETNETBYADDR_R` symbol, which indicates to the C program that the getnetbyaddr\_r() routine is available.
`d_getnetbyname_r` From *d\_getnetbyname\_r.U*:
This variable conditionally defines the `HAS_GETNETBYNAME_R` symbol, which indicates to the C program that the getnetbyname\_r() routine is available.
`d_getnetent_r` From *d\_getnetent\_r.U*:
This variable conditionally defines the `HAS_GETNETENT_R` symbol, which indicates to the C program that the getnetent\_r() routine is available.
`d_getnetprotos` From *d\_getnetprotos.U*:
This variable conditionally defines the `HAS_GETNET_PROTOS` symbol, which indicates to the C program that <netdb.h> supplies prototypes for the various getnet\*() functions. See also *netdbtype.U* for probing for various netdb types.
`d_getpagsz` From *d\_getpagsz.U*:
This variable conditionally defines `HAS_GETPAGESIZE` if getpagesize() is available to get the system page size.
`d_getpbyname` From *d\_getprotby.U*:
This variable conditionally defines the `HAS_GETPROTOBYNAME` symbol, which indicates to the C program that the getprotobyname() routine is available to look up protocols by their name.
`d_getpbynumber` From *d\_getprotby.U*:
This variable conditionally defines the `HAS_GETPROTOBYNUMBER` symbol, which indicates to the C program that the getprotobynumber() routine is available to look up protocols by their number.
`d_getpent` From *d\_getpent.U*:
This variable conditionally defines `HAS_GETPROTOENT` if getprotoent() is available to look up protocols in some data base or another.
`d_getpgid` From *d\_getpgid.U*:
This variable conditionally defines the `HAS_GETPGID` symbol, which indicates to the C program that the getpgid(pid) function is available to get the process group id.
`d_getpgrp` From *d\_getpgrp.U*:
This variable conditionally defines `HAS_GETPGRP` if getpgrp() is available to get the current process group.
`d_getpgrp2` From *d\_getpgrp2.U*:
This variable conditionally defines the HAS\_GETPGRP2 symbol, which indicates to the C program that the getpgrp2() (as in *DG/`UX`*) routine is available to get the current process group.
`d_getppid` From *d\_getppid.U*:
This variable conditionally defines the `HAS_GETPPID` symbol, which indicates to the C program that the getppid() routine is available to get the parent process `ID`.
`d_getprior` From *d\_getprior.U*:
This variable conditionally defines `HAS_GETPRIORITY` if getpriority() is available to get a process's priority.
`d_getprotobyname_r` From *d\_getprotobyname\_r.U*:
This variable conditionally defines the `HAS_GETPROTOBYNAME_R` symbol, which indicates to the C program that the getprotobyname\_r() routine is available.
`d_getprotobynumber_r` From *d\_getprotobynumber\_r.U*:
This variable conditionally defines the `HAS_GETPROTOBYNUMBER_R` symbol, which indicates to the C program that the getprotobynumber\_r() routine is available.
`d_getprotoent_r` From *d\_getprotoent\_r.U*:
This variable conditionally defines the `HAS_GETPROTOENT_R` symbol, which indicates to the C program that the getprotoent\_r() routine is available.
`d_getprotoprotos` From *d\_getprotoprotos.U*:
This variable conditionally defines the `HAS_GETPROTO_PROTOS` symbol, which indicates to the C program that <netdb.h> supplies prototypes for the various getproto\*() functions. See also *netdbtype.U* for probing for various netdb types.
`d_getprpwnam` From *d\_getprpwnam.U*:
This variable conditionally defines `HAS_GETPRPWNAM` if getprpwnam() is available to retrieve protected (shadow) password entries by name.
`d_getpwent` From *d\_getpwent.U*:
This variable conditionally defines the `HAS_GETPWENT` symbol, which indicates to the C program that the getpwent() routine is available for sequential access of the passwd database.
`d_getpwent_r` From *d\_getpwent\_r.U*:
This variable conditionally defines the `HAS_GETPWENT_R` symbol, which indicates to the C program that the getpwent\_r() routine is available.
`d_getpwnam_r` From *d\_getpwnam\_r.U*:
This variable conditionally defines the `HAS_GETPWNAM_R` symbol, which indicates to the C program that the getpwnam\_r() routine is available.
`d_getpwuid_r` From *d\_getpwuid\_r.U*:
This variable conditionally defines the `HAS_GETPWUID_R` symbol, which indicates to the C program that the getpwuid\_r() routine is available.
`d_getsbyname` From *d\_getsrvby.U*:
This variable conditionally defines the `HAS_GETSERVBYNAME` symbol, which indicates to the C program that the getservbyname() routine is available to look up services by their name.
`d_getsbyport` From *d\_getsrvby.U*:
This variable conditionally defines the `HAS_GETSERVBYPORT` symbol, which indicates to the C program that the getservbyport() routine is available to look up services by their port.
`d_getsent` From *d\_getsent.U*:
This variable conditionally defines `HAS_GETSERVENT` if getservent() is available to look up network services in some data base or another.
`d_getservbyname_r` From *d\_getservbyname\_r.U*:
This variable conditionally defines the `HAS_GETSERVBYNAME_R` symbol, which indicates to the C program that the getservbyname\_r() routine is available.
`d_getservbyport_r` From *d\_getservbyport\_r.U*:
This variable conditionally defines the `HAS_GETSERVBYPORT_R` symbol, which indicates to the C program that the getservbyport\_r() routine is available.
`d_getservent_r` From *d\_getservent\_r.U*:
This variable conditionally defines the `HAS_GETSERVENT_R` symbol, which indicates to the C program that the getservent\_r() routine is available.
`d_getservprotos` From *d\_getservprotos.U*:
This variable conditionally defines the `HAS_GETSERV_PROTOS` symbol, which indicates to the C program that <netdb.h> supplies prototypes for the various getserv\*() functions. See also *netdbtype.U* for probing for various netdb types.
`d_getspnam` From *d\_getspnam.U*:
This variable conditionally defines `HAS_GETSPNAM` if getspnam() is available to retrieve SysV shadow password entries by name.
`d_getspnam_r` From *d\_getspnam\_r.U*:
This variable conditionally defines the `HAS_GETSPNAM_R` symbol, which indicates to the C program that the getspnam\_r() routine is available.
`d_gettimeod` From *d\_ftime.U*:
This variable conditionally defines the `HAS_GETTIMEOFDAY` symbol, which indicates that the gettimeofday() system call exists (to obtain a sub-second accuracy clock). You should probably include <sys/resource.h>.
`d_gmtime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_GMTIME64 symbol, which indicates to the C program that the gmtime64 () routine is available.
`d_gmtime_r` From *d\_gmtime\_r.U*:
This variable conditionally defines the `HAS_GMTIME_R` symbol, which indicates to the C program that the gmtime\_r() routine is available.
`d_gnulibc` From *d\_gnulibc.U*:
Defined if we're dealing with the `GNU` C Library.
`d_grpasswd` From *i\_grp.U*:
This variable conditionally defines `GRPASSWD`, which indicates that struct group in <grp.h> contains gr\_passwd.
`d_has_C_UTF8` From *d\_setlocale.U*:
This variable is set to either `true` or `false` depending on whether the compilation system supports the *C.UTF*-8 locale.
`d_hasmntopt` From *d\_hasmntopt.U*:
This variable conditionally defines the `HAS_HASMNTOPT` symbol, which indicates to the C program that the hasmntopt() routine is available to query the mount options of file systems.
`d_htonl` From *d\_htonl.U*:
This variable conditionally defines `HAS_HTONL` if htonl() and its friends are available to do network order byte swapping.
`d_hypot` From *d\_hypot.U*:
This variable conditionally defines `HAS_HYPOT` if hypot is available for numerically stable hypotenuse function.
`d_ilogb` From *d\_ilogb.U*:
This variable conditionally defines the `HAS_ILOGB` symbol, which indicates to the C program that the ilogb() routine is available for extracting the exponent of double x as a signed integer.
`d_ilogbl` From *d\_ilogbl.U*:
This variable conditionally defines the `HAS_ILOGBL` symbol, which indicates to the C program that the ilogbl() routine is available for extracting the exponent of long double x as a signed integer. If scalbnl is also present we can emulate frexpl.
`d_inc_version_list` From *inc\_version\_list.U*:
This variable conditionally defines `PERL_INC_VERSION_LIST`. It is set to undef when `PERL_INC_VERSION_LIST` is empty.
`d_inetaton` From *d\_inetaton.U*:
This variable conditionally defines the `HAS_INET_ATON` symbol, which indicates to the C program that the inet\_aton() function is available to parse `IP` address `dotted-quad` strings.
`d_inetntop` From *d\_inetntop.U*:
This variable conditionally defines the `HAS_INETNTOP` symbol, which indicates to the C program that the inet\_ntop() function is available.
`d_inetpton` From *d\_inetpton.U*:
This variable conditionally defines the `HAS_INETPTON` symbol, which indicates to the C program that the inet\_pton() function is available.
`d_int64_t` From *d\_int64\_t.U*:
This symbol will be defined if the C compiler supports int64\_t.
`d_ip_mreq` From *d\_socket.U*:
This variable conditionally defines the `HAS_IP_MREQ` symbol, which indicates the availability of a struct ip\_mreq.
`d_ip_mreq_source` From *d\_socket.U*:
This variable conditionally defines the `HAS_IP_MREQ_SOURCE` symbol, which indicates the availability of a struct ip\_mreq\_source.
`d_ipv6_mreq` From *d\_socket.U*:
This variable conditionally defines the HAS\_IPV6\_MREQ symbol, which indicates the availability of a struct ipv6\_mreq.
`d_ipv6_mreq_source` From *d\_socket.U*:
This variable conditionally defines the HAS\_IPV6\_MREQ\_SOURCE symbol, which indicates the availability of a struct ipv6\_mreq\_source.
`d_isascii` From *d\_isascii.U*:
This variable conditionally defines the `HAS_ISASCII` constant, which indicates to the C program that isascii() is available.
`d_isblank` From *d\_isblank.U*:
This variable conditionally defines the `HAS_ISBLANK` constant, which indicates to the C program that isblank() is available.
`d_isfinite` From *d\_isfinite.U*:
This variable conditionally defines the `HAS_ISFINITE` symbol, which indicates to the C program that the isfinite() routine is available.
`d_isfinitel` From *d\_isfinitel.U*:
This variable conditionally defines the `HAS_ISFINITEL` symbol, which indicates to the C program that the isfinitel() routine is available.
`d_isinf` From *d\_isinf.U*:
This variable conditionally defines the `HAS_ISINF` symbol, which indicates to the C program that the isinf() routine is available.
`d_isinfl` From *d\_isinfl.U*:
This variable conditionally defines the `HAS_ISINFL` symbol, which indicates to the C program that the isinfl() routine is available.
`d_isless` From *d\_isless.U*:
This variable conditionally defines the `HAS_ISLESS` symbol, which indicates to the C program that the isless() routine is available.
`d_isnan` From *d\_isnan.U*:
This variable conditionally defines the `HAS_ISNAN` symbol, which indicates to the C program that the isnan() routine is available.
`d_isnanl` From *d\_isnanl.U*:
This variable conditionally defines the `HAS_ISNANL` symbol, which indicates to the C program that the isnanl() routine is available.
`d_isnormal` From *d\_isnormal.U*:
This variable conditionally defines the `HAS_ISNORMAL` symbol, which indicates to the C program that the isnormal() routine is available.
`d_j0` From *d\_j0.U*:
This variable conditionally defines the HAS\_J0 symbol, which indicates to the C program that the j0() routine is available.
`d_j0l` From *d\_j0.U*:
This variable conditionally defines the HAS\_J0L symbol, which indicates to the C program that the j0l() routine is available.
`d_killpg` From *d\_killpg.U*:
This variable conditionally defines the `HAS_KILLPG` symbol, which indicates to the C program that the killpg() routine is available to kill process groups.
`d_lc_monetary_2008` From *d\_lc\_monetary\_2008.U*:
This variable conditionally defines HAS\_LC\_MONETARY\_2008 if libc has the international currency locale rules from `POSIX` 1003.1-2008.
`d_lchown` From *d\_lchown.U*:
This variable conditionally defines the `HAS_LCHOWN` symbol, which indicates to the C program that the lchown() routine is available to operate on a symbolic link (instead of following the link).
`d_ldbl_dig` From *d\_ldbl\_dig.U*:
This variable conditionally defines d\_ldbl\_dig if this system's header files provide `LDBL_DIG`, which is the number of significant digits in a long double precision number.
`d_ldexpl` From *d\_longdbl.U*:
This variable conditionally defines the `HAS_LDEXPL` symbol, which indicates to the C program that the ldexpl() routine is available.
`d_lgamma` From *d\_lgamma.U*:
This variable conditionally defines the `HAS_LGAMMA` symbol, which indicates to the C program that the lgamma() routine is available for the log gamma function. See also d\_tgamma and d\_lgamma\_r.
`d_lgamma_r` From *d\_lgamma\_r.U*:
This variable conditionally defines the `HAS_LGAMMA_R` symbol, which indicates to the C program that the lgamma\_r() routine is available for the log gamma function, without using the global signgam variable.
`d_libm_lib_version` From *d\_libm\_lib\_version.U*:
This variable conditionally defines the `LIBM_LIB_VERSION` symbol, which indicates to the C program that *math.h* defines `_LIB_VERSION` being available in libm
`d_libname_unique` From *so.U*:
This variable is defined if the target system insists on unique basenames for shared library files. This is currently true on Android, false everywhere else we know of. Defaults to `undef`.
`d_link` From *d\_link.U*:
This variable conditionally defines `HAS_LINK` if link() is available to create hard links.
`d_linkat` From *d\_fsat.U*:
This variable conditionally defines the `HAS_LINKAT` symbol, which indicates the `POSIX` linkat() function is available.
`d_llrint` From *d\_llrint.U*:
This variable conditionally defines the `HAS_LLRINT` symbol, which indicates to the C program that the llrint() routine is available to return the long long value closest to a double (according to the current rounding mode).
`d_llrintl` From *d\_llrintl.U*:
This variable conditionally defines the `HAS_LLRINTL` symbol, which indicates to the C program that the llrintl() routine is available to return the long long value closest to a long double (according to the current rounding mode).
`d_llround` From *d\_llround.U*:
This variable conditionally defines the `HAS_LLROUND` symbol, which indicates to the C program that the llround() routine is available to return the long long value nearest to x.
`d_llroundl` From *d\_llroundl.U*:
This variable conditionally defines the `HAS_LLROUNDL` symbol, which indicates to the C program that the llroundl() routine is available to return the long long value nearest to x away from zero.
`d_localeconv_l` From *d\_localeconv\_l.U*:
This variable conditionally defines the `HAS_LOCALECONV_L` symbol, which indicates to the C program that the localeconv\_l() routine is available.
`d_localtime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_LOCALTIME64 symbol, which indicates to the C program that the localtime64 () routine is available.
`d_localtime_r` From *d\_localtime\_r.U*:
This variable conditionally defines the `HAS_LOCALTIME_R` symbol, which indicates to the C program that the localtime\_r() routine is available.
`d_localtime_r_needs_tzset` From *d\_localtime\_r.U*:
This variable conditionally defines the `LOCALTIME_R_NEEDS_TZSET` symbol, which makes us call tzset before localtime\_r()
`d_locconv` From *d\_locconv.U*:
This variable conditionally defines `HAS_LOCALECONV` if localeconv() is available for numeric and monetary formatting conventions.
`d_lockf` From *d\_lockf.U*:
This variable conditionally defines `HAS_LOCKF` if lockf() is available to do file locking.
`d_log1p` From *d\_log1p.U*:
This variable conditionally defines the HAS\_LOG1P symbol, which indicates to the C program that the logp1() routine is available to compute log(1 + x) for values of x close to zero.
`d_log2` From *d\_log2.U*:
This variable conditionally defines the HAS\_LOG2 symbol, which indicates to the C program that the log2() routine is available to compute log base two.
`d_logb` From *d\_logb.U*:
This variable conditionally defines the `HAS_LOGB` symbol, which indicates to the C program that the logb() routine is available to extract the exponent of x.
`d_long_double_style_ieee` From *d\_longdbl.U*:
This variable conditionally defines `LONG_DOUBLE_STYLE_IEEE` if 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`.
`d_long_double_style_ieee_doubledouble` From *d\_longdbl.U*:
This variable conditionally defines `LONG_DOUBLE_STYLE_IEEE_DOUBLEDOUBLE` if the long double is the 128-bit `IEEE` 754 double-double.
`d_long_double_style_ieee_extended` From *d\_longdbl.U*:
This variable conditionally defines `LONG_DOUBLE_STYLE_IEEE_EXTENDED` if the long double is the 80-bit `IEEE` 754 extended precision. Note that despite the `extended` this is less than the `std`, since this is an extension of the double precision.
`d_long_double_style_ieee_std` From *d\_longdbl.U*:
This variable conditionally defines `LONG_DOUBLE_STYLE_IEEE_STD` if the long double is the 128-bit `IEEE` 754.
`d_long_double_style_vax` From *d\_longdbl.U*:
This variable conditionally defines `LONG_DOUBLE_STYLE_VAX` if the long double is the 128-bit `VAX` format H.
`d_longdbl` From *d\_longdbl.U*:
This variable conditionally defines `HAS_LONG_DOUBLE` if the long double type is supported.
`d_longlong` From *d\_longlong.U*:
This variable conditionally defines `HAS_LONG_LONG` if the long long type is supported.
`d_lrint` From *d\_lrint.U*:
This variable conditionally defines the `HAS_LRINT` symbol, which indicates to the C program that the lrint() routine is available to return the integral value closest to a double (according to the current rounding mode).
`d_lrintl` From *d\_lrintl.U*:
This variable conditionally defines the `HAS_LRINTL` symbol, which indicates to the C program that the lrintl() routine is available to return the integral value closest to a long double (according to the current rounding mode).
`d_lround` From *d\_lround.U*:
This variable conditionally defines the `HAS_LROUND` symbol, which indicates to the C program that the lround() routine is available to return the integral value nearest to x.
`d_lroundl` From *d\_lroundl.U*:
This variable conditionally defines the `HAS_LROUNDL` symbol, which indicates to the C program that the lroundl() routine is available to return the integral value nearest to x away from zero.
`d_lseekproto` From *d\_lseekproto.U*:
This variable conditionally defines the `HAS_LSEEK_PROTO` symbol, which indicates to the C program that the system provides a prototype for the lseek() function. Otherwise, it is up to the program to supply one.
`d_lstat` From *d\_lstat.U*:
This variable conditionally defines `HAS_LSTAT` if lstat() is available to do file stats on symbolic links.
`d_madvise` From *d\_madvise.U*:
This variable conditionally defines `HAS_MADVISE` if madvise() is available to map a file into memory.
`d_malloc_good_size` From *d\_malloc\_size.U*:
This symbol, if defined, indicates that the malloc\_good\_size routine is available for use.
`d_malloc_size` From *d\_malloc\_size.U*:
This symbol, if defined, indicates that the malloc\_size routine is available for use.
`d_malloc_usable_size` From *d\_malloc\_size.U*:
This symbol, if defined, indicates that the malloc\_usable\_size routine is available for use.
`d_mblen` From *d\_mblen.U*:
This variable conditionally defines the `HAS_MBLEN` symbol, which indicates to the C program that the mblen() routine is available to find the number of bytes in a multibyte character.
`d_mbrlen` From *d\_mbrlen.U*:
This variable conditionally defines the `HAS_MBRLEN` symbol if the mbrlen() routine is available to be used to get the length of multi-byte character strings.
`d_mbrtowc` From *d\_mbrtowc.U*:
This variable conditionally defines the `HAS_MBRTOWC` symbol if the mbrtowc() routine is available to be used to convert a multi-byte character into a wide character.
`d_mbstowcs` From *d\_mbstowcs.U*:
This variable conditionally defines the `HAS_MBSTOWCS` symbol, which indicates to the C program that the mbstowcs() routine is available to convert a multibyte string into a wide character string.
`d_mbtowc` From *d\_mbtowc.U*:
This variable conditionally defines the `HAS_MBTOWC` symbol, which indicates to the C program that the mbtowc() routine is available to convert multibyte to a wide character.
`d_memmem` From *d\_memmem.U*:
This variable conditionally defines the `HAS_MEMMEM` symbol, which indicates to the C program that the memmem() routine is available to return a pointer to the start of the first occurrence of a substring in a memory area (or `NULL` if not found).
`d_memrchr` From *d\_memrchr.U*:
This variable conditionally defines the `HAS_MEMRCHR` symbol, which indicates to the C program that the memrchr() routine is available to return a pointer to the last occurrence of a byte in a memory area (or `NULL` if not found).
`d_mkdir` From *d\_mkdir.U*:
This variable conditionally defines the `HAS_MKDIR` symbol, which indicates to the C program that the mkdir() routine is available to create *directories.*.
`d_mkdtemp` From *d\_mkdtemp.U*:
This variable conditionally defines the `HAS_MKDTEMP` symbol, which indicates to the C program that the mkdtemp() routine is available to exclusively create a uniquely named temporary directory.
`d_mkfifo` From *d\_mkfifo.U*:
This variable conditionally defines the `HAS_MKFIFO` symbol, which indicates to the C program that the mkfifo() routine is available.
`d_mkostemp` From *d\_mkostemp.U*:
This variable conditionally defines `HAS_MKOSTEMP` if mkostemp() is available to exclusively create and open a uniquely named (with a suffix) temporary file.
`d_mkstemp` From *d\_mkstemp.U*:
This variable conditionally defines the `HAS_MKSTEMP` symbol, which indicates to the C program that the mkstemp() routine is available to exclusively create and open a uniquely named temporary file.
`d_mkstemps` From *d\_mkstemps.U*:
This variable conditionally defines the `HAS_MKSTEMPS` symbol, which indicates to the C program that the mkstemps() routine is available to exclusively create and open a uniquely named (with a suffix) temporary file.
`d_mktime` From *d\_mktime.U*:
This variable conditionally defines the `HAS_MKTIME` symbol, which indicates to the C program that the mktime() routine is available.
`d_mktime64` From *d\_timefuncs64.U*:
This variable conditionally defines the HAS\_MKTIME64 symbol, which indicates to the C program that the mktime64 () routine is available.
`d_mmap` From *d\_mmap.U*:
This variable conditionally defines `HAS_MMAP` if mmap() is available to map a file into memory.
`d_modfl` From *d\_modfl.U*:
This variable conditionally defines the `HAS_MODFL` symbol, which indicates to the C program that the modfl() routine is available.
`d_modflproto` From *d\_modfl.U*:
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. C99 says it should be long double modfl(long double, long double \*);
`d_mprotect` From *d\_mprotect.U*:
This variable conditionally defines `HAS_MPROTECT` if mprotect() is available to modify the access protection of a memory mapped file.
`d_msg` From *d\_msg.U*:
This variable conditionally defines the `HAS_MSG` symbol, which indicates that the entire msg\*(2) library is present.
`d_msg_ctrunc` From *d\_socket.U*:
This variable conditionally defines the `HAS_MSG_CTRUNC` symbol, which indicates that the `MSG_CTRUNC` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_msg_dontroute` From *d\_socket.U*:
This variable conditionally defines the `HAS_MSG_DONTROUTE` symbol, which indicates that the `MSG_DONTROUTE` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_msg_oob` From *d\_socket.U*:
This variable conditionally defines the `HAS_MSG_OOB` symbol, which indicates that the `MSG_OOB` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_msg_peek` From *d\_socket.U*:
This variable conditionally defines the `HAS_MSG_PEEK` symbol, which indicates that the `MSG_PEEK` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_msg_proxy` From *d\_socket.U*:
This variable conditionally defines the `HAS_MSG_PROXY` symbol, which indicates that the `MSG_PROXY` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_msgctl` From *d\_msgctl.U*:
This variable conditionally defines the `HAS_MSGCTL` symbol, which indicates to the C program that the msgctl() routine is available.
`d_msgget` From *d\_msgget.U*:
This variable conditionally defines the `HAS_MSGGET` symbol, which indicates to the C program that the msgget() routine is available.
`d_msghdr_s` From *d\_msghdr\_s.U*:
This variable conditionally defines the `HAS_STRUCT_MSGHDR` symbol, which indicates that the struct msghdr is supported.
`d_msgrcv` From *d\_msgrcv.U*:
This variable conditionally defines the `HAS_MSGRCV` symbol, which indicates to the C program that the msgrcv() routine is available.
`d_msgsnd` From *d\_msgsnd.U*:
This variable conditionally defines the `HAS_MSGSND` symbol, which indicates to the C program that the msgsnd() routine is available.
`d_msync` From *d\_msync.U*:
This variable conditionally defines `HAS_MSYNC` if msync() is available to synchronize a mapped file.
`d_munmap` From *d\_munmap.U*:
This variable conditionally defines `HAS_MUNMAP` if munmap() is available to unmap a region mapped by mmap().
`d_mymalloc` From *mallocsrc.U*:
This variable conditionally defines `MYMALLOC` in case other parts of the source want to take special action if `MYMALLOC` is used. This may include different sorts of profiling or error detection.
`d_nan` From *d\_nan.U*:
This variable conditionally defines `HAS_NAN` if nan() is available to generate NaN.
`d_nanosleep` From *d\_nanosleep.U*:
This variable conditionally defines `HAS_NANOSLEEP` if nanosleep() is available to sleep with 1E-9 sec accuracy.
`d_ndbm` From *i\_ndbm.U*:
This variable conditionally defines the `HAS_NDBM` symbol, which indicates that both the *ndbm.h* include file and an appropriate ndbm library exist. Consult the different i\_\*ndbm variables to find out the actual include location. Sometimes, a system has the header file but not the library. This variable will only be set if the system has both.
`d_ndbm_h_uses_prototypes` From *i\_ndbm.U*:
This variable conditionally defines the `NDBM_H_USES_PROTOTYPES` symbol, which indicates that the *ndbm.h* include file uses real `ANSI` C prototypes instead of K&R style function declarations. K&R style declarations are unsupported in C++, so the include file requires special handling when using a C++ compiler and this variable is undefined. Consult the different d\_\*ndbm\_h\_uses\_prototypes variables to get the same information for alternative *ndbm.h* include files.
`d_nearbyint` From *d\_nearbyint.U*:
This variable conditionally defines `HAS_NEARBYINT` if nearbyint() is available to return the integral value closest to (according to the current rounding mode) to x.
`d_newlocale` From *d\_newlocale.U*:
This variable conditionally defines the `HAS_NEWLOCALE` symbol, which indicates to the C program that the newlocale() routine is available to return a new locale object or modify an existing locale object.
`d_nextafter` From *d\_nextafter.U*:
This variable conditionally defines `HAS_NEXTAFTER` if nextafter() is available to return the next machine representable double from x in direction y.
`d_nexttoward` From *d\_nexttoward.U*:
This variable conditionally defines `HAS_NEXTTOWARD` if nexttoward() is available to return the next machine representable long double from x in direction y.
`d_nice` From *d\_nice.U*:
This variable conditionally defines the `HAS_NICE` symbol, which indicates to the C program that the nice() routine is available.
`d_nl_langinfo` From *d\_nl\_langinfo.U*:
This variable conditionally defines the `HAS_NL_LANGINFO` symbol, which indicates to the C program that the nl\_langinfo() routine is available.
`d_nl_langinfo_l` From *d\_nl\_langinfo\_l.U*:
This variable contains the eventual value of the `HAS_NL_LANGINFO_L` symbol, which indicates if the nl\_langinfo\_l() function exists.
`d_non_int_bitfields` From *d\_bitfield.U*:
This variable conditionally defines `HAS_NON_INT_BITFIELDS` which indicates that the C compiler accepts struct bitfields of sizes that aren't `int` or `unsigned int`
`d_nv_preserves_uv` From *perlxv.U*:
This variable indicates whether a variable of type nvtype can preserve all the bits a variable of type uvtype.
`d_nv_zero_is_allbits_zero` From *perlxv.U*:
This variable indicates whether a variable of type nvtype stores 0.0 in memory as all bits zero.
`d_off64_t` From *d\_off64\_t.U*:
This symbol will be defined if the C compiler supports off64\_t.
`d_old_pthread_create_joinable` From *d\_pthrattrj.U*:
This variable conditionally defines pthread\_create\_joinable. undef if *pthread.h* defines `PTHREAD_CREATE_JOINABLE`.
`d_oldpthreads` From *usethreads.U*:
This variable conditionally defines the `OLD_PTHREADS_API` symbol, and indicates that Perl should be built to use the old draft `POSIX` threads `API`. This is only potentially meaningful if usethreads is set.
`d_oldsock` From *d\_socket.U*:
This variable conditionally defines the `OLDSOCKET` symbol, which indicates that the `BSD` socket interface is based on 4.1c and not 4.2.
`d_open3` From *d\_open3.U*:
This variable conditionally defines the HAS\_OPEN3 manifest constant, which indicates to the C program that the 3 argument version of the open(2) function is available.
`d_openat` From *d\_fsat.U*:
This variable conditionally defines the `HAS_OPENAT` symbol, which indicates the `POSIX` openat() function is available.
`d_pathconf` From *d\_pathconf.U*:
This variable conditionally defines the `HAS_PATHCONF` symbol, which indicates to the C program that the pathconf() routine is available to determine file-system related limits and options associated with a given filename.
`d_pause` From *d\_pause.U*:
This variable conditionally defines the `HAS_PAUSE` symbol, which indicates to the C program that the pause() routine is available to suspend a process until a signal is received.
`d_perl_otherlibdirs` From *otherlibdirs.U*:
This variable conditionally defines `PERL_OTHERLIBDIRS`, which contains a colon-separated set of paths for the perl binary to include in @`INC`. See also otherlibdirs.
`d_phostname` From *d\_gethname.U*:
This variable conditionally defines the `HAS_PHOSTNAME` symbol, which contains the shell command which, when fed to popen(), may be used to derive the host name.
`d_pipe` From *d\_pipe.U*:
This variable conditionally defines the `HAS_PIPE` symbol, which indicates to the C program that the pipe() routine is available to create an inter-process channel.
`d_pipe2` From *d\_pipe2.U*:
This variable conditionally defines the HAS\_PIPE2 symbol, which indicates to the C program that the pipe2() routine is available to create an inter-process channel.
`d_poll` From *d\_poll.U*:
This variable conditionally defines the `HAS_POLL` symbol, which indicates to the C program that the poll() routine is available to poll active file descriptors.
`d_portable` From *d\_portable.U*:
This variable conditionally defines the `PORTABLE` symbol, which indicates to the C program that it should not assume that it is running on the machine it was compiled on.
`d_prctl` From *d\_prctl.U*:
This variable conditionally defines the `HAS_PRCTL` symbol, which indicates to the C program that the prctl() routine is available. Note that there are at least two prctl variants: Linux and Irix. While they are somewhat similar, they are incompatible.
`d_prctl_set_name` From *d\_prctl.U*:
This variable conditionally defines the `HAS_PRCTL_SET_NAME` symbol, which indicates to the C program that the prctl() routine supports the `PR_SET_NAME` option.
`d_PRId64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRId64 symbol, which indicates that stdio has a symbol to print 64-bit decimal numbers.
`d_PRIeldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles.
`d_PRIEUldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles. The `U` in the name is to separate this from d\_PRIeldbl so that even case-blind systems can see the difference.
`d_PRIfldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles.
`d_PRIFUldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles. The `U` in the name is to separate this from d\_PRIfldbl so that even case-blind systems can see the difference.
`d_PRIgldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles.
`d_PRIGUldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to print long doubles. The `U` in the name is to separate this from d\_PRIgldbl so that even case-blind systems can see the difference.
`d_PRIi64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRIi64 symbol, which indicates that stdio has a symbol to print 64-bit decimal numbers.
`d_printf_format_null` From *d\_attribut.U*:
This variable conditionally defines `PRINTF_FORMAT_NULL_OK`, which indicates the C compiler allows printf-like formats to be null.
`d_PRIo64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRIo64 symbol, which indicates that stdio has a symbol to print 64-bit octal numbers.
`d_PRIu64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRIu64 symbol, which indicates that stdio has a symbol to print 64-bit unsigned decimal numbers.
`d_PRIx64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRIx64 symbol, which indicates that stdio has a symbol to print 64-bit hexadecimal numbers.
`d_PRIXU64` From *quadfio.U*:
This variable conditionally defines the PERL\_PRIXU64 symbol, which indicates that stdio has a symbol to print 64-bit hExADECimAl numbers. The `U` in the name is to separate this from d\_PRIx64 so that even case-blind systems can see the difference.
`d_procselfexe` From *d\_procselfexe.U*:
Defined if $procselfexe is symlink to the absolute pathname of the executing program.
`d_pseudofork` From *d\_vfork.U*:
This variable conditionally defines the `HAS_PSEUDOFORK` symbol, which indicates that an emulation of the fork routine is available.
`d_pthread_atfork` From *d\_pthread\_atfork.U*:
This variable conditionally defines the `HAS_PTHREAD_ATFORK` symbol, which indicates to the C program that the pthread\_atfork() routine is available.
`d_pthread_attr_setscope` From *d\_pthread\_attr\_ss.U*:
This variable conditionally defines `HAS_PTHREAD_ATTR_SETSCOPE` if pthread\_attr\_setscope() is available to set the contention scope attribute of a thread attribute object.
`d_pthread_yield` From *d\_pthread\_y.U*:
This variable conditionally defines the `HAS_PTHREAD_YIELD` symbol if the pthread\_yield routine is available to yield the execution of the current thread.
`d_ptrdiff_t` From *d\_ptrdiff\_t.U*:
This symbol will be defined if the C compiler supports ptrdiff\_t.
`d_pwage` From *i\_pwd.U*:
This variable conditionally defines `PWAGE`, which indicates that struct passwd contains pw\_age.
`d_pwchange` From *i\_pwd.U*:
This variable conditionally defines `PWCHANGE`, which indicates that struct passwd contains pw\_change.
`d_pwclass` From *i\_pwd.U*:
This variable conditionally defines `PWCLASS`, which indicates that struct passwd contains pw\_class.
`d_pwcomment` From *i\_pwd.U*:
This variable conditionally defines `PWCOMMENT`, which indicates that struct passwd contains pw\_comment.
`d_pwexpire` From *i\_pwd.U*:
This variable conditionally defines `PWEXPIRE`, which indicates that struct passwd contains pw\_expire.
`d_pwgecos` From *i\_pwd.U*:
This variable conditionally defines `PWGECOS`, which indicates that struct passwd contains pw\_gecos.
`d_pwpasswd` From *i\_pwd.U*:
This variable conditionally defines `PWPASSWD`, which indicates that struct passwd contains pw\_passwd.
`d_pwquota` From *i\_pwd.U*:
This variable conditionally defines `PWQUOTA`, which indicates that struct passwd contains pw\_quota.
`d_qgcvt` From *d\_qgcvt.U*:
This variable conditionally defines the `HAS_QGCVT` symbol, which indicates to the C program that the qgcvt() routine is available.
`d_quad` From *quadtype.U*:
This variable, if defined, tells that there's a 64-bit integer type, quadtype.
`d_querylocale` From *d\_newlocale.U*:
This variable conditionally defines the `HAS_QUERYLOCALE` symbol, which indicates to the C program that the querylocale() routine is available to return the name of the locale for a category mask.
`d_random_r` From *d\_random\_r.U*:
This variable conditionally defines the `HAS_RANDOM_R` symbol, which indicates to the C program that the random\_r() routine is available.
`d_re_comp` From *d\_regcmp.U*:
This variable conditionally defines the `HAS_RECOMP` symbol, which indicates to the C program that the re\_comp() routine is available for regular pattern matching (usually on `BSD`). If so, it is likely that re\_exec() exists.
`d_readdir` From *d\_readdir.U*:
This variable conditionally defines `HAS_READDIR` if readdir() is available to read directory entries.
`d_readdir64_r` From *d\_readdir64\_r.U*:
This variable conditionally defines the HAS\_READDIR64\_R symbol, which indicates to the C program that the readdir64\_r() routine is available.
`d_readdir_r` From *d\_readdir\_r.U*:
This variable conditionally defines the `HAS_READDIR_R` symbol, which indicates to the C program that the readdir\_r() routine is available.
`d_readlink` From *d\_readlink.U*:
This variable conditionally defines the `HAS_READLINK` symbol, which indicates to the C program that the readlink() routine is available to read the value of a symbolic link.
`d_readv` From *d\_readv.U*:
This variable conditionally defines the `HAS_READV` symbol, which indicates to the C program that the readv() routine is available.
`d_recvmsg` From *d\_recvmsg.U*:
This variable conditionally defines the `HAS_RECVMSG` symbol, which indicates to the C program that the recvmsg() routine is available.
`d_regcmp` From *d\_regcmp.U*:
This variable conditionally defines the `HAS_REGCMP` symbol, which indicates to the C program that the regcmp() routine is available for regular pattern matching (usually on System V).
`d_regcomp` From *d\_regcmp.U*:
This variable conditionally defines the `HAS_REGCOMP` symbol, which indicates to the C program that the regcomp() routine is available for regular pattern matching (usually on *POSIX.2* conforming systems).
`d_remainder` From *d\_remainder.U*:
This variable conditionally defines the `HAS_REMAINDER` symbol, which indicates to the C program that the remainder() routine is available.
`d_remquo` From *d\_remquo.U*:
This variable conditionally defines the `HAS_REMQUO` symbol, which indicates to the C program that the remquo() routine is available.
`d_rename` From *d\_rename.U*:
This variable conditionally defines the `HAS_RENAME` symbol, which indicates to the C program that the rename() routine is available to rename files.
`d_renameat` From *d\_fsat.U*:
This variable conditionally defines the `HAS_RENAMEAT` symbol, which indicates the `POSIX` renameat() function is available.
`d_rewinddir` From *d\_readdir.U*:
This variable conditionally defines `HAS_REWINDDIR` if rewinddir() is available.
`d_rint` From *d\_rint.U*:
This variable conditionally defines the `HAS_RINT` symbol, which indicates to the C program that the rint() routine is available.
`d_rmdir` From *d\_rmdir.U*:
This variable conditionally defines `HAS_RMDIR` if rmdir() is available to remove directories.
`d_round` From *d\_round.U*:
This variable conditionally defines the `HAS_ROUND` symbol, which indicates to the C program that the round() routine is available.
`d_sbrkproto` From *d\_sbrkproto.U*:
This variable conditionally defines the `HAS_SBRK_PROTO` symbol, which indicates to the C program that the system provides a prototype for the sbrk() function. Otherwise, it is up to the program to supply one.
`d_scalbn` From *d\_scalbn.U*:
This variable conditionally defines the `HAS_SCALBN` symbol, which indicates to the C program that the scalbn() routine is available.
`d_scalbnl` From *d\_scalbnl.U*:
This variable conditionally defines the `HAS_SCALBNL` symbol, which indicates to the C program that the scalbnl() routine is available. If ilogbl is also present we can emulate frexpl.
`d_sched_yield` From *d\_pthread\_y.U*:
This variable conditionally defines the `HAS_SCHED_YIELD` symbol if the sched\_yield routine is available to yield the execution of the current thread.
`d_scm_rights` From *d\_socket.U*:
This variable conditionally defines the `HAS_SCM_RIGHTS` symbol, which indicates that the `SCM_RIGHTS` is available. #ifdef is not enough because it may be an enum, glibc has been known to do this.
`d_SCNfldbl` From *longdblfio.U*:
This variable conditionally defines the PERL\_PRIfldbl symbol, which indicates that stdio has a symbol to scan long doubles.
`d_seekdir` From *d\_readdir.U*:
This variable conditionally defines `HAS_SEEKDIR` if seekdir() is available.
`d_select` From *d\_select.U*:
This variable conditionally defines `HAS_SELECT` if select() is available to select active file descriptors. A <sys/time.h> inclusion may be necessary for the timeout field.
`d_sem` From *d\_sem.U*:
This variable conditionally defines the `HAS_SEM` symbol, which indicates that the entire sem\*(2) library is present.
`d_semctl` From *d\_semctl.U*:
This variable conditionally defines the `HAS_SEMCTL` symbol, which indicates to the C program that the semctl() routine is available.
`d_semctl_semid_ds` From *d\_union\_semun.U*:
This variable conditionally defines `USE_SEMCTL_SEMID_DS`, which indicates that struct semid\_ds \* is to be used for semctl `IPC_STAT`.
`d_semctl_semun` From *d\_union\_semun.U*:
This variable conditionally defines `USE_SEMCTL_SEMUN`, which indicates that union semun is to be used for semctl `IPC_STAT`.
`d_semget` From *d\_semget.U*:
This variable conditionally defines the `HAS_SEMGET` symbol, which indicates to the C program that the semget() routine is available.
`d_semop` From *d\_semop.U*:
This variable conditionally defines the `HAS_SEMOP` symbol, which indicates to the C program that the semop() routine is available.
`d_sendmsg` From *d\_sendmsg.U*:
This variable conditionally defines the `HAS_SENDMSG` symbol, which indicates to the C program that the sendmsg() routine is available.
`d_setegid` From *d\_setegid.U*:
This variable conditionally defines the `HAS_SETEGID` symbol, which indicates to the C program that the setegid() routine is available to change the effective gid of the current program.
`d_seteuid` From *d\_seteuid.U*:
This variable conditionally defines the `HAS_SETEUID` symbol, which indicates to the C program that the seteuid() routine is available to change the effective uid of the current program.
`d_setgrent` From *d\_setgrent.U*:
This variable conditionally defines the `HAS_SETGRENT` symbol, which indicates to the C program that the setgrent() routine is available for initializing sequential access to the group database.
`d_setgrent_r` From *d\_setgrent\_r.U*:
This variable conditionally defines the `HAS_SETGRENT_R` symbol, which indicates to the C program that the setgrent\_r() routine is available.
`d_setgrps` From *d\_setgrps.U*:
This variable conditionally defines the `HAS_SETGROUPS` symbol, which indicates to the C program that the setgroups() routine is available to set the list of process groups.
`d_sethent` From *d\_sethent.U*:
This variable conditionally defines `HAS_SETHOSTENT` if sethostent() is available.
`d_sethostent_r` From *d\_sethostent\_r.U*:
This variable conditionally defines the `HAS_SETHOSTENT_R` symbol, which indicates to the C program that the sethostent\_r() routine is available.
`d_setitimer` From *d\_setitimer.U*:
This variable conditionally defines the `HAS_SETITIMER` symbol, which indicates to the C program that the setitimer() routine is available.
`d_setlinebuf` From *d\_setlnbuf.U*:
This variable conditionally defines the `HAS_SETLINEBUF` symbol, which indicates to the C program that the setlinebuf() routine is available to change stderr or stdout from block-buffered or unbuffered to a line-buffered mode.
`d_setlocale` From *d\_setlocale.U*:
This variable conditionally defines `HAS_SETLOCALE` if setlocale() is available to handle locale-specific ctype implementations.
`d_setlocale_accepts_any_locale_name` From *d\_setlocale.U*:
This variable conditionally defines `SETLOCALE_ACCEPTS_ANY_LOCALE_NAME` if setlocale() accepts any locale name.
`d_setlocale_r` From *d\_setlocale\_r.U*:
This variable conditionally defines the `HAS_SETLOCALE_R` symbol, which indicates to the C program that the setlocale\_r() routine is available.
`d_setnent` From *d\_setnent.U*:
This variable conditionally defines `HAS_SETNETENT` if setnetent() is available.
`d_setnetent_r` From *d\_setnetent\_r.U*:
This variable conditionally defines the `HAS_SETNETENT_R` symbol, which indicates to the C program that the setnetent\_r() routine is available.
`d_setpent` From *d\_setpent.U*:
This variable conditionally defines `HAS_SETPROTOENT` if setprotoent() is available.
`d_setpgid` From *d\_setpgid.U*:
This variable conditionally defines the `HAS_SETPGID` symbol if the setpgid(pid, gpid) function is available to set process group `ID`.
`d_setpgrp` From *d\_setpgrp.U*:
This variable conditionally defines `HAS_SETPGRP` if setpgrp() is available to set the current process group.
`d_setpgrp2` From *d\_setpgrp2.U*:
This variable conditionally defines the HAS\_SETPGRP2 symbol, which indicates to the C program that the setpgrp2() (as in *DG/`UX`*) routine is available to set the current process group.
`d_setprior` From *d\_setprior.U*:
This variable conditionally defines `HAS_SETPRIORITY` if setpriority() is available to set a process's priority.
`d_setproctitle` From *d\_setproctitle.U*:
This variable conditionally defines the `HAS_SETPROCTITLE` symbol, which indicates to the C program that the setproctitle() routine is available.
`d_setprotoent_r` From *d\_setprotoent\_r.U*:
This variable conditionally defines the `HAS_SETPROTOENT_R` symbol, which indicates to the C program that the setprotoent\_r() routine is available.
`d_setpwent` From *d\_setpwent.U*:
This variable conditionally defines the `HAS_SETPWENT` symbol, which indicates to the C program that the setpwent() routine is available for initializing sequential access to the passwd database.
`d_setpwent_r` From *d\_setpwent\_r.U*:
This variable conditionally defines the `HAS_SETPWENT_R` symbol, which indicates to the C program that the setpwent\_r() routine is available.
`d_setregid` From *d\_setregid.U*:
This variable conditionally defines `HAS_SETREGID` if setregid() is available to change the real and effective gid of the current process.
`d_setresgid` From *d\_setregid.U*:
This variable conditionally defines `HAS_SETRESGID` if setresgid() is available to change the real, effective and saved gid of the current process.
`d_setresuid` From *d\_setreuid.U*:
This variable conditionally defines `HAS_SETREUID` if setresuid() is available to change the real, effective and saved uid of the current process.
`d_setreuid` From *d\_setreuid.U*:
This variable conditionally defines `HAS_SETREUID` if setreuid() is available to change the real and effective uid of the current process.
`d_setrgid` From *d\_setrgid.U*:
This variable conditionally defines the `HAS_SETRGID` symbol, which indicates to the C program that the setrgid() routine is available to change the real gid of the current program.
`d_setruid` From *d\_setruid.U*:
This variable conditionally defines the `HAS_SETRUID` symbol, which indicates to the C program that the setruid() routine is available to change the real uid of the current program.
`d_setsent` From *d\_setsent.U*:
This variable conditionally defines `HAS_SETSERVENT` if setservent() is available.
`d_setservent_r` From *d\_setservent\_r.U*:
This variable conditionally defines the `HAS_SETSERVENT_R` symbol, which indicates to the C program that the setservent\_r() routine is available.
`d_setsid` From *d\_setsid.U*:
This variable conditionally defines `HAS_SETSID` if setsid() is available to set the process group `ID`.
`d_setvbuf` From *d\_setvbuf.U*:
This variable conditionally defines the `HAS_SETVBUF` symbol, which indicates to the C program that the setvbuf() routine is available to change buffering on an open stdio stream.
`d_shm` From *d\_shm.U*:
This variable conditionally defines the `HAS_SHM` symbol, which indicates that the entire shm\*(2) library is present.
`d_shmat` From *d\_shmat.U*:
This variable conditionally defines the `HAS_SHMAT` symbol, which indicates to the C program that the shmat() routine is available.
`d_shmatprototype` From *d\_shmat.U*:
This variable conditionally defines the `HAS_SHMAT_PROTOTYPE` symbol, which indicates that *sys/shm.h* has a prototype for shmat.
`d_shmctl` From *d\_shmctl.U*:
This variable conditionally defines the `HAS_SHMCTL` symbol, which indicates to the C program that the shmctl() routine is available.
`d_shmdt` From *d\_shmdt.U*:
This variable conditionally defines the `HAS_SHMDT` symbol, which indicates to the C program that the shmdt() routine is available.
`d_shmget` From *d\_shmget.U*:
This variable conditionally defines the `HAS_SHMGET` symbol, which indicates to the C program that the shmget() routine is available.
`d_sigaction` From *d\_sigaction.U*:
This variable conditionally defines the `HAS_SIGACTION` symbol, which indicates that the Vr4 sigaction() routine is available.
`d_siginfo_si_addr` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_ADDR` symbol, which indicates that the siginfo\_t struct has the si\_addr member.
`d_siginfo_si_band` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_BAND` symbol, which indicates that the siginfo\_t struct has the si\_band member.
`d_siginfo_si_errno` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_ERRNO` symbol, which indicates that the siginfo\_t struct has the si\_errno member.
`d_siginfo_si_fd` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_FD` symbol, which indicates that the siginfo\_t struct has the si\_fd member.
`d_siginfo_si_pid` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_PID` symbol, which indicates that the siginfo\_t struct has the si\_pid member.
`d_siginfo_si_status` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_STATUS` symbol, which indicates that the siginfo\_t struct has the si\_status member.
`d_siginfo_si_uid` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_UID` symbol, which indicates that the siginfo\_t struct has the si\_uid member.
`d_siginfo_si_value` From *d\_siginfo\_si.U*:
This variable conditionally defines the `HAS_SIGINFO_SI_VALUE` symbol, which indicates that the siginfo\_t struct has the si\_value member.
`d_signbit` From *d\_signbit.U*:
This variable conditionally defines the `HAS_SIGNBIT` symbol, which indicates to the C program that the signbit() routine is available and safe to use with perl's intern `NV` type.
`d_sigprocmask` From *d\_sigprocmask.U*:
This variable conditionally defines `HAS_SIGPROCMASK` if sigprocmask() is available to examine or change the signal mask of the calling process.
`d_sigsetjmp` From *d\_sigsetjmp.U*:
This variable conditionally defines the `HAS_SIGSETJMP` symbol, which indicates that the sigsetjmp() routine is available to call setjmp() and optionally save the process's signal mask.
`d_sin6_scope_id` From *d\_socket.U*:
This variable conditionally defines the HAS\_SIN6\_SCOPE\_ID symbol, which indicates that a struct sockaddr\_in6 structure has the sin6\_scope\_id member.
`d_sitearch` From *sitearch.U*:
This variable conditionally defines `SITEARCH` to hold the pathname of architecture-dependent library files for $package. If $sitearch is the same as $archlib, then this is set to undef.
`d_snprintf` From *d\_snprintf.U*:
This variable conditionally defines the `HAS_SNPRINTF` symbol, which indicates to the C program that the snprintf () library function is available.
`d_sockaddr_in6` From *d\_socket.U*:
This variable conditionally defines the HAS\_SOCKADDR\_IN6 symbol, which indicates the availability of a struct sockaddr\_in6.
`d_sockaddr_sa_len` From *d\_socket.U*:
This variable conditionally defines the `HAS_SOCKADDR_SA_LEN` symbol, which indicates that a struct sockaddr structure has the sa\_len member.
`d_sockaddr_storage` From *d\_socket.U*:
This variable conditionally defines the `HAS_SOCKADDR_STORAGE` symbol, which indicates the availability of a struct sockaddr\_storage.
`d_sockatmark` From *d\_sockatmark.U*:
This variable conditionally defines the `HAS_SOCKATMARK` symbol, which indicates to the C program that the sockatmark() routine is available.
`d_sockatmarkproto` From *d\_sockatmarkproto.U*:
This variable conditionally defines the `HAS_SOCKATMARK_PROTO` symbol, which indicates to the C program that the system provides a prototype for the sockatmark() function. Otherwise, it is up to the program to supply one.
`d_socket` From *d\_socket.U*:
This variable conditionally defines `HAS_SOCKET`, which indicates that the `BSD` socket interface is supported.
`d_socklen_t` From *d\_socklen\_t.U*:
This symbol will be defined if the C compiler supports socklen\_t.
`d_sockpair` From *d\_socket.U*:
This variable conditionally defines the `HAS_SOCKETPAIR` symbol, which indicates that the `BSD` socketpair() is supported.
`d_socks5_init` From *d\_socks5\_init.U*:
This variable conditionally defines the HAS\_SOCKS5\_INIT symbol, which indicates to the C program that the socks5\_init() routine is available.
`d_sqrtl` From *d\_sqrtl.U*:
This variable conditionally defines the `HAS_SQRTL` symbol, which indicates to the C program that the sqrtl() routine is available.
`d_srand48_r` From *d\_srand48\_r.U*:
This variable conditionally defines the HAS\_SRAND48\_R symbol, which indicates to the C program that the srand48\_r() routine is available.
`d_srandom_r` From *d\_srandom\_r.U*:
This variable conditionally defines the `HAS_SRANDOM_R` symbol, which indicates to the C program that the srandom\_r() routine is available.
`d_sresgproto` From *d\_sresgproto.U*:
This variable conditionally defines the `HAS_SETRESGID_PROTO` symbol, which indicates to the C program that the system provides a prototype for the setresgid() function. Otherwise, it is up to the program to supply one.
`d_sresuproto` From *d\_sresuproto.U*:
This variable conditionally defines the `HAS_SETRESUID_PROTO` symbol, which indicates to the C program that the system provides a prototype for the setresuid() function. Otherwise, it is up to the program to supply one.
`d_stat` From *d\_stat.U*:
This variable conditionally defines `HAS_STAT` if stat() is available to get file status.
`d_statblks` From *d\_statblks.U*:
This variable conditionally defines `USE_STAT_BLOCKS` if this system has a stat structure declaring st\_blksize and st\_blocks.
`d_statfs_f_flags` From *d\_statfs\_f\_flags.U*:
This variable conditionally defines the `HAS_STRUCT_STATFS_F_FLAGS` symbol, which indicates to struct statfs from has f\_flags member. This kind of struct statfs is coming from *sys/mount.h* (`BSD`), not from *sys/statfs.h* (`SYSV`).
`d_statfs_s` From *d\_statfs\_s.U*:
This variable conditionally defines the `HAS_STRUCT_STATFS` symbol, which indicates that the struct statfs is supported.
`d_static_inline` From *d\_static\_inline.U*:
This variable conditionally defines the `HAS_STATIC_INLINE` symbol, which indicates that the C compiler supports C99-style static inline. That is, the function can't be called from another translation unit.
`d_statvfs` From *d\_statvfs.U*:
This variable conditionally defines the `HAS_STATVFS` symbol, which indicates to the C program that the statvfs() routine is available.
`d_stdio_cnt_lval` From *d\_stdstdio.U*:
This variable conditionally defines `STDIO_CNT_LVALUE` if the `FILE_cnt` macro can be used as an lvalue.
`d_stdio_ptr_lval` From *d\_stdstdio.U*:
This variable conditionally defines `STDIO_PTR_LVALUE` if the `FILE_ptr` macro can be used as an lvalue.
`d_stdio_ptr_lval_nochange_cnt` From *d\_stdstdio.U*:
This symbol is defined if using the `FILE_ptr` macro as an lvalue to increase the pointer by n leaves File\_cnt(fp) unchanged.
`d_stdio_ptr_lval_sets_cnt` From *d\_stdstdio.U*:
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.
`d_stdio_stream_array` From *stdio\_streams.U*:
This variable tells whether there is an array holding the stdio streams.
`d_stdiobase` From *d\_stdstdio.U*:
This variable conditionally defines `USE_STDIO_BASE` if this system has a `FILE` structure declaring a usable \_base field (or equivalent) in *stdio.h*.
`d_stdstdio` From *d\_stdstdio.U*:
This variable conditionally defines `USE_STDIO_PTR` if this system has a `FILE` structure declaring usable \_ptr and \_cnt fields (or equivalent) in *stdio.h*.
`d_strcoll` From *d\_strcoll.U*:
This variable conditionally defines `HAS_STRCOLL` if strcoll() is available to compare strings using collating information.
`d_strerror_l` From *d\_strerror\_l.U*:
This variable conditionally defines the `HAS_STRERROR_L` symbol, which indicates to the C program that the strerror\_l() routine is available to return the error message for a given errno value in a particular locale (identified by a locale\_t object).
`d_strerror_r` From *d\_strerror\_r.U*:
This variable conditionally defines the `HAS_STRERROR_R` symbol, which indicates to the C program that the strerror\_r() routine is available.
`d_strftime` From *d\_strftime.U*:
This variable conditionally defines the `HAS_STRFTIME` symbol, which indicates to the C program that the strftime() routine is available.
`d_strlcat` From *d\_strlcat.U*:
This variable conditionally defines the `HAS_STRLCAT` symbol, which indicates to the C program that the strlcat () routine is available.
`d_strlcpy` From *d\_strlcpy.U*:
This variable conditionally defines the `HAS_STRLCPY` symbol, which indicates to the C program that the strlcpy () routine is available.
`d_strnlen` From *d\_strnlen.U*:
This variable conditionally defines the `HAS_STRNLEN` symbol, which indicates to the C program that the strnlen () routine is available.
`d_strtod` From *d\_strtod.U*:
This variable conditionally defines the `HAS_STRTOD` symbol, which indicates to the C program that the strtod() routine is available to provide better numeric string conversion than atof().
`d_strtod_l` From *d\_strtod\_l.U*:
This variable conditionally defines the `HAS_STRTOD_L` symbol, which indicates to the C program that the strtod\_l() routine is available.
`d_strtol` From *d\_strtol.U*:
This variable conditionally defines the `HAS_STRTOL` symbol, which indicates to the C program that the strtol() routine is available to provide better numeric string conversion than atoi() and friends.
`d_strtold` From *d\_strtold.U*:
This variable conditionally defines the `HAS_STRTOLD` symbol, which indicates to the C program that the strtold() routine is available.
`d_strtold_l` From *d\_strtold\_l.U*:
This variable conditionally defines the `HAS_STRTOLD_L` symbol, which indicates to the C program that the strtold\_l() routine is available.
`d_strtoll` From *d\_strtoll.U*:
This variable conditionally defines the `HAS_STRTOLL` symbol, which indicates to the C program that the strtoll() routine is available.
`d_strtoq` From *d\_strtoq.U*:
This variable conditionally defines the `HAS_STRTOQ` symbol, which indicates to the C program that the strtoq() routine is available.
`d_strtoul` From *d\_strtoul.U*:
This variable conditionally defines the `HAS_STRTOUL` symbol, which indicates to the C program that the strtoul() routine is available to provide conversion of strings to unsigned long.
`d_strtoull` From *d\_strtoull.U*:
This variable conditionally defines the `HAS_STRTOULL` symbol, which indicates to the C program that the strtoull() routine is available.
`d_strtouq` From *d\_strtouq.U*:
This variable conditionally defines the `HAS_STRTOUQ` symbol, which indicates to the C program that the strtouq() routine is available.
`d_strxfrm` From *d\_strxfrm.U*:
This variable conditionally defines `HAS_STRXFRM` if strxfrm() is available to transform strings.
`d_strxfrm_l` From *d\_strxfrm\_l.U*:
This variable conditionally defines `HAS_STRXFRM_L` if strxfrm\_l() is available to transform strings.
`d_suidsafe` From *d\_dosuid.U*:
This variable conditionally defines `SETUID_SCRIPTS_ARE_SECURE_NOW` if setuid scripts can be secure. This test looks in */dev/fd/*.
`d_symlink` From *d\_symlink.U*:
This variable conditionally defines the `HAS_SYMLINK` symbol, which indicates to the C program that the symlink() routine is available to create symbolic links.
`d_syscall` From *d\_syscall.U*:
This variable conditionally defines `HAS_SYSCALL` if syscall() is available call arbitrary system calls.
`d_syscallproto` From *d\_syscallproto.U*:
This variable conditionally defines the `HAS_SYSCALL_PROTO` symbol, which indicates to the C program that the system provides a prototype for the syscall() function. Otherwise, it is up to the program to supply one.
`d_sysconf` From *d\_sysconf.U*:
This variable conditionally defines the `HAS_SYSCONF` symbol, which indicates to the C program that the sysconf() routine is available to determine system related limits and options.
`d_sysernlst` From *d\_strerror.U*:
This variable conditionally defines `HAS_SYS_ERRNOLIST` if sys\_errnolist[] is available to translate error numbers to the symbolic name.
`d_syserrlst` From *d\_strerror.U*:
This variable conditionally defines `HAS_SYS_ERRLIST` if sys\_errlist[] is available to translate error numbers to strings.
`d_system` From *d\_system.U*:
This variable conditionally defines `HAS_SYSTEM` if system() is available to issue a shell command.
`d_tcgetpgrp` From *d\_tcgtpgrp.U*:
This variable conditionally defines the `HAS_TCGETPGRP` symbol, which indicates to the C program that the tcgetpgrp() routine is available. to get foreground process group `ID`.
`d_tcsetpgrp` From *d\_tcstpgrp.U*:
This variable conditionally defines the `HAS_TCSETPGRP` symbol, which indicates to the C program that the tcsetpgrp() routine is available to set foreground process group `ID`.
`d_telldir` From *d\_readdir.U*:
This variable conditionally defines `HAS_TELLDIR` if telldir() is available.
`d_telldirproto` From *d\_telldirproto.U*:
This variable conditionally defines the `HAS_TELLDIR_PROTO` symbol, which indicates to the C program that the system provides a prototype for the telldir() function. Otherwise, it is up to the program to supply one.
`d_tgamma` From *d\_tgamma.U*:
This variable conditionally defines the `HAS_TGAMMA` symbol, which indicates to the C program that the tgamma() routine is available for the gamma function. See also d\_lgamma.
`d_thread_local` From *d\_thread\_local.U*:
This variable conditionally defines the `PERL_THREAD_LOCAL` symbol. In turn that gives a linkage specification for thread-local storage.
`d_thread_safe_nl_langinfo_l` From *d\_nl\_langinfo\_l.U*:
This variable contains the eventual value of the `HAS_THREAD_SAFE_NL_LANGINFO_L` symbol, which indicates if the nl\_langinfo\_l() function exists and is thread-safe.
`d_time` From *d\_time.U*:
This variable conditionally defines the `HAS_TIME` symbol, which indicates that the time() routine exists. The time() routine is normally provided on `UNIX` systems.
`d_timegm` From *d\_timegm.U*:
This variable conditionally defines the `HAS_TIMEGM` symbol, which indicates to the C program that the timegm () routine is available.
`d_times` From *d\_times.U*:
This variable conditionally defines the `HAS_TIMES` symbol, which indicates that the times() routine exists. The times() routine is normally provided on `UNIX` systems. You may have to include <sys/times.h>.
`d_tm_tm_gmtoff` From *i\_time.U*:
This variable conditionally defines `HAS_TM_TM_GMTOFF`, which indicates to the C program that the struct tm has the tm\_gmtoff field.
`d_tm_tm_zone` From *i\_time.U*:
This variable conditionally defines `HAS_TM_TM_ZONE`, which indicates to the C program that the struct tm has the tm\_zone field.
`d_tmpnam_r` From *d\_tmpnam\_r.U*:
This variable conditionally defines the `HAS_TMPNAM_R` symbol, which indicates to the C program that the tmpnam\_r() routine is available.
`d_towlower` From *d\_towlower.U*:
This variable conditionally defines the `HAS_TOWLOWER` symbol, which indicates to the C program that the towlower() routine is available.
`d_towupper` From *d\_towupper.U*:
This variable conditionally defines the `HAS_TOWUPPER` symbol, which indicates to the C program that the towupper() routine is available.
`d_trunc` From *d\_trunc.U*:
This variable conditionally defines the `HAS_TRUNC` symbol, which indicates to the C program that the trunc() routine is available to round doubles towards zero.
`d_truncate` From *d\_truncate.U*:
This variable conditionally defines `HAS_TRUNCATE` if truncate() is available to truncate files.
`d_truncl` From *d\_truncl.U*:
This variable conditionally defines the `HAS_TRUNCL` symbol, which indicates to the C program that the truncl() routine is available to round long doubles towards zero. If copysignl is also present, we can emulate modfl.
`d_ttyname_r` From *d\_ttyname\_r.U*:
This variable conditionally defines the `HAS_TTYNAME_R` symbol, which indicates to the C program that the ttyname\_r() routine is available.
`d_tzname` From *d\_tzname.U*:
This variable conditionally defines `HAS_TZNAME` if tzname[] is available to access timezone names.
`d_u32align` From *d\_u32align.U*:
This variable tells whether you must access character data through U32-aligned pointers.
`d_ualarm` From *d\_ualarm.U*:
This variable conditionally defines the `HAS_UALARM` symbol, which indicates to the C program that the ualarm() routine is available.
`d_umask` From *d\_umask.U*:
This variable conditionally defines the `HAS_UMASK` symbol, which indicates to the C program that the umask() routine is available. to set and get the value of the file creation mask.
`d_uname` From *d\_gethname.U*:
This variable conditionally defines the `HAS_UNAME` symbol, which indicates to the C program that the uname() routine may be used to derive the host name.
`d_union_semun` From *d\_union\_semun.U*:
This variable conditionally defines `HAS_UNION_SEMUN` if the union semun is defined by including <sys/sem.h>.
`d_unlinkat` From *d\_fsat.U*:
This variable conditionally defines the `HAS_UNLINKAT` symbol, which indicates the `POSIX` unlinkat() function isavailable.
`d_unordered` From *d\_unordered.U*:
This variable conditionally defines the `HAS_UNORDERED` symbol, which indicates to the C program that the unordered() routine is available.
`d_unsetenv` From *d\_unsetenv.U*:
This variable conditionally defines the `HAS_UNSETENV` symbol, which indicates to the C program that the unsetenv () routine is available.
`d_uselocale` From *d\_newlocale.U*:
This variable conditionally defines the `HAS_USELOCALE` symbol, which indicates to the C program that the uselocale() routine is available to set the current locale for the calling thread.
`d_usleep` From *d\_usleep.U*:
This variable conditionally defines `HAS_USLEEP` if usleep() is available to do high granularity sleeps.
`d_usleepproto` From *d\_usleepproto.U*:
This variable conditionally defines the `HAS_USLEEP_PROTO` symbol, which indicates to the C program that the system provides a prototype for the usleep() function. Otherwise, it is up to the program to supply one.
`d_ustat` From *d\_ustat.U*:
This variable conditionally defines `HAS_USTAT` if ustat() is available to query file system statistics by dev\_t.
`d_vendorarch` From *vendorarch.U*:
This variable conditionally defined `PERL_VENDORARCH`.
`d_vendorbin` From *vendorbin.U*:
This variable conditionally defines `PERL_VENDORBIN`.
`d_vendorlib` From *vendorlib.U*:
This variable conditionally defines `PERL_VENDORLIB`.
`d_vendorscript` From *vendorscript.U*:
This variable conditionally defines `PERL_VENDORSCRIPT`.
`d_vfork` From *d\_vfork.U*:
This variable conditionally defines the `HAS_VFORK` symbol, which indicates the vfork() routine is available.
`d_void_closedir` From *d\_closedir.U*:
This variable conditionally defines `VOID_CLOSEDIR` if closedir() does not return a value.
`d_voidsig` From *d\_voidsig.U*:
This variable conditionally defines `VOIDSIG` if this system declares "void (\*signal(...))()" in *signal.h*. The old way was to declare it as "int (\*signal(...))()".
`d_voidtty` From *i\_sysioctl.U*:
This variable conditionally defines `USE_IOCNOTTY` to indicate that the ioctl() call with `TIOCNOTTY` should be used to void tty association. Otherwise (on `USG` probably), it is enough to close the standard file descriptors and do a setpgrp().
`d_vsnprintf` From *d\_snprintf.U*:
This variable conditionally defines the `HAS_VSNPRINTF` symbol, which indicates to the C program that the vsnprintf () library function is available.
`d_wait4` From *d\_wait4.U*:
This variable conditionally defines the HAS\_WAIT4 symbol, which indicates the wait4() routine is available.
`d_waitpid` From *d\_waitpid.U*:
This variable conditionally defines `HAS_WAITPID` if waitpid() is available to wait for child process.
`d_wcrtomb` From *d\_wcrtomb.U*:
This variable conditionally defines the `HAS_WCRTOMB` symbol if the wcrtomb() routine is available to be used to convert a wide character into a multi-byte character.
`d_wcscmp` From *d\_wcscmp.U*:
This variable conditionally defines the `HAS_WCSCMP` symbol if the wcscmp() routine is available and can be used to compare wide character strings.
`d_wcstombs` From *d\_wcstombs.U*:
This variable conditionally defines the `HAS_WCSTOMBS` symbol, which indicates to the C program that the wcstombs() routine is available to convert wide character strings to multibyte strings.
`d_wcsxfrm` From *d\_wcsxfrm.U*:
This variable conditionally defines the `HAS_WCSXFRM` symbol if the wcsxfrm() routine is available and can be used to compare wide character strings.
`d_wctomb` From *d\_wctomb.U*:
This variable conditionally defines the `HAS_WCTOMB` symbol, which indicates to the C program that the wctomb() routine is available to convert a wide character to a multibyte.
`d_writev` From *d\_writev.U*:
This variable conditionally defines the `HAS_WRITEV` symbol, which indicates to the C program that the writev() routine is available.
`d_xenix` From *Guess.U*:
This variable conditionally defines the symbol `XENIX`, which alerts the C program that it runs under Xenix.
`date` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the date program. After Configure runs, the value is reset to a plain `date` and is not useful.
`db_hashtype` From *i\_db.U*:
This variable contains the type of the hash 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.
`db_prefixtype` From *i\_db.U*:
This variable 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_version_major` From *i\_db.U*:
This variable contains the major version number of Berkeley `DB` found in the <db.h> header file.
`db_version_minor` From *i\_db.U*:
This variable contains the minor version number of Berkeley `DB` found in the <db.h> header file. For `DB` version 1 this is always 0.
`db_version_patch` From *i\_db.U*:
This variable contains the patch version number of Berkeley `DB` found in the <db.h> header file. For `DB` version 1 this is always 0.
`default_inc_excludes_dot` From *defaultincdot.U*:
When defined, remove the legacy *.* from @`INC`
`direntrytype` From *i\_dirent.U*:
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.
`dlext` From *dlext.U*:
This variable contains the extension that is to be used for the dynamically loaded modules that perl generates.
`dlsrc` From *dlsrc.U*:
This variable contains the name of the dynamic loading file that will be used with the package.
`doubleinfbytes` From *infnan.U*:
This variable contains comma-separated list of hexadecimal bytes for the double precision infinity.
`doublekind` From *longdblfio.U*:
This variable, if defined, encodes the type of a double: 1 = `IEEE` 754 32-bit little endian, 2 = `IEEE` 754 32-bit big endian, 3 = `IEEE` 754 64-bit little endian, 4 = `IEEE` 754 64-bit big endian, 5 = `IEEE` 754 128-bit little endian, 6 = `IEEE` 754 128-bit big endian, 7 = `IEEE` 754 64-bit mixed endian le-be, 8 = `IEEE` 754 64-bit mixed endian be-le, 9 = `VAX` 32bit little endian F float format 10 = `VAX` 64bit little endian D float format 11 = `VAX` 64bit little endian G float format 12 = `IBM` 32bit format 13 = `IBM` 64bit format 14 = Cray 64bit format -1 = unknown format.
`doublemantbits` From *mantbits.U*:
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` From *infnan.U*:
This variable contains comma-separated list of hexadecimal bytes for the double precision not-a-number.
`doublesize` From *doublesize.U*:
This variable contains the value of the `DOUBLESIZE` symbol, which indicates to the C program how many bytes there are in a double.
`drand01` From *randfunc.U*:
Indicates the macro to be used to generate normalized random numbers. Uses randfunc, often divided by (double) (((unsigned long) 1 << randbits)) in order to normalize the result. In C programs, the macro `Drand01` is mapped to drand01.
`drand48_r_proto` From *d\_drand48\_r.U*:
This variable 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.
`dtrace` From *usedtrace.U*:
This variable holds the location of the dtrace executable.
`dtraceobject` From *dtraceobject.U*:
Whether we need to build an object file with the dtrace tool.
`dtracexnolibs` From *dtraceobject.U*:
Whether dtrace accepts -xnolibs. If available we call dtrace -h and dtrace -G with -xnolibs to allow dtrace to run in a jail on FreeBSD.
`dynamic_ext` From *Extensions.U*:
This variable holds a list of `XS` extension files we want to link dynamically into the package. It is used by Makefile.
### e
`eagain` From *nblock\_io.U*:
This variable bears the symbolic errno code set by read() when no data is present on the file and non-blocking I/O was enabled (otherwise, read() blocks naturally).
`ebcdic` From *ebcdic.U*:
This variable conditionally defines `EBCDIC` if this system uses `EBCDIC` encoding.
`echo` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the echo program. After Configure runs, the value is reset to a plain `echo` and is not useful.
`egrep` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the egrep program. After Configure runs, the value is reset to a plain `egrep` and is not useful.
`emacs` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`endgrent_r_proto` From *d\_endgrent\_r.U*:
This variable 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` From *d\_endhostent\_r.U*:
This variable 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` From *d\_endnetent\_r.U*:
This variable 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` From *d\_endprotoent\_r.U*:
This variable 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` From *d\_endpwent\_r.U*:
This variable 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` From *d\_endservent\_r.U*:
This variable 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.
`eunicefix` From *Init.U*:
When running under Eunice this variable contains a command which will convert a shell script to the proper form of text file for it to be executable by the shell. On other systems it is a no-op.
`exe_ext` From *Unix.U*:
This is an old synonym for \_exe.
`expr` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the expr program. After Configure runs, the value is reset to a plain `expr` and is not useful.
`extensions` From *Extensions.U*:
This variable holds a list of all extension files (both `XS` and non-xs) installed with the package. It is propagated to *Config.pm* and is typically used to test whether a particular extension is available.
`extern_C` From *Csym.U*:
`ANSI` C requires `extern` where C++ requires 'extern `C`'. This variable can be used in Configure to do the right thing.
`extras` From *Extras.U*:
This variable holds a list of extra modules to install.
### f
`fflushall` From *fflushall.U*:
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.
`fflushNULL` From *fflushall.U*:
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.
`find` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`firstmakefile` From *Unix.U*:
This variable defines the first file searched by make. On unix, it is makefile (then Makefile). On case-insensitive systems, it might be something else. This is only used to deal with convoluted make depend tricks.
`flex` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`fpossize` From *fpossize.U*:
This variable contains the size of a fpostype in bytes.
`fpostype` From *fpostype.U*:
This variable defines Fpos\_t to be something like fpos\_t, long, uint, or whatever type is used to declare file positions in libc.
`freetype` From *mallocsrc.U*:
This variable contains the return type of free(). It is usually void, but occasionally int.
`from` From *Cross.U*:
This variable contains the command used by Configure to copy files from the target host. Useful and available only during Perl build. The string `:` if not cross-compiling.
`full_ar` From *Loc\_ar.U*:
This variable contains the full pathname to `ar`, whether or not the user has specified `portability`. This is only used in the *Makefile.SH*.
`full_csh` From *d\_csh.U*:
This variable contains the full pathname to `csh`, whether or not the user has specified `portability`. This is only used in the compiled C program, and we assume that all systems which can share this executable will have the same full pathname to *csh.*
`full_sed` From *Loc\_sed.U*:
This variable contains the full pathname to `sed`, whether or not the user has specified `portability`. This is only used in the compiled C program, and we assume that all systems which can share this executable will have the same full pathname to *sed.*
### g
`gccansipedantic` From *gccvers.U*:
If `GNU` cc (gcc) is used, this variable will enable (if set) the -ansi and -pedantic ccflags for building core files (through cflags script). (See *Porting/pumpkin.pod* for full description).
`gccosandvers` From *gccvers.U*:
If `GNU` cc (gcc) is used, this variable holds the operating system and version used to compile gcc. It is set to '' if not gcc, or if nothing useful can be parsed as the os version.
`gccversion` From *gccvers.U*:
If `GNU` cc (gcc) is used, this variable holds `1` or `2` to indicate whether the compiler is version 1 or 2. This is used in setting some of the default cflags. It is set to '' if not gcc.
`getgrent_r_proto` From *d\_getgrent\_r.U*:
This variable 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` From *d\_getgrgid\_r.U*:
This variable 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` From *d\_getgrnam\_r.U*:
This variable 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` From *d\_gethostbyaddr\_r.U*:
This variable 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` From *d\_gethostbyname\_r.U*:
This variable 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` From *d\_gethostent\_r.U*:
This variable 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` From *d\_getlogin\_r.U*:
This variable 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` From *d\_getnetbyaddr\_r.U*:
This variable 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` From *d\_getnetbyname\_r.U*:
This variable 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` From *d\_getnetent\_r.U*:
This variable 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` From *d\_getprotobyname\_r.U*:
This variable 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` From *d\_getprotobynumber\_r.U*:
This variable 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` From *d\_getprotoent\_r.U*:
This variable 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` From *d\_getpwent\_r.U*:
This variable 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` From *d\_getpwnam\_r.U*:
This variable 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` From *d\_getpwuid\_r.U*:
This variable 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` From *d\_getservbyname\_r.U*:
This variable 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` From *d\_getservbyport\_r.U*:
This variable 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` From *d\_getservent\_r.U*:
This variable 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` From *d\_getspnam\_r.U*:
This variable 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.
`gidformat` From *gidf.U*:
This variable contains the format string used for printing a Gid\_t.
`gidsign` From *gidsign.U*:
This variable contains the signedness of a gidtype. 1 for unsigned, -1 for signed.
`gidsize` From *gidsize.U*:
This variable contains the size of a gidtype in bytes.
`gidtype` From *gidtype.U*:
This variable defines Gid\_t to be something like gid\_t, int, ushort, or whatever type is used to declare the return type of getgid(). Typically, it is the type of group ids in the kernel.
`glibpth` From *libpth.U*:
This variable holds the general path (space-separated) used to find libraries. It may contain directories that do not exist on this platform, libpth is the cleaned-up version.
`gmake` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the gmake program. After Configure runs, the value is reset to a plain `gmake` and is not useful.
`gmtime_r_proto` From *d\_gmtime\_r.U*:
This variable 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.
`gnulibc_version` From *d\_gnulibc.U*:
This variable contains the version number of the `GNU` C library. It is usually something like *2.2.5*. It is a plain '' if this is not the `GNU` C library, or if the version is unknown.
`grep` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the grep program. After Configure runs, the value is reset to a plain `grep` and is not useful.
`groupcat` From *nis.U*:
This variable contains a command that produces the text of the */etc/group* file. This is normally "cat */etc/group*", but can be "ypcat group" when `NIS` is used. On some systems, such as os390, there may be no equivalent command, in which case this variable is unset.
`groupstype` From *groupstype.U*:
This variable defines Groups\_t to be something like gid\_t, int, ushort, or whatever type is used for the second argument to getgroups() and setgroups(). Usually, this is the same as gidtype (gid\_t), but sometimes it isn't.
`gzip` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the gzip program. After Configure runs, the value is reset to a plain `gzip` and is not useful.
### h
`h_fcntl` From *h\_fcntl.U*:
This is variable gets set in various places to tell i\_fcntl that <fcntl.h> should be included.
`h_sysfile` From *h\_sysfile.U*:
This is variable gets set in various places to tell i\_sys\_file that <sys/file.h> should be included.
`hint` From *Oldconfig.U*:
Gives the type of hints used for previous answers. May be one of `default`, `recommended` or `previous`.
`hostcat` From *nis.U*:
This variable contains a command that produces the text of the */etc/hosts* file. This is normally "cat */etc/hosts*", but can be "ypcat hosts" when `NIS` is used. On some systems, such as os390, there may be no equivalent command, in which case this variable is unset.
`hostgenerate` From *Cross.U*:
This variable contains the path to a generate\_uudmap binary that can be run on the host `OS` when cross-compiling. Useful and available only during Perl build. Empty string '' if not cross-compiling.
`hostosname` From *Cross.U*:
This variable contains the original value of `$^O` for hostperl when cross-compiling. This is useful to pick the proper tools when running build code in the host. Empty string '' if not cross-compiling.
`hostperl` From *Cross.U*:
This variable contains the path to a miniperl binary that can be run on the host `OS` when cross-compiling. Useful and available only during Perl build. Empty string '' if not cross-compiling.
`html1dir` From *html1dir.U*:
This variable contains the name of the directory in which html source pages are to be put. This directory is for pages that describe whole programs, not libraries or modules. It is intended to correspond roughly to section 1 of the Unix manuals.
`html1direxp` From *html1dir.U*:
This variable is the same as the html1dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`html3dir` From *html3dir.U*:
This variable contains the name of the directory in which html source pages are to be put. This directory is for pages that describe libraries or modules. It is intended to correspond roughly to section 3 of the Unix manuals.
`html3direxp` From *html3dir.U*:
This variable is the same as the html3dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
### i
`i16size` From *perlxv.U*:
This variable is the size of an I16 in bytes.
`i16type` From *perlxv.U*:
This variable contains the C type used for Perl's I16.
`i32size` From *perlxv.U*:
This variable is the size of an I32 in bytes.
`i32type` From *perlxv.U*:
This variable contains the C type used for Perl's I32.
`i64size` From *perlxv.U*:
This variable is the size of an I64 in bytes.
`i64type` From *perlxv.U*:
This variable contains the C type used for Perl's I64.
`i8size` From *perlxv.U*:
This variable is the size of an I8 in bytes.
`i8type` From *perlxv.U*:
This variable contains the C type used for Perl's I8.
`i_arpainet` From *i\_arpainet.U*:
This variable conditionally defines the `I_ARPA_INET` symbol, and indicates whether a C program should include <arpa/inet.h>.
`i_bfd` From *i\_bfd.U*:
This variable conditionally defines the `I_BFD` symbol, and indicates whether a C program can include <bfd.h>.
`i_bsdioctl` From *i\_sysioctl.U*:
This variable conditionally defines the `I_SYS_BSDIOCTL` symbol, which indicates to the C program that <sys/bsdioctl.h> exists and should be included.
`i_crypt` From *i\_crypt.U*:
This variable conditionally defines the `I_CRYPT` symbol, and indicates whether a C program should include <crypt.h>.
`i_db` From *i\_db.U*:
This variable conditionally defines the `I_DB` symbol, and indicates whether a C program may include Berkeley's `DB` include file <db.h>.
`i_dbm` From *i\_dbm.U*:
This variable conditionally defines the `I_DBM` symbol, which indicates to the C program that <dbm.h> exists and should be included.
`i_dirent` From *i\_dirent.U*:
This variable conditionally defines `I_DIRENT`, which indicates to the C program that it should include <dirent.h>.
`i_dlfcn` From *i\_dlfcn.U*:
This variable conditionally defines the `I_DLFCN` symbol, which indicates to the C program that <dlfcn.h> exists and should be included.
`i_execinfo` From *i\_execinfo.U*:
This variable conditionally defines the `I_EXECINFO` symbol, and indicates whether a C program may include <execinfo.h>, for backtrace() support.
`i_fcntl` From *i\_fcntl.U*:
This variable controls the value of `I_FCNTL` (which tells the C program to include <fcntl.h>).
`i_fenv` From *i\_fenv.U*:
This variable conditionally defines the `I_FENV` symbol, which indicates to the C program that <fenv.h> exists and should be included.
`i_fp` From *i\_fp.U*:
This variable conditionally defines the `I_FP` symbol, and indicates whether a C program should include <fp.h>.
`i_fp_class` From *i\_fp\_class.U*:
This variable conditionally defines the `I_FP_CLASS` symbol, and indicates whether a C program should include <fp\_class.h>.
`i_gdbm` From *i\_gdbm.U*:
This variable conditionally defines the `I_GDBM` symbol, which indicates to the C program that <gdbm.h> exists and should be included.
`i_gdbm_ndbm` From *i\_ndbm.U*:
This variable conditionally defines the `I_GDBM_NDBM` symbol, which indicates to the C program that <gdbm-*ndbm.h*> exists and should be included. This is the location of the *ndbm.h* compatibility file in Debian 4.0.
`i_gdbmndbm` From *i\_ndbm.U*:
This variable conditionally defines the `I_GDBMNDBM` symbol, which indicates to the C program that <gdbm/ndbm.h> exists and should be included. This was the location of the *ndbm.h* compatibility file in RedHat 7.1.
`i_grp` From *i\_grp.U*:
This variable conditionally defines the `I_GRP` symbol, and indicates whether a C program should include <grp.h>.
`i_ieeefp` From *i\_ieeefp.U*:
This variable conditionally defines the `I_IEEEFP` symbol, and indicates whether a C program should include <ieeefp.h>.
`i_inttypes` From *i\_inttypes.U*:
This variable conditionally defines the `I_INTTYPES` symbol, and indicates whether a C program should include <inttypes.h>.
`i_langinfo` From *i\_langinfo.U*:
This variable conditionally defines the `I_LANGINFO` symbol, and indicates whether a C program should include <langinfo.h>.
`i_libutil` From *i\_libutil.U*:
This variable conditionally defines the `I_LIBUTIL` symbol, and indicates whether a C program should include <libutil.h>.
`i_locale` From *i\_locale.U*:
This variable conditionally defines the `I_LOCALE` symbol, and indicates whether a C program should include <locale.h>.
`i_machcthr` From *i\_machcthr.U*:
This variable conditionally defines the `I_MACH_CTHREADS` symbol, and indicates whether a C program should include <mach/cthreads.h>.
`i_malloc` From *i\_malloc.U*:
This variable conditionally defines the `I_MALLOC` symbol, and indicates whether a C program should include <malloc.h>.
`i_mallocmalloc` From *i\_mallocmalloc.U*:
This variable conditionally defines the `I_MALLOCMALLOC` symbol, and indicates whether a C program should include <malloc/malloc.h>.
`i_mntent` From *i\_mntent.U*:
This variable conditionally defines the `I_MNTENT` symbol, and indicates whether a C program should include <mntent.h>.
`i_ndbm` From *i\_ndbm.U*:
This variable conditionally defines the `I_NDBM` symbol, which indicates to the C program that <ndbm.h> exists and should be included.
`i_netdb` From *i\_netdb.U*:
This variable conditionally defines the `I_NETDB` symbol, and indicates whether a C program should include <netdb.h>.
`i_neterrno` From *i\_neterrno.U*:
This variable conditionally defines the `I_NET_ERRNO` symbol, which indicates to the C program that <net/errno.h> exists and should be included.
`i_netinettcp` From *i\_netinettcp.U*:
This variable conditionally defines the `I_NETINET_TCP` symbol, and indicates whether a C program should include <netinet/tcp.h>.
`i_niin` From *i\_niin.U*:
This variable conditionally defines `I_NETINET_IN`, which indicates to the C program that it should include <netinet/in.h>. Otherwise, you may try <sys/in.h>.
`i_poll` From *i\_poll.U*:
This variable conditionally defines the `I_POLL` symbol, and indicates whether a C program should include <poll.h>.
`i_prot` From *i\_prot.U*:
This variable conditionally defines the `I_PROT` symbol, and indicates whether a C program should include <prot.h>.
`i_pthread` From *i\_pthread.U*:
This variable conditionally defines the `I_PTHREAD` symbol, and indicates whether a C program should include <pthread.h>.
`i_pwd` From *i\_pwd.U*:
This variable conditionally defines `I_PWD`, which indicates to the C program that it should include <pwd.h>.
`i_quadmath` From *i\_quadmath.U*:
This variable conditionally defines `I_QUADMATH`, which indicates to the C program that it should include <quadmath.h>.
`i_rpcsvcdbm` From *i\_dbm.U*:
This variable conditionally defines the `I_RPCSVC_DBM` symbol, which indicates to the C program that <rpcsvc/dbm.h> exists and should be included. Some System V systems might need this instead of <dbm.h>.
`i_sgtty` From *i\_termio.U*:
This variable conditionally defines the `I_SGTTY` symbol, which indicates to the C program that it should include <sgtty.h> rather than <termio.h>.
`i_shadow` From *i\_shadow.U*:
This variable conditionally defines the `I_SHADOW` symbol, and indicates whether a C program should include <shadow.h>.
`i_socks` From *i\_socks.U*:
This variable conditionally defines the `I_SOCKS` symbol, and indicates whether a C program should include <socks.h>.
`i_stdbool` From *i\_stdbool.U*:
This variable conditionally defines the `I_STDBOOL` symbol, which indicates to the C program that <stdbool.h> exists and should be included.
`i_stdint` From *i\_stdint.U*:
This variable conditionally defines the `I_STDINT` symbol, which indicates to the C program that <stdint.h> exists and should be included.
`i_stdlib` From *i\_stdlib.U*:
This variable unconditionally defines the `I_STDLIB` symbol.
`i_sunmath` From *i\_sunmath.U*:
This variable conditionally defines the `I_SUNMATH` symbol, and indicates whether a C program should include <sunmath.h>.
`i_sysaccess` From *i\_sysaccess.U*:
This variable conditionally defines the `I_SYS_ACCESS` symbol, and indicates whether a C program should include <sys/access.h>.
`i_sysdir` From *i\_sysdir.U*:
This variable conditionally defines the `I_SYS_DIR` symbol, and indicates whether a C program should include <sys/dir.h>.
`i_sysfile` From *i\_sysfile.U*:
This variable conditionally defines the `I_SYS_FILE` symbol, and indicates whether a C program should include <sys/file.h> to get `R_OK` and friends.
`i_sysfilio` From *i\_sysioctl.U*:
This variable conditionally defines the `I_SYS_FILIO` symbol, which indicates to the C program that <sys/filio.h> exists and should be included in preference to <sys/ioctl.h>.
`i_sysin` From *i\_niin.U*:
This variable conditionally defines `I_SYS_IN`, which indicates to the C program that it should include <sys/in.h> instead of <netinet/in.h>.
`i_sysioctl` From *i\_sysioctl.U*:
This variable conditionally defines the `I_SYS_IOCTL` symbol, which indicates to the C program that <sys/ioctl.h> exists and should be included.
`i_syslog` From *i\_syslog.U*:
This variable conditionally defines the `I_SYSLOG` symbol, and indicates whether a C program should include <syslog.h>.
`i_sysmman` From *i\_sysmman.U*:
This variable conditionally defines the `I_SYS_MMAN` symbol, and indicates whether a C program should include <sys/mman.h>.
`i_sysmode` From *i\_sysmode.U*:
This variable conditionally defines the `I_SYSMODE` symbol, and indicates whether a C program should include <sys/mode.h>.
`i_sysmount` From *i\_sysmount.U*:
This variable conditionally defines the `I_SYSMOUNT` symbol, and indicates whether a C program should include <sys/mount.h>.
`i_sysndir` From *i\_sysndir.U*:
This variable conditionally defines the `I_SYS_NDIR` symbol, and indicates whether a C program should include <sys/ndir.h>.
`i_sysparam` From *i\_sysparam.U*:
This variable conditionally defines the `I_SYS_PARAM` symbol, and indicates whether a C program should include <sys/param.h>.
`i_syspoll` From *i\_syspoll.U*:
This variable conditionally defines the `I_SYS_POLL` symbol, which indicates to the C program that it should include <sys/poll.h>.
`i_sysresrc` From *i\_sysresrc.U*:
This variable conditionally defines the `I_SYS_RESOURCE` symbol, and indicates whether a C program should include <sys/resource.h>.
`i_syssecrt` From *i\_syssecrt.U*:
This variable conditionally defines the `I_SYS_SECURITY` symbol, and indicates whether a C program should include <sys/security.h>.
`i_sysselct` From *i\_sysselct.U*:
This variable conditionally defines `I_SYS_SELECT`, which indicates to the C program that it should include <sys/select.h> in order to get the definition of struct timeval.
`i_syssockio` From *i\_sysioctl.U*:
This variable conditionally defines `I_SYS_SOCKIO` to indicate to the C program that socket ioctl codes may be found in <sys/sockio.h> instead of <sys/ioctl.h>.
`i_sysstat` From *i\_sysstat.U*:
This variable conditionally defines the `I_SYS_STAT` symbol, and indicates whether a C program should include <sys/stat.h>.
`i_sysstatfs` From *i\_sysstatfs.U*:
This variable conditionally defines the `I_SYSSTATFS` symbol, and indicates whether a C program should include <sys/statfs.h>.
`i_sysstatvfs` From *i\_sysstatvfs.U*:
This variable conditionally defines the `I_SYSSTATVFS` symbol, and indicates whether a C program should include <sys/statvfs.h>.
`i_systime` From *i\_time.U*:
This variable conditionally defines `I_SYS_TIME`, which indicates to the C program that it should include <sys/time.h>.
`i_systimek` From *i\_time.U*:
This variable conditionally defines `I_SYS_TIME_KERNEL`, which indicates to the C program that it should include <sys/time.h> with `KERNEL` defined.
`i_systimes` From *i\_systimes.U*:
This variable conditionally defines the `I_SYS_TIMES` symbol, and indicates whether a C program should include <sys/times.h>.
`i_systypes` From *i\_systypes.U*:
This variable conditionally defines the `I_SYS_TYPES` symbol, and indicates whether a C program should include <sys/types.h>.
`i_sysuio` From *i\_sysuio.U*:
This variable conditionally defines the `I_SYSUIO` symbol, and indicates whether a C program should include <sys/uio.h>.
`i_sysun` From *i\_sysun.U*:
This variable conditionally defines `I_SYS_UN`, which indicates to the C program that it should include <sys/un.h> to get `UNIX` domain socket definitions.
`i_sysutsname` From *i\_sysutsname.U*:
This variable conditionally defines the `I_SYSUTSNAME` symbol, and indicates whether a C program should include <sys/utsname.h>.
`i_sysvfs` From *i\_sysvfs.U*:
This variable conditionally defines the `I_SYSVFS` symbol, and indicates whether a C program should include <sys/vfs.h>.
`i_syswait` From *i\_syswait.U*:
This variable conditionally defines `I_SYS_WAIT`, which indicates to the C program that it should include <sys/wait.h>.
`i_termio` From *i\_termio.U*:
This variable conditionally defines the `I_TERMIO` symbol, which indicates to the C program that it should include <termio.h> rather than <sgtty.h>.
`i_termios` From *i\_termio.U*:
This variable conditionally defines the `I_TERMIOS` symbol, which indicates to the C program that the `POSIX` <termios.h> file is to be included.
`i_time` From *i\_time.U*:
This variable unconditionally defines `I_TIME`, which indicates to the C program that it should include <time.h>.
`i_unistd` From *i\_unistd.U*:
This variable conditionally defines the `I_UNISTD` symbol, and indicates whether a C program should include <unistd.h>.
`i_ustat` From *i\_ustat.U*:
This variable conditionally defines the `I_USTAT` symbol, and indicates whether a C program should include <ustat.h>.
`i_utime` From *i\_utime.U*:
This variable conditionally defines the `I_UTIME` symbol, and indicates whether a C program should include <utime.h>.
`i_vfork` From *i\_vfork.U*:
This variable conditionally defines the `I_VFORK` symbol, and indicates whether a C program should include *vfork.h*.
`i_wchar` From *i\_wchar.U*:
This variable conditionally defines the `I_WCHAR` symbol, that indicates whether a C program may include <wchar.h>.
`i_wctype` From *i\_wctype.U*:
This variable conditionally defines the `I_WCTYPE` symbol, that indicates whether a C program may include <wctype.h>.
`i_xlocale` From *d\_newlocale.U*:
This symbol, if defined, indicates to the C program that the header *xlocale.h* is available. See also xlocale\_needed.
`ignore_versioned_solibs` From *libs.U*:
This variable should be non-empty if non-versioned shared libraries (*libfoo.so.x.y*) are to be ignored (because they cannot be linked against).
`inc_version_list` From *inc\_version\_list.U*:
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`. The elements in the list are separated by spaces. This is only useful if you have a perl library directory tree structured like the default one. See `INSTALL` for how this works. The versioned site\_perl directory was introduced in 5.005, so that is the lowest possible value.
This list includes architecture-dependent directories back to version $api\_versionstring (e.g. 5.5.640) and architecture-independent directories all the way back to 5.005.
`inc_version_list_init` From *inc\_version\_list.U*:
This variable holds the same list as inc\_version\_list, but each item is enclosed in double quotes and separated by commas, suitable for use in the `PERL_INC_VERSION_LIST` initialization.
`incpath` From *usrinc.U*:
This variable must precede the normal include path to get the right one, as in *$incpath/usr/include* or *$incpath/usr/lib*. Value can be "" or */bsd43* on mips.
`incpth` From *libpth.U*:
This variable must precede the normal include path to get the right one, as in *$incpath/usr/include* or *$incpath/usr/lib*. Value can be "" or */bsd43* on mips.
`inews` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`initialinstalllocation` From *bin.U*:
When userelocatableinc is true, this variable holds the location that make install should copy the perl binary to, with all the run-time relocatable paths calculated from this at install time. When used, it is initialized to the original value of binexp, and then binexp is set to *.../*, as the other binaries are found relative to the perl binary.
`installarchlib` From *archlib.U*:
This variable is really the same as archlibexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installbin` From *bin.U*:
This variable is the same as binexp unless `AFS` is running in which case the user is explicitly prompted for it. This variable should always be used in your makefiles for maximum portability.
`installhtml1dir` From *html1dir.U*:
This variable is really the same as html1direxp, unless you are using a different installprefix. For extra portability, you should only use this variable within your makefiles.
`installhtml3dir` From *html3dir.U*:
This variable is really the same as html3direxp, unless you are using a different installprefix. For extra portability, you should only use this variable within your makefiles.
`installman1dir` From *man1dir.U*:
This variable is really the same as man1direxp, unless you are using `AFS` in which case it points to the read/write location whereas man1direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installman3dir` From *man3dir.U*:
This variable is really the same as man3direxp, unless you are using `AFS` in which case it points to the read/write location whereas man3direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installprefix` From *installprefix.U*:
This variable holds the name of the directory below which "make install" will install the package. For most users, this is the same as prefix. However, it is useful for installing the software into a different (usually temporary) location after which it can be bundled up and moved somehow to the final location specified by prefix.
`installprefixexp` From *installprefix.U*:
This variable holds the full absolute path of installprefix with all *~*-expansion done.
`installprivlib` From *privlib.U*:
This variable is really the same as privlibexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installscript` From *scriptdir.U*:
This variable is usually the same as scriptdirexp, unless you are on a system running `AFS`, in which case they may differ slightly. You should always use this variable within your makefiles for portability.
`installsitearch` From *sitearch.U*:
This variable is really the same as sitearchexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installsitebin` From *sitebin.U*:
This variable is usually the same as sitebinexp, unless you are on a system running `AFS`, in which case they may differ slightly. You should always use this variable within your makefiles for portability.
`installsitehtml1dir` From *sitehtml1dir.U*:
This variable is really the same as sitehtml1direxp, unless you are using `AFS` in which case it points to the read/write location whereas html1direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installsitehtml3dir` From *sitehtml3dir.U*:
This variable is really the same as sitehtml3direxp, unless you are using `AFS` in which case it points to the read/write location whereas html3direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installsitelib` From *sitelib.U*:
This variable is really the same as sitelibexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installsiteman1dir` From *siteman1dir.U*:
This variable is really the same as siteman1direxp, unless you are using `AFS` in which case it points to the read/write location whereas man1direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installsiteman3dir` From *siteman3dir.U*:
This variable is really the same as siteman3direxp, unless you are using `AFS` in which case it points to the read/write location whereas man3direxp only points to the read-only access location. For extra portability, you should only use this variable within your makefiles.
`installsitescript` From *sitescript.U*:
This variable is usually the same as sitescriptexp, unless you are on a system running `AFS`, in which case they may differ slightly. You should always use this variable within your makefiles for portability.
`installstyle` From *installstyle.U*:
This variable describes the `style` of the perl installation. This is intended to be useful for tools that need to manipulate entire perl distributions. Perl itself doesn't use this to find its libraries -- the library directories are stored directly in *Config.pm*. Currently, there are only two styles: `lib` and *lib/perl5*. The default library locations (e.g. privlib, sitelib) are either *$prefix/lib* or *$prefix/lib/perl5*. The former is useful if $prefix is a directory dedicated to perl (e.g. */opt/perl*), while the latter is useful if $prefix is shared by many packages, e.g. if $prefix=*/usr/local*.
Unfortunately, while this `style` variable is used to set defaults for all three directory hierarchies (core, vendor, and site), there is no guarantee that the same style is actually appropriate for all those directories. For example, $prefix might be */opt/perl*, but $siteprefix might be */usr/local*. (Perhaps, in retrospect, the `lib` style should never have been supported, but it did seem like a nice idea at the time.)
The situation is even less clear for tools such as MakeMaker that can be used to install additional modules into non-standard places. For example, if a user intends to install a module into a private directory (perhaps by setting `PREFIX` on the *Makefile.PL* command line), then there is no reason to assume that the Configure-time $installstyle setting will be relevant for that `PREFIX`.
This may later be extended to include other information, so be careful with pattern-matching on the results.
For compatibility with *perl5.005* and earlier, the default setting is based on whether or not $prefix contains the string `perl`.
`installusrbinperl` From *instubperl.U*:
This variable tells whether Perl should be installed also as */usr/bin/perl* in addition to *$installbin/perl*
`installvendorarch` From *vendorarch.U*:
This variable is really the same as vendorarchexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorbin` From *vendorbin.U*:
This variable is really the same as vendorbinexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorhtml1dir` From *vendorhtml1dir.U*:
This variable is really the same as vendorhtml1direxp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorhtml3dir` From *vendorhtml3dir.U*:
This variable is really the same as vendorhtml3direxp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorlib` From *vendorlib.U*:
This variable is really the same as vendorlibexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorman1dir` From *vendorman1dir.U*:
This variable is really the same as vendorman1direxp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorman3dir` From *vendorman3dir.U*:
This variable is really the same as vendorman3direxp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`installvendorscript` From *vendorscript.U*:
This variable is really the same as vendorscriptexp but may differ on those systems using `AFS`. For extra portability, only this variable should be used in makefiles.
`intsize` From *intsize.U*:
This variable contains the value of the `INTSIZE` symbol, which indicates to the C program how many bytes there are in an int.
`issymlink` From *issymlink.U*:
This variable holds the test command to test for a symbolic link (if they are supported). Typical values include `test -h` and `test -L`.
`ivdformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `IV` as a signed decimal integer.
`ivsize` From *perlxv.U*:
This variable is the size of an `IV` in bytes.
`ivtype` From *perlxv.U*:
This variable contains the C type used for Perl's `IV`.
### k
`known_extensions` From *Extensions.U*:
This variable holds a list of all extensions (both `XS` and non-xs) included in the package source distribution. This information is only really of use during the Perl build, as the list makes no distinction between extensions which were build and installed, and those which where not. See `extensions` for the list of extensions actually built and available.
`ksh` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
### l
`ld` From *dlsrc.U*:
This variable indicates the program to be used to link libraries for dynamic loading. On some systems, it is `ld`. On `ELF` systems, it should be $cc. Mostly, we'll try to respect the hint file setting.
`ld_can_script` From *dlsrc.U*:
This variable shows if the loader accepts scripts in the form of -Wl,--version-script=*ld.script*. This is currently only supported for `GNU` ld on `ELF` in dynamic loading builds.
`lddlflags` From *dlsrc.U*:
This variable contains any special flags that might need to be passed to $ld to create a shared library suitable for dynamic loading. It is up to the makefile to use it. For hpux, it should be `-b`. For sunos 4.1, it is empty.
`ldflags` From *ccflags.U*:
This variable contains any additional C loader flags desired by the user. It is up to the Makefile to use this.
`ldflags_uselargefiles` From *uselfs.U*:
This variable contains the loader flags needed by large file builds and added to ldflags by hints files.
`ldlibpthname` From *libperl.U*:
This variable holds the name of the shared library search path, often `LD_LIBRARY_PATH`. To get an empty string, the hints file must set this to `none`.
`less` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the less program. After Configure runs, the value is reset to a plain `less` and is not useful.
`lib_ext` From *Unix.U*:
This is an old synonym for \_a.
`libc` From *libc.U*:
This variable contains the location of the C library.
`libperl` From *libperl.U*:
The perl executable is obtained by linking *perlmain.c* with libperl, any static extensions (usually just DynaLoader), and any other libraries needed on this system. libperl is usually *libperl.a*, but can also be *libperl.so.xxx* if the user wishes to build a perl executable with a shared library.
`libpth` From *libpth.U*:
This variable holds the general path (space-separated) used to find libraries. It is intended to be used by other units.
`libs` From *libs.U*:
This variable holds the additional libraries we want to use. It is up to the Makefile to deal with it. The list can be empty.
`libsdirs` From *libs.U*:
This variable holds the directory names aka dirnames of the libraries we found and accepted, duplicates are removed.
`libsfiles` From *libs.U*:
This variable holds the filenames aka basenames of the libraries we found and accepted.
`libsfound` From *libs.U*:
This variable holds the full pathnames of the libraries we found and accepted.
`libspath` From *libs.U*:
This variable holds the directory names probed for libraries.
`libswanted` From *Myinit.U*:
This variable holds a list of all the libraries we want to search. The order is chosen to pick up the c library ahead of ucb or bsd libraries for SVR4.
`libswanted_uselargefiles` From *uselfs.U*:
This variable contains the libraries needed by large file builds and added to ldflags by hints files. It is a space separated list of the library names without the `lib` prefix or any suffix, just like *libswanted.*.
`line` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`lint` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`lkflags` From *ccflags.U*:
This variable contains any additional C partial linker flags desired by the user. It is up to the Makefile to use this.
`ln` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the ln program. After Configure runs, the value is reset to a plain `ln` and is not useful.
`lns` From *lns.U*:
This variable holds the name of the command to make symbolic links (if they are supported). It can be used in the Makefile. It is either `ln -s` or `ln`
`localtime_r_proto` From *d\_localtime\_r.U*:
This variable 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.
`locincpth` From *ccflags.U*:
This variable contains a list of additional directories to be searched by the compiler. The appropriate `-I` directives will be added to ccflags. This is intended to simplify setting local directories from the Configure command line. It's not much, but it parallels the loclibpth stuff in *libpth.U*.
`loclibpth` From *libpth.U*:
This variable holds the paths (space-separated) used to find local libraries. It is prepended to libpth, and is intended to be easily set from the command line.
`longdblinfbytes` From *infnan.U*:
This variable contains comma-separated list of hexadecimal bytes for the long double precision infinity.
`longdblkind` From *d\_longdbl.U*:
This variable, if defined, encodes the type of a long double: 0 = double, 1 = `IEEE` 754 128-bit little endian, 2 = `IEEE` 754 128-bit big endian, 3 = x86 80-bit little endian, 4 = x86 80-bit big endian, 5 = double-double 128-bit little endian, 6 = double-double 128-bit big endian, 7 = 128-bit mixed-endian double-double (64-bit LEs in `BE`), 8 = 128-bit mixed-endian double-double (64-bit BEs in `LE`), 9 = 128-bit `PDP`-style mixed-endian long doubles, -1 = unknown format.
`longdblmantbits` From *mantbits.U*:
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` From *infnan.U*:
This variable contains comma-separated list of hexadecimal bytes for the long double precision not-a-number.
`longdblsize` From *d\_longdbl.U*:
This variable contains the value of the `LONG_DOUBLESIZE` symbol, which indicates to the C program how many bytes there are in a long double, if this system supports long doubles. Note that this is sizeof(long double), which may include unused bytes.
`longlongsize` From *d\_longlong.U*:
This variable contains the value of the `LONGLONGSIZE` symbol, which indicates to the C program how many bytes there are in a long long, if this system supports long long.
`longsize` From *intsize.U*:
This variable contains the value of the `LONGSIZE` symbol, which indicates to the C program how many bytes there are in a long.
`lp` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`lpr` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`ls` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the ls program. After Configure runs, the value is reset to a plain `ls` and is not useful.
`lseeksize` From *lseektype.U*:
This variable defines lseektype to be something like off\_t, long, or whatever type is used to declare lseek offset's type in the kernel (which also appears to be lseek's return type).
`lseektype` From *lseektype.U*:
This variable defines lseektype to be something like off\_t, long, or whatever type is used to declare lseek offset's type in the kernel (which also appears to be lseek's return type).
### m
`mail` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`mailx` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`make` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the make program. After Configure runs, the value is reset to a plain `make` and is not useful.
`make_set_make` From *make.U*:
Some versions of `make` set the variable `MAKE`. Others do not. This variable contains the string to be included in *Makefile.SH* so that `MAKE` is set if needed, and not if not needed. Possible values are:
make\_set\_make=`#` # If your make program handles this for you,
make\_set\_make=`MAKE=$make` # if it doesn't.
This uses a comment character so that we can distinguish a `set` value (from a previous *config.sh* or Configure `-D` option) from an uncomputed value.
`mallocobj` From *mallocsrc.U*:
This variable contains the name of the *malloc.o* that this package generates, if that *malloc.o* is preferred over the system malloc. Otherwise the value is null. This variable is intended for generating Makefiles. See mallocsrc.
`mallocsrc` From *mallocsrc.U*:
This variable contains the name of the *malloc.c* that comes with the package, if that *malloc.c* is preferred over the system malloc. Otherwise the value is null. This variable is intended for generating Makefiles.
`malloctype` From *mallocsrc.U*:
This variable contains the kind of ptr returned by malloc and realloc.
`man1dir` From *man1dir.U*:
This variable contains the name of the directory in which manual source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself.
`man1direxp` From *man1dir.U*:
This variable is the same as the man1dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`man1ext` From *man1dir.U*:
This variable contains the extension that the manual page should have: one of `n`, `l`, or `1`. The Makefile must supply the *.*. See man1dir.
`man3dir` From *man3dir.U*:
This variable contains the name of the directory in which manual source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself.
`man3direxp` From *man3dir.U*:
This variable is the same as the man3dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`man3ext` From *man3dir.U*:
This variable contains the extension that the manual page should have: one of `n`, `l`, or `3`. The Makefile must supply the *.*. See man3dir.
`mips_type` From *usrinc.U*:
This variable holds the environment type for the mips system. Possible values are "BSD 4.3" and "System V".
`mistrustnm` From *Csym.U*:
This variable can be used to establish a fallthrough for the cases where nm fails to find a symbol. If usenm is false or usenm is true and mistrustnm is false, this variable has no effect. If usenm is true and mistrustnm is `compile`, a test program will be compiled to try to find any symbol that can't be located via nm lookup. If mistrustnm is `run`, the test program will be run as well as being compiled.
`mkdir` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the mkdir program. After Configure runs, the value is reset to a plain `mkdir` and is not useful.
`mmaptype` From *d\_mmap.U*:
This symbol contains the type of pointer returned by mmap() (and simultaneously the type of the first argument). It can be `void *` or `caddr_t`.
`modetype` From *modetype.U*:
This variable defines modetype to be something like mode\_t, int, unsigned short, or whatever type is used to declare file modes for system calls.
`more` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the more program. After Configure runs, the value is reset to a plain `more` and is not useful.
`multiarch` From *multiarch.U*:
This variable conditionally defines the `MULTIARCH` symbol which signifies the presence of multiplatform files. This is normally set by hints files.
`mv` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`myarchname` From *archname.U*:
This variable holds the architecture name computed by Configure in a previous run. It is not intended to be perused by any user and should never be set in a hint file.
`mydomain` From *myhostname.U*:
This variable contains the eventual value of the `MYDOMAIN` symbol, which is the domain of the host the program is going to run on. The domain must be appended to myhostname to form a complete host name. The dot comes with mydomain, and need not be supplied by the program.
`myhostname` From *myhostname.U*:
This variable contains the eventual value of the `MYHOSTNAME` symbol, which is the name of the host the program is going to run on. The domain is not kept with hostname, but must be gotten from mydomain. The dot comes with mydomain, and need not be supplied by the program.
`myuname` From *Oldconfig.U*:
The output of `uname -a` if available, otherwise the hostname. The whole thing is then lower-cased and slashes and single quotes are removed.
### n
`n` From *n.U*:
This variable contains the `-n` flag if that is what causes the echo command to suppress newline. Otherwise it is null. Correct usage is $echo $n "prompt for a question: $c".
`need_va_copy` From *need\_va\_copy.U*:
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.
`netdb_hlen_type` From *netdbtype.U*:
This variable holds the type used for the 2nd argument to gethostbyaddr(). Usually, this is int or size\_t or unsigned. This is only useful if you have gethostbyaddr(), naturally.
`netdb_host_type` From *netdbtype.U*:
This variable holds the type used for the 1st argument to gethostbyaddr(). Usually, this is char \* or void \*, possibly with or without a const prefix. This is only useful if you have gethostbyaddr(), naturally.
`netdb_name_type` From *netdbtype.U*:
This variable holds the type used for the argument to gethostbyname(). Usually, this is char \* or const char \*. This is only useful if you have gethostbyname(), naturally.
`netdb_net_type` From *netdbtype.U*:
This variable holds the type used for the 1st argument to getnetbyaddr(). Usually, this is int or long. This is only useful if you have getnetbyaddr(), naturally.
`nm` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the nm program. After Configure runs, the value is reset to a plain `nm` and is not useful.
`nm_opt` From *usenm.U*:
This variable holds the options that may be necessary for nm.
`nm_so_opt` From *usenm.U*:
This variable holds the options that may be necessary for nm to work on a shared library but that can not be used on an archive library. Currently, this is only used by Linux, where nm --dynamic is \*required\* to get symbols from an `ELF` library which has been stripped, but nm --dynamic is \*fatal\* on an archive library. Maybe Linux should just always set usenm=false.
`nonxs_ext` From *Extensions.U*:
This variable holds a list of all non-xs extensions built and installed by the package. By default, all non-xs extensions distributed will be built, with the exception of platform-specific extensions (currently only one `VMS` specific extension).
`nroff` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the nroff program. After Configure runs, the value is reset to a plain `nroff` and is not useful.
`nv_overflows_integers_at` From *perlxv.U*:
This variable gives the largest integer value that NVs can hold as a constant floating point expression. If it could not be determined, it holds the value 0.
`nv_preserves_uv_bits` From *perlxv.U*:
This variable indicates how many of bits type uvtype a variable nvtype can preserve.
`nveformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %e-ish floating point format.
`nvEUformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %E-ish floating point format.
`nvfformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %f-ish floating point format.
`nvFUformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %F-ish floating point format.
`nvgformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %g-ish floating point format.
`nvGUformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `NV` using %G-ish floating point format.
`nvmantbits` From *mantbits.U*:
This variable tells how many bits the mantissa of a Perl `NV` has, not including the possible implicit bit.
`nvsize` From *perlxv.U*:
This variable is the size of a Perl `NV` in bytes. Note that some floating point formats have unused bytes.
`nvtype` From *perlxv.U*:
This variable contains the C type used for Perl's `NV`.
### o
`o_nonblock` From *nblock\_io.U*:
This variable bears the symbol value to be used during open() or fcntl() to turn on non-blocking I/O for a file descriptor. If you wish to switch between blocking and non-blocking, you may try ioctl(`FIOSNBIO`) instead, but that is only supported by some devices.
`obj_ext` From *Unix.U*:
This is an old synonym for \_o.
`old_pthread_create_joinable` From *d\_pthrattrj.U*:
This variable defines the constant to use for creating joinable (aka undetached) pthreads. Unused if *pthread.h* defines `PTHREAD_CREATE_JOINABLE`. If used, possible values are `PTHREAD_CREATE_UNDETACHED` and `__UNDETACHED`.
`optimize` From *ccflags.U*:
This variable contains any *optimizer/debugger* flag that should be used. It is up to the Makefile to use it.
`orderlib` From *orderlib.U*:
This variable is `true` if the components of libraries must be ordered (with `lorder $\* | tsort`) before placing them in an archive. Set to `false` if ranlib or ar can generate random libraries.
`osname` From *Oldconfig.U*:
This variable contains the operating system name (e.g. sunos, solaris, hpux, etc.). It can be useful later on for setting defaults. Any spaces are replaced with underscores. It is set to a null string if we can't figure it out.
`osvers` From *Oldconfig.U*:
This variable contains the operating system version (e.g. 4.1.3, 5.2, etc.). It is primarily used for helping select an appropriate hints file, but might be useful elsewhere for setting defaults. It is set to '' if we can't figure it out. We try to be flexible about how much of the version number to keep, e.g. if 4.1.1, 4.1.2, and 4.1.3 are essentially the same for this package, hints files might just be *os\_4.0* or *os\_4.1*, etc., not keeping separate files for each little release.
`otherlibdirs` From *otherlibdirs.U*:
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 inc\_version\_list for more details. A value of means `none` and is used to preserve this value for the next run through Configure.
### p
`package` From *package.U*:
This variable contains the name of the package being constructed. It is primarily intended for the use of later Configure units.
`pager` From *pager.U*:
This variable contains the name of the preferred pager on the system. Usual values are (the full pathnames of) more, less, pg, or cat.
`passcat` From *nis.U*:
This variable contains a command that produces the text of the */etc/passwd* file. This is normally "cat */etc/passwd*", but can be "ypcat passwd" when `NIS` is used. On some systems, such as os390, there may be no equivalent command, in which case this variable is unset.
`patchlevel` From *patchlevel.U*:
The patchlevel level of this package. The value of patchlevel comes from the *patchlevel.h* file. In a version number such as 5.6.1, this is the `6`. In *patchlevel.h*, this is referred to as `PERL_VERSION`.
`path_sep` From *Unix.U*:
This is an old synonym for p\_ in *Head.U*, the character used to separate elements in the command shell search `PATH`.
`perl` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the perl program. After Configure runs, the value is reset to a plain `perl` and is not useful.
`perl5` From *perl5.U*:
This variable contains the full path (if any) to a previously installed *perl5.005* or later suitable for running the script to determine inc\_version\_list.
### P
`PERL_API_REVISION` From *patchlevel.h*:
This number describes the earliest compatible `PERL_REVISION` of Perl (`compatibility` here being defined as sufficient *binary/`API`* compatibility to run `XS` code built with the older version). Normally this does not change across maintenance releases. Please read the comment in *patchlevel.h*.
`PERL_API_SUBVERSION` From *patchlevel.h*:
This number describes the earliest compatible `PERL_SUBVERSION` of Perl (`compatibility` here being defined as sufficient *binary/`API`* compatibility to run `XS` code built with the older version). Normally this does not change across maintenance releases. Please read the comment in *patchlevel.h*.
`PERL_API_VERSION` From *patchlevel.h*:
This number describes the earliest compatible `PERL_VERSION` of Perl (`compatibility` here being defined as sufficient *binary/`API`* compatibility to run `XS` code built with the older version). Normally this does not change across maintenance releases. Please read the comment in *patchlevel.h*.
`PERL_CONFIG_SH` From *Oldsyms.U*:
This is set to `true` in *config.sh* so that a shell script sourcing *config.sh* can tell if it has been sourced already.
`PERL_PATCHLEVEL` From *Oldsyms.U*:
This symbol reflects the patchlevel, if available. Will usually come from the *.patch* file, which is available when the perl source tree was fetched with rsync.
`perl_patchlevel` From *patchlevel.U*:
This is the Perl patch level, a numeric change identifier, as defined by whichever source code maintenance system is used to maintain the patches; currently Perforce. It does not correlate with the Perl version numbers or the maintenance versus development dichotomy except by also being increasing.
`PERL_REVISION` From *Oldsyms.U*:
In a Perl version number such as 5.6.2, this is the 5. This value is manually set in *patchlevel.h*
`perl_static_inline` From *d\_static\_inline.U*:
This variable defines the `PERL_STATIC_INLINE` symbol to the best-guess incantation to use for static inline functions. Possibilities include static inline (c99) static \_\_inline\_\_ (gcc -ansi) static \_\_inline (`MSVC`) static \_inline (older `MSVC`) static (c89 compilers)
`PERL_SUBVERSION` From *Oldsyms.U*:
In a Perl version number such as 5.6.2, this is the 2. Values greater than 50 represent potentially unstable development subversions. This value is manually set in *patchlevel.h*
`perl_thread_local` From *d\_thread\_local.U*:
This variable gives the value for the `PERL_THREAD_LOCAL` symbol (when defined), which gives a linkage specification for thread-local storage.
`PERL_VERSION` From *Oldsyms.U*:
In a Perl version number such as 5.6.2, this is the 6. This value is manually set in *patchlevel.h*
`perladmin` From *perladmin.U*:
Electronic mail address of the perl5 administrator.
`perllibs` From *End.U*:
The list of libraries needed by Perl only (any libraries needed by extensions only will by dropped, if using dynamic loading).
`perlpath` From *perlpath.U*:
This variable contains the eventual value of the `PERLPATH` symbol, which contains the name of the perl interpreter to be used in shell scripts and in the "eval `exec`" idiom. This variable is not necessarily the pathname of the file containing the perl interpreter; you must append the executable extension (\_exe) if it is not already present. Note that Perl code that runs during the Perl build process cannot reference this variable, as Perl may not have been installed, or even if installed, may be a different version of Perl.
`pg` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the pg program. After Configure runs, the value is reset to a plain `pg` and is not useful.
`phostname` From *myhostname.U*:
This variable contains the eventual value of the `PHOSTNAME` symbol, which is a command that can be fed to popen() to get the host name. The program should probably not presume that the domain is or isn't there already.
`pidtype` From *pidtype.U*:
This variable defines `PIDTYPE` to be something like pid\_t, int, ushort, or whatever type is used to declare process ids in the kernel.
`plibpth` From *libpth.U*:
Holds the private path used by Configure to find out the libraries. Its value is prepend to libpth. This variable takes care of special machines, like the mips. Usually, it should be empty.
`pmake` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`pr` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`prefix` From *prefix.U*:
This variable holds the name of the directory below which the user will install the package. Usually, this is */usr/local*, and executables go in */usr/local/bin*, library stuff in */usr/local/lib*, man pages in */usr/local/man*, etc. It is only used to set defaults for things in *bin.U*, *mansrc.U*, *privlib.U*, or *scriptdir.U*.
`prefixexp` From *prefix.U*:
This variable holds the full absolute path of the directory below which the user will install the package. Derived from prefix.
`privlib` From *privlib.U*:
This variable contains the eventual value of the `PRIVLIB` symbol, which is the name of the private library for this package. It may have a *~* on the front. It is up to the makefile to eventually create this directory while performing installation (with *~* substitution).
`privlibexp` From *privlib.U*:
This variable is the *~name* expanded version of privlib, so that you may use it directly in Makefiles or shell scripts.
`procselfexe` From *d\_procselfexe.U*:
If d\_procselfexe is defined, $procselfexe is the filename of the symbolic link pointing to the absolute pathname of the executing program.
`ptrsize` From *ptrsize.U*:
This variable contains the value of the `PTRSIZE` symbol, which indicates to the C program how many bytes there are in a pointer.
### q
`quadkind` From *quadtype.U*:
This variable, if defined, encodes the type of a quad: 1 = int, 2 = long, 3 = long long, 4 = int64\_t.
`quadtype` From *quadtype.U*:
This variable defines Quad\_t to be something like long, int, long long, int64\_t, or whatever type is used for 64-bit integers.
### r
`randbits` From *randfunc.U*:
Indicates how many bits are produced by the function used to generate normalized random numbers.
`randfunc` From *randfunc.U*:
Indicates the name of the random number function to use. Values include drand48, random, and rand. In C programs, the `Drand01` macro is defined to generate uniformly distributed random numbers over the range [0., 1.[ (see drand01 and nrand).
`random_r_proto` From *d\_random\_r.U*:
This variable 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.
`randseedtype` From *randfunc.U*:
Indicates the type of the argument of the seedfunc.
`ranlib` From *orderlib.U*:
This variable is set to the pathname of the ranlib program, if it is needed to generate random libraries. Set to `:` if ar can generate random libraries or if random libraries are not supported
`rd_nodata` From *nblock\_io.U*:
This variable holds the return code from read() when no data is present. It should be -1, but some systems return 0 when `O_NDELAY` is used, which is a shame because you cannot make the difference between no data and an *EOF.*. Sigh!
`readdir64_r_proto` From *d\_readdir64\_r.U*:
This variable 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.
`readdir_r_proto` From *d\_readdir\_r.U*:
This variable 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.
`revision` From *patchlevel.U*:
The value of revision comes from the *patchlevel.h* file. In a version number such as 5.6.1, this is the `5`. In *patchlevel.h*, this is referred to as `PERL_REVISION`.
`rm` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the rm program. After Configure runs, the value is reset to a plain `rm` and is not useful.
`rm_try` From *Unix.U*:
This is a cleanup variable for try test programs. Internal Configure use only.
`rmail` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`run` From *Cross.U*:
This variable contains the command used by Configure to copy and execute a cross-compiled executable in the target host. Useful and available only during Perl build. Empty string '' if not cross-compiling.
`runnm` From *usenm.U*:
This variable contains `true` or `false` depending whether the nm extraction should be performed or not, according to the value of usenm and the flags on the Configure command line.
### s
`sched_yield` From *d\_pthread\_y.U*:
This variable defines the way to yield the execution of the current thread.
`scriptdir` From *scriptdir.U*:
This variable holds the name of the directory in which the user wants to put publicly scripts for the package in question. It is either the same directory as for binaries, or a special one that can be mounted across different architectures, like */usr/share*. Programs must be prepared to deal with *~name* expansion.
`scriptdirexp` From *scriptdir.U*:
This variable is the same as scriptdir, but is filename expanded at configuration time, for programs not wanting to bother with it.
`sed` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the sed program. After Configure runs, the value is reset to a plain `sed` and is not useful.
`seedfunc` From *randfunc.U*:
Indicates the random number generating seed function. Values include srand48, srandom, and srand.
`selectminbits` From *selectminbits.U*:
This variable 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.
`selecttype` From *selecttype.U*:
This variable 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(), naturally.
`sendmail` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`setgrent_r_proto` From *d\_setgrent\_r.U*:
This variable 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` From *d\_sethostent\_r.U*:
This variable 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` From *d\_setlocale\_r.U*:
This variable 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` From *d\_setnetent\_r.U*:
This variable 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` From *d\_setprotoent\_r.U*:
This variable 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` From *d\_setpwent\_r.U*:
This variable 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` From *d\_setservent\_r.U*:
This variable 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.
`sGMTIME_max` From *time\_size.U*:
This variable defines the maximum value of the time\_t offset that the system function gmtime () accepts
`sGMTIME_min` From *time\_size.U*:
This variable defines the minimum value of the time\_t offset that the system function gmtime () accepts
`sh` From *sh.U*:
This variable contains the full pathname of the shell used 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*. This unit comes before *Options.U*, so you can't set sh with a `-D` option, though you can override this (and startsh) with `-O -Dsh=*/bin/whatever* -Dstartsh=whatever`
`shar` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`sharpbang` From *spitshell.U*:
This variable contains the string #! if this system supports that construct.
`shmattype` From *d\_shmat.U*:
This symbol contains the type of pointer returned by shmat(). It can be `void *` or `char *`.
`shortsize` From *intsize.U*:
This variable contains the value of the `SHORTSIZE` symbol which indicates to the C program how many bytes there are in a short.
`shrpenv` From *libperl.U*:
If the user builds a shared *libperl.so*, then we need to tell the `perl` executable where it will be able to find the installed *libperl.so*. One way to do this on some systems is to set the environment variable `LD_RUN_PATH` to the directory that will be the final location of the shared *libperl.so*. The makefile can use this with something like $shrpenv $(`CC`) -o perl *perlmain.o* $libperl $libs Typical values are shrpenv="env `LD_RUN_PATH`=*$archlibexp/`CORE`*" or shrpenv='' See the main perl *Makefile.SH* for actual working usage.
Alternatively, we might be able to use a command line option such as -R *$archlibexp/`CORE`* (Solaris) or -Wl,-rpath *$archlibexp/`CORE`* (Linux).
`shsharp` From *spitshell.U*:
This variable tells further Configure units whether your sh can handle # comments.
`sig_count` From *sig\_name.U*:
This variable holds a number larger than the largest valid signal number. This is usually the same as the `NSIG` macro.
`sig_name` From *sig\_name.U*:
This variable holds the signal names, space separated. The leading `SIG` in signal name is removed. A `ZERO` is prepended to the list. This is currently not used, sig\_name\_init is used instead.
`sig_name_init` From *sig\_name.U*:
This variable holds the signal names, enclosed in double quotes and separated by commas, suitable for use in the `SIG_NAME` definition below. A `ZERO` is prepended to the list, and the list is terminated with a plain 0. The leading `SIG` in signal names is removed. See sig\_num.
`sig_num` From *sig\_name.U*:
This variable holds the signal numbers, space separated. A `ZERO` is prepended to the list (corresponding to the fake `SIGZERO`). Those numbers correspond to the value of the signal listed in the same place within the sig\_name list. This is currently not used, sig\_num\_init is used instead.
`sig_num_init` From *sig\_name.U*:
This variable holds the signal numbers, enclosed in double quotes and separated by commas, suitable for use in the `SIG_NUM` definition below. A `ZERO` is prepended to the list, and the list is terminated with a plain 0.
`sig_size` From *sig\_name.U*:
This variable contains the number of elements of the sig\_name and sig\_num arrays.
`signal_t` From *d\_voidsig.U*:
This variable holds the type of the signal handler (void or int).
`sitearch` From *sitearch.U*:
This variable contains the eventual value of the `SITEARCH` symbol, which is the name of the private library for this package. It may have a *~* on the front. It is up to the makefile to eventually create this directory while performing installation (with *~* substitution). 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` for details.
`sitearchexp` From *sitearch.U*:
This variable is the *~name* expanded version of sitearch, so that you may use it directly in Makefiles or shell scripts.
`sitebin` From *sitebin.U*:
This variable holds the name of the directory in which the user wants to put add-on publicly executable files for the package in question. It is most often a local directory such as */usr/local/bin*. Programs using this variable must be prepared to deal with *~name* substitution. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local executables in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`sitebinexp` From *sitebin.U*:
This is the same as the sitebin variable, but is filename expanded at configuration time, for use in your makefiles.
`sitehtml1dir` From *sitehtml1dir.U*:
This variable contains the name of the directory in which site-specific html source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local html pages in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`sitehtml1direxp` From *sitehtml1dir.U*:
This variable is the same as the sitehtml1dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`sitehtml3dir` From *sitehtml3dir.U*:
This variable contains the name of the directory in which site-specific library html source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local library html pages in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`sitehtml3direxp` From *sitehtml3dir.U*:
This variable is the same as the sitehtml3dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`sitelib` From *sitelib.U*:
This variable contains the eventual value of the `SITELIB` symbol, which is the name of the private library for this package. It may have a *~* on the front. It is up to the makefile to eventually create this directory while performing installation (with *~* substitution). 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` for details.
`sitelib_stem` From *sitelib.U*:
This variable is $sitelibexp with any trailing version-specific component removed. The elements in inc\_version\_list (*inc\_version\_list.U*) can be tacked onto this variable to generate a list of directories to search.
`sitelibexp` From *sitelib.U*:
This variable is the *~name* expanded version of sitelib, so that you may use it directly in Makefiles or shell scripts.
`siteman1dir` From *siteman1dir.U*:
This variable contains the name of the directory in which site-specific manual source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local man1 pages in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`siteman1direxp` From *siteman1dir.U*:
This variable is the same as the siteman1dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`siteman3dir` From *siteman3dir.U*:
This variable contains the name of the directory in which site-specific library man source pages are to be put. It is the responsibility of the *Makefile.SH* to get the value of this into the proper command. You must be prepared to do the *~name* expansion yourself. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local man3 pages in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`siteman3direxp` From *siteman3dir.U*:
This variable is the same as the siteman3dir variable, but is filename expanded at configuration time, for convenient use in makefiles.
`siteprefix` From *siteprefix.U*:
This variable holds the full absolute path of the directory below which the user will install add-on packages. See `INSTALL` for usage and examples.
`siteprefixexp` From *siteprefix.U*:
This variable holds the full absolute path of the directory below which the user will install add-on packages. Derived from siteprefix.
`sitescript` From *sitescript.U*:
This variable holds the name of the directory in which the user wants to put add-on publicly executable files for the package in question. It is most often a local directory such as */usr/local/bin*. Programs using this variable must be prepared to deal with *~name* substitution. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local scripts in this directory with MakeMaker *Makefile.PL* or equivalent. See `INSTALL` for details.
`sitescriptexp` From *sitescript.U*:
This is the same as the sitescript variable, but is filename expanded at configuration time, for use in your makefiles.
`sizesize` From *sizesize.U*:
This variable contains the size of a sizetype in bytes.
`sizetype` From *sizetype.U*:
This variable defines sizetype to be something like size\_t, unsigned long, or whatever type is used to declare length parameters for string functions.
`sleep` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`sLOCALTIME_max` From *time\_size.U*:
This variable defines the maximum value of the time\_t offset that the system function localtime () accepts
`sLOCALTIME_min` From *time\_size.U*:
This variable defines the minimum value of the time\_t offset that the system function localtime () accepts
`smail` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`so` From *so.U*:
This variable holds the extension used to identify shared libraries (also known as shared objects) on the system. Usually set to `so`.
`sockethdr` From *d\_socket.U*:
This variable has any cpp `-I` flags needed for socket support.
`socketlib` From *d\_socket.U*:
This variable has the names of any libraries needed for socket support.
`socksizetype` From *socksizetype.U*:
This variable holds the type used for the size argument for various socket calls like accept. Usual values include socklen\_t, size\_t, and int.
`sort` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the sort program. After Configure runs, the value is reset to a plain `sort` and is not useful.
`spackage` From *package.U*:
This variable contains the name of the package being constructed, with the first letter uppercased, *i.e*. suitable for starting sentences.
`spitshell` From *spitshell.U*:
This variable contains the command necessary to spit out a runnable shell on this system. It is either cat or a grep `-v` for # comments.
`sPRId64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit decimal numbers (format `d`) for output.
`sPRIeldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `e`) for output.
`sPRIEUldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `E`) for output. The `U` in the name is to separate this from sPRIeldbl so that even case-blind systems can see the difference.
`sPRIfldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `f`) for output.
`sPRIFUldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `F`) for output. The `U` in the name is to separate this from sPRIfldbl so that even case-blind systems can see the difference.
`sPRIgldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `g`) for output.
`sPRIGUldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `G`) for output. The `U` in the name is to separate this from sPRIgldbl so that even case-blind systems can see the difference.
`sPRIi64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit decimal numbers (format `i`) for output.
`sPRIo64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit octal numbers (format `o`) for output.
`sPRIu64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit unsigned decimal numbers (format `u`) for output.
`sPRIx64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit hexadecimal numbers (format `x`) for output.
`sPRIXU64` From *quadfio.U*:
This variable, if defined, contains the string used by stdio to format 64-bit hExADECimAl numbers (format `X`) for output. The `U` in the name is to separate this from sPRIx64 so that even case-blind systems can see the difference.
`srand48_r_proto` From *d\_srand48\_r.U*:
This variable 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` From *d\_srandom\_r.U*:
This variable 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.
`src` From *src.U*:
This variable holds the (possibly relative) path of the package source. It is up to the Makefile to use this variable and set `VPATH` accordingly to find the sources remotely. Use $pkgsrc to have an absolute path.
`sSCNfldbl` From *longdblfio.U*:
This variable, if defined, contains the string used by stdio to format long doubles (format `f`) for input.
`ssizetype` From *ssizetype.U*:
This variable defines ssizetype to be something like ssize\_t, long or int. It is used by functions that return a count of bytes or an error condition. It must be a signed type. We will pick a type such that sizeof(SSize\_t) == sizeof(Size\_t).
`st_dev_sign` From *st\_dev\_def.U*:
This variable contains the signedness of struct stat's st\_dev. 1 for unsigned, -1 for signed.
`st_dev_size` From *st\_dev\_def.U*:
This variable contains the size of struct stat's st\_dev in bytes.
`st_ino_sign` From *st\_ino\_def.U*:
This variable contains the signedness of struct stat's st\_ino. 1 for unsigned, -1 for signed.
`st_ino_size` From *st\_ino\_def.U*:
This variable contains the size of struct stat's st\_ino in bytes.
`startperl` From *startperl.U*:
This variable contains the string to put on the front of a perl script to make sure (hopefully) that it runs with perl and not some shell. Of course, that leading line must be followed by the classical perl idiom: eval 'exec perl -S $0 ${1+`$@`}' if $running\_under\_some\_shell; to guarantee perl startup should the shell execute the script. Note that this magic incantation is not understood by csh.
`startsh` From *startsh.U*:
This variable contains the string to put on the front of a shell script to make sure (hopefully) that it runs with sh and not some other shell.
`static_ext` From *Extensions.U*:
This variable holds a list of `XS` extension files we want to link statically into the package. It is used by Makefile.
`stdchar` From *stdchar.U*:
This variable conditionally defines `STDCHAR` to be the type of char used in *stdio.h*. It has the values "unsigned char" or `char`.
`stdio_base` From *d\_stdstdio.U*:
This variable defines how, given a `FILE` pointer, fp, to access the \_base field (or equivalent) of *stdio.h*'s `FILE` structure. This will be used to define the macro FILE\_base(fp).
`stdio_bufsiz` From *d\_stdstdio.U*:
This variable defines how, given a `FILE` pointer, fp, to determine the number of bytes store in the I/O buffer pointer to by the \_base field (or equivalent) of *stdio.h*'s `FILE` structure. This will be used to define the macro FILE\_bufsiz(fp).
`stdio_cnt` From *d\_stdstdio.U*:
This variable defines how, given a `FILE` pointer, fp, to access the \_cnt field (or equivalent) of *stdio.h*'s `FILE` structure. This will be used to define the macro FILE\_cnt(fp).
`stdio_filbuf` From *d\_stdstdio.U*:
This variable defines how, given a `FILE` pointer, fp, to tell stdio to refill its internal buffers (?). This will be used to define the macro FILE\_filbuf(fp).
`stdio_ptr` From *d\_stdstdio.U*:
This variable defines how, given a `FILE` pointer, fp, to access the \_ptr field (or equivalent) of *stdio.h*'s `FILE` structure. This will be used to define the macro FILE\_ptr(fp).
`stdio_stream_array` From *stdio\_streams.U*:
This variable tells the name of the array holding the stdio streams. Usual values include \_iob, \_\_iob, and \_\_sF.
`strerror_r_proto` From *d\_strerror\_r.U*:
This variable 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.
`submit` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`subversion` From *patchlevel.U*:
The subversion level of this package. The value of subversion comes from the *patchlevel.h* file. In a version number such as 5.6.1, this is the `1`. In *patchlevel.h*, this is referred to as `PERL_SUBVERSION`. This is unique to perl.
`sysman` From *sysman.U*:
This variable holds the place where the manual is located on this system. It is not the place where the user wants to put his manual pages. Rather it is the place where Configure may look to find manual for unix commands (section 1 of the manual usually). See mansrc.
`sysroot` From *Sysroot.U*:
This variable is empty unless supplied by the Configure user. It can contain a path to an alternative root directory, under which headers and libraries for the compilation target can be found. This is generally used when cross-compiling using a gcc-like compiler.
### t
`tail` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`tar` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`targetarch` From *Cross.U*:
If cross-compiling, this variable contains the target architecture. If not, this will be empty.
`targetdir` From *Cross.U*:
This variable contains a path that will be created on the target host using targetmkdir, and then used to copy the cross-compiled executables to. Defaults to */tmp* if not set.
`targetenv` From *Cross.U*:
If cross-compiling, this variable can be used to modify the environment on the target system. However, how and where it's used, and even if it's used at all, is entirely dependent on both the transport mechanism (targetrun) and what the target system is. Unless the relevant documentation says otherwise, it is genereally not useful.
`targethost` From *Cross.U*:
This variable contains the name of a separate host machine that can be used to run compiled test programs and perl tests on. Set to empty string if not in use.
`targetmkdir` From *Cross.U*:
This variable contains the command used by Configure to create a new directory on the target host.
`targetport` From *Cross.U*:
This variable contains the number of a network port to be used to connect to the host in targethost, if unset defaults to 22 for ssh.
`targetsh` From *sh.U*:
If cross-compiling, this variable contains the location of sh on the target system. If not, this will be the same as $sh.
`tbl` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`tee` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`test` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the test program. After Configure runs, the value is reset to a plain `test` and is not useful.
`timeincl` From *i\_time.U*:
This variable holds the full path of the included time header(s).
`timetype` From *d\_time.U*:
This variable 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). Anyway, the type Time\_t should be used.
`tmpnam_r_proto` From *d\_tmpnam\_r.U*:
This variable 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.
`to` From *Cross.U*:
This variable contains the command used by Configure to copy to from the target host. Useful and available only during Perl build. The string `:` if not cross-compiling.
`touch` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the touch program. After Configure runs, the value is reset to a plain `touch` and is not useful.
`tr` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the tr program. After Configure runs, the value is reset to a plain `tr` and is not useful.
`trnl` From *trnl.U*:
This variable contains the value to be passed to the tr(1) command to transliterate a newline. Typical values are `\012` and `\n`. This is needed for `EBCDIC` systems where newline is not necessarily `\012`.
`troff` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`ttyname_r_proto` From *d\_ttyname\_r.U*:
This variable 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.
### u
`u16size` From *perlxv.U*:
This variable is the size of an U16 in bytes.
`u16type` From *perlxv.U*:
This variable contains the C type used for Perl's U16.
`u32size` From *perlxv.U*:
This variable is the size of an U32 in bytes.
`u32type` From *perlxv.U*:
This variable contains the C type used for Perl's U32.
`u64size` From *perlxv.U*:
This variable is the size of an U64 in bytes.
`u64type` From *perlxv.U*:
This variable contains the C type used for Perl's U64.
`u8size` From *perlxv.U*:
This variable is the size of an U8 in bytes.
`u8type` From *perlxv.U*:
This variable contains the C type used for Perl's U8.
`uidformat` From *uidf.U*:
This variable contains the format string used for printing a Uid\_t.
`uidsign` From *uidsign.U*:
This variable contains the signedness of a uidtype. 1 for unsigned, -1 for signed.
`uidsize` From *uidsize.U*:
This variable contains the size of a uidtype in bytes.
`uidtype` From *uidtype.U*:
This variable defines Uid\_t to be something like uid\_t, int, ushort, or whatever type is used to declare user ids in the kernel.
`uname` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the uname program. After Configure runs, the value is reset to a plain `uname` and is not useful.
`uniq` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the uniq program. After Configure runs, the value is reset to a plain `uniq` and is not useful.
`uquadtype` From *quadtype.U*:
This variable defines Uquad\_t to be something like unsigned long, unsigned int, unsigned long long, uint64\_t, or whatever type is used for 64-bit integers.
`use64bitall` From *use64bits.U*:
This variable conditionally defines the USE\_64\_BIT\_ALL symbol, and indicates that 64-bit integer types should be used when available. 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.
`use64bitint` From *use64bits.U*:
This variable conditionally defines the USE\_64\_BIT\_INT symbol, and indicates that 64-bit integer types should be used when available. The minimal possible 64-bitness is employed, 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.
`usecbacktrace` From *usebacktrace.U*:
This variable indicates whether we are compiling with backtrace support.
`usecrosscompile` From *Cross.U*:
This variable conditionally defines the `USE_CROSS_COMPILE` symbol, and indicates that Perl has been cross-compiled.
`usedefaultstrict` From *usedefaultstrict.U*:
This setting provides a mechanism for perl developers to enable strict by default. These defaults do not apply when perl is run via -e or -E.
`usedevel` From *Devel.U*:
This variable indicates that Perl was configured with development features enabled. This should not be done for production builds.
`usedl` From *dlsrc.U*:
This variable indicates if the system supports dynamic loading of some sort. See also dlsrc and dlobj.
`usedtrace` From *usedtrace.U*:
This variable indicates whether we are compiling with dtrace support. See also dtrace.
`usefaststdio` From *usefaststdio.U*:
This variable conditionally defines the `USE_FAST_STDIO` symbol, and indicates that Perl should be built to use `fast stdio`. Defaults to define in Perls 5.8 and earlier, to undef later.
`useithreads` From *usethreads.U*:
This variable conditionally defines the `USE_ITHREADS` symbol, and indicates that Perl should be built to use the interpreter-based threading implementation.
`usekernprocpathname` From *usekernprocpathname.U*:
This variable, 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.
`uselanginfo` From *Extensions.U*:
This variable holds either `true` or `false` to indicate whether the I18N::Langinfo extension should be used. The sole use for this currently is to allow an easy mechanism for users to skip this extension from the Configure command line.
`uselargefiles` From *uselfs.U*:
This variable conditionally defines the `USE_LARGE_FILES` symbol, and indicates that large file interfaces should be used when available.
`uselongdouble` From *uselongdbl.U*:
This variable conditionally defines the `USE_LONG_DOUBLE` symbol, and indicates that long doubles should be used when available.
`usemallocwrap` From *mallocsrc.U*:
This variable contains y if we are wrapping malloc to prevent integer overflow during size calculations.
`usemorebits` From *usemorebits.U*:
This variable conditionally defines the `USE_MORE_BITS` symbol, and indicates that explicit 64-bit interfaces and long doubles should be used when available.
`usemultiplicity` From *usemultiplicity.U*:
This variable conditionally defines the `MULTIPLICITY` symbol, and indicates that Perl should be built to use multiplicity.
`usemymalloc` From *mallocsrc.U*:
This variable contains y if the malloc that comes with this package is desired over the system's version of malloc. People often include special versions of malloc for efficiency, but such versions are often less portable. See also mallocsrc and mallocobj. If this is `y`, then -lmalloc is removed from $libs.
`usenm` From *usenm.U*:
This variable contains `true` or `false` depending whether the nm extraction is wanted or not.
`usensgetexecutablepath` From *usensgetexecutablepath.U*:
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.
`useopcode` From *Extensions.U*:
This variable holds either `true` or `false` to indicate whether the Opcode extension should be used. The sole use for this currently is to allow an easy mechanism for users to skip the Opcode extension from the Configure command line.
`useperlio` From *useperlio.U*:
This variable conditionally defines the `USE_PERLIO` symbol, and indicates that the PerlIO abstraction should be used throughout.
`useposix` From *Extensions.U*:
This variable holds either `true` or `false` to indicate whether the `POSIX` extension should be used. The sole use for this currently is to allow an easy mechanism for hints files to indicate that `POSIX` will not compile on a particular system.
`usequadmath` From *usequadmath.U*:
This variable conditionally defines the `USE_QUADMATH` symbol, and indicates that the quadmath library \_\_float128 long doubles should be used when available.
`usereentrant` From *usethreads.U*:
This variable conditionally defines the `USE_REENTRANT_API` symbol, which indicates that the thread code may try to use the various \_r versions of library functions. This is only potentially meaningful if usethreads is set and is very experimental, it is not even prompted for.
`userelocatableinc` From *bin.U*:
This variable is set to true to indicate that perl should relocate @`INC` entries at runtime based on the path to the perl binary. Any @`INC` paths starting *.../* are relocated relative to the directory containing the perl binary, and a logical cleanup of the path is then made around the join point (removing *dir/../* pairs)
`useshrplib` From *libperl.U*:
This variable is set to `true` if the user wishes to build a shared libperl, and `false` otherwise.
`usesitecustomize` From *d\_sitecustomize.U*:
This variable is set to true when the user requires a mechanism that allows the sysadmin to add entries to @`INC` at runtime. This variable being set, makes perl run *$sitelib/sitecustomize.pl* at startup.
`usesocks` From *usesocks.U*:
This variable conditionally defines the `USE_SOCKS` symbol, and indicates that Perl should be built to use `SOCKS`.
`usethreads` From *usethreads.U*:
This variable conditionally defines the `USE_THREADS` symbol, and indicates that Perl should be built to use threads.
`usevendorprefix` From *vendorprefix.U*:
This variable tells whether the vendorprefix and consequently other vendor\* paths are in use.
`useversionedarchname` From *archname.U*:
This variable indicates whether to include the $api\_versionstring as a component of the $archname.
`usevfork` From *d\_vfork.U*:
This variable is set to true when the user accepts to use vfork. It is set to false when no vfork is available or when the user explicitly requests not to use vfork.
`usrinc` From *usrinc.U*:
This variable holds the path of the include files, which is usually */usr/include*. It is mainly used by other Configure units.
`uuname` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`uvoformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `UV` as an unsigned octal integer.
`uvsize` From *perlxv.U*:
This variable is the size of a `UV` in bytes.
`uvtype` From *perlxv.U*:
This variable contains the C type used for Perl's `UV`.
`uvuformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `UV` as an unsigned decimal integer.
`uvxformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `UV` as an unsigned hexadecimal integer in lowercase abcdef.
`uvXUformat` From *perlxvf.U*:
This variable contains the format string used for printing a Perl `UV` as an unsigned hexadecimal integer in uppercase `ABCDEF`.
### v
`vendorarch` From *vendorarch.U*:
This variable contains the value of the `PERL_VENDORARCH` symbol. 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` for details.
`vendorarchexp` From *vendorarch.U*:
This variable is the *~name* expanded version of vendorarch, so that you may use it directly in Makefiles or shell scripts.
`vendorbin` From *vendorbin.U*:
This variable contains the eventual value of the `VENDORBIN` symbol. It may have a *~* on the front. The standard distribution will put nothing in this directory. Vendors who distribute perl may wish to place additional binaries in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorbinexp` From *vendorbin.U*:
This variable is the *~name* expanded version of vendorbin, so that you may use it directly in Makefiles or shell scripts.
`vendorhtml1dir` From *vendorhtml1dir.U*:
This variable contains the name of the directory for html pages. 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 html pages in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorhtml1direxp` From *vendorhtml1dir.U*:
This variable is the *~name* expanded version of vendorhtml1dir, so that you may use it directly in Makefiles or shell scripts.
`vendorhtml3dir` From *vendorhtml3dir.U*:
This variable contains the name of the directory for html library pages. 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 html pages for modules and extensions in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorhtml3direxp` From *vendorhtml3dir.U*:
This variable is the *~name* expanded version of vendorhtml3dir, so that you may use it directly in Makefiles or shell scripts.
`vendorlib` From *vendorlib.U*:
This variable contains the eventual value of the `VENDORLIB` symbol, which is the name of the private library for this package. The standard distribution will put nothing in this directory. Vendors who distribute perl may wish to place their own modules in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorlib_stem` From *vendorlib.U*:
This variable is $vendorlibexp with any trailing version-specific component removed. The elements in inc\_version\_list (*inc\_version\_list.U*) can be tacked onto this variable to generate a list of directories to search.
`vendorlibexp` From *vendorlib.U*:
This variable is the *~name* expanded version of vendorlib, so that you may use it directly in Makefiles or shell scripts.
`vendorman1dir` From *vendorman1dir.U*:
This variable contains the name of the directory for man1 pages. 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 man1 pages in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorman1direxp` From *vendorman1dir.U*:
This variable is the *~name* expanded version of vendorman1dir, so that you may use it directly in Makefiles or shell scripts.
`vendorman3dir` From *vendorman3dir.U*:
This variable contains the name of the directory for man3 pages. 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 man3 pages in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorman3direxp` From *vendorman3dir.U*:
This variable is the *~name* expanded version of vendorman3dir, so that you may use it directly in Makefiles or shell scripts.
`vendorprefix` From *vendorprefix.U*:
This variable holds the full absolute path of the directory below which the vendor will install add-on packages. See `INSTALL` for usage and examples.
`vendorprefixexp` From *vendorprefix.U*:
This variable holds the full absolute path of the directory below which the vendor will install add-on packages. Derived from vendorprefix.
`vendorscript` From *vendorscript.U*:
This variable contains the eventual value of the `VENDORSCRIPT` symbol. It may have a *~* on the front. The standard distribution will put nothing in this directory. Vendors who distribute perl may wish to place additional executable scripts in this directory with MakeMaker *Makefile.PL* `INSTALLDIRS`=vendor or equivalent. See `INSTALL` for details.
`vendorscriptexp` From *vendorscript.U*:
This variable is the *~name* expanded version of vendorscript, so that you may use it directly in Makefiles or shell scripts.
`version` From *patchlevel.U*:
The full version number of this package, such as 5.6.1 (or 5\_6\_1). This combines revision, patchlevel, and subversion to get the full version number, including any possible subversions. This is suitable for use as a directory name, and hence is filesystem dependent.
`version_patchlevel_string` From *patchlevel.U*:
This is a string combining version, subversion and perl\_patchlevel (if perl\_patchlevel is non-zero). It is typically something like 'version 7 subversion 1' or 'version 7 subversion 1 patchlevel 11224' It is computed here to avoid duplication of code in *myconfig.SH* and *lib/Config.pm*.
`versiononly` From *versiononly.U*:
If set, this symbol indicates that only the version-specific components of a perl installation should be installed. This may be useful for making a test installation of a new version without disturbing the existing installation. Setting versiononly is equivalent to setting installperl's -v option. In particular, the non-versioned scripts and programs such as a2p, c2ph, h2xs, pod2\*, and perldoc are not installed (see `INSTALL` for a more complete list). Nor are the man pages installed. Usually, this is undef.
`vi` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
### x
`xlibpth` From *libpth.U*:
This variable holds extra path (space-separated) used to find libraries on this platform, for example `CPU`-specific libraries (on multi-`CPU` platforms) may be listed here.
`xlocale_needed` From *d\_newlocale.U*:
This symbol, if defined, indicates that the C program should include <xlocale.h> to get newlocale() and its friends.
### y
`yacc` From *yacc.U*:
This variable holds the name of the compiler compiler we want to use in the Makefile. It can be yacc, byacc, or bison -y.
`yaccflags` From *yacc.U*:
This variable contains any additional yacc flags desired by the user. It is up to the Makefile to use this.
### z
`zcat` From *Loc.U*:
This variable is defined but not used by Configure. The value is the empty string and is not useful.
`zip` From *Loc.U*:
This variable is used internally by Configure to determine the full pathname (if any) of the zip program. After Configure runs, the value is reset to a plain `zip` and is not useful.
GIT DATA
---------
Information on the git commit from which the current perl binary was compiled can be found in the variable `$Config::Git_Data`. The variable is a structured string that looks something like this:
```
git_commit_id='ea0c2dbd5f5ac6845ecc7ec6696415bf8e27bd52'
git_describe='GitLive-blead-1076-gea0c2db'
git_branch='smartmatch'
git_uncommitted_changes=''
git_commit_id_title='Commit id:'
git_commit_date='2009-05-09 17:47:31 +0200'
```
Its format is not guaranteed not to change over time.
NOTE
----
This module contains a good example of how to use tie to implement a cache and an example of how to make a tied variable readonly to those outside of it.
| programming_docs |
perl Test2::Event::Bail Test2::Event::Bail
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Bail - Bailout!
DESCRIPTION
-----------
The bailout event is generated when things go horribly wrong and you need to halt all testing in the current file.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Bail;
my $ctx = context();
my $event = $ctx->bail('Stuff is broken');
```
METHODS
-------
Inherits from <Test2::Event>. Also defines:
$reason = $e->reason The reason for the bailout.
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::Hub Test2::Hub
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [COMMON TASKS](#COMMON-TASKS)
+ [SENDING EVENTS](#SENDING-EVENTS)
+ [ALTERING OR REMOVING EVENTS](#ALTERING-OR-REMOVING-EVENTS)
+ [LISTENING FOR EVENTS](#LISTENING-FOR-EVENTS)
+ [POST-TEST BEHAVIORS](#POST-TEST-BEHAVIORS)
+ [SETTING THE FORMATTER](#SETTING-THE-FORMATTER)
* [METHODS](#METHODS)
+ [STATE METHODS](#STATE-METHODS)
* [THIRD PARTY META-DATA](#THIRD-PARTY-META-DATA)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Hub - The conduit through which all events flow.
SYNOPSIS
--------
```
use Test2::Hub;
my $hub = Test2::Hub->new();
$hub->send(...);
```
DESCRIPTION
-----------
The hub is the place where all events get processed and handed off to the formatter. The hub also tracks test state, and provides several hooks into the event pipeline.
COMMON TASKS
-------------
###
SENDING EVENTS
```
$hub->send($event)
```
The `send()` method is used to issue an event to the hub. This method will handle thread/fork sync, filters, listeners, TAP output, etc.
###
ALTERING OR REMOVING EVENTS
You can use either `filter()` or `pre_filter()`, depending on your needs. Both have identical syntax, so only `filter()` is shown here.
```
$hub->filter(sub {
my ($hub, $event) = @_;
my $action = get_action($event);
# No action should be taken
return $event if $action eq 'none';
# You want your filter to remove the event
return undef if $action eq 'delete';
if ($action eq 'do_it') {
my $new_event = copy_event($event);
... Change your copy of the event ...
return $new_event;
}
die "Should not happen";
});
```
By default, filters are not inherited by child hubs. That means if you start a subtest, the subtest will not inherit the filter. You can change this behavior with the `inherit` parameter:
```
$hub->filter(sub { ... }, inherit => 1);
```
###
LISTENING FOR EVENTS
```
$hub->listen(sub {
my ($hub, $event, $number) = @_;
... do whatever you want with the event ...
# return is ignored
});
```
By default listeners are not inherited by child hubs. That means if you start a subtest, the subtest will not inherit the listener. You can change this behavior with the `inherit` parameter:
```
$hub->listen(sub { ... }, inherit => 1);
```
###
POST-TEST BEHAVIORS
```
$hub->follow_up(sub {
my ($trace, $hub) = @_;
... do whatever you need to ...
# Return is ignored
});
```
follow\_up subs are called only once, either when done\_testing is called, or in an END block.
###
SETTING THE FORMATTER
By default an instance of <Test2::Formatter::TAP> is created and used.
```
my $old = $hub->format(My::Formatter->new);
```
Setting the formatter will REPLACE any existing formatter. You may set the formatter to undef to prevent output. The old formatter will be returned if one was already set. Only one formatter is allowed at a time.
METHODS
-------
$hub->send($event) This is where all events enter the hub for processing.
$hub->process($event) This is called by send after it does any IPC handling. You can use this to bypass the IPC process, but in general you should avoid using this.
$old = $hub->format($formatter) Replace the existing formatter instance with a new one. Formatters must be objects that implement a `$formatter->write($event)` method.
$sub = $hub->listen(sub { ... }, %optional\_params) You can use this to record all events AFTER they have been sent to the formatter. No changes made here will be meaningful, except possibly to other listeners.
```
$hub->listen(sub {
my ($hub, $event, $number) = @_;
... do whatever you want with the event ...
# return is ignored
});
```
Normally listeners are not inherited by child hubs such as subtests. You can add the `inherit => 1` parameter to allow a listener to be inherited.
$hub->unlisten($sub) You can use this to remove a listen callback. You must pass in the coderef returned by the `listen()` method.
$sub = $hub->filter(sub { ... }, %optional\_params)
$sub = $hub->pre\_filter(sub { ... }, %optional\_params) These can be used to add filters. Filters can modify, replace, or remove events before anything else can see them.
```
$hub->filter(
sub {
my ($hub, $event) = @_;
return $event; # No Changes
return; # Remove the event
# Or you can modify an event before returning it.
$event->modify;
return $event;
}
);
```
If you are not using threads, forking, or IPC then the only difference between a `filter` and a `pre_filter` is that `pre_filter` subs run first. When you are using threads, forking, or IPC, pre\_filters happen to events before they are sent to their destination proc/thread, ordinary filters happen only in the destination hub/thread.
You cannot add a regular filter to a hub if the hub was created in another process or thread. You can always add a pre\_filter.
$hub->unfilter($sub)
$hub->pre\_unfilter($sub) These can be used to remove filters and pre\_filters. The `$sub` argument is the reference returned by `filter()` or `pre_filter()`.
$hub->follow\_op(sub { ... }) Use this to add behaviors that are called just before the hub is finalized. The only argument to your codeblock will be a <Test2::EventFacet::Trace> instance.
```
$hub->follow_up(sub {
my ($trace, $hub) = @_;
... do whatever you need to ...
# Return is ignored
});
```
follow\_up subs are called only once, ether when done\_testing is called, or in an END block.
$sub = $hub->add\_context\_acquire(sub { ... }); Add a callback that will be called every time someone tries to acquire a context. It gets a single argument, a reference of 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.
**Note** Using this hook could have a huge performance impact.
The coderef you provide is returned and can be used to remove the hook later.
$hub->remove\_context\_acquire($sub); This can be used to remove a context acquire hook.
$sub = $hub->add\_context\_init(sub { ... }); This allows you to add callbacks that will trigger every time a new context is created for the hub. The only argument to the sub will be the <Test2::API::Context> instance that was created.
**Note** Using this hook could have a huge performance impact.
The coderef you provide is returned and can be used to remove the hook later.
$hub->remove\_context\_init($sub); This can be used to remove a context init hook.
$sub = $hub->add\_context\_release(sub { ... }); This allows you to add callbacks that will trigger every time a context for this hub is released. The only argument to the sub will be the <Test2::API::Context> instance that was released. These will run in reverse order.
**Note** Using this hook could have a huge performance impact.
The coderef you provide is returned and can be used to remove the hook later.
$hub->remove\_context\_release($sub); This can be used to remove a context release hook.
$hub->cull() Cull any IPC events (and process them).
$pid = $hub->pid() Get the process id under which the hub was created.
$tid = $hub->tid() Get the thread id under which the hub was created.
$hud = $hub->hid() Get the identifier string of the hub.
$uuid = $hub->uuid() If UUID tagging is enabled (see <Test2::API>) then the hub will have a UUID.
$ipc = $hub->ipc() Get the IPC object used by the hub.
$hub->set\_no\_ending($bool)
$bool = $hub->no\_ending This can be used to disable auto-ending behavior for a hub. The auto-ending behavior is triggered by an end block and is used to cull IPC events, and output the final plan if the plan was 'NO PLAN'.
$bool = $hub->active
$hub->set\_active($bool) These are used to get/set the 'active' attribute. When true this attribute will force `hub->finalize()` to take action even if there is no plan, and no tests have been run. This flag is useful for plugins that add follow-up behaviors that need to run even if no events are seen.
###
STATE METHODS
$hub->reset\_state() Reset all state to the start. This sets the test count to 0, clears the plan, removes the failures, etc.
$num = $hub->count Get the number of tests that have been run.
$num = $hub->failed Get the number of failures (Not all failures come from a test fail, so this number can be larger than the count).
$bool = $hub->ended True if the testing has ended. This MAY return the stack frame of the tool that ended the test, but that is not guaranteed.
$bool = $hub->is\_passing
$hub->is\_passing($bool) Check if the overall test run is a failure. Can also be used to set the pass/fail status.
$hub->plan($plan)
$plan = $hub->plan Get or set the plan. The plan must be an integer larger than 0, the string 'NO PLAN', or the string 'SKIP'.
$bool = $hub->check\_plan Check if the plan and counts match, but only if the tests have ended. If tests have not ended this will return undef, otherwise it will be a true/false.
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 TAP::Formatter::Console TAP::Formatter::Console
=======================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
+ [open\_test](#open_test)
NAME
----
TAP::Formatter::Console - Harness output delegate for default console output
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides console orientated output formatting for TAP::Harness.
SYNOPSIS
--------
```
use TAP::Formatter::Console;
my $harness = TAP::Formatter::Console->new( \%args );
```
### `open_test`
See <TAP::Formatter::Base>
perl Pod::Perldoc::ToPod Pod::Perldoc::ToPod
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToPod - let Perldoc render Pod as ... Pod!
SYNOPSIS
--------
```
perldoc -opod Some::Modulename
```
(That's currently the same as the following:)
```
perldoc -u Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to display Pod source as itself! Pretty Zen, huh?
Currently this class works by just filtering out the non-Pod stuff from a given input file.
SEE ALSO
---------
<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 `<mallencpan.org>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl perldsc perldsc
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [REFERENCES](#REFERENCES)
* [COMMON MISTAKES](#COMMON-MISTAKES)
* [CAVEAT ON PRECEDENCE](#CAVEAT-ON-PRECEDENCE)
* [WHY YOU SHOULD ALWAYS use VERSION](#WHY-YOU-SHOULD-ALWAYS-use-VERSION)
* [DEBUGGING](#DEBUGGING)
* [CODE EXAMPLES](#CODE-EXAMPLES)
* [ARRAYS OF ARRAYS](#ARRAYS-OF-ARRAYS)
+ [Declaration of an ARRAY OF ARRAYS](#Declaration-of-an-ARRAY-OF-ARRAYS)
+ [Generation of an ARRAY OF ARRAYS](#Generation-of-an-ARRAY-OF-ARRAYS)
+ [Access and Printing of an ARRAY OF ARRAYS](#Access-and-Printing-of-an-ARRAY-OF-ARRAYS)
* [HASHES OF ARRAYS](#HASHES-OF-ARRAYS)
+ [Declaration of a HASH OF ARRAYS](#Declaration-of-a-HASH-OF-ARRAYS)
+ [Generation of a HASH OF ARRAYS](#Generation-of-a-HASH-OF-ARRAYS)
+ [Access and Printing of a HASH OF ARRAYS](#Access-and-Printing-of-a-HASH-OF-ARRAYS)
* [ARRAYS OF HASHES](#ARRAYS-OF-HASHES)
+ [Declaration of an ARRAY OF HASHES](#Declaration-of-an-ARRAY-OF-HASHES)
+ [Generation of an ARRAY OF HASHES](#Generation-of-an-ARRAY-OF-HASHES)
+ [Access and Printing of an ARRAY OF HASHES](#Access-and-Printing-of-an-ARRAY-OF-HASHES)
* [HASHES OF HASHES](#HASHES-OF-HASHES)
+ [Declaration of a HASH OF HASHES](#Declaration-of-a-HASH-OF-HASHES)
+ [Generation of a HASH OF HASHES](#Generation-of-a-HASH-OF-HASHES)
+ [Access and Printing of a HASH OF HASHES](#Access-and-Printing-of-a-HASH-OF-HASHES)
* [MORE ELABORATE RECORDS](#MORE-ELABORATE-RECORDS)
+ [Declaration of MORE ELABORATE RECORDS](#Declaration-of-MORE-ELABORATE-RECORDS)
+ [Declaration of a HASH OF COMPLEX RECORDS](#Declaration-of-a-HASH-OF-COMPLEX-RECORDS)
+ [Generation of a HASH OF COMPLEX RECORDS](#Generation-of-a-HASH-OF-COMPLEX-RECORDS)
* [Database Ties](#Database-Ties)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perldsc - Perl Data Structures Cookbook
DESCRIPTION
-----------
Perl lets us have complex data structures. You can write something like this and all of a sudden, you'd have an array with three dimensions!
```
for my $x (1 .. 10) {
for my $y (1 .. 10) {
for my $z (1 .. 10) {
$AoA[$x][$y][$z] =
$x ** $y + $z;
}
}
}
```
Alas, however simple this may appear, underneath it's a much more elaborate construct than meets the eye!
How do you print it out? Why can't you say just `print @AoA`? How do you sort it? How can you pass it to a function or get one of these back from a function? Is it an object? Can you save it to disk to read back later? How do you access whole rows or columns of that matrix? Do all the values have to be numeric?
As you see, it's quite easy to become confused. While some small portion of the blame for this can be attributed to the reference-based implementation, it's really more due to a lack of existing documentation with examples designed for the beginner.
This document is meant to be a detailed but understandable treatment of the many different sorts of data structures you might want to develop. It should also serve as a cookbook of examples. That way, when you need to create one of these complex data structures, you can just pinch, pilfer, or purloin a drop-in example from here.
Let's look at each of these possible constructs in detail. There are separate sections on each of the following:
* arrays of arrays
* hashes of arrays
* arrays of hashes
* hashes of hashes
* more elaborate constructs
But for now, let's look at general issues common to all these types of data structures.
REFERENCES
----------
The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl `@ARRAY`s and `%HASH`es are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference). They cannot directly contain other arrays or hashes, but instead contain *references* to other arrays or hashes.
You can't use a reference to an array or hash in quite the same way that you would a real array or hash. For C or C++ programmers unused to distinguishing between arrays and pointers to the same, this can be confusing. If so, just think of it as the difference between a structure and a pointer to a structure.
You can (and should) read more about references in <perlref>. Briefly, references are rather like pointers that know what they point to. (Objects are also a kind of reference, but we won't be needing them right away--if ever.) This means that when you have something which looks to you like an access to a two-or-more-dimensional array and/or hash, what's really going on is that the base type is merely a one-dimensional entity that contains references to the next level. It's just that you can *use* it as though it were a two-dimensional one. This is actually the way almost all C multidimensional arrays work as well.
```
$array[7][12] # array of arrays
$array[7]{string} # array of hashes
$hash{string}[7] # hash of arrays
$hash{string}{'another string'} # hash of hashes
```
Now, because the top level contains only references, if you try to print out your array in with a simple print() function, you'll get something that doesn't look very nice, like this:
```
my @AoA = ( [2, 3], [4, 5, 7], [0] );
print $AoA[1][2];
7
print @AoA;
ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
```
That's because Perl doesn't (ever) implicitly dereference your variables. If you want to get at the thing a reference is referring to, then you have to do this yourself using either prefix typing indicators, like `${$blah}`, `@{$blah}`, `@{$blah[$i]}`, or else postfix pointer arrows, like `$a->[3]`, `$h->{fred}`, or even `$ob->method()->[3]`.
COMMON MISTAKES
----------------
The two most common mistakes made in constructing something like an array of arrays is either accidentally counting the number of elements or else taking a reference to the same memory location repeatedly. Here's the case where you just get the count instead of a nested array:
```
for my $i (1..10) {
my @array = somefunc($i);
$AoA[$i] = @array; # WRONG!
}
```
That's just the simple case of assigning an array to a scalar and getting its element count. If that's what you really and truly want, then you might do well to consider being a tad more explicit about it, like this:
```
for my $i (1..10) {
my @array = somefunc($i);
$counts[$i] = scalar @array;
}
```
Here's the case of taking a reference to the same memory location again and again:
```
# Either without strict or having an outer-scope my @array;
# declaration.
for my $i (1..10) {
@array = somefunc($i);
$AoA[$i] = \@array; # WRONG!
}
```
So, what's the big problem with that? It looks right, doesn't it? After all, I just told you that you need an array of references, so by golly, you've made me one!
Unfortunately, while this is true, it's still broken. All the references in @AoA refer to the *very same place*, and they will therefore all hold whatever was last in @array! It's similar to the problem demonstrated in the following C program:
```
#include <pwd.h>
main() {
struct passwd *getpwnam(), *rp, *dp;
rp = getpwnam("root");
dp = getpwnam("daemon");
printf("daemon name is %s\nroot name is %s\n",
dp->pw_name, rp->pw_name);
}
```
Which will print
```
daemon name is daemon
root name is daemon
```
The problem is that both `rp` and `dp` are pointers to the same location in memory! In C, you'd have to remember to malloc() yourself some new memory. In Perl, you'll want to use the array constructor `[]` or the hash constructor `{}` instead. Here's the right way to do the preceding broken code fragments:
```
# Either without strict or having an outer-scope my @array;
# declaration.
for my $i (1..10) {
@array = somefunc($i);
$AoA[$i] = [ @array ];
}
```
The square brackets make a reference to a new array with a *copy* of what's in @array at the time of the assignment. This is what you want.
Note that this will produce something similar:
```
# Either without strict or having an outer-scope my @array;
# declaration.
for my $i (1..10) {
@array = 0 .. $i;
$AoA[$i]->@* = @array;
}
```
Is it the same? Well, maybe so--and maybe not. The subtle difference is that when you assign something in square brackets, you know for sure it's always a brand new reference with a new *copy* of the data. Something else could be going on in this new case with the `$AoA[$i]->@*` dereference on the left-hand-side of the assignment. It all depends on whether `$AoA[$i]` had been undefined to start with, or whether it already contained a reference. If you had already populated @AoA with references, as in
```
$AoA[3] = \@another_array;
```
Then the assignment with the indirection on the left-hand-side would use the existing reference that was already there:
```
$AoA[3]->@* = @array;
```
Of course, this *would* have the "interesting" effect of clobbering @another\_array. (Have you ever noticed how when a programmer says something is "interesting", that rather than meaning "intriguing", they're disturbingly more apt to mean that it's "annoying", "difficult", or both? :-)
So just remember always to use the array or hash constructors with `[]` or `{}`, and you'll be fine, although it's not always optimally efficient.
Surprisingly, the following dangerous-looking construct will actually work out fine:
```
for my $i (1..10) {
my @array = somefunc($i);
$AoA[$i] = \@array;
}
```
That's because my() is more of a run-time statement than it is a compile-time declaration *per se*. This means that the my() variable is remade afresh each time through the loop. So even though it *looks* as though you stored the same variable reference each time, you actually did not! This is a subtle distinction that can produce more efficient code at the risk of misleading all but the most experienced of programmers. So I usually advise against teaching it to beginners. In fact, except for passing arguments to functions, I seldom like to see the gimme-a-reference operator (backslash) used much at all in code. Instead, I advise beginners that they (and most of the rest of us) should try to use the much more easily understood constructors `[]` and `{}` instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes.
Note also that there exists another way to write a dereference! These two lines are equivalent:
```
$AoA[$i]->@* = @array;
@{ $AoA[$i] } = @array;
```
The first form, called *postfix dereference* is generally easier to read, because the expression can be read from left to right, and there are no enclosing braces to balance. On the other hand, it is also newer. It was added to the language in 2014, so you will often encounter the other form, *circumfix dereference*, in older code.
In summary:
```
$AoA[$i] = [ @array ]; # usually best
$AoA[$i] = \@array; # perilous; just how my() was that array?
$AoA[$i]->@* = @array; # way too tricky for most programmers
@{ $AoA[$i] } = @array; # just as tricky, and also harder to read
```
CAVEAT ON PRECEDENCE
---------------------
Speaking of things like `@{$AoA[$i]}`, the following are actually the same thing:
```
$aref->[2][2] # clear
$$aref[2][2] # confusing
```
That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: `$ @ * % &`) make them bind more tightly than the postfix subscripting brackets or braces! This will no doubt come as a great shock to the C or C++ programmer, who is quite accustomed to using `*a[i]` to mean what's pointed to by the *i'th* element of `a`. That is, they first take the subscript, and only then dereference the thing at that subscript. That's fine in C, but this isn't C.
The seemingly equivalent construct in Perl, `$$aref[$i]` first does the deref of $aref, making it take $aref as a reference to an array, and then dereference that, and finally tell you the *i'th* value of the array pointed to by $AoA. If you wanted the C notion, you could write `$AoA[$i]->$*` to explicitly dereference the *i'th* item, reading left to right.
WHY YOU SHOULD ALWAYS `use VERSION`
------------------------------------
If this is starting to sound scarier than it's worth, relax. Perl has some features to help you avoid its most common pitfalls. One way to avoid getting confused is to start every program with:
```
use strict;
```
This way, you'll be forced to declare all your variables with my() and also disallow accidental "symbolic dereferencing". Therefore if you'd done this:
```
my $aref = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "homer", "bart", "marge", "maggie", ],
[ "george", "jane", "elroy", "judy", ],
];
print $aref[2][2];
```
The compiler would immediately flag that as an error *at compile time*, because you were accidentally accessing `@aref`, an undeclared variable, and it would thereby remind you to write instead:
```
print $aref->[2][2]
```
Since Perl version 5.12, a `use VERSION` declaration will also enable the `strict` pragma. In addition, it will also enable a feature bundle, giving more useful features. Since version 5.36 it will also enable the `warnings` pragma. Often the best way to activate all these things at once is to start a file with:
```
use v5.36;
```
In this way, every file will start with `strict`, `warnings`, and many useful named features all switched on, as well as several older features being switched off (such as [`indirect`](feature#The-%27indirect%27-feature)). For more information, see ["use VERSION" in perlfunc](perlfunc#use-VERSION).
DEBUGGING
---------
You can use the debugger's `x` command to dump out complex data structures. For example, given the assignment to $AoA above, here's the debugger output:
```
DB<1> x $AoA
$AoA = ARRAY(0x13b5a0)
0 ARRAY(0x1f0a24)
0 'fred'
1 'barney'
2 'pebbles'
3 'bambam'
4 'dino'
1 ARRAY(0x13b558)
0 'homer'
1 'bart'
2 'marge'
3 'maggie'
2 ARRAY(0x13b540)
0 'george'
1 'jane'
2 'elroy'
3 'judy'
```
CODE EXAMPLES
--------------
Presented with little comment here are short code examples illustrating access of various types of data structures.
ARRAYS OF ARRAYS
-----------------
###
Declaration of an ARRAY OF ARRAYS
```
my @AoA = (
[ "fred", "barney" ],
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
);
```
###
Generation of an ARRAY OF ARRAYS
```
# reading from file
while ( <> ) {
push @AoA, [ split ];
}
# calling a function
for my $i ( 1 .. 10 ) {
$AoA[$i] = [ somefunc($i) ];
}
# using temp vars
for my $i ( 1 .. 10 ) {
my @tmp = somefunc($i);
$AoA[$i] = [ @tmp ];
}
# add to an existing row
push $AoA[0]->@*, "wilma", "betty";
```
###
Access and Printing of an ARRAY OF ARRAYS
```
# one element
$AoA[0][0] = "Fred";
# another element
$AoA[1][1] =~ s/(\w)/\u$1/;
# print the whole thing with refs
for my $aref ( @AoA ) {
print "\t [ @$aref ],\n";
}
# print the whole thing with indices
for my $i ( 0 .. $#AoA ) {
print "\t [ $AoA[$i]->@* ],\n";
}
# print the whole thing one at a time
for my $i ( 0 .. $#AoA ) {
for my $j ( 0 .. $AoA[$i]->$#* ) {
print "elem at ($i, $j) is $AoA[$i][$j]\n";
}
}
```
HASHES OF ARRAYS
-----------------
###
Declaration of a HASH OF ARRAYS
```
my %HoA = (
flintstones => [ "fred", "barney" ],
jetsons => [ "george", "jane", "elroy" ],
simpsons => [ "homer", "marge", "bart" ],
);
```
###
Generation of a HASH OF ARRAYS
```
# reading from file
# flintstones: fred barney wilma dino
while ( <> ) {
next unless s/^(.*?):\s*//;
$HoA{$1} = [ split ];
}
# reading from file; more temps
# flintstones: fred barney wilma dino
while ( my $line = <> ) {
my ($who, $rest) = split /:\s*/, $line, 2;
my @fields = split ' ', $rest;
$HoA{$who} = [ @fields ];
}
# calling a function that returns a list
for my $group ( "simpsons", "jetsons", "flintstones" ) {
$HoA{$group} = [ get_family($group) ];
}
# likewise, but using temps
for my $group ( "simpsons", "jetsons", "flintstones" ) {
my @members = get_family($group);
$HoA{$group} = [ @members ];
}
# append new members to an existing family
push $HoA{flintstones}->@*, "wilma", "betty";
```
###
Access and Printing of a HASH OF ARRAYS
```
# one element
$HoA{flintstones}[0] = "Fred";
# another element
$HoA{simpsons}[1] =~ s/(\w)/\u$1/;
# print the whole thing
foreach my $family ( keys %HoA ) {
print "$family: $HoA{$family}->@* \n"
}
# print the whole thing with indices
foreach my $family ( keys %HoA ) {
print "family: ";
foreach my $i ( 0 .. $HoA{$family}->$#* ) {
print " $i = $HoA{$family}[$i]";
}
print "\n";
}
# print the whole thing sorted by number of members
foreach my $family ( sort { $HoA{$b}->@* <=> $HoA{$a}->@* } keys %HoA ) {
print "$family: $HoA{$family}->@* \n"
}
# print the whole thing sorted by number of members and name
foreach my $family ( sort {
$HoA{$b}->@* <=> $HoA{$a}->@*
||
$a cmp $b
} keys %HoA )
{
print "$family: ", join(", ", sort $HoA{$family}->@* ), "\n";
}
```
ARRAYS OF HASHES
-----------------
###
Declaration of an ARRAY OF HASHES
```
my @AoH = (
{
Lead => "fred",
Friend => "barney",
},
{
Lead => "george",
Wife => "jane",
Son => "elroy",
},
{
Lead => "homer",
Wife => "marge",
Son => "bart",
}
);
```
###
Generation of an ARRAY OF HASHES
```
# reading from file
# format: LEAD=fred FRIEND=barney
while ( <> ) {
my $rec = {};
for my $field ( split ) {
my ($key, $value) = split /=/, $field;
$rec->{$key} = $value;
}
push @AoH, $rec;
}
# reading from file
# format: LEAD=fred FRIEND=barney
# no temp
while ( <> ) {
push @AoH, { split /[\s+=]/ };
}
# calling a function that returns a key/value pair list, like
# "lead","fred","daughter","pebbles"
while ( my %fields = getnextpairset() ) {
push @AoH, { %fields };
}
# likewise, but using no temp vars
while (<>) {
push @AoH, { parsepairs($_) };
}
# add key/value to an element
$AoH[0]{pet} = "dino";
$AoH[2]{pet} = "santa's little helper";
```
###
Access and Printing of an ARRAY OF HASHES
```
# one element
$AoH[0]{lead} = "fred";
# another element
$AoH[1]{lead} =~ s/(\w)/\u$1/;
# print the whole thing with refs
for my $href ( @AoH ) {
print "{ ";
for my $role ( keys %$href ) {
print "$role=$href->{$role} ";
}
print "}\n";
}
# print the whole thing with indices
for my $i ( 0 .. $#AoH ) {
print "$i is { ";
for my $role ( keys $AoH[$i]->%* ) {
print "$role=$AoH[$i]{$role} ";
}
print "}\n";
}
# print the whole thing one at a time
for my $i ( 0 .. $#AoH ) {
for my $role ( keys $AoH[$i]->%* ) {
print "elem at ($i, $role) is $AoH[$i]{$role}\n";
}
}
```
HASHES OF HASHES
-----------------
###
Declaration of a HASH OF HASHES
```
my %HoH = (
flintstones => {
lead => "fred",
pal => "barney",
},
jetsons => {
lead => "george",
wife => "jane",
"his boy" => "elroy",
},
simpsons => {
lead => "homer",
wife => "marge",
kid => "bart",
},
);
```
###
Generation of a HASH OF HASHES
```
# reading from file
# flintstones: lead=fred pal=barney wife=wilma pet=dino
while ( <> ) {
next unless s/^(.*?):\s*//;
my $who = $1;
for my $field ( split ) {
my ($key, $value) = split /=/, $field;
$HoH{$who}{$key} = $value;
}
}
# reading from file; more temps
while ( <> ) {
next unless s/^(.*?):\s*//;
my $who = $1;
my $rec = {};
$HoH{$who} = $rec;
for my $field ( split ) {
my ($key, $value) = split /=/, $field;
$rec->{$key} = $value;
}
}
# calling a function that returns a key,value hash
for my $group ( "simpsons", "jetsons", "flintstones" ) {
$HoH{$group} = { get_family($group) };
}
# likewise, but using temps
for my $group ( "simpsons", "jetsons", "flintstones" ) {
my %members = get_family($group);
$HoH{$group} = { %members };
}
# append new members to an existing family
my %new_folks = (
wife => "wilma",
pet => "dino",
);
for my $what (keys %new_folks) {
$HoH{flintstones}{$what} = $new_folks{$what};
}
```
###
Access and Printing of a HASH OF HASHES
```
# one element
$HoH{flintstones}{wife} = "wilma";
# another element
$HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
# print the whole thing
foreach my $family ( keys %HoH ) {
print "$family: { ";
for my $role ( keys $HoH{$family}->%* ) {
print "$role=$HoH{$family}{$role} ";
}
print "}\n";
}
# print the whole thing somewhat sorted
foreach my $family ( sort keys %HoH ) {
print "$family: { ";
for my $role ( sort keys $HoH{$family}->%* ) {
print "$role=$HoH{$family}{$role} ";
}
print "}\n";
}
# print the whole thing sorted by number of members
foreach my $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {
print "$family: { ";
for my $role ( sort keys $HoH{$family}->%* ) {
print "$role=$HoH{$family}{$role} ";
}
print "}\n";
}
# establish a sort order (rank) for each role
my $i = 0;
my %rank;
for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
# now print the whole thing sorted by number of members
foreach my $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {
print "$family: { ";
# and print these according to rank order
for my $role ( sort { $rank{$a} <=> $rank{$b} }
keys $HoH{$family}->%* )
{
print "$role=$HoH{$family}{$role} ";
}
print "}\n";
}
```
MORE ELABORATE RECORDS
-----------------------
###
Declaration of MORE ELABORATE RECORDS
Here's a sample showing how to create and use a record whose fields are of many different sorts:
```
my $rec = {
TEXT => $string,
SEQUENCE => [ @old_values ],
LOOKUP => { %some_table },
THATCODE => \&some_function,
THISCODE => sub { $_[0] ** $_[1] },
HANDLE => \*STDOUT,
};
print $rec->{TEXT};
print $rec->{SEQUENCE}[0];
my $last = pop $rec->{SEQUENCE}->@*;
print $rec->{LOOKUP}{"key"};
my ($first_k, $first_v) = each $rec->{LOOKUP}->%*;
my $answer = $rec->{THATCODE}->($arg);
$answer = $rec->{THISCODE}->($arg1, $arg2);
# careful of extra block braces on fh ref
print { $rec->{HANDLE} } "a string\n";
use FileHandle;
$rec->{HANDLE}->autoflush(1);
$rec->{HANDLE}->print(" a string\n");
```
###
Declaration of a HASH OF COMPLEX RECORDS
```
my %TV = (
flintstones => {
series => "flintstones",
nights => [ qw(monday thursday friday) ],
members => [
{ name => "fred", role => "lead", age => 36, },
{ name => "wilma", role => "wife", age => 31, },
{ name => "pebbles", role => "kid", age => 4, },
],
},
jetsons => {
series => "jetsons",
nights => [ qw(wednesday saturday) ],
members => [
{ name => "george", role => "lead", age => 41, },
{ name => "jane", role => "wife", age => 39, },
{ name => "elroy", role => "kid", age => 9, },
],
},
simpsons => {
series => "simpsons",
nights => [ qw(monday) ],
members => [
{ name => "homer", role => "lead", age => 34, },
{ name => "marge", role => "wife", age => 37, },
{ name => "bart", role => "kid", age => 11, },
],
},
);
```
###
Generation of a HASH OF COMPLEX RECORDS
```
# reading from file
# this is most easily done by having the file itself be
# in the raw data format as shown above. perl is happy
# to parse complex data structures if declared as data, so
# sometimes it's easiest to do that
# here's a piece by piece build up
my $rec = {};
$rec->{series} = "flintstones";
$rec->{nights} = [ find_days() ];
my @members = ();
# assume this file in field=value syntax
while (<>) {
my %fields = split /[\s=]+/;
push @members, { %fields };
}
$rec->{members} = [ @members ];
# now remember the whole thing
$TV{ $rec->{series} } = $rec;
###########################################################
# now, you might want to make interesting extra fields that
# include pointers back into the same data structure so if
# change one piece, it changes everywhere, like for example
# if you wanted a {kids} field that was a reference
# to an array of the kids' records without having duplicate
# records and thus update problems.
###########################################################
foreach my $family (keys %TV) {
my $rec = $TV{$family}; # temp pointer
my @kids = ();
for my $person ( $rec->{members}->@* ) {
if ($person->{role} =~ /kid|son|daughter/) {
push @kids, $person;
}
}
# REMEMBER: $rec and $TV{$family} point to same data!!
$rec->{kids} = [ @kids ];
}
# you copied the array, but the array itself contains pointers
# to uncopied objects. this means that if you make bart get
# older via
$TV{simpsons}{kids}[0]{age}++;
# then this would also change in
print $TV{simpsons}{members}[2]{age};
# because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
# both point to the same underlying anonymous hash table
# print the whole thing
foreach my $family ( keys %TV ) {
print "the $family";
print " is on during $TV{$family}{nights}->@*\n";
print "its members are:\n";
for my $who ( $TV{$family}{members}->@* ) {
print " $who->{name} ($who->{role}), age $who->{age}\n";
}
print "it turns out that $TV{$family}{lead} has ";
print scalar ( $TV{$family}{kids}->@* ), " kids named ";
print join (", ", map { $_->{name} } $TV{$family}{kids}->@* );
print "\n";
}
```
Database Ties
--------------
You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One experimental module that does partially attempt to address this need is the MLDBM module. Check your nearest CPAN site as described in <perlmodlib> for source code to MLDBM.
SEE ALSO
---------
<perlref>, <perllol>, <perldata>, <perlobj>
AUTHOR
------
Tom Christiansen <*[email protected]*>
| programming_docs |
perl Test::Tester::Capture Test::Tester::Capture
=====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
Test::Tester::Capture - Help testing test modules built with Test::Builder
DESCRIPTION
-----------
This is a subclass of Test::Builder that overrides many of the methods so that they don't output anything. It also keeps track of its own set of test results so that you can use Test::Builder based modules to perform tests on other Test::Builder based modules.
AUTHOR
------
Most of the code here was lifted straight from Test::Builder and then had chunks removed by Fergal Daly <[email protected]>.
LICENSE
-------
Under the same license as Perl itself
See http://www.perl.com/perl/misc/Artistic.html
perl TAP::Formatter::Console::ParallelSession TAP::Formatter::Console::ParallelSession
========================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [header](#header)
- [result](#result)
- [clear\_for\_close](#clear_for_close)
- [close\_test](#close_test)
NAME
----
TAP::Formatter::Console::ParallelSession - Harness output delegate for parallel console output
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides console orientated output formatting for <TAP::Harness> when run with multiple ["jobs" in TAP::Harness](TAP::Harness#jobs).
SYNOPSIS
--------
METHODS
-------
###
Class Methods
#### `header`
Output test preamble
#### `result`
```
Called by the harness for each line of TAP it receives .
```
#### `clear_for_close`
#### `close_test`
perl Encode::Encoder Encode::Encoder
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [Description](#Description)
+ [Predefined Methods](#Predefined-Methods)
+ [Example: base64 transcoder](#Example:-base64-transcoder)
+ [Operator Overloading](#Operator-Overloading)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Encoder -- Object Oriented Encoder
SYNOPSIS
--------
```
use Encode::Encoder;
# Encode::encode("ISO-8859-1", $data);
Encode::Encoder->new($data)->iso_8859_1; # OOP way
# shortcut
use Encode::Encoder qw(encoder);
encoder($data)->iso_8859_1;
# you can stack them!
encoder($data)->iso_8859_1->base64; # provided base64() is defined
# you can use it as a decoder as well
encoder($base64)->bytes('base64')->latin1;
# stringified
print encoder($data)->utf8->latin1; # prints the string in latin1
# numified
encoder("\x{abcd}\x{ef}g")->utf8 == 6; # true. bytes::length($data)
```
ABSTRACT
--------
**Encode::Encoder** allows you to use Encode in an object-oriented style. This is not only more intuitive than a functional approach, but also handier when you want to stack encodings. Suppose you want your UTF-8 string converted to Latin1 then Base64: you can simply say
```
my $base64 = encoder($utf8)->latin1->base64;
```
instead of
```
my $latin1 = encode("latin1", $utf8);
my $base64 = encode_base64($utf8);
```
or the lazier and more convoluted
```
my $base64 = encode_base64(encode("latin1", $utf8));
```
Description
-----------
Here is how to use this module.
* There are at least two instance variables stored in a hash reference, {data} and {encoding}.
* When there is no method, it takes the method name as the name of the encoding and encodes the instance *data* with *encoding*. If successful, the instance *encoding* is set accordingly.
* You can retrieve the result via ->data but usually you don't have to because the stringify operator ("") is overridden to do exactly that.
###
Predefined Methods
This module predefines the methods below:
$e = Encode::Encoder->new([$data, $encoding]); returns an encoder object. Its data is initialized with $data if present, and its encoding is set to $encoding if present.
When $encoding is omitted, it defaults to utf8 if $data is already in utf8 or "" (empty string) otherwise.
encoder() is an alias of Encode::Encoder->new(). This one is exported on demand.
$e->data([$data]) When $data is present, sets the instance data to $data and returns the object itself. Otherwise, the current instance data is returned.
$e->encoding([$encoding]) When $encoding is present, sets the instance encoding to $encoding and returns the object itself. Otherwise, the current instance encoding is returned.
$e->bytes([$encoding]) decodes instance data from $encoding, or the instance encoding if omitted. If the conversion is successful, the instance encoding will be set to "".
The name *bytes* was deliberately picked to avoid namespace tainting -- this module may be used as a base class so method names that appear in Encode::Encoding are avoided.
###
Example: base64 transcoder
This module is designed to work with <Encode::Encoding>. To make the Base64 transcoder example above really work, you could write a module like this:
```
package Encode::Base64;
use parent 'Encode::Encoding';
__PACKAGE__->Define('base64');
use MIME::Base64;
sub encode{
my ($obj, $data) = @_;
return encode_base64($data);
}
sub decode{
my ($obj, $data) = @_;
return decode_base64($data);
}
1;
__END__
```
And your caller module would be something like this:
```
use Encode::Encoder;
use Encode::Base64;
# now you can really do the following
encoder($data)->iso_8859_1->base64;
encoder($base64)->bytes('base64')->latin1;
```
###
Operator Overloading
This module overloads two operators, stringify ("") and numify (0+).
Stringify dumps the data inside the object.
Numify returns the number of bytes in the instance data.
They come in handy when you want to print or find the size of data.
SEE ALSO
---------
[Encode](encode), <Encode::Encoding>
perl Test2::Formatter::TAP Test2::Formatter::TAP
=====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Formatter::TAP - Standard TAP formatter
DESCRIPTION
-----------
This is what takes events and turns them into TAP.
SYNOPSIS
--------
```
use Test2::Formatter::TAP;
my $tap = Test2::Formatter::TAP->new();
# Switch to utf8
$tap->encoding('utf8');
$tap->write($event, $number); # Output an event
```
METHODS
-------
$bool = $tap->no\_numbers
$tap->set\_no\_numbers($bool) Use to turn numbers on and off.
$arrayref = $tap->handles
$tap->set\_handles(\@handles); Can be used to get/set the filehandles. Indexes are identified by the `OUT_STD` and `OUT_ERR` constants.
$encoding = $tap->encoding
$tap->encoding($encoding) Get or set the encoding. By default no encoding is set, the original settings of STDOUT and STDERR are used.
This directly modifies the stored filehandles, it does not create new ones.
$tap->write($e, $num) Write an event to the console.
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/*
perl Test2::Event::Exception Test2::Event::Exception
=======================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [CAVEATS](#CAVEATS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Exception - Exception event
DESCRIPTION
-----------
An exception event will display to STDERR, and will prevent the overall test file from passing.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Exception;
my $ctx = context();
my $event = $ctx->send_event('Exception', error => 'Stuff is broken');
```
METHODS
-------
Inherits from <Test2::Event>. Also defines:
$reason = $e->error The reason for the exception.
CAVEATS
-------
Be aware that all exceptions are stringified during construction.
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 CPAN::Meta::History CPAN::Meta::History
===================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [HISTORY](#HISTORY)
+ [Version 2](#Version-2)
+ [Version 1.4](#Version-1.4)
+ [Version 1.3](#Version-1.3)
+ [Version 1.2](#Version-1.2)
+ [Version 1.1](#Version-1.1)
+ [Version 1.0](#Version-1.0)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::History - history of CPAN Meta Spec changes
VERSION
-------
version 2.150010
DESCRIPTION
-----------
The CPAN Meta Spec has gone through several iterations. It was originally written in HTML and later revised into POD (though published in HTML generated from the POD). Fields were added, removed or changed, sometimes by design and sometimes to reflect real-world usage after the fact.
This document reconstructs the history of the CPAN Meta Spec based on change logs, repository commit messages and the published HTML files. In some cases, particularly prior to version 1.2, the exact version when certain fields were introduced or changed is inconsistent between sources. When in doubt, the published HTML files for versions 1.0 to 1.4 as they existed when version 2 was developed are used as the definitive source.
Starting with version 2, the specification document is part of the CPAN-Meta distribution and will be published on CPAN as <CPAN::Meta::Spec>.
Going forward, specification version numbers will be integers and decimal portions will correspond to a release date for the CPAN::Meta library.
HISTORY
-------
###
Version 2
April 2010
* Revised spec examples as perl data structures rather than YAML
* Switched to JSON serialization from YAML
* Specified allowed version number formats
* Replaced 'requires', 'build\_requires', 'configure\_requires', 'recommends' and 'conflicts' with new 'prereqs' data structure divided by *phase* (configure, build, test, runtime, etc.) and *relationship* (requires, recommends, suggests, conflicts)
* Added support for 'develop' phase for requirements for maintaining a list of authoring tools
* Changed 'license' to a list and revised the set of valid licenses
* Made 'dynamic\_config' mandatory to reduce confusion
* Changed 'resources' subkey 'repository' to a hash that clarifies repository type, url for browsing and url for checkout
* Changed 'resources' subkey 'bugtracker' to a hash for either web or mailto resource
* Changed specification of 'optional\_features':
+ Added formal specification and usage guide instead of just example
+ Changed to use new prereqs data structure instead of individual keys
* Clarified intended use of 'author' as generalized contact list
* Added 'release\_status' field to indicate stable, testing or unstable status to provide hints to indexers
* Added 'description' field for a longer description of the distribution
* Formalized use of "x\_" or "X\_" for all custom keys not listed in the official spec
###
Version 1.4
June 2008
* Noted explicit support for 'perl' in prerequisites
* Added 'configure\_requires' prerequisite type
* Changed 'optional\_features'
+ Example corrected to show map of maps instead of list of maps (though descriptive text said 'map' even in v1.3)
+ Removed 'requires\_packages', 'requires\_os' and 'excluded\_os' as valid subkeys
###
Version 1.3
November 2006
* Added 'no\_index' subkey 'directory' and removed 'dir' to match actual usage in the wild
* Added a 'repository' subkey to 'resources'
###
Version 1.2
August 2005
* Re-wrote and restructured spec in POD syntax
* Changed 'name' to be mandatory
* Changed 'generated\_by' to be mandatory
* Changed 'license' to be mandatory
* Added version range specifications for prerequisites
* Added required 'abstract' field
* Added required 'author' field
* Added required 'meta-spec' field to define 'version' (and 'url') of the CPAN Meta Spec used for metadata
* Added 'provides' field
* Added 'no\_index' field and deprecated 'private' field. 'no\_index' subkeys include 'file', 'dir', 'package' and 'namespace'
* Added 'keywords' field
* Added 'resources' field with subkeys 'homepage', 'license', and 'bugtracker'
* Added 'optional\_features' field as an alternate under 'recommends'. Includes 'description', 'requires', 'build\_requires', 'conflicts', 'requires\_packages', 'requires\_os' and 'excluded\_os' as valid subkeys
* Removed 'license\_uri' field
###
Version 1.1
May 2003
* Changed 'version' to be mandatory
* Added 'private' field
* Added 'license\_uri' field
###
Version 1.0
March 2003
* Original release (in HTML format only)
* Included 'name', 'version', 'license', 'distribution\_type', 'requires', 'recommends', 'build\_requires', 'conflicts', 'dynamic\_config', 'generated\_by'
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 perllinux perllinux
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Deploying Perl on Linux](#Deploying-Perl-on-Linux)
+ [Experimental Support for Sun Studio Compilers for Linux OS](#Experimental-Support-for-Sun-Studio-Compilers-for-Linux-OS)
* [AUTHOR](#AUTHOR)
NAME
----
perllinux - Perl version 5 on Linux systems
DESCRIPTION
-----------
This document describes various features of Linux that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
Deploying Perl on Linux
Normally one can install */usr/bin/perl* on Linux using your distribution's package manager (e.g: `sudo apt-get install perl`, or `sudo dnf install perl`). Note that sometimes one needs to install some extra system packages in order to be able to use CPAN frontends, and that messing with the system's perl is not always recommended. One can use [perlbrew](https://perlbrew.pl/) to avoid such issues.
Otherwise, perl should build fine on Linux using the mainstream compilers GCC and clang, while following the usual instructions.
###
Experimental Support for Sun Studio Compilers for Linux OS
Sun Microsystems has released a port of their Sun Studio compilers for Linux. As of May 2019, the last stable release took place on 2017, and one can buy support contracts for them.
There are some special instructions for building Perl with Sun Studio on Linux. Following the normal `Configure`, you have to run make as follows:
```
LDLOADLIBS=-lc make
```
`LDLOADLIBS` is an environment variable used by the linker to link `/ext` modules to glibc. Currently, that environment variable is not getting populated by a combination of `Config` entries and `ExtUtil::MakeMaker`. While there may be a bug somewhere in Perl's configuration or `ExtUtil::MakeMaker` causing the problem, the most likely cause is an incomplete understanding of Sun Studio by this author. Further investigation is needed to get this working better.
AUTHOR
------
Steve Peters <[email protected]>
Please report any errors, updates, or suggestions to <https://github.com/Perl/perl5/issues>.
perl perldebug perldebug
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [The Perl Debugger](#The-Perl-Debugger)
+ [Calling the Debugger](#Calling-the-Debugger)
+ [Debugger Commands](#Debugger-Commands)
+ [Configurable Options](#Configurable-Options)
+ [Debugger Input/Output](#Debugger-Input/Output)
+ [Debugging Compile-Time Statements](#Debugging-Compile-Time-Statements)
+ [Debugger Customization](#Debugger-Customization)
+ [Readline Support / History in the Debugger](#Readline-Support-/-History-in-the-Debugger)
+ [Editor Support for Debugging](#Editor-Support-for-Debugging)
+ [The Perl Profiler](#The-Perl-Profiler)
* [Debugging Regular Expressions](#Debugging-Regular-Expressions)
* [Debugging Memory Usage](#Debugging-Memory-Usage)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
NAME
----
perldebug - Perl debugging
DESCRIPTION
-----------
First of all, have you tried using [`use strict;`](strict) and [`use warnings;`](warnings)?
If you're new to the Perl debugger, you may prefer to read <perldebtut>, which is a tutorial introduction to the debugger.
If you're looking for the nitty gritty details of how the debugger is *implemented*, you may prefer to read <perldebguts>.
For in-depth technical usage details, see <perl5db.pl>, the documentation of the debugger itself.
The Perl Debugger
------------------
If you invoke Perl with the **-d** switch, your script runs under the Perl source debugger. This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. This is so convenient that you often fire up the debugger all by itself just to test out Perl constructs interactively to see what they do. For example:
```
$ perl -d -e 42
```
In Perl, the debugger is not a separate program the way it usually is in the typical compiled environment. Instead, the **-d** flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. That means your code must first compile correctly for the debugger to work on it. Then when the interpreter starts up, it preloads a special Perl library file containing the debugger.
The program will halt *right before* the first run-time executable statement (but see below regarding compile-time statements) and ask you to enter a debugger command. Contrary to popular expectations, whenever the debugger halts and shows you a line of code, it always displays the line it's *about* to execute, rather than the one it has just executed.
Any command not recognized by the debugger is directly executed (`eval`'d) as Perl code in the current package. (The debugger uses the DB package for keeping its own state information.)
Note that the said `eval` is bound by an implicit scope. As a result any newly introduced lexical variable or any modified capture buffer content is lost after the eval. The debugger is a nice environment to learn Perl, but if you interactively experiment using material which should be in the same scope, stuff it in one line.
For any text entered at the debugger prompt, leading and trailing whitespace is first stripped before further processing. If a debugger command coincides with some function in your own program, merely precede the function with something that doesn't look like a debugger command, such as a leading `;` or perhaps a `+`, or by wrapping it with parentheses or braces.
###
Calling the Debugger
There are several ways to call the debugger:
perl -d program\_name On the given program identified by `program_name`.
perl -d -e 0 Interactively supply an arbitrary `expression` using `-e`.
perl -d:ptkdb program\_name Debug a given program via the `Devel::ptkdb` GUI.
perl -dt threaded\_program\_name Debug a given program using threads (experimental).
If Perl is called with the `-d` switch, the variable `$^P` will hold a true value. This is useful if you need to know if your code is running under the debugger:
```
if ( $^P ) {
# running under the debugger
}
```
See ["$^P" in perlvar](perlvar#%24%5EP) for more information on the variable.
###
Debugger Commands
The interactive debugger understands the following commands:
h Prints out a summary help message
h [command] Prints out a help message for the given debugger command.
h h The special argument of `h h` produces the entire help page, which is quite long.
If the output of the `h h` command (or any command, for that matter) scrolls past your screen, precede the command with a leading pipe symbol so that it's run through your pager, as in
```
DB> |h h
```
You may change the pager which is used via `o pager=...` command.
p expr Same as `print {$DB::OUT} expr` in the current package. In particular, because this is just Perl's own `print` function, this means that nested data structures and objects are not dumped, unlike with the `x` command.
The `DB::OUT` filehandle is opened to */dev/tty*, regardless of where STDOUT may be redirected to.
x [maxdepth] expr Evaluates its expression in list context and dumps out the result in a pretty-printed fashion. Nested data structures are printed out recursively, unlike the real `print` function in Perl. When dumping hashes, you'll probably prefer 'x \%h' rather than 'x %h'. See [Dumpvalue](dumpvalue) if you'd like to do this yourself.
The output format is governed by multiple options described under ["Configurable Options"](#Configurable-Options).
If the `maxdepth` is included, it must be a numeral *N*; the value is dumped only *N* levels deep, as if the `dumpDepth` option had been temporarily set to *N*.
V [pkg [vars]] Display all (or some) variables in package (defaulting to `main`) using a data pretty-printer (hashes show their keys and values so you see what's what, control characters are made printable, etc.). Make sure you don't put the type specifier (like `$`) there, just the symbol names, like this:
```
V DB filename line
```
Use `~pattern` and `!pattern` for positive and negative regexes.
This is similar to calling the `x` command on each applicable var.
X [vars] Same as `V currentpackage [vars]`.
y [level [vars]] Display all (or some) lexical variables (mnemonic: `mY` variables) in the current scope or *level* scopes higher. You can limit the variables that you see with *vars* which works exactly as it does for the `V` and `X` commands. Requires the `PadWalker` module version 0.08 or higher; will warn if this isn't installed. Output is pretty-printed in the same style as for `V` and the format is controlled by the same options.
T Produce a stack backtrace. See below for details on its output.
s [expr] Single step. Executes until the beginning of another statement, descending into subroutine calls. If an expression is supplied that includes function calls, it too will be single-stepped.
n [expr] Next. Executes over subroutine calls, until the beginning of the next statement. If an expression is supplied that includes function calls, those functions will be executed with stops before each statement.
r Continue until the return from the current subroutine. Dump the return value if the `PrintRet` option is set (default).
<CR> Repeat last `n` or `s` command.
c [line|sub] Continue, optionally inserting a one-time-only breakpoint at the specified line or subroutine.
l List next window of lines.
l min+incr List `incr+1` lines starting at `min`.
l min-max List lines `min` through `max`. `l -` is synonymous to `-`.
l line List a single line.
l subname List first window of lines from subroutine. *subname* may be a variable that contains a code reference.
- List previous window of lines.
v [line] View a few lines of code around the current line.
. Return the internal debugger pointer to the line last executed, and print out that line.
f filename Switch to viewing a different file or `eval` statement. If *filename* is not a full pathname found in the values of %INC, it is considered a regex.
`eval`ed strings (when accessible) are considered to be filenames: `f (eval 7)` and `f eval 7\b` access the body of the 7th `eval`ed string (in the order of execution). The bodies of the currently executed `eval` and of `eval`ed strings that define subroutines are saved and thus accessible.
/pattern/ Search forwards for pattern (a Perl regex); final / is optional. The search is case-insensitive by default.
?pattern? Search backwards for pattern; final ? is optional. The search is case-insensitive by default.
L [abw] List (default all) actions, breakpoints and watch expressions
S [[!]regex] List subroutine names [not] matching the regex.
t [n] Toggle trace mode (see also the `AutoTrace` option). Optional argument is the maximum number of levels to trace below the current one; anything deeper than that will be silent.
t [n] expr Trace through execution of `expr`. Optional first argument is the maximum number of levels to trace below the current one; anything deeper than that will be silent. See ["Frame Listing Output Examples" in perldebguts](perldebguts#Frame-Listing-Output-Examples) for examples.
b Sets breakpoint on current line
b [line] [condition] Set a breakpoint before the given line. If a condition is specified, it's evaluated each time the statement is reached: a breakpoint is taken only if the condition is true. Breakpoints may only be set on lines that begin an executable statement. Conditions don't use `if`:
```
b 237 $x > 30
b 237 ++$count237 < 11
b 33 /pattern/i
```
If the line number is `.`, sets a breakpoint on the current line:
```
b . $n > 100
```
b [file]:[line] [condition] Set a breakpoint before the given line in a (possibly different) file. If a condition is specified, it's evaluated each time the statement is reached: a breakpoint is taken only if the condition is true. Breakpoints may only be set on lines that begin an executable statement. Conditions don't use `if`:
```
b lib/MyModule.pm:237 $x > 30
b /usr/lib/perl5/site_perl/CGI.pm:100 ++$count100 < 11
```
b subname [condition] Set a breakpoint before the first line of the named subroutine. *subname* may be a variable containing a code reference (in this case *condition* is not supported).
b postpone subname [condition] Set a breakpoint at first line of subroutine after it is compiled.
b load filename Set a breakpoint before the first executed line of the *filename*, which should be a full pathname found amongst the %INC values.
b compile subname Sets a breakpoint before the first statement executed after the specified subroutine is compiled.
B line Delete a breakpoint from the specified *line*.
B \* Delete all installed breakpoints.
disable [file]:[line] Disable the breakpoint so it won't stop the execution of the program. Breakpoints are enabled by default and can be re-enabled using the `enable` command.
disable [line] Disable the breakpoint so it won't stop the execution of the program. Breakpoints are enabled by default and can be re-enabled using the `enable` command.
This is done for a breakpoint in the current file.
enable [file]:[line] Enable the breakpoint so it will stop the execution of the program.
enable [line] Enable the breakpoint so it will stop the execution of the program.
This is done for a breakpoint in the current file.
a [line] command Set an action to be done before the line is executed. If *line* is omitted, set an action on the line about to be executed. The sequence of steps taken by the debugger is
```
1. check for a breakpoint at this line
2. print the line if necessary (tracing)
3. do any actions associated with that line
4. prompt user if at a breakpoint or in single-step
5. evaluate line
```
For example, this will print out $foo every time line 53 is passed:
```
a 53 print "DB FOUND $foo\n"
```
A line Delete an action from the specified line.
A \* Delete all installed actions.
w expr Add a global watch-expression. Whenever a watched global changes the debugger will stop and display the old and new values.
W expr Delete watch-expression
W \* Delete all watch-expressions.
o Display all options.
o booloption ... Set each listed Boolean option to the value `1`.
o anyoption? ... Print out the value of one or more options.
o option=value ... Set the value of one or more options. If the value has internal whitespace, it should be quoted. For example, you could set `o pager="less -MQeicsNfr"` to call **less** with those specific options. You may use either single or double quotes, but if you do, you must escape any embedded instances of same sort of quote you began with, as well as any escaping any escapes that immediately precede that quote but which are not meant to escape the quote itself. In other words, you follow single-quoting rules irrespective of the quote; eg: `o option='this isn\'t bad'` or `o option="She said, \"Isn't it?\""`.
For historical reasons, the `=value` is optional, but defaults to 1 only where it is safe to do so--that is, mostly for Boolean options. It is always better to assign a specific value using `=`. The `option` can be abbreviated, but for clarity probably should not be. Several options can be set together. See ["Configurable Options"](#Configurable-Options) for a list of these.
< ? List out all pre-prompt Perl command actions.
< [ command ] Set an action (Perl command) to happen before every debugger prompt. A multi-line command may be entered by backslashing the newlines.
< \* Delete all pre-prompt Perl command actions.
<< command Add an action (Perl command) to happen before every debugger prompt. A multi-line command may be entered by backwhacking the newlines.
> ? List out post-prompt Perl command actions.
> command Set an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script. A multi-line command may be entered by backslashing the newlines (we bet you couldn't have guessed this by now).
> \* Delete all post-prompt Perl command actions.
>> command Adds an action (Perl command) to happen after the prompt when you've just given a command to return to executing the script. A multi-line command may be entered by backslashing the newlines.
{ ? List out pre-prompt debugger commands.
{ [ command ] Set an action (debugger command) to happen before every debugger prompt. A multi-line command may be entered in the customary fashion.
Because this command is in some senses new, a warning is issued if you appear to have accidentally entered a block instead. If that's what you mean to do, write it as with `;{ ... }` or even `do { ... }`.
{ \* Delete all pre-prompt debugger commands.
{{ command Add an action (debugger command) to happen before every debugger prompt. A multi-line command may be entered, if you can guess how: see above.
! number Redo a previous command (defaults to the previous command).
! -number Redo number'th previous command.
! pattern Redo last command that started with pattern. See `o recallCommand`, too.
!! cmd Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT) See `o shellBang`, also. Note that the user's current shell (well, their `$ENV{SHELL}` variable) will be used, which can interfere with proper interpretation of exit status or signal and coredump information.
source file Read and execute debugger commands from *file*. *file* may itself contain `source` commands.
H -number Display last n commands. Only commands longer than one character are listed. If *number* is omitted, list them all.
q or ^D Quit. ("quit" doesn't work for this, unless you've made an alias) This is the only supported way to exit the debugger, though typing `exit` twice might work.
Set the `inhibit_exit` option to 0 if you want to be able to step off the end the script. You may also need to set $finished to 0 if you want to step through global destruction.
R Restart the debugger by `exec()`ing a new session. We try to maintain your history across this, but internal settings and command-line options may be lost.
The following setting are currently preserved: history, breakpoints, actions, debugger options, and the Perl command-line options **-w**, **-I**, and **-e**.
|dbcmd Run the debugger command, piping DB::OUT into your current pager.
||dbcmd Same as `|dbcmd` but DB::OUT is temporarily `select`ed as well.
= [alias value] Define a command alias, like
```
= quit q
```
or list current aliases.
command Execute command as a Perl statement. A trailing semicolon will be supplied. If the Perl statement would otherwise be confused for a Perl debugger, use a leading semicolon, too.
m expr List which methods may be called on the result of the evaluated expression. The expression may evaluated to a reference to a blessed object, or to a package name.
M Display all loaded modules and their versions.
man [manpage] Despite its name, this calls your system's default documentation viewer on the given page, or on the viewer itself if *manpage* is omitted. If that viewer is **man**, the current `Config` information is used to invoke **man** using the proper MANPATH or **-M** *manpath* option. Failed lookups of the form `XXX` that match known manpages of the form *perlXXX* will be retried. This lets you type `man debug` or `man op` from the debugger.
On systems traditionally bereft of a usable **man** command, the debugger invokes **perldoc**. Occasionally this determination is incorrect due to recalcitrant vendors or rather more felicitously, to enterprising users. If you fall into either category, just manually set the $DB::doccmd variable to whatever viewer to view the Perl documentation on your system. This may be set in an rc file, or through direct assignment. We're still waiting for a working example of something along the lines of:
```
$DB::doccmd = 'netscape -remote http://something.here/';
```
###
Configurable Options
The debugger has numerous options settable using the `o` command, either interactively or from the environment or an rc file. The file is named *./.perldb* or *~/.perldb* under Unix with */dev/tty*, *perldb.ini* otherwise.
`recallCommand`, `ShellBang` The characters used to recall a command or spawn a shell. By default, both are set to `!`, which is unfortunate.
`pager` Program to use for output of pager-piped commands (those beginning with a `|` character.) By default, `$ENV{PAGER}` will be used. Because the debugger uses your current terminal characteristics for bold and underlining, if the chosen pager does not pass escape sequences through unchanged, the output of some debugger commands will not be readable when sent through the pager.
`tkRunning` Run Tk while prompting (with ReadLine).
`signalLevel`, `warnLevel`, `dieLevel` Level of verbosity. By default, the debugger leaves your exceptions and warnings alone, because altering them can break correctly running programs. It will attempt to print a message when uncaught INT, BUS, or SEGV signals arrive. (But see the mention of signals in ["BUGS"](#BUGS) below.)
To disable this default safe mode, set these values to something higher than 0. At a level of 1, you get backtraces upon receiving any kind of warning (this is often annoying) or exception (this is often valuable). Unfortunately, the debugger cannot discern fatal exceptions from non-fatal ones. If `dieLevel` is even 1, then your non-fatal exceptions are also traced and unceremoniously altered if they came from `eval'ed` strings or from any kind of `eval` within modules you're attempting to load. If `dieLevel` is 2, the debugger doesn't care where they came from: It usurps your exception handler and prints out a trace, then modifies all exceptions with its own embellishments. This may perhaps be useful for some tracing purposes, but tends to hopelessly destroy any program that takes its exception handling seriously.
`AutoTrace` Trace mode (similar to `t` command, but can be put into `PERLDB_OPTS`).
`LineInfo` File or pipe to print line number info to. If it is a pipe (say, `|visual_perl_db`), then a short message is used. This is the mechanism used to interact with a client editor or visual debugger, such as the special `vi` or `emacs` hooks, or the `ddd` graphical debugger.
`inhibit_exit` If 0, allows *stepping off* the end of the script.
`PrintRet` Print return value after `r` command if set (default).
`ornaments` Affects screen appearance of the command line (see <Term::ReadLine>). There is currently no way to disable these, which can render some output illegible on some displays, or with some pagers. This is considered a bug.
`frame` Affects the printing of messages upon entry and exit from subroutines. If `frame & 2` is false, messages are printed on entry only. (Printing on exit might be useful if interspersed with other messages.)
If `frame & 4`, arguments to functions are printed, plus context and caller info. If `frame & 8`, overloaded `stringify` and `tie`d `FETCH` is enabled on the printed arguments. If `frame & 16`, the return value from the subroutine is printed.
The length at which the argument list is truncated is governed by the next option:
`maxTraceLen` Length to truncate the argument list when the `frame` option's bit 4 is set.
`windowSize` Change the size of code list window (default is 10 lines).
The following options affect what happens with `V`, `X`, and `x` commands:
`arrayDepth`, `hashDepth` Print only first N elements ('' for all).
`dumpDepth` Limit recursion depth to N levels when dumping structures. Negative values are interpreted as infinity. Default: infinity.
`compactDump`, `veryCompact` Change the style of array and hash output. If `compactDump`, short array may be printed on one line.
`globPrint` Whether to print contents of globs.
`DumpDBFiles` Dump arrays holding debugged files.
`DumpPackages` Dump symbol tables of packages.
`DumpReused` Dump contents of "reused" addresses.
`quote`, `HighBit`, `undefPrint` Change the style of string dump. The default value for `quote` is `auto`; one can enable double-quotish or single-quotish format by setting it to `"` or `'`, respectively. By default, characters with their high bit set are printed verbatim.
`UsageOnly` Rudimentary per-package memory usage dump. Calculates total size of strings found in variables in the package. This does not include lexicals in a module's file scope, or lost in closures.
`HistFile` The path of the file from which the history (assuming a usable Term::ReadLine backend) will be read on the debugger's startup, and to which it will be saved on shutdown (for persistence across sessions). Similar in concept to Bash's `.bash_history` file.
`HistSize` The count of the saved lines in the history (assuming `HistFile` above).
After the rc file is read, the debugger reads the `$ENV{PERLDB_OPTS}` environment variable and parses this as the remainder of a "O ..." line as one might enter at the debugger prompt. You may place the initialization options `TTY`, `noTTY`, `ReadLine`, and `NonStop` there.
If your rc file contains:
```
parse_options("NonStop=1 LineInfo=db.out AutoTrace");
```
then your script will run without human intervention, putting trace information into the file *db.out*. (If you interrupt it, you'd better reset `LineInfo` to */dev/tty* if you expect to see anything.)
`TTY` The TTY to use for debugging I/O.
`noTTY` If set, the debugger goes into `NonStop` mode and will not connect to a TTY. If interrupted (or if control goes to the debugger via explicit setting of $DB::signal or $DB::single from the Perl script), it connects to a TTY specified in the `TTY` option at startup, or to a tty found at runtime using the `Term::Rendezvous` module of your choice.
This module should implement a method named `new` that returns an object with two methods: `IN` and `OUT`. These should return filehandles to use for debugging input and output correspondingly. The `new` method should inspect an argument containing the value of `$ENV{PERLDB_NOTTY}` at startup, or `"$ENV{HOME}/.perldbtty$$"` otherwise. This file is not inspected for proper ownership, so security hazards are theoretically possible.
`ReadLine` If false, readline support in the debugger is disabled in order to debug applications that themselves use ReadLine.
`NonStop` If set, the debugger goes into non-interactive mode until interrupted, or programmatically by setting $DB::signal or $DB::single.
Here's an example of using the `$ENV{PERLDB_OPTS}` variable:
```
$ PERLDB_OPTS="NonStop frame=2" perl -d myprogram
```
That will run the script **myprogram** without human intervention, printing out the call tree with entry and exit points. Note that `NonStop=1 frame=2` is equivalent to `N f=2`, and that originally, options could be uniquely abbreviated by the first letter (modulo the `Dump*` options). It is nevertheless recommended that you always spell them out in full for legibility and future compatibility.
Other examples include
```
$ PERLDB_OPTS="NonStop LineInfo=listing frame=2" perl -d myprogram
```
which runs script non-interactively, printing info on each entry into a subroutine and each executed line into the file named *listing*. (If you interrupt it, you would better reset `LineInfo` to something "interactive"!)
Other examples include (using standard shell syntax to show environment variable settings):
```
$ ( PERLDB_OPTS="NonStop frame=1 AutoTrace LineInfo=tperl.out"
perl -d myprogram )
```
which may be useful for debugging a program that uses `Term::ReadLine` itself. Do not forget to detach your shell from the TTY in the window that corresponds to */dev/ttyXX*, say, by issuing a command like
```
$ sleep 1000000
```
See ["Debugger Internals" in perldebguts](perldebguts#Debugger-Internals) for details.
###
Debugger Input/Output
Prompt The debugger prompt is something like
```
DB<8>
```
or even
```
DB<<17>>
```
where that number is the command number, and which you'd use to access with the built-in **csh**-like history mechanism. For example, `!17` would repeat command number 17. The depth of the angle brackets indicates the nesting depth of the debugger. You could get more than one set of brackets, for example, if you'd already at a breakpoint and then printed the result of a function call that itself has a breakpoint, or you step into an expression via `s/n/t expression` command.
Multiline commands If you want to enter a multi-line command, such as a subroutine definition with several statements or a format, escape the newline that would normally end the debugger command with a backslash. Here's an example:
```
DB<1> for (1..4) { \
cont: print "ok\n"; \
cont: }
ok
ok
ok
ok
```
Note that this business of escaping a newline is specific to interactive commands typed into the debugger.
Stack backtrace Here's an example of what a stack backtrace via `T` command might look like:
```
$ = main::infested called from file 'Ambulation.pm' line 10
@ = Ambulation::legs(1, 2, 3, 4) called from file 'camel_flea'
line 7
$ = main::pests('bactrian', 4) called from file 'camel_flea'
line 4
```
The left-hand character up there indicates the context in which the function was called, with `$` and `@` meaning scalar or list contexts respectively, and `.` meaning void context (which is actually a sort of scalar context). The display above says that you were in the function `main::infested` when you ran the stack dump, and that it was called in scalar context from line 10 of the file *Ambulation.pm*, but without any arguments at all, meaning it was called as `&infested`. The next stack frame shows that the function `Ambulation::legs` was called in list context from the *camel\_flea* file with four arguments. The last stack frame shows that `main::pests` was called in scalar context, also from *camel\_flea*, but from line 4.
If you execute the `T` command from inside an active `use` statement, the backtrace will contain both a `require` frame and an `eval` frame.
Line Listing Format This shows the sorts of output the `l` command can produce:
```
DB<<13>> l
101: @i{@i} = ();
102:b @isa{@i,$pack} = ()
103 if(exists $i{$prevpack} || exists $isa{$pack});
104 }
105
106 next
107==> if(exists $isa{$pack});
108
109:a if ($extra-- > 0) {
110: %isa = ($pack,1);
```
Breakable lines are marked with `:`. Lines with breakpoints are marked by `b` and those with actions by `a`. The line that's about to be executed is marked by `==>`.
Please be aware that code in debugger listings may not look the same as your original source code. Line directives and external source filters can alter the code before Perl sees it, causing code to move from its original positions or take on entirely different forms.
Frame listing When the `frame` option is set, the debugger would print entered (and optionally exited) subroutines in different styles. See <perldebguts> for incredibly long examples of these.
###
Debugging Compile-Time Statements
If you have compile-time executable statements (such as code within BEGIN, UNITCHECK and CHECK blocks or `use` statements), these will *not* be stopped by debugger, although `require`s and INIT blocks will, and compile-time statements can be traced with the `AutoTrace` option set in `PERLDB_OPTS`). From your own Perl code, however, you can transfer control back to the debugger using the following statement, which is harmless if the debugger is not running:
```
$DB::single = 1;
```
If you set `$DB::single` to 2, it's equivalent to having just typed the `n` command, whereas a value of 1 means the `s` command. The `$DB::trace` variable should be set to 1 to simulate having typed the `t` command.
Another way to debug compile-time code is to start the debugger, set a breakpoint on the *load* of some module:
```
DB<7> b load f:/perllib/lib/Carp.pm
Will stop on load of 'f:/perllib/lib/Carp.pm'.
```
and then restart the debugger using the `R` command (if possible). One can use `b compile subname` for the same purpose.
###
Debugger Customization
The debugger probably contains enough configuration hooks that you won't ever have to modify it yourself. You may change the behaviour of the debugger from within the debugger using its `o` command, from the command line via the `PERLDB_OPTS` environment variable, and from customization files.
You can do some customization by setting up a *.perldb* file, which contains initialization code. For instance, you could make aliases like these (the last one is one people expect to be there):
```
$DB::alias{'len'} = 's/^len(.*)/p length($1)/';
$DB::alias{'stop'} = 's/^stop (at|in)/b/';
$DB::alias{'ps'} = 's/^ps\b/p scalar /';
$DB::alias{'quit'} = 's/^quit(\s*)/exit/';
```
You can change options from *.perldb* by using calls like this one;
```
parse_options("NonStop=1 LineInfo=db.out AutoTrace=1 frame=2");
```
The code is executed in the package `DB`. Note that *.perldb* is processed before processing `PERLDB_OPTS`. If *.perldb* defines the subroutine `afterinit`, that function is called after debugger initialization ends. *.perldb* may be contained in the current directory, or in the home directory. Because this file is sourced in by Perl and may contain arbitrary commands, for security reasons, it must be owned by the superuser or the current user, and writable by no one but its owner.
You can mock TTY input to debugger by adding arbitrary commands to @DB::typeahead. For example, your *.perldb* file might contain:
```
sub afterinit { push @DB::typeahead, "b 4", "b 6"; }
```
Which would attempt to set breakpoints on lines 4 and 6 immediately after debugger initialization. Note that @DB::typeahead is not a supported interface and is subject to change in future releases.
If you want to modify the debugger, copy *perl5db.pl* from the Perl library to another name and hack it to your heart's content. You'll then want to set your `PERL5DB` environment variable to say something like this:
```
BEGIN { require "myperl5db.pl" }
```
As a last resort, you could also use `PERL5DB` to customize the debugger by directly setting internal variables or calling debugger functions.
Note that any variables and functions that are not documented in this document (or in <perldebguts>) are considered for internal use only, and as such are subject to change without notice.
###
Readline Support / History in the Debugger
As shipped, the only command-line history supplied is a simplistic one that checks for leading exclamation points. However, if you install the Term::ReadKey and Term::ReadLine modules from CPAN (such as Term::ReadLine::Gnu, Term::ReadLine::Perl, ...) you will have full editing capabilities much like those GNU *readline*(3) provides. Look for these in the *modules/by-module/Term* directory on CPAN. These do not support normal **vi** command-line editing, however.
A rudimentary command-line completion is also available, including lexical variables in the current scope if the `PadWalker` module is installed.
Without Readline support you may see the symbols "^[[A", "^[[C", "^[[B", "^[[D"", "^H", ... when using the arrow keys and/or the backspace key.
###
Editor Support for Debugging
If you have the GNU's version of **emacs** installed on your system, it can interact with the Perl debugger to provide an integrated software development environment reminiscent of its interactions with C debuggers.
Recent versions of Emacs come with a start file for making **emacs** act like a syntax-directed editor that understands (some of) Perl's syntax. See <perlfaq3>.
Users of **vi** should also look into **vim** and **gvim**, the mousey and windy version, for coloring of Perl keywords.
Note that only perl can truly parse Perl, so all such CASE tools fall somewhat short of the mark, especially if you don't program your Perl as a C programmer might.
###
The Perl Profiler
If you wish to supply an alternative debugger for Perl to run, invoke your script with a colon and a package argument given to the **-d** flag. Perl's alternative debuggers include a Perl profiler, <Devel::NYTProf>, which is available separately as a CPAN distribution. To profile your Perl program in the file *mycode.pl*, just type:
```
$ perl -d:NYTProf mycode.pl
```
When the script terminates the profiler will create a database of the profile information that you can turn into reports using the profiler's tools. See <perlperf> for details.
Debugging Regular Expressions
------------------------------
`use re 'debug'` enables you to see the gory details of how the Perl regular expression engine works. In order to understand this typically voluminous output, one must not only have some idea about how regular expression matching works in general, but also know how Perl's regular expressions are internally compiled into an automaton. These matters are explored in some detail in ["Debugging Regular Expressions" in perldebguts](perldebguts#Debugging-Regular-Expressions).
Debugging Memory Usage
-----------------------
Perl contains internal support for reporting its own memory usage, but this is a fairly advanced concept that requires some understanding of how memory allocation works. See ["Debugging Perl Memory Usage" in perldebguts](perldebguts#Debugging-Perl-Memory-Usage) for the details.
SEE ALSO
---------
You do have `use strict` and `use warnings` enabled, don't you?
<perldebtut>, <perldebguts>, <perl5db.pl>, <re>, [DB](db), <Devel::NYTProf>, [Dumpvalue](dumpvalue), and <perlrun>.
When debugging a script that uses #! and is thus normally found in $PATH, the -S option causes perl to search $PATH for it, so you don't have to type the path or `which $scriptname`.
```
$ perl -Sd foo.pl
```
BUGS
----
You cannot get stack frame information or in any fashion debug functions that were not compiled by Perl, such as those from C or C++ extensions.
If you alter your @\_ arguments in a subroutine (such as with `shift` or `pop`), the stack backtrace will not show the original values.
The debugger does not currently work in conjunction with the **-W** command-line switch, because it itself is not free of warnings.
If you're in a slow syscall (like `wait`ing, `accept`ing, or `read`ing from your keyboard or a socket) and haven't set up your own `$SIG{INT}` handler, then you won't be able to CTRL-C your way back to the debugger, because the debugger's own `$SIG{INT}` handler doesn't understand that it needs to raise an exception to longjmp(3) out of slow syscalls.
| programming_docs |
perl Memoize::ExpireFile Memoize::ExpireFile
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Memoize::ExpireFile - test for Memoize expiration semantics
DESCRIPTION
-----------
See <Memoize::Expire>.
perl Encode::Guess Encode::Guess
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [TO DO](#TO-DO)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Guess -- Guesses encoding from data
SYNOPSIS
--------
```
# if you are sure $data won't contain anything bogus
use Encode;
use Encode::Guess qw/euc-jp shiftjis 7bit-jis/;
my $utf8 = decode("Guess", $data);
my $data = encode("Guess", $utf8); # this doesn't work!
# more elaborate way
use Encode::Guess;
my $enc = guess_encoding($data, qw/euc-jp shiftjis 7bit-jis/);
ref($enc) or die "Can't guess: $enc"; # trap error this way
$utf8 = $enc->decode($data);
# or
$utf8 = decode($enc->name, $data)
```
ABSTRACT
--------
Encode::Guess enables you to guess in what encoding a given data is encoded, or at least tries to.
DESCRIPTION
-----------
By default, it checks only ascii, utf8 and UTF-16/32 with BOM.
```
use Encode::Guess; # ascii/utf8/BOMed UTF
```
To use it more practically, you have to give the names of encodings to check (*suspects* as follows). The name of suspects can either be canonical names or aliases.
CAVEAT: Unlike UTF-(16|32), BOM in utf8 is NOT AUTOMATICALLY STRIPPED.
```
# tries all major Japanese Encodings as well
use Encode::Guess qw/euc-jp shiftjis 7bit-jis/;
```
If the `$Encode::Guess::NoUTFAutoGuess` variable is set to a true value, no heuristics will be applied to UTF8/16/32, and the result will be limited to the suspects and `ascii`.
Encode::Guess->set\_suspects You can also change the internal suspects list via `set_suspects` method.
```
use Encode::Guess;
Encode::Guess->set_suspects(qw/euc-jp shiftjis 7bit-jis/);
```
Encode::Guess->add\_suspects Or you can use `add_suspects` method. The difference is that `set_suspects` flushes the current suspects list while `add_suspects` adds.
```
use Encode::Guess;
Encode::Guess->add_suspects(qw/euc-jp shiftjis 7bit-jis/);
# now the suspects are euc-jp,shiftjis,7bit-jis, AND
# euc-kr,euc-cn, and big5-eten
Encode::Guess->add_suspects(qw/euc-kr euc-cn big5-eten/);
```
Encode::decode("Guess" ...) When you are content with suspects list, you can now
```
my $utf8 = Encode::decode("Guess", $data);
```
Encode::Guess->guess($data) But it will croak if:
* Two or more suspects remain
* No suspects left
So you should instead try this;
```
my $decoder = Encode::Guess->guess($data);
```
On success, $decoder is an object that is documented in <Encode::Encoding>. So you can now do this;
```
my $utf8 = $decoder->decode($data);
```
On failure, $decoder now contains an error message so the whole thing would be as follows;
```
my $decoder = Encode::Guess->guess($data);
die $decoder unless ref($decoder);
my $utf8 = $decoder->decode($data);
```
guess\_encoding($data, [, *list of suspects*]) You can also try `guess_encoding` function which is exported by default. It takes $data to check and it also takes the list of suspects by option. The optional suspect list is *not reflected* to the internal suspects list.
```
my $decoder = guess_encoding($data, qw/euc-jp euc-kr euc-cn/);
die $decoder unless ref($decoder);
my $utf8 = $decoder->decode($data);
# check only ascii, utf8 and UTF-(16|32) with BOM
my $decoder = guess_encoding($data);
```
CAVEATS
-------
* Because of the algorithm used, ISO-8859 series and other single-byte encodings do not work well unless either one of ISO-8859 is the only one suspect (besides ascii and utf8).
```
use Encode::Guess;
# perhaps ok
my $decoder = guess_encoding($data, 'latin1');
# definitely NOT ok
my $decoder = guess_encoding($data, qw/latin1 greek/);
```
The reason is that Encode::Guess guesses encoding by trial and error. It first splits $data into lines and tries to decode the line for each suspect. It keeps it going until all but one encoding is eliminated out of suspects list. ISO-8859 series is just too successful for most cases (because it fills almost all code points in \x00-\xff).
* Do not mix national standard encodings and the corresponding vendor encodings.
```
# a very bad idea
my $decoder
= guess_encoding($data, qw/shiftjis MacJapanese cp932/);
```
The reason is that vendor encoding is usually a superset of national standard so it becomes too ambiguous for most cases.
* On the other hand, mixing various national standard encodings automagically works unless $data is too short to allow for guessing.
```
# This is ok if $data is long enough
my $decoder =
guess_encoding($data, qw/euc-cn
euc-jp shiftjis 7bit-jis
euc-kr
big5-eten/);
```
* DO NOT PUT TOO MANY SUSPECTS! Don't you try something like this!
```
my $decoder = guess_encoding($data,
Encode->encodings(":all"));
```
It is, after all, just a guess. You should alway be explicit when it comes to encodings. But there are some, especially Japanese, environment that guess-coding is a must. Use this module with care.
TO DO
------
Encode::Guess does not work on EBCDIC platforms.
SEE ALSO
---------
[Encode](encode), <Encode::Encoding>
perl Encode::Config Encode::Config
==============
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::Config -- internally used by Encode
perl Test2::EventFacet::Info Test2::EventFacet::Info
=======================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Info - Facet for information a developer might care about.
DESCRIPTION
-----------
This facet represents messages intended for humans that will help them either understand a result, or diagnose a failure.
NOTES
-----
This facet appears in a list instead of being a single item.
FIELDS
------
$string\_or\_structure = $info->{details}
$string\_or\_structure = $info->details() Human readable string or data structure, this is the information to display. Formatters are free to render the structures however they please. This may contain a blessed object.
If the `table` attribute (see below) is set then a renderer may choose to display the table instead of the details.
$structure = $info->{table}
$structure = $info->table() If the data the `info` facet needs to convey can be represented as a table then the data may be placed in this attribute in a more raw form for better display. The data must also be represented in the `details` attribute for renderers which do not support rendering tables directly.
The table structure:
```
my %table = {
header => [ 'column 1 header', 'column 2 header', ... ], # Optional
rows => [
['row 1 column 1', 'row 1, column 2', ... ],
['row 2 column 1', 'row 2, column 2', ... ],
...
],
# Allow the renderer to hide empty columns when true, Optional
collapse => $BOOL,
# List by name or number columns that should never be collapsed
no_collapse => \@LIST,
}
```
$short\_string = $info->{tag}
$short\_string = $info->tag() Short tag to categorize the info. This is usually 10 characters or less, formatters may truncate longer tags.
$bool = $info->{debug}
$bool = $info->debug() Set this to true if the message is critical, or explains a failure. This is info that should be displayed by formatters even in less-verbose modes.
When false the information is not considered critical and may not be rendered in less-verbose modes.
$bool = $info->{important}
$bool = $info->important This should be set for non debug messages that are still important enough to show when a formatter is in quiet mode. A formatter should send these to STDOUT not STDERR, but should show them even in non-verbose mode.
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 Cwd Cwd
===
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [getcwd and friends](#getcwd-and-friends)
+ [abs\_path and friends](#abs_path-and-friends)
+ [$ENV{PWD}](#%24ENV%7BPWD%7D)
* [NOTES](#NOTES)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Cwd - get pathname of current working directory
SYNOPSIS
--------
```
use Cwd;
my $dir = getcwd;
use Cwd 'abs_path';
my $abs_path = abs_path($file);
```
DESCRIPTION
-----------
This module provides functions for determining the pathname of the current working directory. It is recommended that getcwd (or another \*cwd() function) be used in *all* code to ensure portability.
By default, it exports the functions cwd(), getcwd(), fastcwd(), and fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace.
###
getcwd and friends
Each of these functions are called without arguments and return the absolute path of the current working directory.
getcwd
```
my $cwd = getcwd();
```
Returns the current working directory. On error returns `undef`, with `$!` set to indicate the error.
Exposes the POSIX function getcwd(3) or re-implements it if it's not available.
cwd
```
my $cwd = cwd();
```
The cwd() is the most natural form for the current architecture. For most systems it is identical to `pwd` (but without the trailing line terminator).
fastcwd
```
my $cwd = fastcwd();
```
A more dangerous version of getcwd(), but potentially faster.
It might conceivably chdir() you out of a directory that it can't chdir() you back into. If fastcwd encounters a problem it will return undef but will probably leave you in a different directory. For a measure of extra security, if everything appears to have worked, the fastcwd() function will check that it leaves you in the same directory that it started in. If it has changed it will `die` with the message "Unstable directory path, current directory changed unexpectedly". That should never happen.
fastgetcwd
```
my $cwd = fastgetcwd();
```
The fastgetcwd() function is provided as a synonym for cwd().
getdcwd
```
my $cwd = getdcwd();
my $cwd = getdcwd('C:');
```
The getdcwd() function is also provided on Win32 to get the current working directory on the specified drive, since Windows maintains a separate current working directory for each drive. If no drive is specified then the current drive is assumed.
This function simply calls the Microsoft C library \_getdcwd() function.
###
abs\_path and friends
These functions are exported only on request. They each take a single argument and return the absolute pathname for it. If no argument is given they'll use the current working directory.
abs\_path
```
my $abs_path = abs_path($file);
```
Uses the same algorithm as getcwd(). Symbolic links and relative-path components ("." and "..") are resolved to return the canonical pathname, just like realpath(3). On error returns `undef`, with `$!` set to indicate the error.
realpath
```
my $abs_path = realpath($file);
```
A synonym for abs\_path().
fast\_abs\_path
```
my $abs_path = fast_abs_path($file);
```
A more dangerous, but potentially faster version of abs\_path.
###
$ENV{PWD}
If you ask to override your chdir() built-in function,
```
use Cwd qw(chdir);
```
then your PWD environment variable will be kept up to date. Note that it will only be kept up to date if all packages which use chdir import it from Cwd.
NOTES
-----
* Since the path separators are different on some operating systems ('/' on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec modules wherever portability is a concern.
* Actually, on Mac OS, the `getcwd()`, `fastgetcwd()` and `fastcwd()` functions are all aliases for the `cwd()` function, which, on Mac OS, calls `pwd`. Likewise, the `abs_path()` function is an alias for `fast_abs_path()`.
AUTHOR
------
Maintained by perl5-porters <*[email protected]*>.
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.
Portions of the C code in this library are copyright (c) 1994 by the Regents of the University of California. All rights reserved. The license on this code is compatible with the licensing of the rest of the distribution - please see the source code in *Cwd.xs* for the details.
SEE ALSO
---------
<File::chdir>
perl App::Prove App::Prove
==========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [state\_class](#state_class)
- [state\_manager](#state_manager)
- [add\_rc\_file](#add_rc_file)
- [process\_args](#process_args)
- [run](#run)
- [require\_harness](#require_harness)
- [print\_version](#print_version)
+ [Attributes](#Attributes)
* [PLUGINS](#PLUGINS)
+ [Sample Plugin](#Sample-Plugin)
* [SEE ALSO](#SEE-ALSO)
NAME
----
App::Prove - Implements the `prove` command.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
<Test::Harness> provides a command, `prove`, which runs a TAP based test suite and prints a report. The `prove` command is a minimal wrapper around an instance of this module.
SYNOPSIS
--------
```
use App::Prove;
my $app = App::Prove->new;
$app->process_args(@ARGV);
$app->run;
```
METHODS
-------
###
Class Methods
#### `new`
Create a new `App::Prove`. Optionally a hash ref of attribute initializers may be passed.
#### `state_class`
Getter/setter for the name of the class used for maintaining state. This class should either subclass from `App::Prove::State` or provide an identical interface.
#### `state_manager`
Getter/setter for the instance of the `state_class`.
#### `add_rc_file`
```
$prove->add_rc_file('myproj/.proverc');
```
Called before `process_args` to prepend the contents of an rc file to the options.
#### `process_args`
```
$prove->process_args(@args);
```
Processes the command-line arguments. Attributes will be set appropriately. Any filenames may be found in the `argv` attribute.
Dies on invalid arguments.
#### `run`
Perform whatever actions the command line args specified. The `prove` command line tool consists of the following code:
```
use App::Prove;
my $app = App::Prove->new;
$app->process_args(@ARGV);
exit( $app->run ? 0 : 1 ); # if you need the exit code
```
#### `require_harness`
Load a harness replacement class.
```
$prove->require_harness($for => $class_name);
```
#### `print_version`
Display the version numbers of the loaded <TAP::Harness> and the current Perl.
### Attributes
After command line parsing the following attributes reflect the values of the corresponding command line switches. They may be altered before calling `run`.
`archive` `argv` `backwards` `blib` `color` `directives` `dry` `exec` `extensions` `failures` `comments` `formatter` `harness` `ignore_exit` `includes` `jobs` `lib` `merge` `modules` `parse` `plugins` `quiet` `really_quiet` `recurse` `rules` `show_count` `show_help` `show_man` `show_version` `shuffle` `state` `state_class` `taint_fail` `taint_warn` `test_args` `timer` `verbose` `warnings_fail` `warnings_warn` `tapversion` `trap` PLUGINS
-------
`App::Prove` provides support for 3rd-party plugins. These are currently loaded at run-time, *after* arguments have been parsed (so you can not change the way arguments are processed, sorry), typically with the `-P*plugin*` switch, eg:
```
prove -PMyPlugin
```
This will search for a module named `App::Prove::Plugin::MyPlugin`, or failing that, `MyPlugin`. If the plugin can't be found, `prove` will complain & exit.
You can pass an argument to your plugin by appending an `=` after the plugin name, eg `-PMyPlugin=foo`. You can pass multiple arguments using commas:
```
prove -PMyPlugin=foo,bar,baz
```
These are passed in to your plugin's `load()` class method (if it has one), along with a reference to the `App::Prove` object that is invoking your plugin:
```
sub load {
my ($class, $p) = @_;
my @args = @{ $p->{args} };
# @args will contain ( 'foo', 'bar', 'baz' )
$p->{app_prove}->do_something;
...
}
```
Note that the user's arguments are also passed to your plugin's `import()` function as a list, eg:
```
sub import {
my ($class, @args) = @_;
# @args will contain ( 'foo', 'bar', 'baz' )
...
}
```
This is for backwards compatibility, and may be deprecated in the future.
###
Sample Plugin
Here's a sample plugin, for your reference:
```
package App::Prove::Plugin::Foo;
# Sample plugin, try running with:
# prove -PFoo=bar -r -j3
# prove -PFoo -Q
# prove -PFoo=bar,My::Formatter
use strict;
use warnings;
sub load {
my ($class, $p) = @_;
my @args = @{ $p->{args} };
my $app = $p->{app_prove};
print "loading plugin: $class, args: ", join(', ', @args ), "\n";
# turn on verbosity
$app->verbose( 1 );
# set the formatter?
$app->formatter( $args[1] ) if @args > 1;
# print some of App::Prove's state:
for my $attr (qw( jobs quiet really_quiet recurse verbose )) {
my $val = $app->$attr;
$val = 'undef' unless defined( $val );
print "$attr: $val\n";
}
return 1;
}
1;
```
SEE ALSO
---------
<prove>, <TAP::Harness>
perl Unicode::Collate::CJK::JISX0208 Unicode::Collate::CJK::JISX0208
===============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::JISX0208 - weighting JIS KANJI for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::JISX0208;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::JISX0208::weightJISX0208
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::JISX0208` provides `weightJISX0208()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of 6355 kanji (CJK Unified Ideographs) in the JIS X 0208 order.
SEE ALSO
---------
<Unicode::Collate>
<Unicode::Collate::Locale>
perl Test2::Event::Plan Test2::Event::Plan
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ACCESSORS](#ACCESSORS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Plan - The event of a plan
DESCRIPTION
-----------
Plan events are fired off whenever a plan is declared, done testing is called, or a subtext completes.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Plan;
my $ctx = context();
# Plan for 10 tests to run
my $event = $ctx->plan(10);
# Plan to skip all tests (will exit 0)
$ctx->plan(0, skip_all => "These tests need to be skipped");
```
ACCESSORS
---------
$num = $plan->max Get the number of expected tests
$dir = $plan->directive Get the directive (such as TODO, skip\_all, or no\_plan).
$reason = $plan->reason Get the reason for the directive.
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::Parser::Result::Comment TAP::Parser::Result::Comment
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDDEN METHODS](#OVERRIDDEN-METHODS)
+ [Instance Methods](#Instance-Methods)
- [comment](#comment)
NAME
----
TAP::Parser::Result::Comment - Comment 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 comment line is encountered.
```
1..1
ok 1 - woo hooo!
# this is a comment
```
OVERRIDDEN METHODS
-------------------
Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night.
* `as_string`
Note that this method merely returns the comment preceded by a '# '.
###
Instance Methods
#### `comment`
```
if ( $result->is_comment ) {
my $comment = $result->comment;
print "I have something to say: $comment";
}
```
perl IO::Uncompress::Inflate IO::Uncompress::Inflate
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [inflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#inflate-%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::Inflate - Read RFC 1950 files/buffers
SYNOPSIS
--------
```
use IO::Uncompress::Inflate qw(inflate $InflateError) ;
my $status = inflate $input => $output [,OPTS]
or die "inflate failed: $InflateError\n";
my $z = IO::Uncompress::Inflate->new( $input [OPTS] )
or die "inflate failed: $InflateError\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()
$InflateError ;
# 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 1950.
For writing RFC 1950 files/buffers, see the companion module IO::Compress::Deflate.
Functional Interface
---------------------
A top-level function, `inflate`, 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::Inflate qw(inflate $InflateError) ;
inflate $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "inflate failed: $InflateError\n";
```
The functional interface needs Perl5.005 or better.
###
inflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`inflate` 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 ">" `inflate` 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 ">" `inflate` 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 `inflate` 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 `inflate` 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 `inflate` 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.1950` and write the uncompressed data to the file `file1.txt`.
```
use strict ;
use warnings ;
use IO::Uncompress::Inflate qw(inflate $InflateError) ;
my $input = "file1.txt.1950";
my $output = "file1.txt";
inflate $input => $output
or die "inflate failed: $InflateError\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::Inflate qw(inflate $InflateError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.1950" )
or die "Cannot open 'file1.txt.1950': $!\n" ;
my $buffer ;
inflate $input => \$buffer
or die "inflate failed: $InflateError\n";
```
To uncompress all files in the directory "/my/home" that match "\*.txt.1950" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Uncompress::Inflate qw(inflate $InflateError) ;
inflate '</my/home/*.txt.1950>' => '</my/home/#1.txt>'
or die "inflate failed: $InflateError\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::Inflate qw(inflate $InflateError) ;
for my $input ( glob "/my/home/*.txt.1950" )
{
my $output = $input;
$output =~ s/.1950// ;
inflate $input => $output
or die "Error compressing '$input': $InflateError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::Inflate is shown below
```
my $z = IO::Uncompress::Inflate->new( $input [OPTS] )
or die "IO::Uncompress::Inflate failed: $InflateError\n";
```
Returns an `IO::Uncompress::Inflate` object on success and undef on failure. The variable `$InflateError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::Inflate 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::Inflate 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::Inflate 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. The ADLER32 checksum field must be present.
2. The value of the ADLER32 field read must match the adler32 value of the uncompressed data actually contained in the file.
### 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::Inflate 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::Inflate 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::Inflate at present.
:all Imports `inflate` and `$InflateError`. Same as doing this
```
use IO::Uncompress::Inflate qw(inflate $InflateError) ;
```
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::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 perliol perliol
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [History and Background](#History-and-Background)
+ [Basic Structure](#Basic-Structure)
+ [Layers vs Disciplines](#Layers-vs-Disciplines)
+ [Data Structures](#Data-Structures)
+ [Functions and Attributes](#Functions-and-Attributes)
+ [Per-instance Data](#Per-instance-Data)
+ [Layers in action.](#Layers-in-action.)
+ [Per-instance flag bits](#Per-instance-flag-bits)
+ [Methods in Detail](#Methods-in-Detail)
+ [Utilities](#Utilities)
+ [Implementing PerlIO Layers](#Implementing-PerlIO-Layers)
+ [Core Layers](#Core-Layers)
+ [Extension Layers](#Extension-Layers)
* [TODO](#TODO)
NAME
----
perliol - C API for Perl's implementation of IO in Layers.
SYNOPSIS
--------
```
/* Defining a layer ... */
#include <perliol.h>
```
DESCRIPTION
-----------
This document describes the behavior and implementation of the PerlIO abstraction described in <perlapio> when `USE_PERLIO` is defined.
###
History and Background
The PerlIO abstraction was introduced in perl5.003\_02 but languished as just an abstraction until perl5.7.0. However during that time a number of perl extensions switched to using it, so the API is mostly fixed to maintain (source) compatibility.
The aim of the implementation is to provide the PerlIO API in a flexible and platform neutral manner. It is also a trial of an "Object Oriented C, with vtables" approach which may be applied to Raku.
###
Basic Structure
PerlIO is a stack of layers.
The low levels of the stack work with the low-level operating system calls (file descriptors in C) getting bytes in and out, the higher layers of the stack buffer, filter, and otherwise manipulate the I/O, and return characters (or bytes) to Perl. Terms *above* and *below* are used to refer to the relative positioning of the stack layers.
A layer contains a "vtable", the table of I/O operations (at C level a table of function pointers), and status flags. The functions in the vtable implement operations like "open", "read", and "write".
When I/O, for example "read", is requested, the request goes from Perl first down the stack using "read" functions of each layer, then at the bottom the input is requested from the operating system services, then the result is returned up the stack, finally being interpreted as Perl data.
The requests do not necessarily go always all the way down to the operating system: that's where PerlIO buffering comes into play.
When you do an open() and specify extra PerlIO layers to be deployed, the layers you specify are "pushed" on top of the already existing default stack. One way to see it is that "operating system is on the left" and "Perl is on the right".
What exact layers are in this default stack depends on a lot of things: your operating system, Perl version, Perl compile time configuration, and Perl runtime configuration. See [PerlIO](perlio), ["PERLIO" in perlrun](perlrun#PERLIO), and <open> for more information.
binmode() operates similarly to open(): by default the specified layers are pushed on top of the existing stack.
However, note that even as the specified layers are "pushed on top" for open() and binmode(), this doesn't mean that the effects are limited to the "top": PerlIO layers can be very 'active' and inspect and affect layers also deeper in the stack. As an example there is a layer called "raw" which repeatedly "pops" layers until it reaches the first layer that has declared itself capable of handling binary data. The "pushed" layers are processed in left-to-right order.
sysopen() operates (unsurprisingly) at a lower level in the stack than open(). For example in Unix or Unix-like systems sysopen() operates directly at the level of file descriptors: in the terms of PerlIO layers, it uses only the "unix" layer, which is a rather thin wrapper on top of the Unix file descriptors.
###
Layers vs Disciplines
Initial discussion of the ability to modify IO streams behaviour used the term "discipline" for the entities which were added. This came (I believe) from the use of the term in "sfio", which in turn borrowed it from "line disciplines" on Unix terminals. However, this document (and the C code) uses the term "layer".
This is, I hope, a natural term given the implementation, and should avoid connotations that are inherent in earlier uses of "discipline" for things which are rather different.
###
Data Structures
The basic data structure is a PerlIOl:
```
typedef struct _PerlIO PerlIOl;
typedef struct _PerlIO_funcs PerlIO_funcs;
typedef PerlIOl *PerlIO;
struct _PerlIO
{
PerlIOl * next; /* Lower layer */
PerlIO_funcs * tab; /* Functions for this layer */
U32 flags; /* Various flags for state */
};
```
A `PerlIOl *` is a pointer to the struct, and the *application* level `PerlIO *` is a pointer to a `PerlIOl *` - i.e. a pointer to a pointer to the struct. This allows the application level `PerlIO *` to remain constant while the actual `PerlIOl *` underneath changes. (Compare perl's `SV *` which remains constant while its `sv_any` field changes as the scalar's type changes.) An IO stream is then in general represented as a pointer to this linked-list of "layers".
It should be noted that because of the double indirection in a `PerlIO *`, a `&(perlio->next)` "is" a `PerlIO *`, and so to some degree at least one layer can use the "standard" API on the next layer down.
A "layer" is composed of two parts:
1. The functions and attributes of the "layer class".
2. The per-instance data for a particular handle.
###
Functions and Attributes
The functions and attributes are accessed via the "tab" (for table) member of `PerlIOl`. The functions (methods of the layer "class") are fixed, and are defined by the `PerlIO_funcs` type. They are broadly the same as the public `PerlIO_xxxxx` functions:
```
struct _PerlIO_funcs
{
Size_t fsize;
char * name;
Size_t size;
IV kind;
IV (*Pushed)(pTHX_ PerlIO *f,
const char *mode,
SV *arg,
PerlIO_funcs *tab);
IV (*Popped)(pTHX_ PerlIO *f);
PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab,
PerlIO_list_t *layers, IV n,
const char *mode,
int fd, int imode, int perm,
PerlIO *old,
int narg, SV **args);
IV (*Binmode)(pTHX_ PerlIO *f);
SV * (*Getarg)(pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
IV (*Fileno)(pTHX_ PerlIO *f);
PerlIO * (*Dup)(pTHX_ PerlIO *f,
PerlIO *o,
CLONE_PARAMS *param,
int flags)
/* Unix-like functions - cf sfio line disciplines */
SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count);
SSize_t (*Unread)(pTHX_ PerlIO *f, const void *vbuf, Size_t count);
SSize_t (*Write)(pTHX_ PerlIO *f, const void *vbuf, Size_t count);
IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence);
Off_t (*Tell)(pTHX_ PerlIO *f);
IV (*Close)(pTHX_ PerlIO *f);
/* Stdio-like buffered IO functions */
IV (*Flush)(pTHX_ PerlIO *f);
IV (*Fill)(pTHX_ PerlIO *f);
IV (*Eof)(pTHX_ PerlIO *f);
IV (*Error)(pTHX_ PerlIO *f);
void (*Clearerr)(pTHX_ PerlIO *f);
void (*Setlinebuf)(pTHX_ PerlIO *f);
/* Perl's snooping functions */
STDCHAR * (*Get_base)(pTHX_ PerlIO *f);
Size_t (*Get_bufsiz)(pTHX_ PerlIO *f);
STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f);
SSize_t (*Get_cnt)(pTHX_ PerlIO *f);
void (*Set_ptrcnt)(pTHX_ PerlIO *f,STDCHAR *ptr,SSize_t cnt);
};
```
The first few members of the struct give a function table size for compatibility check "name" for the layer, the size to `malloc` for the per-instance data, and some flags which are attributes of the class as whole (such as whether it is a buffering layer), then follow the functions which fall into four basic groups:
1. Opening and setup functions
2. Basic IO operations
3. Stdio class buffering options.
4. Functions to support Perl's traditional "fast" access to the buffer.
A layer does not have to implement all the functions, but the whole table has to be present. Unimplemented slots can be NULL (which will result in an error when called) or can be filled in with stubs to "inherit" behaviour from a "base class". This "inheritance" is fixed for all instances of the layer, but as the layer chooses which stubs to populate the table, limited "multiple inheritance" is possible.
###
Per-instance Data
The per-instance data are held in memory beyond the basic PerlIOl struct, by making a PerlIOl the first member of the layer's struct thus:
```
typedef struct
{
struct _PerlIO base; /* Base "class" info */
STDCHAR * buf; /* Start of buffer */
STDCHAR * end; /* End of valid part of buffer */
STDCHAR * ptr; /* Current position in buffer */
Off_t posn; /* Offset of buf into the file */
Size_t bufsiz; /* Real size of buffer */
IV oneword; /* Emergency buffer */
} PerlIOBuf;
```
In this way (as for perl's scalars) a pointer to a PerlIOBuf can be treated as a pointer to a PerlIOl.
###
Layers in action.
```
table perlio unix
| |
+-----------+ +----------+ +--------+
PerlIO ->| |--->| next |--->| NULL |
+-----------+ +----------+ +--------+
| | | buffer | | fd |
+-----------+ | | +--------+
| | +----------+
```
The above attempts to show how the layer scheme works in a simple case. The application's `PerlIO *` points to an entry in the table(s) representing open (allocated) handles. For example the first three slots in the table correspond to `stdin`,`stdout` and `stderr`. The table in turn points to the current "top" layer for the handle - in this case an instance of the generic buffering layer "perlio". That layer in turn points to the next layer down - in this case the low-level "unix" layer.
The above is roughly equivalent to a "stdio" buffered stream, but with much more flexibility:
* If Unix level `read`/`write`/`lseek` is not appropriate for (say) sockets then the "unix" layer can be replaced (at open time or even dynamically) with a "socket" layer.
* Different handles can have different buffering schemes. The "top" layer could be the "mmap" layer if reading disk files was quicker using `mmap` than `read`. An "unbuffered" stream can be implemented simply by not having a buffer layer.
* Extra layers can be inserted to process the data as it flows through. This was the driving need for including the scheme in perl 5.7.0+ - we needed a mechanism to allow data to be translated between perl's internal encoding (conceptually at least Unicode as UTF-8), and the "native" format used by the system. This is provided by the ":encoding(xxxx)" layer which typically sits above the buffering layer.
* A layer can be added that does "\n" to CRLF translation. This layer can be used on any platform, not just those that normally do such things.
###
Per-instance flag bits
The generic flag bits are a hybrid of `O_XXXXX` style flags deduced from the mode string passed to `PerlIO_open()`, and state bits for typical buffer layers.
PERLIO\_F\_EOF End of file.
PERLIO\_F\_CANWRITE Writes are permitted, i.e. opened as "w" or "r+" or "a", etc.
PERLIO\_F\_CANREAD Reads are permitted i.e. opened "r" or "w+" (or even "a+" - ick).
PERLIO\_F\_ERROR An error has occurred (for `PerlIO_error()`).
PERLIO\_F\_TRUNCATE Truncate file suggested by open mode.
PERLIO\_F\_APPEND All writes should be appends.
PERLIO\_F\_CRLF Layer is performing Win32-like "\n" mapped to CR,LF for output and CR,LF mapped to "\n" for input. Normally the provided "crlf" layer is the only layer that need bother about this. `PerlIO_binmode()` will mess with this flag rather than add/remove layers if the `PERLIO_K_CANCRLF` bit is set for the layers class.
PERLIO\_F\_UTF8 Data written to this layer should be UTF-8 encoded; data provided by this layer should be considered UTF-8 encoded. Can be set on any layer by ":utf8" dummy layer. Also set on ":encoding" layer.
PERLIO\_F\_UNBUF Layer is unbuffered - i.e. write to next layer down should occur for each write to this layer.
PERLIO\_F\_WRBUF The buffer for this layer currently holds data written to it but not sent to next layer.
PERLIO\_F\_RDBUF The buffer for this layer currently holds unconsumed data read from layer below.
PERLIO\_F\_LINEBUF Layer is line buffered. Write data should be passed to next layer down whenever a "\n" is seen. Any data beyond the "\n" should then be processed.
PERLIO\_F\_TEMP File has been `unlink()`ed, or should be deleted on `close()`.
PERLIO\_F\_OPEN Handle is open.
PERLIO\_F\_FASTGETS This instance of this layer supports the "fast `gets`" interface. Normally set based on `PERLIO_K_FASTGETS` for the class and by the existence of the function(s) in the table. However a class that normally provides that interface may need to avoid it on a particular instance. The "pending" layer needs to do this when it is pushed above a layer which does not support the interface. (Perl's `sv_gets()` does not expect the streams fast `gets` behaviour to change during one "get".)
###
Methods in Detail
fsize
```
Size_t fsize;
```
Size of the function table. This is compared against the value PerlIO code "knows" as a compatibility check. Future versions *may* be able to tolerate layers compiled against an old version of the headers.
name
```
char * name;
```
The name of the layer whose open() method Perl should invoke on open(). For example if the layer is called APR, you will call:
```
open $fh, ">:APR", ...
```
and Perl knows that it has to invoke the PerlIOAPR\_open() method implemented by the APR layer.
size
```
Size_t size;
```
The size of the per-instance data structure, e.g.:
```
sizeof(PerlIOAPR)
```
If this field is zero then `PerlIO_pushed` does not malloc anything and assumes layer's Pushed function will do any required layer stack manipulation - used to avoid malloc/free overhead for dummy layers. If the field is non-zero it must be at least the size of `PerlIOl`, `PerlIO_pushed` will allocate memory for the layer's data structures and link new layer onto the stream's stack. (If the layer's Pushed method returns an error indication the layer is popped again.)
kind
```
IV kind;
```
* PERLIO\_K\_BUFFERED
The layer is buffered.
* PERLIO\_K\_RAW
The layer is acceptable to have in a binmode(FH) stack - i.e. it does not (or will configure itself not to) transform bytes passing through it.
* PERLIO\_K\_CANCRLF
Layer can translate between "\n" and CRLF line ends.
* PERLIO\_K\_FASTGETS
Layer allows buffer snooping.
* PERLIO\_K\_MULTIARG
Used when the layer's open() accepts more arguments than usual. The extra arguments should come not before the `MODE` argument. When this flag is used it's up to the layer to validate the args.
Pushed
```
IV (*Pushed)(pTHX_ PerlIO *f,const char *mode, SV *arg);
```
The only absolutely mandatory method. Called when the layer is pushed onto the stack. The `mode` argument may be NULL if this occurs post-open. The `arg` will be non-`NULL` if an argument string was passed. In most cases this should call `PerlIOBase_pushed()` to convert `mode` into the appropriate `PERLIO_F_XXXXX` flags in addition to any actions the layer itself takes. If a layer is not expecting an argument it need neither save the one passed to it, nor provide `Getarg()` (it could perhaps `Perl_warn` that the argument was un-expected).
Returns 0 on success. On failure returns -1 and should set errno.
Popped
```
IV (*Popped)(pTHX_ PerlIO *f);
```
Called when the layer is popped from the stack. A layer will normally be popped after `Close()` is called. But a layer can be popped without being closed if the program is dynamically managing layers on the stream. In such cases `Popped()` should free any resources (buffers, translation tables, ...) not held directly in the layer's struct. It should also `Unread()` any unconsumed data that has been read and buffered from the layer below back to that layer, so that it can be re-provided to what ever is now above.
Returns 0 on success and failure. If `Popped()` returns *true* then *perlio.c* assumes that either the layer has popped itself, or the layer is super special and needs to be retained for other reasons. In most cases it should return *false*.
Open
```
PerlIO * (*Open)(...);
```
The `Open()` method has lots of arguments because it combines the functions of perl's `open`, `PerlIO_open`, perl's `sysopen`, `PerlIO_fdopen` and `PerlIO_reopen`. The full prototype is as follows:
```
PerlIO * (*Open)(pTHX_ PerlIO_funcs *tab,
PerlIO_list_t *layers, IV n,
const char *mode,
int fd, int imode, int perm,
PerlIO *old,
int narg, SV **args);
```
Open should (perhaps indirectly) call `PerlIO_allocate()` to allocate a slot in the table and associate it with the layers information for the opened file, by calling `PerlIO_push`. The *layers* is an array of all the layers destined for the `PerlIO *`, and any arguments passed to them, *n* is the index into that array of the layer being called. The macro `PerlIOArg` will return a (possibly `NULL`) SV \* for the argument passed to the layer.
Where a layer opens or takes ownership of a file descriptor, that layer is responsible for getting the file descriptor's close-on-exec flag into the correct state. The flag should be clear for a file descriptor numbered less than or equal to `PL_maxsysfd`, and set for any file descriptor numbered higher. For thread safety, when a layer opens a new file descriptor it should if possible open it with the close-on-exec flag initially set.
The *mode* string is an "`fopen()`-like" string which would match the regular expression `/^[I#]?[rwa]\+?[bt]?$/`.
The `'I'` prefix is used during creation of `stdin`..`stderr` via special `PerlIO_fdopen` calls; the `'#'` prefix means that this is `sysopen` and that *imode* and *perm* should be passed to `PerlLIO_open3`; `'r'` means **r**ead, `'w'` means **w**rite and `'a'` means **a**ppend. The `'+'` suffix means that both reading and writing/appending are permitted. The `'b'` suffix means file should be binary, and `'t'` means it is text. (Almost all layers should do the IO in binary mode, and ignore the b/t bits. The `:crlf` layer should be pushed to handle the distinction.)
If *old* is not `NULL` then this is a `PerlIO_reopen`. Perl itself does not use this (yet?) and semantics are a little vague.
If *fd* not negative then it is the numeric file descriptor *fd*, which will be open in a manner compatible with the supplied mode string, the call is thus equivalent to `PerlIO_fdopen`. In this case *nargs* will be zero. The file descriptor may have the close-on-exec flag either set or clear; it is the responsibility of the layer that takes ownership of it to get the flag into the correct state.
If *nargs* is greater than zero then it gives the number of arguments passed to `open`, otherwise it will be 1 if for example `PerlIO_open` was called. In simple cases SvPV\_nolen(\*args) is the pathname to open.
If a layer provides `Open()` it should normally call the `Open()` method of next layer down (if any) and then push itself on top if that succeeds. `PerlIOBase_open` is provided to do exactly that, so in most cases you don't have to write your own `Open()` method. If this method is not defined, other layers may have difficulty pushing themselves on top of it during open.
If `PerlIO_push` was performed and open has failed, it must `PerlIO_pop` itself, since if it's not, the layer won't be removed and may cause bad problems.
Returns `NULL` on failure.
Binmode
```
IV (*Binmode)(pTHX_ PerlIO *f);
```
Optional. Used when `:raw` layer is pushed (explicitly or as a result of binmode(FH)). If not present layer will be popped. If present should configure layer as binary (or pop itself) and return 0. If it returns -1 for error `binmode` will fail with layer still on the stack.
Getarg
```
SV * (*Getarg)(pTHX_ PerlIO *f,
CLONE_PARAMS *param, int flags);
```
Optional. If present should return an SV \* representing the string argument passed to the layer when it was pushed. e.g. ":encoding(ascii)" would return an SvPV with value "ascii". (*param* and *flags* arguments can be ignored in most cases)
`Dup` uses `Getarg` to retrieve the argument originally passed to `Pushed`, so you must implement this function if your layer has an extra argument to `Pushed` and will ever be `Dup`ed.
Fileno
```
IV (*Fileno)(pTHX_ PerlIO *f);
```
Returns the Unix/Posix numeric file descriptor for the handle. Normally `PerlIOBase_fileno()` (which just asks next layer down) will suffice for this.
Returns -1 on error, which is considered to include the case where the layer cannot provide such a file descriptor.
Dup
```
PerlIO * (*Dup)(pTHX_ PerlIO *f, PerlIO *o,
CLONE_PARAMS *param, int flags);
```
XXX: Needs more docs.
Used as part of the "clone" process when a thread is spawned (in which case param will be non-NULL) and when a stream is being duplicated via '&' in the `open`.
Similar to `Open`, returns PerlIO\* on success, `NULL` on failure.
Read
```
SSize_t (*Read)(pTHX_ PerlIO *f, void *vbuf, Size_t count);
```
Basic read operation.
Typically will call `Fill` and manipulate pointers (possibly via the API). `PerlIOBuf_read()` may be suitable for derived classes which provide "fast gets" methods.
Returns actual bytes read, or -1 on an error.
Unread
```
SSize_t (*Unread)(pTHX_ PerlIO *f,
const void *vbuf, Size_t count);
```
A superset of stdio's `ungetc()`. Should arrange for future reads to see the bytes in `vbuf`. If there is no obviously better implementation then `PerlIOBase_unread()` provides the function by pushing a "fake" "pending" layer above the calling layer.
Returns the number of unread chars.
Write
```
SSize_t (*Write)(PerlIO *f, const void *vbuf, Size_t count);
```
Basic write operation.
Returns bytes written or -1 on an error.
Seek
```
IV (*Seek)(pTHX_ PerlIO *f, Off_t offset, int whence);
```
Position the file pointer. Should normally call its own `Flush` method and then the `Seek` method of next layer down.
Returns 0 on success, -1 on failure.
Tell
```
Off_t (*Tell)(pTHX_ PerlIO *f);
```
Return the file pointer. May be based on layers cached concept of position to avoid overhead.
Returns -1 on failure to get the file pointer.
Close
```
IV (*Close)(pTHX_ PerlIO *f);
```
Close the stream. Should normally call `PerlIOBase_close()` to flush itself and close layers below, and then deallocate any data structures (buffers, translation tables, ...) not held directly in the data structure.
Returns 0 on success, -1 on failure.
Flush
```
IV (*Flush)(pTHX_ PerlIO *f);
```
Should make stream's state consistent with layers below. That is, any buffered write data should be written, and file position of lower layers adjusted for data read from below but not actually consumed. (Should perhaps `Unread()` such data to the lower layer.)
Returns 0 on success, -1 on failure.
Fill
```
IV (*Fill)(pTHX_ PerlIO *f);
```
The buffer for this layer should be filled (for read) from layer below. When you "subclass" PerlIOBuf layer, you want to use its *\_read* method and to supply your own fill method, which fills the PerlIOBuf's buffer.
Returns 0 on success, -1 on failure.
Eof
```
IV (*Eof)(pTHX_ PerlIO *f);
```
Return end-of-file indicator. `PerlIOBase_eof()` is normally sufficient.
Returns 0 on end-of-file, 1 if not end-of-file, -1 on error.
Error
```
IV (*Error)(pTHX_ PerlIO *f);
```
Return error indicator. `PerlIOBase_error()` is normally sufficient.
Returns 1 if there is an error (usually when `PERLIO_F_ERROR` is set), 0 otherwise.
Clearerr
```
void (*Clearerr)(pTHX_ PerlIO *f);
```
Clear end-of-file and error indicators. Should call `PerlIOBase_clearerr()` to set the `PERLIO_F_XXXXX` flags, which may suffice.
Setlinebuf
```
void (*Setlinebuf)(pTHX_ PerlIO *f);
```
Mark the stream as line buffered. `PerlIOBase_setlinebuf()` sets the PERLIO\_F\_LINEBUF flag and is normally sufficient.
Get\_base
```
STDCHAR * (*Get_base)(pTHX_ PerlIO *f);
```
Allocate (if not already done so) the read buffer for this layer and return pointer to it. Return NULL on failure.
Get\_bufsiz
```
Size_t (*Get_bufsiz)(pTHX_ PerlIO *f);
```
Return the number of bytes that last `Fill()` put in the buffer.
Get\_ptr
```
STDCHAR * (*Get_ptr)(pTHX_ PerlIO *f);
```
Return the current read pointer relative to this layer's buffer.
Get\_cnt
```
SSize_t (*Get_cnt)(pTHX_ PerlIO *f);
```
Return the number of bytes left to be read in the current buffer.
Set\_ptrcnt
```
void (*Set_ptrcnt)(pTHX_ PerlIO *f,
STDCHAR *ptr, SSize_t cnt);
```
Adjust the read pointer and count of bytes to match `ptr` and/or `cnt`. The application (or layer above) must ensure they are consistent. (Checking is allowed by the paranoid.)
### Utilities
To ask for the next layer down use PerlIONext(PerlIO \*f).
To check that a PerlIO\* is valid use PerlIOValid(PerlIO \*f). (All this does is really just to check that the pointer is non-NULL and that the pointer behind that is non-NULL.)
PerlIOBase(PerlIO \*f) returns the "Base" pointer, or in other words, the `PerlIOl*` pointer.
PerlIOSelf(PerlIO\* f, type) return the PerlIOBase cast to a type.
Perl\_PerlIO\_or\_Base(PerlIO\* f, callback, base, failure, args) either calls the *callback* from the functions of the layer *f* (just by the name of the IO function, like "Read") with the *args*, or if there is no such callback, calls the *base* version of the callback with the same args, or if the f is invalid, set errno to EBADF and return *failure*.
Perl\_PerlIO\_or\_fail(PerlIO\* f, callback, failure, args) either calls the *callback* of the functions of the layer *f* with the *args*, or if there is no such callback, set errno to EINVAL. Or if the f is invalid, set errno to EBADF and return *failure*.
Perl\_PerlIO\_or\_Base\_void(PerlIO\* f, callback, base, args) either calls the *callback* of the functions of the layer *f* with the *args*, or if there is no such callback, calls the *base* version of the callback with the same args, or if the f is invalid, set errno to EBADF.
Perl\_PerlIO\_or\_fail\_void(PerlIO\* f, callback, args) either calls the *callback* of the functions of the layer *f* with the *args*, or if there is no such callback, set errno to EINVAL. Or if the f is invalid, set errno to EBADF.
###
Implementing PerlIO Layers
If you find the implementation document unclear or not sufficient, look at the existing PerlIO layer implementations, which include:
* C implementations
The *perlio.c* and *perliol.h* in the Perl core implement the "unix", "perlio", "stdio", "crlf", "utf8", "byte", "raw", "pending" layers, and also the "mmap" and "win32" layers if applicable. (The "win32" is currently unfinished and unused, to see what is used instead in Win32, see ["Querying the layers of filehandles" in PerlIO](perlio#Querying-the-layers-of-filehandles) .)
PerlIO::encoding, PerlIO::scalar, PerlIO::via in the Perl core.
PerlIO::gzip and APR::PerlIO (mod\_perl 2.0) on CPAN.
* Perl implementations
PerlIO::via::QuotedPrint in the Perl core and PerlIO::via::\* on CPAN.
If you are creating a PerlIO layer, you may want to be lazy, in other words, implement only the methods that interest you. The other methods you can either replace with the "blank" methods
```
PerlIOBase_noop_ok
PerlIOBase_noop_fail
```
(which do nothing, and return zero and -1, respectively) or for certain methods you may assume a default behaviour by using a NULL method. The Open method looks for help in the 'parent' layer. The following table summarizes the behaviour:
```
method behaviour with NULL
Clearerr PerlIOBase_clearerr
Close PerlIOBase_close
Dup PerlIOBase_dup
Eof PerlIOBase_eof
Error PerlIOBase_error
Fileno PerlIOBase_fileno
Fill FAILURE
Flush SUCCESS
Getarg SUCCESS
Get_base FAILURE
Get_bufsiz FAILURE
Get_cnt FAILURE
Get_ptr FAILURE
Open INHERITED
Popped SUCCESS
Pushed SUCCESS
Read PerlIOBase_read
Seek FAILURE
Set_cnt FAILURE
Set_ptrcnt FAILURE
Setlinebuf PerlIOBase_setlinebuf
Tell FAILURE
Unread PerlIOBase_unread
Write FAILURE
FAILURE Set errno (to EINVAL in Unixish, to LIB$_INVARG in VMS)
and return -1 (for numeric return values) or NULL (for
pointers)
INHERITED Inherited from the layer below
SUCCESS Return 0 (for numeric return values) or a pointer
```
###
Core Layers
The file `perlio.c` provides the following layers:
"unix" A basic non-buffered layer which calls Unix/POSIX `read()`, `write()`, `lseek()`, `close()`. No buffering. Even on platforms that distinguish between O\_TEXT and O\_BINARY this layer is always O\_BINARY.
"perlio" A very complete generic buffering layer which provides the whole of PerlIO API. It is also intended to be used as a "base class" for other layers. (For example its `Read()` method is implemented in terms of the `Get_cnt()`/`Get_ptr()`/`Set_ptrcnt()` methods).
"perlio" over "unix" provides a complete replacement for stdio as seen via PerlIO API. This is the default for USE\_PERLIO when system's stdio does not permit perl's "fast gets" access, and which do not distinguish between `O_TEXT` and `O_BINARY`.
"stdio" A layer which provides the PerlIO API via the layer scheme, but implements it by calling system's stdio. This is (currently) the default if system's stdio provides sufficient access to allow perl's "fast gets" access and which do not distinguish between `O_TEXT` and `O_BINARY`.
"crlf" A layer derived using "perlio" as a base class. It provides Win32-like "\n" to CR,LF translation. Can either be applied above "perlio" or serve as the buffer layer itself. "crlf" over "unix" is the default if system distinguishes between `O_TEXT` and `O_BINARY` opens. (At some point "unix" will be replaced by a "native" Win32 IO layer on that platform, as Win32's read/write layer has various drawbacks.) The "crlf" layer is a reasonable model for a layer which transforms data in some way.
"mmap" If Configure detects `mmap()` functions this layer is provided (with "perlio" as a "base") which does "read" operations by mmap()ing the file. Performance improvement is marginal on modern systems, so it is mainly there as a proof of concept. It is likely to be unbundled from the core at some point. The "mmap" layer is a reasonable model for a minimalist "derived" layer.
"pending" An "internal" derivative of "perlio" which can be used to provide Unread() function for layers which have no buffer or cannot be bothered. (Basically this layer's `Fill()` pops itself off the stack and so resumes reading from layer below.)
"raw" A dummy layer which never exists on the layer stack. Instead when "pushed" it actually pops the stack removing itself, it then calls Binmode function table entry on all the layers in the stack - normally this (via PerlIOBase\_binmode) removes any layers which do not have `PERLIO_K_RAW` bit set. Layers can modify that behaviour by defining their own Binmode entry.
"utf8" Another dummy layer. When pushed it pops itself and sets the `PERLIO_F_UTF8` flag on the layer which was (and now is once more) the top of the stack.
In addition *perlio.c* also provides a number of `PerlIOBase_xxxx()` functions which are intended to be used in the table slots of classes which do not need to do anything special for a particular method.
###
Extension Layers
Layers can be made available by extension modules. When an unknown layer is encountered the PerlIO code will perform the equivalent of :
```
use PerlIO 'layer';
```
Where *layer* is the unknown layer. *PerlIO.pm* will then attempt to:
```
require PerlIO::layer;
```
If after that process the layer is still not defined then the `open` will fail.
The following extension layers are bundled with perl:
":encoding"
```
use Encoding;
```
makes this layer available, although *PerlIO.pm* "knows" where to find it. It is an example of a layer which takes an argument as it is called thus:
```
open( $fh, "<:encoding(iso-8859-7)", $pathname );
```
":scalar" Provides support for reading data from and writing data to a scalar.
```
open( $fh, "+<:scalar", \$scalar );
```
When a handle is so opened, then reads get bytes from the string value of *$scalar*, and writes change the value. In both cases the position in *$scalar* starts as zero but can be altered via `seek`, and determined via `tell`.
Please note that this layer is implied when calling open() thus:
```
open( $fh, "+<", \$scalar );
```
":via" Provided to allow layers to be implemented as Perl code. For instance:
```
use PerlIO::via::StripHTML;
open( my $fh, "<:via(StripHTML)", "index.html" );
```
See <PerlIO::via> for details.
TODO
----
Things that need to be done to improve this document.
* Explain how to make a valid fh without going through open()(i.e. apply a layer). For example if the file is not opened through perl, but we want to get back a fh, like it was opened by Perl.
How PerlIO\_apply\_layera fits in, where its docs, was it made public?
Currently the example could be something like this:
```
PerlIO *foo_to_PerlIO(pTHX_ char *mode, ...)
{
char *mode; /* "w", "r", etc */
const char *layers = ":APR"; /* the layer name */
PerlIO *f = PerlIO_allocate(aTHX);
if (!f) {
return NULL;
}
PerlIO_apply_layers(aTHX_ f, mode, layers);
if (f) {
PerlIOAPR *st = PerlIOSelf(f, PerlIOAPR);
/* fill in the st struct, as in _open() */
st->file = file;
PerlIOBase(f)->flags |= PERLIO_F_OPEN;
return f;
}
return NULL;
}
```
* fix/add the documentation in places marked as XXX.
* The handling of errors by the layer is not specified. e.g. when $! should be set explicitly, when the error handling should be just delegated to the top layer.
Probably give some hints on using SETERRNO() or pointers to where they can be found.
* I think it would help to give some concrete examples to make it easier to understand the API. Of course I agree that the API has to be concise, but since there is no second document that is more of a guide, I think that it'd make it easier to start with the doc which is an API, but has examples in it in places where things are unclear, to a person who is not a PerlIO guru (yet).
| programming_docs |
perl perlsec perlsec
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SECURITY VULNERABILITY CONTACT INFORMATION](#SECURITY-VULNERABILITY-CONTACT-INFORMATION)
* [SECURITY MECHANISMS AND CONCERNS](#SECURITY-MECHANISMS-AND-CONCERNS)
+ [Taint mode](#Taint-mode)
+ [Laundering and Detecting Tainted Data](#Laundering-and-Detecting-Tainted-Data)
+ [Switches On the "#!" Line](#Switches-On-the-%22%23!%22-Line)
+ [Taint mode and @INC](#Taint-mode-and-@INC)
+ [Cleaning Up Your Path](#Cleaning-Up-Your-Path)
+ [Shebang Race Condition](#Shebang-Race-Condition)
+ [Protecting Your Programs](#Protecting-Your-Programs)
+ [Unicode](#Unicode)
+ [Algorithmic Complexity Attacks](#Algorithmic-Complexity-Attacks)
+ [Using Sudo](#Using-Sudo)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlsec - Perl security
DESCRIPTION
-----------
Perl is designed to make it easy to program securely even when running with extra privileges, like setuid or setgid programs. Unlike most command line shells, which are based on multiple substitution passes on each line of the script, Perl uses a more conventional evaluation scheme with fewer hidden snags. Additionally, because the language has more builtin functionality, it can rely less upon external (and possibly untrustworthy) programs to accomplish its purposes.
SECURITY VULNERABILITY CONTACT INFORMATION
-------------------------------------------
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.
See <perlsecpolicy> for additional information.
SECURITY MECHANISMS AND CONCERNS
---------------------------------
###
Taint mode
By default, Perl automatically enables a set of special security checks, called *taint mode*, when it detects its program running with differing real and effective user or group IDs. The setuid bit in Unix permissions is mode 04000, the setgid bit mode 02000; either or both may be set. You can also enable taint mode explicitly by using the **-T** command line flag. This flag is *strongly* suggested for server programs and any program run on behalf of someone else, such as a CGI script. Once taint mode is on, it's on for the remainder of your script.
While in this mode, Perl takes special precautions called *taint checks* to prevent both obvious and subtle traps. Some of these checks are reasonably simple, such as verifying that path directories aren't writable by others; careful programmers have always used checks like these. Other checks, however, are best supported by the language itself, and it is these checks especially that contribute to making a set-id Perl program more secure than the corresponding C program.
You may not use data derived from outside your program to affect something else outside your program--at least, not by accident. All command line arguments, environment variables, locale information (see <perllocale>), results of certain system calls (`readdir()`, `readlink()`, the variable of `shmread()`, the messages returned by `msgrcv()`, the password, gcos and shell fields returned by the `getpwxxx()` calls), and all file input are marked as "tainted". Tainted data may not be used directly or indirectly in any command that invokes a sub-shell, nor in any command that modifies files, directories, or processes, **with the following exceptions**:
Support for taint checks adds an overhead to all Perl programs, whether or not you're using the taint features. Perl 5.18 introduced C preprocessor symbols that can be used to disable the taint features.
* Arguments to `print` and `syswrite` are **not** checked for taintedness.
* Symbolic methods
```
$obj->$method(@args);
```
and symbolic sub references
```
&{$foo}(@args);
$foo->(@args);
```
are not checked for taintedness. This requires extra carefulness unless you want external data to affect your control flow. Unless you carefully limit what these symbolic values are, people are able to call functions **outside** your Perl code, such as POSIX::system, in which case they are able to run arbitrary external code.
* Hash keys are **never** tainted.
For efficiency reasons, Perl takes a conservative view of whether data is tainted. If an expression contains tainted data, any subexpression may be considered tainted, even if the value of the subexpression is not itself affected by the tainted data.
Because taintedness is associated with each scalar value, some elements of an array or hash can be tainted and others not. The keys of a hash are **never** tainted.
For example:
```
$arg = shift; # $arg is tainted
$hid = $arg . 'bar'; # $hid is also tainted
$line = <>; # Tainted
$line = <STDIN>; # Also tainted
open FOO, "/home/me/bar" or die $!;
$line = <FOO>; # Still tainted
$path = $ENV{'PATH'}; # Tainted, but see below
$data = 'abc'; # Not tainted
system "echo $arg"; # Insecure
system "/bin/echo", $arg; # Considered insecure
# (Perl doesn't know about /bin/echo)
system "echo $hid"; # Insecure
system "echo $data"; # Insecure until PATH set
$path = $ENV{'PATH'}; # $path now tainted
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
$path = $ENV{'PATH'}; # $path now NOT tainted
system "echo $data"; # Is secure now!
open(FOO, "< $arg"); # OK - read-only file
open(FOO, "> $arg"); # Not OK - trying to write
open(FOO,"echo $arg|"); # Not OK
open(FOO,"-|")
or exec 'echo', $arg; # Also not OK
$shout = `echo $arg`; # Insecure, $shout now tainted
unlink $data, $arg; # Insecure
umask $arg; # Insecure
exec "echo $arg"; # Insecure
exec "echo", $arg; # Insecure
exec "sh", '-c', $arg; # Very insecure!
@files = <*.c>; # insecure (uses readdir() or similar)
@files = glob('*.c'); # insecure (uses readdir() or similar)
# In either case, the results of glob are tainted, since the list of
# filenames comes from outside of the program.
$bad = ($arg, 23); # $bad will be tainted
$arg, `true`; # Insecure (although it isn't really)
```
If you try to do something insecure, you will get a fatal error saying something like "Insecure dependency" or "Insecure $ENV{PATH}".
The exception to the principle of "one tainted value taints the whole expression" is with the ternary conditional operator `?:`. Since code with a ternary conditional
```
$result = $tainted_value ? "Untainted" : "Also untainted";
```
is effectively
```
if ( $tainted_value ) {
$result = "Untainted";
} else {
$result = "Also untainted";
}
```
it doesn't make sense for `$result` to be tainted.
###
Laundering and Detecting Tainted Data
To test whether a variable contains tainted data, and whose use would thus trigger an "Insecure dependency" message, you can use the `tainted()` function of the Scalar::Util module, available in your nearby CPAN mirror, and included in Perl starting from the release 5.8.0. Or you may be able to use the following `is_tainted()` function.
```
sub is_tainted {
local $@; # Don't pollute caller's value.
return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 };
}
```
This function makes use of the fact that the presence of tainted data anywhere within an expression renders the entire expression tainted. It would be inefficient for every operator to test every argument for taintedness. Instead, the slightly more efficient and conservative approach is used that if any tainted value has been accessed within the same expression, the whole expression is considered tainted.
But testing for taintedness gets you only so far. Sometimes you have just to clear your data's taintedness. Values may be untainted by using them as keys in a hash; otherwise the only way to bypass the tainting mechanism is by referencing subpatterns from a regular expression match. Perl presumes that if you reference a substring using $1, $2, etc. in a non-tainting pattern, that you knew what you were doing when you wrote that pattern. That means using a bit of thought--don't just blindly untaint anything, or you defeat the entire mechanism. It's better to verify that the variable has only good characters (for certain values of "good") rather than checking whether it has any bad characters. That's because it's far too easy to miss bad characters that you never thought of.
Here's a test to make sure that the data contains nothing but "word" characters (alphabetics, numerics, and underscores), a hyphen, an at sign, or a dot.
```
if ($data =~ /^([-\@\w.]+)$/) {
$data = $1; # $data now untainted
} else {
die "Bad data in '$data'"; # log this somewhere
}
```
This is fairly secure because `/\w+/` doesn't normally match shell metacharacters, nor are dot, dash, or at going to mean something special to the shell. Use of `/.+/` would have been insecure in theory because it lets everything through, but Perl doesn't check for that. The lesson is that when untainting, you must be exceedingly careful with your patterns. Laundering data using regular expression is the *only* mechanism for untainting dirty data, unless you use the strategy detailed below to fork a child of lesser privilege.
The example does not untaint `$data` if `use locale` is in effect, because the characters matched by `\w` are determined by the locale. Perl considers that locale definitions are untrustworthy because they contain data from outside the program. If you are writing a locale-aware program, and want to launder data with a regular expression containing `\w`, put `no locale` ahead of the expression in the same block. See ["SECURITY" in perllocale](perllocale#SECURITY) for further discussion and examples.
###
Switches On the "#!" Line
When you make a script executable, in order to make it usable as a command, the system will pass switches to perl from the script's #! line. Perl checks that any command line switches given to a setuid (or setgid) script actually match the ones set on the #! line. Some Unix and Unix-like environments impose a one-switch limit on the #! line, so you may need to use something like `-wU` instead of `-w -U` under such systems. (This issue should arise only in Unix or Unix-like environments that support #! and setuid or setgid scripts.)
###
Taint mode and @INC
+When the taint mode (`-T`) is in effect, the environment variables +`PERL5LIB`, `PERLLIB`, and `PERL_USE_UNSAFE_INC` are ignored by Perl. You can still adjust `@INC` from outside the program by using the `-I` command line option as explained in [perlrun](perlrun#-Idirectory). The two environment variables are ignored because they are obscured, and a user running a program could be unaware that they are set, whereas the `-I` option is clearly visible and therefore permitted.
Another way to modify `@INC` without modifying the program, is to use the `lib` pragma, e.g.:
```
perl -Mlib=/foo program
```
The benefit of using `-Mlib=/foo` over `-I/foo`, is that the former will automagically remove any duplicated directories, while the latter will not.
Note that if a tainted string is added to `@INC`, the following problem will be reported:
```
Insecure dependency in require while running with -T switch
```
On versions of Perl before 5.26, activating taint mode will also remove the current directory (".") from the default value of `@INC`. Since version 5.26, the current directory isn't included in `@INC` by default.
###
Cleaning Up Your Path
For "Insecure `$ENV{PATH}`" messages, you need to set `$ENV{'PATH'}` to a known value, and each directory in the path must be absolute and non-writable by others than its owner and group. You may be surprised to get this message even if the pathname to your executable is fully qualified. This is *not* generated because you didn't supply a full path to the program; instead, it's generated because you never set your PATH environment variable, or you didn't set it to something that was safe. Because Perl can't guarantee that the executable in question isn't itself going to turn around and execute some other program that is dependent on your PATH, it makes sure you set the PATH.
The PATH isn't the only environment variable which can cause problems. Because some shells may use the variables IFS, CDPATH, ENV, and BASH\_ENV, Perl checks that those are either empty or untainted when starting subprocesses. You may wish to add something like this to your setid and taint-checking scripts.
```
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # Make %ENV safer
```
It's also possible to get into trouble with other operations that don't care whether they use tainted values. Make judicious use of the file tests in dealing with any user-supplied filenames. When possible, do opens and such **after** properly dropping any special user (or group!) privileges. Perl doesn't prevent you from opening tainted filenames for reading, so be careful what you print out. The tainting mechanism is intended to prevent stupid mistakes, not to remove the need for thought.
Perl does not call the shell to expand wild cards when you pass `system` and `exec` explicit parameter lists instead of strings with possible shell wildcards in them. Unfortunately, the `open`, `glob`, and backtick functions provide no such alternate calling convention, so more subterfuge will be required.
Perl provides a reasonably safe way to open a file or pipe from a setuid or setgid program: just create a child process with reduced privilege who does the dirty work for you. First, fork a child using the special `open` syntax that connects the parent and child by a pipe. Now the child resets its ID set and any other per-process attributes, like environment variables, umasks, current working directories, back to the originals or known safe values. Then the child process, which no longer has any special permissions, does the `open` or other system call. Finally, the child passes the data it managed to access back to the parent. Because the file or pipe was opened in the child while running under less privilege than the parent, it's not apt to be tricked into doing something it shouldn't.
Here's a way to do backticks reasonably safely. Notice how the `exec` is not called with a string that the shell could expand. This is by far the best way to call something that might be subjected to shell escapes: just never call the shell at all.
```
use English;
die "Can't fork: $!" unless defined($pid = open(KID, "-|"));
if ($pid) { # parent
while (<KID>) {
# do something
}
close KID;
} else {
my @temp = ($EUID, $EGID);
my $orig_uid = $UID;
my $orig_gid = $GID;
$EUID = $UID;
$EGID = $GID;
# Drop privileges
$UID = $orig_uid;
$GID = $orig_gid;
# Make sure privs are really gone
($EUID, $EGID) = @temp;
die "Can't drop privileges"
unless $UID == $EUID && $GID eq $EGID;
$ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH.
# Consider sanitizing the environment even more.
exec 'myprog', 'arg1', 'arg2'
or die "can't exec myprog: $!";
}
```
A similar strategy would work for wildcard expansion via `glob`, although you can use `readdir` instead.
Taint checking is most useful when although you trust yourself not to have written a program to give away the farm, you don't necessarily trust those who end up using it not to try to trick it into doing something bad. This is the kind of security checking that's useful for set-id programs and programs launched on someone else's behalf, like CGI programs.
This is quite different, however, from not even trusting the writer of the code not to try to do something evil. That's the kind of trust needed when someone hands you a program you've never seen before and says, "Here, run this." For that kind of safety, you might want to check out the Safe module, included standard in the Perl distribution. This module allows the programmer to set up special compartments in which all system operations are trapped and namespace access is carefully controlled. Safe should not be considered bullet-proof, though: it will not prevent the foreign code to set up infinite loops, allocate gigabytes of memory, or even abusing perl bugs to make the host interpreter crash or behave in unpredictable ways. In any case it's better avoided completely if you're really concerned about security.
###
Shebang Race Condition
Beyond the obvious problems that stem from giving special privileges to systems as flexible as scripts, on many versions of Unix, set-id scripts are inherently insecure right from the start. The problem is a race condition in the kernel. Between the time the kernel opens the file to see which interpreter to run and when the (now-set-id) interpreter turns around and reopens the file to interpret it, the file in question may have changed, especially if you have symbolic links on your system.
Some Unixes, especially more recent ones, are free of this inherent security bug. On such systems, when the kernel passes the name of the set-id script to open to the interpreter, rather than using a pathname subject to meddling, it instead passes */dev/fd/3*. This is a special file already opened on the script, so that there can be no race condition for evil scripts to exploit. On these systems, Perl should be compiled with `-DSETUID_SCRIPTS_ARE_SECURE_NOW`. The *Configure* program that builds Perl tries to figure this out for itself, so you should never have to specify this yourself. Most modern releases of SysVr4 and BSD 4.4 use this approach to avoid the kernel race condition.
If you don't have the safe version of set-id scripts, all is not lost. Sometimes this kernel "feature" can be disabled, so that the kernel either doesn't run set-id scripts with the set-id or doesn't run them at all. Either way avoids the exploitability of the race condition, but doesn't help in actually running scripts set-id.
If the kernel set-id script feature isn't disabled, then any set-id script provides an exploitable vulnerability. Perl can't avoid being exploitable, but will point out vulnerable scripts where it can. If Perl detects that it is being applied to a set-id script then it will complain loudly that your set-id script is insecure, and won't run it. When Perl complains, you need to remove the set-id bit from the script to eliminate the vulnerability. Refusing to run the script doesn't in itself close the vulnerability; it is just Perl's way of encouraging you to do this.
To actually run a script set-id, if you don't have the safe version of set-id scripts, you'll need to put a C wrapper around the script. A C wrapper is just a compiled program that does nothing except call your Perl program. Compiled programs are not subject to the kernel bug that plagues set-id scripts. Here's a simple wrapper, written in C:
```
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define REAL_PATH "/path/to/script"
int main(int argc, char **argv)
{
execv(REAL_PATH, argv);
fprintf(stderr, "%s: %s: %s\n",
argv[0], REAL_PATH, strerror(errno));
return 127;
}
```
Compile this wrapper into a binary executable and then make *it* rather than your script setuid or setgid. Note that this wrapper isn't doing anything to sanitise the execution environment other than ensuring that a safe path to the script is used. It only avoids the shebang race condition. It relies on Perl's own features, and on the script itself being careful, to make it safe enough to run the script set-id.
###
Protecting Your Programs
There are a number of ways to hide the source to your Perl programs, with varying levels of "security".
First of all, however, you *can't* take away read permission, because the source code has to be readable in order to be compiled and interpreted. (That doesn't mean that a CGI script's source is readable by people on the web, though.) So you have to leave the permissions at the socially friendly 0755 level. This lets people on your local system only see your source.
Some people mistakenly regard this as a security problem. If your program does insecure things, and relies on people not knowing how to exploit those insecurities, it is not secure. It is often possible for someone to determine the insecure things and exploit them without viewing the source. Security through obscurity, the name for hiding your bugs instead of fixing them, is little security indeed.
You can try using encryption via source filters (Filter::\* from CPAN, or Filter::Util::Call and Filter::Simple since Perl 5.8). But crackers might be able to decrypt it. You can try using the byte code compiler and interpreter described below, but crackers might be able to de-compile it. You can try using the native-code compiler described below, but crackers might be able to disassemble it. These pose varying degrees of difficulty to people wanting to get at your code, but none can definitively conceal it (this is true of every language, not just Perl).
If you're concerned about people profiting from your code, then the bottom line is that nothing but a restrictive license will give you legal security. License your software and pepper it with threatening statements like "This is unpublished proprietary software of XYZ Corp. Your access to it does not give you permission to use it blah blah blah." You should see a lawyer to be sure your license's wording will stand up in court.
### Unicode
Unicode is a new and complex technology and one may easily overlook certain security pitfalls. See <perluniintro> for an overview and <perlunicode> for details, and ["Security Implications of Unicode" in perlunicode](perlunicode#Security-Implications-of-Unicode) for security implications in particular.
###
Algorithmic Complexity Attacks
Certain internal algorithms used in the implementation of Perl can be attacked by choosing the input carefully to consume large amounts of either time or space or both. This can lead into the so-called *Denial of Service* (DoS) attacks.
* Hash Algorithm - Hash algorithms like the one used in Perl are well known to be vulnerable to collision attacks on their hash function. Such attacks involve constructing a set of keys which collide into the same bucket producing inefficient behavior. Such attacks often depend on discovering the seed of the hash function used to map the keys to buckets. That seed is then used to brute-force a key set which can be used to mount a denial of service attack. In Perl 5.8.1 changes were introduced to harden Perl to such attacks, and then later in Perl 5.18.0 these features were enhanced and additional protections added.
At the time of this writing, Perl 5.18.0 is considered to be well-hardened against algorithmic complexity attacks on its hash implementation. This is largely owed to the following measures mitigate attacks:
Hash Seed Randomization In order to make it impossible to know what seed to generate an attack key set for, this seed is randomly initialized at process start. This may be overridden by using the PERL\_HASH\_SEED environment variable, see ["PERL\_HASH\_SEED" in perlrun](perlrun#PERL_HASH_SEED). This environment variable controls how items are actually stored, not how they are presented via `keys`, `values` and `each`.
Hash Traversal Randomization Independent of which seed is used in the hash function, `keys`, `values`, and `each` return items in a per-hash randomized order. Modifying a hash by insertion will change the iteration order of that hash. This behavior can be overridden by using `hash_traversal_mask()` from <Hash::Util> or by using the PERL\_PERTURB\_KEYS environment variable, see ["PERL\_PERTURB\_KEYS" in perlrun](perlrun#PERL_PERTURB_KEYS). Note that this feature controls the "visible" order of the keys, and not the actual order they are stored in.
Bucket Order Perturbance When items collide into a given hash bucket the order they are stored in the chain is no longer predictable in Perl 5.18. This has the intention to make it harder to observe a collision. This behavior can be overridden by using the PERL\_PERTURB\_KEYS environment variable, see ["PERL\_PERTURB\_KEYS" in perlrun](perlrun#PERL_PERTURB_KEYS).
New Default Hash Function The default hash function has been modified with the intention of making it harder to infer the hash seed.
Alternative Hash Functions The source code includes multiple hash algorithms to choose from. While we believe that the default perl hash is robust to attack, we have included the hash function Siphash as a fall-back option. At the time of release of Perl 5.18.0 Siphash is believed to be of cryptographic strength. This is not the default as it is much slower than the default hash.
Without compiling a special Perl, there is no way to get the exact same behavior of any versions prior to Perl 5.18.0. The closest one can get is by setting PERL\_PERTURB\_KEYS to 0 and setting the PERL\_HASH\_SEED to a known value. We do not advise those settings for production use due to the above security considerations.
**Perl has never guaranteed any ordering of the hash keys**, and the ordering has already changed several times during the lifetime of Perl 5. Also, the ordering of hash keys has always been, and continues to be, affected by the insertion order and the history of changes made to the hash over its lifetime.
Also note that while the order of the hash elements might be randomized, this "pseudo-ordering" should **not** be used for applications like shuffling a list randomly (use `List::Util::shuffle()` for that, see <List::Util>, a standard core module since Perl 5.8.0; or the CPAN module `Algorithm::Numerical::Shuffle`), or for generating permutations (use e.g. the CPAN modules `Algorithm::Permute` or `Algorithm::FastPermute`), or for any cryptographic applications.
Tied hashes may have their own ordering and algorithmic complexity attacks.
* Regular expressions - Perl's regular expression engine is so called NFA (Non-deterministic Finite Automaton), which among other things means that it can rather easily consume large amounts of both time and space if the regular expression may match in several ways. Careful crafting of the regular expressions can help but quite often there really isn't much one can do (the book "Mastering Regular Expressions" is required reading, see <perlfaq2>). Running out of space manifests itself by Perl running out of memory.
* Sorting - the quicksort algorithm used in Perls before 5.8.0 to implement the sort() function was very easy to trick into misbehaving so that it consumes a lot of time. Starting from Perl 5.8.0 a different sorting algorithm, mergesort, is used by default. Mergesort cannot misbehave on any input.
See <https://www.usenix.org/legacy/events/sec03/tech/full_papers/crosby/crosby.pdf> for more information, and any computer science textbook on algorithmic complexity.
###
Using Sudo
The popular tool `sudo` provides a controlled way for users to be able to run programs as other users. It sanitises the execution environment to some extent, and will avoid the [shebang race condition](#Shebang-Race-Condition). If you don't have the safe version of set-id scripts, then `sudo` may be a more convenient way of executing a script as another user than writing a C wrapper would be.
However, `sudo` sets the real user or group ID to that of the target identity, not just the effective ID as set-id bits do. As a result, Perl can't detect that it is running under `sudo`, and so won't automatically take its own security precautions such as turning on taint mode. Where `sudo` configuration dictates exactly which command can be run, the approved command may include a `-T` option to perl to enable taint mode.
In general, it is necessary to evaluate the suitability of a script to run under `sudo` specifically with that kind of execution environment in mind. It is neither necessary nor sufficient for the same script to be suitable to run in a traditional set-id arrangement, though many of the issues overlap.
SEE ALSO
---------
["ENVIRONMENT" in perlrun](perlrun#ENVIRONMENT) for its description of cleaning up environment variables.
| programming_docs |
perl User::grent User::grent
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
User::grent - by-name interface to Perl's built-in getgr\*() functions
SYNOPSIS
--------
```
use User::grent;
$gr = getgrgid(0) or die "No group zero";
if ( $gr->name eq 'wheel' && @{$gr->members} > 1 ) {
print "gid zero name wheel, with other members";
}
use User::grent qw(:FIELDS);
getgrgid(0) or die "No group zero";
if ( $gr_name eq 'wheel' && @gr_members > 1 ) {
print "gid zero name wheel, with other members";
}
$gr = getgr($whoever);
```
DESCRIPTION
-----------
This module's default exports override the core getgrent(), getgrgid(), and getgrnam() functions, replacing them with versions that return "User::grent" objects. This object has methods that return the similarly named structure field name from the C's passwd structure from *grp.h*; namely name, passwd, gid, and members (not mem). The first three return scalars, the last an array reference.
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 `gr_`. Thus, `$group_obj->gid()` corresponds to $gr\_gid if you import the fields. Array references are available as regular array variables, so `@{ $group_obj->members() }` would be simply @gr\_members.
The getgr() function is a simple front-end that forwards a numeric argument to getgrgid() and the rest to getgrnam().
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 Amiga::Exec Amiga::Exec
===========
CONTENTS
--------
* [NAME](#NAME)
* [ABSTRACT](#ABSTRACT)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Amiga::ARexx METHODS](#Amiga::ARexx-METHODS)
+ [Wait](#Wait)
- [Signal](#Signal)
- [TimeOut](#TimeOut)
+ [EXPORT](#EXPORT)
+ [Exportable constants](#Exportable-constants)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Amiga::Exec - Perl extension for low level amiga support
ABSTRACT
--------
This a perl class / module to enables you to use various low level Amiga features such as waiting on an Exec signal
SYNOPSIS
--------
```
# Wait for signla
use Amiga::Exec;
my $result = Amiga::ARexx->Wait('SignalMask' => $signalmask,
'TimeOut' => $timeoutinusecs);
```
DESCRIPTION
-----------
The interface to Exec in entirely encapsulated within the perl class, there is no need to access the low level methods directly and they are not exported by default.
Amiga::ARexx METHODS
---------------------
### Wait
```
$signals = Amiga::Exec->Wait('SignalMask' => $signalmask,
'TimeOut' => $timeoutinusecs );
```
Wait on a signal set with optional timeout. The result ($signals) should be checked to determine which signal was raised. It will be 0 for timeout.
#### Signal
The signal Exec signal mask
#### TimeOut
optional time out in microseconds.
### EXPORT
None by default.
###
Exportable constants
None
AUTHOR
------
Andy Broad <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2013 by Andy Broad.
perl TAP::Parser::SourceHandler TAP::Parser::SourceHandler
==========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [can\_handle](#can_handle)
- [make\_iterator](#make_iterator)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::SourceHandler - Base class for different TAP source handlers
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
# abstract class - don't use directly!
# see TAP::Parser::IteratorFactory for general usage
# must be sub-classed for use
package MySourceHandler;
use base 'TAP::Parser::SourceHandler';
sub can_handle { return $confidence_level }
sub make_iterator { return $iterator }
# see example below for more details
```
DESCRIPTION
-----------
This is an abstract base class for <TAP::Parser::Source> handlers / handlers.
A `TAP::Parser::SourceHandler` does whatever is necessary 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.
`SourceHandlers` must implement the *source detection & handling* interface used by <TAP::Parser::IteratorFactory>. At 2 methods, the interface is pretty simple: ["can\_handle"](#can_handle) and ["make\_source"](#make_source).
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
#### `can_handle`
*Abstract method*.
```
my $vote = $class->can_handle( $source );
```
`$source` is a <TAP::Parser::Source>.
Returns a number between `0` & `1` reflecting how confidently the raw source can be handled. For example, `0` means the source cannot handle it, `0.5` means it may be able to, and `1` means it definitely can. See ["detect\_source" in TAP::Parser::IteratorFactory](TAP::Parser::IteratorFactory#detect_source) for details on how this is used.
#### `make_iterator`
*Abstract method*.
```
my $iterator = $class->make_iterator( $source );
```
`$source` is a <TAP::Parser::Source>.
Returns a new <TAP::Parser::Iterator> object for use by the <TAP::Parser>. `croak`s on error.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview, and any of the subclasses that ship with this module as an example. What follows is a quick overview.
Start by familiarizing yourself with <TAP::Parser::Source> and <TAP::Parser::IteratorFactory>. <TAP::Parser::SourceHandler::RawTAP> is the easiest sub-class to use as an example.
It's important to point out that if you want your subclass to be automatically used by <TAP::Parser> you'll have to and make sure it gets loaded somehow. If you're using <prove> you can write an <App::Prove> plugin. If you're using <TAP::Parser> or <TAP::Harness> directly (e.g. through a custom script, <ExtUtils::MakeMaker>, or <Module::Build>) you can use the `config` option which will cause ["load\_sources" in TAP::Parser::IteratorFactory](TAP::Parser::IteratorFactory#load_sources) to load your subclass).
Don't forget to register your class with ["register\_handler" in TAP::Parser::IteratorFactory](TAP::Parser::IteratorFactory#register_handler).
### Example
```
package MySourceHandler;
use strict;
use MySourceHandler; # see TAP::Parser::SourceHandler
use TAP::Parser::IteratorFactory;
use base 'TAP::Parser::SourceHandler';
TAP::Parser::IteratorFactory->register_handler( __PACKAGE__ );
sub can_handle {
my ( $class, $src ) = @_;
my $meta = $src->meta;
my $config = $src->config_for( $class );
if ($config->{accept_all}) {
return 1.0;
} elsif (my $file = $meta->{file}) {
return 0.0 unless $file->{exists};
return 1.0 if $file->{lc_ext} eq '.tap';
return 0.9 if $file->{shebang} && $file->{shebang} =~ /^#!.+tap/;
return 0.5 if $file->{text};
return 0.1 if $file->{binary};
} elsif ($meta->{scalar}) {
return 0.8 if $$raw_source_ref =~ /\d\.\.\d/;
return 0.6 if $meta->{has_newlines};
} elsif ($meta->{array}) {
return 0.8 if $meta->{size} < 5;
return 0.6 if $raw_source_ref->[0] =~ /foo/;
return 0.5;
} elsif ($meta->{hash}) {
return 0.6 if $raw_source_ref->{foo};
return 0.2;
}
return 0;
}
sub make_iterator {
my ($class, $source) = @_;
# this is where you manipulate the source and
# capture the stream of TAP in an iterator
# either pick a TAP::Parser::Iterator::* or write your own...
my $iterator = TAP::Parser::Iterator::Array->new([ 'foo', 'bar' ]);
return $iterator;
}
1;
```
AUTHORS
-------
TAPx Developers.
Source detection stuff added by Steve Purkis
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Source>, <TAP::Parser::Iterator>, <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler::Executable>, <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::File>, <TAP::Parser::SourceHandler::Handle>, <TAP::Parser::SourceHandler::RawTAP>
perl TAP::Parser::SourceHandler::Handle TAP::Parser::SourceHandler::Handle
==================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [can\_handle](#can_handle)
- [make\_iterator](#make_iterator)
- [iterator\_class](#iterator_class)
* [SUBCLASSING](#SUBCLASSING)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::SourceHandler::Handle - Stream TAP from an IO::Handle or a GLOB.
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Source;
use TAP::Parser::SourceHandler::Executable;
my $source = TAP::Parser::Source->new->raw( \*TAP_FILE );
$source->assemble_meta;
my $class = 'TAP::Parser::SourceHandler::Handle';
my $vote = $class->can_handle( $source );
my $iter = $class->make_iterator( $source );
```
DESCRIPTION
-----------
This is a *raw TAP stored in an IO Handle* <TAP::Parser::SourceHandler> class. It has 2 jobs:
1. Figure out if the <TAP::Parser::Source> it's given is an <IO::Handle> or GLOB containing raw TAP output (["can\_handle"](#can_handle)).
2. Creates an iterator for IO::Handle's & globs (["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 );
```
Casts the following votes:
```
0.9 if $source is an IO::Handle
0.8 if $source is a glob
```
#### `make_iterator`
```
my $iterator = $class->make_iterator( $source );
```
Returns a new <TAP::Parser::Iterator::Stream> for the source.
#### `iterator_class`
The class of iterator to use, override if you're sub-classing. Defaults to <TAP::Parser::Iterator::Stream>.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Iterator>, <TAP::Parser::Iterator::Stream>, <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler>, <TAP::Parser::SourceHandler::Executable>, <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::File>, <TAP::Parser::SourceHandler::RawTAP>
perl Memoize::NDBM_File Memoize::NDBM\_File
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Memoize::NDBM\_File - glue to provide EXISTS for NDBM\_File for Storable use
DESCRIPTION
-----------
See [Memoize](memoize).
perl Unicode::Collate::CJK::Zhuyin Unicode::Collate::CJK::Zhuyin
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::Zhuyin - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::Zhuyin;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::Zhuyin::weightZhuyin
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::Zhuyin` provides `weightZhuyin()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's zhuyin (bopomofo) ordering.
CAVEAT
------
The zhuyin ordering includes some characters that are not CJK Unified Ideographs and can't utilize `weightZhuyin()` 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 IO::Poll IO::Poll
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Poll - Object interface to system poll call
SYNOPSIS
--------
```
use IO::Poll qw(POLLRDNORM POLLWRNORM POLLIN POLLHUP);
$poll = IO::Poll->new();
$poll->mask($input_handle => POLLIN);
$poll->mask($output_handle => POLLOUT);
$poll->poll($timeout);
$ev = $poll->events($input);
```
DESCRIPTION
-----------
`IO::Poll` is a simple interface to the system level poll routine.
METHODS
-------
mask ( IO [, EVENT\_MASK ] ) If EVENT\_MASK is given, then, if EVENT\_MASK is non-zero, IO is added to the list of file descriptors and the next call to poll will check for any event specified in EVENT\_MASK. If EVENT\_MASK is zero then IO will be removed from the list of file descriptors.
If EVENT\_MASK is not given then the return value will be the current event mask value for IO.
poll ( [ TIMEOUT ] ) Call the system level poll routine. If TIMEOUT is not specified then the call will block. Returns the number of handles which had events happen, or -1 on error.
events ( IO ) Returns the event mask which represents the events that happened on IO during the last call to `poll`.
remove ( IO ) Remove IO from the list of file descriptors for the next poll.
handles( [ EVENT\_MASK ] ) Returns a list of handles. If EVENT\_MASK is not given then a list of all handles known will be returned. If EVENT\_MASK is given then a list of handles will be returned which had one of the events specified by EVENT\_MASK happen during the last call ti `poll`
SEE ALSO
---------
[poll(2)](http://man.he.net/man2/poll), <IO::Handle>, <IO::Select>
AUTHOR
------
Graham Barr. Currently maintained by the Perl 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.
perl Socket Socket
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTANTS](#CONSTANTS)
+ [PF\_INET, PF\_INET6, PF\_UNIX, ...](#PF_INET,-PF_INET6,-PF_UNIX,-...)
+ [AF\_INET, AF\_INET6, AF\_UNIX, ...](#AF_INET,-AF_INET6,-AF_UNIX,-...)
+ [SOCK\_STREAM, SOCK\_DGRAM, SOCK\_RAW, ...](#SOCK_STREAM,-SOCK_DGRAM,-SOCK_RAW,-...)
+ [SOCK\_NONBLOCK. SOCK\_CLOEXEC](#SOCK_NONBLOCK.-SOCK_CLOEXEC)
+ [SOL\_SOCKET](#SOL_SOCKET)
+ [SO\_ACCEPTCONN, SO\_BROADCAST, SO\_ERROR, ...](#SO_ACCEPTCONN,-SO_BROADCAST,-SO_ERROR,-...)
+ [IP\_OPTIONS, IP\_TOS, IP\_TTL, ...](#IP_OPTIONS,-IP_TOS,-IP_TTL,-...)
+ [IP\_PMTUDISC\_WANT, IP\_PMTUDISC\_DONT, ...](#IP_PMTUDISC_WANT,-IP_PMTUDISC_DONT,-...)
+ [IPTOS\_LOWDELAY, IPTOS\_THROUGHPUT, IPTOS\_RELIABILITY, ...](#IPTOS_LOWDELAY,-IPTOS_THROUGHPUT,-IPTOS_RELIABILITY,-...)
+ [MSG\_BCAST, MSG\_OOB, MSG\_TRUNC, ...](#MSG_BCAST,-MSG_OOB,-MSG_TRUNC,-...)
+ [SHUT\_RD, SHUT\_RDWR, SHUT\_WR](#SHUT_RD,-SHUT_RDWR,-SHUT_WR)
+ [INADDR\_ANY, INADDR\_BROADCAST, INADDR\_LOOPBACK, INADDR\_NONE](#INADDR_ANY,-INADDR_BROADCAST,-INADDR_LOOPBACK,-INADDR_NONE)
+ [IPPROTO\_IP, IPPROTO\_IPV6, IPPROTO\_TCP, ...](#IPPROTO_IP,-IPPROTO_IPV6,-IPPROTO_TCP,-...)
+ [TCP\_CORK, TCP\_KEEPALIVE, TCP\_NODELAY, ...](#TCP_CORK,-TCP_KEEPALIVE,-TCP_NODELAY,-...)
+ [IN6ADDR\_ANY, IN6ADDR\_LOOPBACK](#IN6ADDR_ANY,-IN6ADDR_LOOPBACK)
+ [IPV6\_ADD\_MEMBERSHIP, IPV6\_MTU, IPV6\_V6ONLY, ...](#IPV6_ADD_MEMBERSHIP,-IPV6_MTU,-IPV6_V6ONLY,-...)
* [STRUCTURE MANIPULATORS](#STRUCTURE-MANIPULATORS)
+ [$family = sockaddr\_family $sockaddr](#%24family-=-sockaddr_family-%24sockaddr)
+ [$sockaddr = pack\_sockaddr\_in $port, $ip\_address](#%24sockaddr-=-pack_sockaddr_in-%24port,-%24ip_address)
+ [($port, $ip\_address) = unpack\_sockaddr\_in $sockaddr](#(%24port,-%24ip_address)-=-unpack_sockaddr_in-%24sockaddr)
+ [$sockaddr = sockaddr\_in $port, $ip\_address](#%24sockaddr-=-sockaddr_in-%24port,-%24ip_address)
+ [($port, $ip\_address) = sockaddr\_in $sockaddr](#(%24port,-%24ip_address)-=-sockaddr_in-%24sockaddr)
+ [$sockaddr = pack\_sockaddr\_in6 $port, $ip6\_address, [$scope\_id, [$flowinfo]]](#%24sockaddr-=-pack_sockaddr_in6-%24port,-%24ip6_address,-%5B%24scope_id,-%5B%24flowinfo%5D%5D)
+ [($port, $ip6\_address, $scope\_id, $flowinfo) = unpack\_sockaddr\_in6 $sockaddr](#(%24port,-%24ip6_address,-%24scope_id,-%24flowinfo)-=-unpack_sockaddr_in6-%24sockaddr)
+ [$sockaddr = sockaddr\_in6 $port, $ip6\_address, [$scope\_id, [$flowinfo]]](#%24sockaddr-=-sockaddr_in6-%24port,-%24ip6_address,-%5B%24scope_id,-%5B%24flowinfo%5D%5D)
+ [($port, $ip6\_address, $scope\_id, $flowinfo) = sockaddr\_in6 $sockaddr](#(%24port,-%24ip6_address,-%24scope_id,-%24flowinfo)-=-sockaddr_in6-%24sockaddr)
+ [$sockaddr = pack\_sockaddr\_un $path](#%24sockaddr-=-pack_sockaddr_un-%24path)
+ [($path) = unpack\_sockaddr\_un $sockaddr](#(%24path)-=-unpack_sockaddr_un-%24sockaddr)
+ [$sockaddr = sockaddr\_un $path](#%24sockaddr-=-sockaddr_un-%24path)
+ [($path) = sockaddr\_un $sockaddr](#(%24path)-=-sockaddr_un-%24sockaddr)
+ [$ip\_mreq = pack\_ip\_mreq $multiaddr, $interface](#%24ip_mreq-=-pack_ip_mreq-%24multiaddr,-%24interface)
+ [($multiaddr, $interface) = unpack\_ip\_mreq $ip\_mreq](#(%24multiaddr,-%24interface)-=-unpack_ip_mreq-%24ip_mreq)
+ [$ip\_mreq\_source = pack\_ip\_mreq\_source $multiaddr, $source, $interface](#%24ip_mreq_source-=-pack_ip_mreq_source-%24multiaddr,-%24source,-%24interface)
+ [($multiaddr, $source, $interface) = unpack\_ip\_mreq\_source $ip\_mreq](#(%24multiaddr,-%24source,-%24interface)-=-unpack_ip_mreq_source-%24ip_mreq)
+ [$ipv6\_mreq = pack\_ipv6\_mreq $multiaddr6, $ifindex](#%24ipv6_mreq-=-pack_ipv6_mreq-%24multiaddr6,-%24ifindex)
+ [($multiaddr6, $ifindex) = unpack\_ipv6\_mreq $ipv6\_mreq](#(%24multiaddr6,-%24ifindex)-=-unpack_ipv6_mreq-%24ipv6_mreq)
* [FUNCTIONS](#FUNCTIONS)
+ [$ip\_address = inet\_aton $string](#%24ip_address-=-inet_aton-%24string)
+ [$string = inet\_ntoa $ip\_address](#%24string-=-inet_ntoa-%24ip_address)
+ [$address = inet\_pton $family, $string](#%24address-=-inet_pton-%24family,-%24string)
+ [$string = inet\_ntop $family, $address](#%24string-=-inet_ntop-%24family,-%24address)
+ [($err, @result) = getaddrinfo $host, $service, [$hints]](#(%24err,-@result)-=-getaddrinfo-%24host,-%24service,-%5B%24hints%5D)
+ [($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]]](#(%24err,-%24hostname,-%24servicename)-=-getnameinfo-%24sockaddr,-%5B%24flags,-%5B%24xflags%5D%5D)
* [getaddrinfo() / getnameinfo() ERROR CONSTANTS](#getaddrinfo()-/-getnameinfo()-ERROR-CONSTANTS)
* [EXAMPLES](#EXAMPLES)
+ [Lookup for connect()](#Lookup-for-connect())
+ [Making a human-readable string out of an address](#Making-a-human-readable-string-out-of-an-address)
+ [Resolving hostnames into IP addresses](#Resolving-hostnames-into-IP-addresses)
+ [Accessing socket options](#Accessing-socket-options)
* [AUTHOR](#AUTHOR)
NAME
----
`Socket` - networking constants and support functions
SYNOPSIS
--------
`Socket` a low-level module used by, among other things, the <IO::Socket> family of modules. The following examples demonstrate some low-level uses but a practical program would likely use the higher-level API provided by `IO::Socket` or similar instead.
```
use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);
socket(my $socket, PF_INET, SOCK_STREAM, 0)
or die "socket: $!";
my $port = getservbyname "echo", "tcp";
connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
or die "connect: $!";
print $socket "Hello, world!\n";
print <$socket>;
```
See also the ["EXAMPLES"](#EXAMPLES) section.
DESCRIPTION
-----------
This module provides a variety of constants, structure manipulators and other functions related to socket-based networking. The values and functions provided are useful when used in conjunction with Perl core functions such as socket(), setsockopt() and bind(). It also provides several other support functions, mostly for dealing with conversions of network addresses between human-readable and native binary forms, and for hostname resolver operations.
Some constants and functions are exported by default by this module; but for backward-compatibility any recently-added symbols are not exported by default and must be requested explicitly. When an import list is provided to the `use Socket` line, the default exports are not automatically imported. It is therefore best practice to always to explicitly list all the symbols required.
Also, some common socket "newline" constants are provided: the constants `CR`, `LF`, and `CRLF`, as well as `$CR`, `$LF`, and `$CRLF`, which map to `\015`, `\012`, and `\015\012`. If you do not want to use the literal characters in your programs, then use the constants provided here. They are not exported by default, but can be imported individually, and with the `:crlf` export tag:
```
use Socket qw(:DEFAULT :crlf);
$sock->print("GET / HTTP/1.0$CRLF");
```
The entire getaddrinfo() subsystem can be exported using the tag `:addrinfo`; this exports the getaddrinfo() and getnameinfo() functions, and all the `AI_*`, `NI_*`, `NIx_*` and `EAI_*` constants.
CONSTANTS
---------
In each of the following groups, there may be many more constants provided than just the ones given as examples in the section heading. If the heading ends `...` then this means there are likely more; the exact constants provided will depend on the OS and headers found at compile-time.
###
PF\_INET, PF\_INET6, PF\_UNIX, ...
Protocol family constants to use as the first argument to socket() or the value of the `SO_DOMAIN` or `SO_FAMILY` socket option.
###
AF\_INET, AF\_INET6, AF\_UNIX, ...
Address family constants used by the socket address structures, to pass to such functions as inet\_pton() or getaddrinfo(), or are returned by such functions as sockaddr\_family().
###
SOCK\_STREAM, SOCK\_DGRAM, SOCK\_RAW, ...
Socket type constants to use as the second argument to socket(), or the value of the `SO_TYPE` socket option.
###
SOCK\_NONBLOCK. SOCK\_CLOEXEC
Linux-specific shortcuts to specify the `O_NONBLOCK` and `FD_CLOEXEC` flags during a `socket(2)` call.
```
socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )
```
### SOL\_SOCKET
Socket option level constant for setsockopt() and getsockopt().
###
SO\_ACCEPTCONN, SO\_BROADCAST, SO\_ERROR, ...
Socket option name constants for setsockopt() and getsockopt() at the `SOL_SOCKET` level.
###
IP\_OPTIONS, IP\_TOS, IP\_TTL, ...
Socket option name constants for IPv4 socket options at the `IPPROTO_IP` level.
###
IP\_PMTUDISC\_WANT, IP\_PMTUDISC\_DONT, ...
Socket option value constants for `IP_MTU_DISCOVER` socket option.
###
IPTOS\_LOWDELAY, IPTOS\_THROUGHPUT, IPTOS\_RELIABILITY, ...
Socket option value constants for `IP_TOS` socket option.
###
MSG\_BCAST, MSG\_OOB, MSG\_TRUNC, ...
Message flag constants for send() and recv().
###
SHUT\_RD, SHUT\_RDWR, SHUT\_WR
Direction constants for shutdown().
###
INADDR\_ANY, INADDR\_BROADCAST, INADDR\_LOOPBACK, INADDR\_NONE
Constants giving the special `AF_INET` addresses for wildcard, broadcast, local loopback, and invalid addresses.
Normally equivalent to inet\_aton('0.0.0.0'), inet\_aton('255.255.255.255'), inet\_aton('localhost') and inet\_aton('255.255.255.255') respectively.
###
IPPROTO\_IP, IPPROTO\_IPV6, IPPROTO\_TCP, ...
IP protocol constants to use as the third argument to socket(), the level argument to getsockopt() or setsockopt(), or the value of the `SO_PROTOCOL` socket option.
###
TCP\_CORK, TCP\_KEEPALIVE, TCP\_NODELAY, ...
Socket option name constants for TCP socket options at the `IPPROTO_TCP` level.
###
IN6ADDR\_ANY, IN6ADDR\_LOOPBACK
Constants giving the special `AF_INET6` addresses for wildcard and local loopback.
Normally equivalent to inet\_pton(AF\_INET6, "::") and inet\_pton(AF\_INET6, "::1") respectively.
###
IPV6\_ADD\_MEMBERSHIP, IPV6\_MTU, IPV6\_V6ONLY, ...
Socket option name constants for IPv6 socket options at the `IPPROTO_IPV6` level.
STRUCTURE MANIPULATORS
-----------------------
The following functions convert between lists of Perl values and packed binary strings representing structures.
###
$family = sockaddr\_family $sockaddr
Takes a packed socket address (as returned by pack\_sockaddr\_in(), pack\_sockaddr\_un() or the perl builtin functions getsockname() and getpeername()). Returns the address family tag. This will be one of the `AF_*` constants, such as `AF_INET` for a `sockaddr_in` addresses or `AF_UNIX` for a `sockaddr_un`. It can be used to figure out what unpack to use for a sockaddr of unknown type.
###
$sockaddr = pack\_sockaddr\_in $port, $ip\_address
Takes two arguments, a port number and an opaque string (as returned by inet\_aton(), or a v-string). Returns the `sockaddr_in` structure with those arguments packed in and `AF_INET` filled in. For Internet domain sockets, this structure is normally what you need for the arguments in bind(), connect(), and send().
An undefined $port argument is taken as zero; an undefined $ip\_address is considered a fatal error.
###
($port, $ip\_address) = unpack\_sockaddr\_in $sockaddr
Takes a `sockaddr_in` structure (as returned by pack\_sockaddr\_in(), getpeername() or recv()). Returns a list of two elements: the port and an opaque string representing the IP address (you can use inet\_ntoa() to convert the address to the four-dotted numeric format). Will croak if the structure does not represent an `AF_INET` address.
In scalar context will return just the IP address.
###
$sockaddr = sockaddr\_in $port, $ip\_address
###
($port, $ip\_address) = sockaddr\_in $sockaddr
A wrapper of pack\_sockaddr\_in() or unpack\_sockaddr\_in(). In list context, unpacks its argument and returns a list consisting of the port and IP address. In scalar context, packs its port and IP address arguments as a `sockaddr_in` and returns it.
Provided largely for legacy compatibility; it is better to use pack\_sockaddr\_in() or unpack\_sockaddr\_in() explicitly.
###
$sockaddr = pack\_sockaddr\_in6 $port, $ip6\_address, [$scope\_id, [$flowinfo]]
Takes two to four arguments, a port number, an opaque string (as returned by inet\_pton()), optionally a scope ID number, and optionally a flow label number. Returns the `sockaddr_in6` structure with those arguments packed in and `AF_INET6` filled in. IPv6 equivalent of pack\_sockaddr\_in().
An undefined $port argument is taken as zero; an undefined $ip6\_address is considered a fatal error.
###
($port, $ip6\_address, $scope\_id, $flowinfo) = unpack\_sockaddr\_in6 $sockaddr
Takes a `sockaddr_in6` structure. Returns a list of four elements: the port number, an opaque string representing the IPv6 address, the scope ID, and the flow label. (You can use inet\_ntop() to convert the address to the usual string format). Will croak if the structure does not represent an `AF_INET6` address.
In scalar context will return just the IP address.
###
$sockaddr = sockaddr\_in6 $port, $ip6\_address, [$scope\_id, [$flowinfo]]
###
($port, $ip6\_address, $scope\_id, $flowinfo) = sockaddr\_in6 $sockaddr
A wrapper of pack\_sockaddr\_in6() or unpack\_sockaddr\_in6(). In list context, unpacks its argument according to unpack\_sockaddr\_in6(). In scalar context, packs its arguments according to pack\_sockaddr\_in6().
Provided largely for legacy compatibility; it is better to use pack\_sockaddr\_in6() or unpack\_sockaddr\_in6() explicitly.
###
$sockaddr = pack\_sockaddr\_un $path
Takes one argument, a pathname. Returns the `sockaddr_un` structure with that path packed in with `AF_UNIX` filled in. For `PF_UNIX` sockets, this structure is normally what you need for the arguments in bind(), connect(), and send().
###
($path) = unpack\_sockaddr\_un $sockaddr
Takes a `sockaddr_un` structure (as returned by pack\_sockaddr\_un(), getpeername() or recv()). Returns a list of one element: the pathname. Will croak if the structure does not represent an `AF_UNIX` address.
###
$sockaddr = sockaddr\_un $path
###
($path) = sockaddr\_un $sockaddr
A wrapper of pack\_sockaddr\_un() or unpack\_sockaddr\_un(). In a list context, unpacks its argument and returns a list consisting of the pathname. In a scalar context, packs its pathname as a `sockaddr_un` and returns it.
Provided largely for legacy compatibility; it is better to use pack\_sockaddr\_un() or unpack\_sockaddr\_un() explicitly.
These are only supported if your system has <*sys/un.h*>.
###
$ip\_mreq = pack\_ip\_mreq $multiaddr, $interface
Takes an IPv4 multicast address and optionally an interface address (or `INADDR_ANY`). Returns the `ip_mreq` structure with those arguments packed in. Suitable for use with the `IP_ADD_MEMBERSHIP` and `IP_DROP_MEMBERSHIP` sockopts.
###
($multiaddr, $interface) = unpack\_ip\_mreq $ip\_mreq
Takes an `ip_mreq` structure. Returns a list of two elements; the IPv4 multicast address and interface address.
###
$ip\_mreq\_source = pack\_ip\_mreq\_source $multiaddr, $source, $interface
Takes an IPv4 multicast address, source address, and optionally an interface address (or `INADDR_ANY`). Returns the `ip_mreq_source` structure with those arguments packed in. Suitable for use with the `IP_ADD_SOURCE_MEMBERSHIP` and `IP_DROP_SOURCE_MEMBERSHIP` sockopts.
###
($multiaddr, $source, $interface) = unpack\_ip\_mreq\_source $ip\_mreq
Takes an `ip_mreq_source` structure. Returns a list of three elements; the IPv4 multicast address, source address and interface address.
###
$ipv6\_mreq = pack\_ipv6\_mreq $multiaddr6, $ifindex
Takes an IPv6 multicast address and an interface number. Returns the `ipv6_mreq` structure with those arguments packed in. Suitable for use with the `IPV6_ADD_MEMBERSHIP` and `IPV6_DROP_MEMBERSHIP` sockopts.
###
($multiaddr6, $ifindex) = unpack\_ipv6\_mreq $ipv6\_mreq
Takes an `ipv6_mreq` structure. Returns a list of two elements; the IPv6 address and an interface number.
FUNCTIONS
---------
###
$ip\_address = inet\_aton $string
Takes a string giving the name of a host, or a textual representation of an IP address and translates that to an packed binary address structure suitable to pass to pack\_sockaddr\_in(). If passed a hostname that cannot be resolved, returns `undef`. For multi-homed hosts (hosts with more than one address), the first address found is returned.
For portability do not assume that the result of inet\_aton() is 32 bits wide, in other words, that it would contain only the IPv4 address in network order.
This IPv4-only function is provided largely for legacy reasons. Newly-written code should use getaddrinfo() or inet\_pton() instead for IPv6 support.
###
$string = inet\_ntoa $ip\_address
Takes a packed binary address structure such as returned by unpack\_sockaddr\_in() (or a v-string representing the four octets of the IPv4 address in network order) and translates it into a string of the form `d.d.d.d` where the `d`s are numbers less than 256 (the normal human-readable four dotted number notation for Internet addresses).
This IPv4-only function is provided largely for legacy reasons. Newly-written code should use getnameinfo() or inet\_ntop() instead for IPv6 support.
###
$address = inet\_pton $family, $string
Takes an address family (such as `AF_INET` or `AF_INET6`) and a string containing a textual representation of an address in that family and translates that to an packed binary address structure.
See also getaddrinfo() for a more powerful and flexible function to look up socket addresses given hostnames or textual addresses.
###
$string = inet\_ntop $family, $address
Takes an address family and a packed binary address structure and translates it into a human-readable textual representation of the address; typically in `d.d.d.d` form for `AF_INET` or `hhhh:hhhh::hhhh` form for `AF_INET6`.
See also getnameinfo() for a more powerful and flexible function to turn socket addresses into human-readable textual representations.
###
($err, @result) = getaddrinfo $host, $service, [$hints]
Given both a hostname and service name, this function attempts to resolve the host name into a list of network addresses, and the service name into a protocol and port number, and then returns a list of address structures suitable to connect() to it.
Given just a host name, this function attempts to resolve it to a list of network addresses, and then returns a list of address structures giving these addresses.
Given just a service name, this function attempts to resolve it to a protocol and port number, and then returns a list of address structures that represent it suitable to bind() to. This use should be combined with the `AI_PASSIVE` flag; see below.
Given neither name, it generates an error.
If present, $hints should be a reference to a hash, where the following keys are recognised:
flags => INT A bitfield containing `AI_*` constants; see below.
family => INT Restrict to only generating addresses in this address family
socktype => INT Restrict to only generating addresses of this socket type
protocol => INT Restrict to only generating addresses for this protocol
The return value will be a list; the first value being an error indication, followed by a list of address structures (if no error occurred).
The error value will be a dualvar; comparable to the `EAI_*` error constants, or printable as a human-readable error message string. If no error occurred it will be zero numerically and an empty string.
Each value in the results list will be a hash reference containing the following fields:
family => INT The address family (e.g. `AF_INET`)
socktype => INT The socket type (e.g. `SOCK_STREAM`)
protocol => INT The protocol (e.g. `IPPROTO_TCP`)
addr => STRING The address in a packed string (such as would be returned by pack\_sockaddr\_in())
canonname => STRING The canonical name for the host if the `AI_CANONNAME` flag was provided, or `undef` otherwise. This field will only be present on the first returned address.
The following flag constants are recognised in the $hints hash. Other flag constants may exist as provided by the OS.
AI\_PASSIVE Indicates that this resolution is for a local bind() for a passive (i.e. listening) socket, rather than an active (i.e. connecting) socket.
AI\_CANONNAME Indicates that the caller wishes the canonical hostname (`canonname`) field of the result to be filled in.
AI\_NUMERICHOST Indicates that the caller will pass a numeric address, rather than a hostname, and that getaddrinfo() must not perform a resolve operation on this name. This flag will prevent a possibly-slow network lookup operation, and instead return an error if a hostname is passed.
###
($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags, [$xflags]]
Given a packed socket address (such as from getsockname(), getpeername(), or returned by getaddrinfo() in a `addr` field), returns the hostname and symbolic service name it represents. $flags may be a bitmask of `NI_*` constants, or defaults to 0 if unspecified.
The return value will be a list; the first value being an error condition, followed by the hostname and service name.
The error value will be a dualvar; comparable to the `EAI_*` error constants, or printable as a human-readable error message string. The host and service names will be plain strings.
The following flag constants are recognised as $flags. Other flag constants may exist as provided by the OS.
NI\_NUMERICHOST Requests that a human-readable string representation of the numeric address be returned directly, rather than performing a name resolve operation that may convert it into a hostname. This will also avoid potentially-blocking network IO.
NI\_NUMERICSERV Requests that the port number be returned directly as a number representation rather than performing a name resolve operation that may convert it into a service name.
NI\_NAMEREQD If a name resolve operation fails to provide a name, then this flag will cause getnameinfo() to indicate an error, rather than returning the numeric representation as a human-readable string.
NI\_DGRAM Indicates that the socket address relates to a `SOCK_DGRAM` socket, for the services whose name differs between TCP and UDP protocols.
The following constants may be supplied as $xflags.
NIx\_NOHOST Indicates that the caller is not interested in the hostname of the result, so it does not have to be converted. `undef` will be returned as the hostname.
NIx\_NOSERV Indicates that the caller is not interested in the service name of the result, so it does not have to be converted. `undef` will be returned as the service name.
getaddrinfo() / getnameinfo() ERROR CONSTANTS
----------------------------------------------
The following constants may be returned by getaddrinfo() or getnameinfo(). Others may be provided by the OS.
EAI\_AGAIN A temporary failure occurred during name resolution. The operation may be successful if it is retried later.
EAI\_BADFLAGS The value of the `flags` hint to getaddrinfo(), or the $flags parameter to getnameinfo() contains unrecognised flags.
EAI\_FAMILY The `family` hint to getaddrinfo(), or the family of the socket address passed to getnameinfo() is not supported.
EAI\_NODATA The host name supplied to getaddrinfo() did not provide any usable address data.
EAI\_NONAME The host name supplied to getaddrinfo() does not exist, or the address supplied to getnameinfo() is not associated with a host name and the `NI_NAMEREQD` flag was supplied.
EAI\_SERVICE The service name supplied to getaddrinfo() is not available for the socket type given in the $hints.
EXAMPLES
--------
###
Lookup for connect()
The getaddrinfo() function converts a hostname and a service name into a list of structures, each containing a potential way to connect() to the named service on the named host.
```
use IO::Socket;
use Socket qw(SOCK_STREAM getaddrinfo);
my %hints = (socktype => SOCK_STREAM);
my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
die "Cannot getaddrinfo - $err" if $err;
my $sock;
foreach my $ai (@res) {
my $candidate = IO::Socket->new();
$candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
or next;
$candidate->connect($ai->{addr})
or next;
$sock = $candidate;
last;
}
die "Cannot connect to localhost:echo" unless $sock;
$sock->print("Hello, world!\n");
print <$sock>;
```
Because a list of potential candidates is returned, the `while` loop tries each in turn until it finds one that succeeds both the socket() and connect() calls.
This function performs the work of the legacy functions gethostbyname(), getservbyname(), inet\_aton() and pack\_sockaddr\_in().
In practice this logic is better performed by <IO::Socket::IP>.
###
Making a human-readable string out of an address
The getnameinfo() function converts a socket address, such as returned by getsockname() or getpeername(), into a pair of human-readable strings representing the address and service name.
```
use IO::Socket::IP;
use Socket qw(getnameinfo);
my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
die "Cannot listen - $@";
my $socket = $server->accept or die "accept: $!";
my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
die "Cannot getnameinfo - $err" if $err;
print "The peer is connected from $hostname\n";
```
Since in this example only the hostname was used, the redundant conversion of the port number into a service name may be omitted by passing the `NIx_NOSERV` flag.
```
use Socket qw(getnameinfo NIx_NOSERV);
my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
```
This function performs the work of the legacy functions unpack\_sockaddr\_in(), inet\_ntoa(), gethostbyaddr() and getservbyport().
In practice this logic is better performed by <IO::Socket::IP>.
###
Resolving hostnames into IP addresses
To turn a hostname into a human-readable plain IP address use getaddrinfo() to turn the hostname into a list of socket structures, then getnameinfo() on each one to make it a readable IP address again.
```
use Socket qw(:addrinfo SOCK_RAW);
my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
die "Cannot getaddrinfo - $err" if $err;
while( my $ai = shift @res ) {
my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
die "Cannot getnameinfo - $err" if $err;
print "$ipaddr\n";
}
```
The `socktype` hint to getaddrinfo() filters the results to only include one socket type and protocol. Without this most OSes return three combinations, for `SOCK_STREAM`, `SOCK_DGRAM` and `SOCK_RAW`, resulting in triplicate output of addresses. The `NI_NUMERICHOST` flag to getnameinfo() causes it to return a string-formatted plain IP address, rather than reverse resolving it back into a hostname.
This combination performs the work of the legacy functions gethostbyname() and inet\_ntoa().
###
Accessing socket options
The many `SO_*` and other constants provide the socket option names for getsockopt() and setsockopt().
```
use IO::Socket::INET;
use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
or die "Cannot create socket: $@";
$socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
die "setsockopt: $!";
print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
" bytes\n";
print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
```
As a convenience, <IO::Socket>'s setsockopt() method will convert a number into a packed byte buffer, and getsockopt() will unpack a byte buffer of the correct size back into a number.
AUTHOR
------
This module was originally maintained in Perl core by the Perl 5 Porters.
It was extracted to dual-life on CPAN at version 1.95 by Paul Evans <[email protected]>
| programming_docs |
perl File::Spec::Win32 File::Spec::Win32
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Note For File::Spec::Win32 Maintainers](#Note-For-File::Spec::Win32-Maintainers)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::Win32 - methods for Win32 file specs
SYNOPSIS
--------
```
require File::Spec::Win32; # 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.
devnull Returns a string representation of the null device.
tmpdir Returns a string representation of the first existing directory from the following list:
```
$ENV{TMPDIR}
$ENV{TEMP}
$ENV{TMP}
SYS:/temp
C:\system\temp
C:/temp
/tmp
/
```
The SYS:/temp is preferred in Novell NetWare and the C:\system\temp for Symbian (the File::Spec::Win32 is used also for those platforms).
If running under taint mode, and if the environment variables are tainted, they are not used.
case\_tolerant MSWin32 case-tolerance depends on GetVolumeInformation() $ouFsFlags == FS\_CASE\_SENSITIVE, indicating the case significance when comparing file specifications. Since XP FS\_CASE\_SENSITIVE is effectively disabled for the NT subsubsystem. See <http://cygwin.com/ml/cygwin/2007-07/msg00891.html> Default: 1
file\_name\_is\_absolute As of right now, this returns 2 if the path is absolute with a volume, 1 if it's absolute with no volume, 0 otherwise.
catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename
canonpath No physical check on the filesystem, but a logical cleanup of a path. On UNIX eliminated successive slashes and successive "/.". On Win32 makes
```
dir1\dir2\dir3\..\..\dir4 -> \dir\dir4 and even
dir1\dir2\dir3\...\dir4 -> \dir\dir4
```
splitpath
```
($volume,$directories,$file) = File::Spec->splitpath( $path );
($volume,$directories,$file) = File::Spec->splitpath( $path,
$no_file );
```
Splits a path into volume, directory, and filename portions. Assumes that the last file is a path unless the path ends in '\\', '\\.', '\\..' or $no\_file is true. On Win32 this means that $no\_file true makes this return ( $volume, $path, '' ).
Separators accepted are \ and /.
Volumes can be drive letters or UNC sharenames (\\server\share).
The results can be passed to ["catpath"](#catpath) to get back a path equivalent to (usually identical to) the original path.
splitdir The opposite of [catdir()](File::Spec#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, leading empty and trailing directory entries can be returned, because these are significant on some OSs. So,
```
File::Spec->splitdir( "/a/b/c" );
```
Yields:
```
( '', 'a', 'b', '', 'c', '' )
```
catpath Takes volume, directory and file portions and returns an entire path. Under Unix, $volume is ignored, and this is just like catfile(). On other OSs, the $volume become significant.
###
Note For File::Spec::Win32 Maintainers
Novell NetWare inherits its File::Spec behaviour from File::Spec::Win32.
COPYRIGHT
---------
Copyright (c) 2004,2007 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.
perl ExtUtils::ParseXS::Constants ExtUtils::ParseXS::Constants
============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::ParseXS::Constants - Initialization values for some globals
SYNOPSIS
--------
```
use ExtUtils::ParseXS::Constants ();
$PrototypeRegexp = $ExtUtils::ParseXS::Constants::PrototypeRegexp;
```
DESCRIPTION
-----------
Initialization of certain non-subroutine variables in ExtUtils::ParseXS and some of its supporting packages has been moved into this package so that those values can be defined exactly once and then re-used in any package.
Nothing is exported. Use fully qualified variable names.
perl Tie::Array Tie::Array
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [AUTHOR](#AUTHOR)
NAME
----
Tie::Array - base class for tied arrays
SYNOPSIS
--------
```
package Tie::NewArray;
use Tie::Array;
@ISA = ('Tie::Array');
# mandatory methods
sub TIEARRAY { ... }
sub FETCH { ... }
sub FETCHSIZE { ... }
sub STORE { ... } # mandatory if elements writeable
sub STORESIZE { ... } # mandatory if elements can be added/deleted
sub EXISTS { ... } # mandatory if exists() expected to work
sub DELETE { ... } # mandatory if delete() expected to work
# optional methods - for efficiency
sub CLEAR { ... }
sub PUSH { ... }
sub POP { ... }
sub SHIFT { ... }
sub UNSHIFT { ... }
sub SPLICE { ... }
sub EXTEND { ... }
sub DESTROY { ... }
package Tie::NewStdArray;
use Tie::Array;
@ISA = ('Tie::StdArray');
# all methods provided by default
package main;
$object = tie @somearray,'Tie::NewArray';
$object = tie @somearray,'Tie::StdArray';
$object = tie @somearray,'Tie::NewStdArray';
```
DESCRIPTION
-----------
This module provides methods for array-tying classes. See <perltie> for a list of the functions required in order to tie an array to a package. The basic **Tie::Array** package provides stub `DESTROY`, and `EXTEND` methods that do nothing, stub `DELETE` and `EXISTS` methods that croak() if the delete() or exists() builtins are ever called on the tied array, and implementations of `PUSH`, `POP`, `SHIFT`, `UNSHIFT`, `SPLICE` and `CLEAR` in terms of basic `FETCH`, `STORE`, `FETCHSIZE`, `STORESIZE`.
The **Tie::StdArray** package provides efficient methods required for tied arrays which are implemented as blessed references to an "inner" perl array. It inherits from **Tie::Array**, and should cause tied arrays to behave exactly like standard arrays, allowing for selective overloading of methods.
For developers wishing to write their own tied arrays, the required methods are briefly defined below. See the <perltie> section for more detailed descriptive, as well as example code:
TIEARRAY classname, LIST The class method is invoked by the command `tie @array, classname`. Associates an array 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. The method should return an object of a class which provides the methods below.
STORE this, index, value Store datum *value* into *index* for the tied array associated with object *this*. If this makes the array larger then class's mapping of `undef` should be returned for new positions.
FETCH this, index Retrieve the datum in *index* for the tied array associated with object *this*.
FETCHSIZE this Returns the total number of items in the tied array associated with object *this*. (Equivalent to `scalar(@array)`).
STORESIZE this, count Sets the total number of items in the tied array associated with object *this* to be *count*. If this makes the array larger then class's mapping of `undef` should be returned for new positions. If the array becomes smaller then entries beyond count should be deleted.
EXTEND this, count Informative call that array is likely to grow to have *count* entries. Can be used to optimize allocation. This method need do nothing.
EXISTS this, key Verify that the element at index *key* exists in the tied array *this*.
The **Tie::Array** implementation is a stub that simply croaks.
DELETE this, key Delete the element at index *key* from the tied array *this*.
The **Tie::Array** implementation is a stub that simply croaks.
CLEAR this Clear (remove, delete, ...) all values from the tied array associated with object *this*.
DESTROY this Normal object destructor method.
PUSH this, LIST Append elements of LIST to the array.
POP this Remove last element of the array and return it.
SHIFT this Remove the first element of the array (shifting other elements down) and return it.
UNSHIFT this, LIST Insert LIST elements at the beginning of the array, moving existing elements up to make room.
SPLICE this, offset, length, LIST Perform the equivalent of `splice` on the array.
*offset* is optional and defaults to zero, negative values count back from the end of the array.
*length* is optional and defaults to rest of the array.
*LIST* may be empty.
Returns a list of the original *length* elements at *offset*.
CAVEATS
-------
There is no support at present for tied @ISA. There is a potential conflict between magic entries needed to notice setting of @ISA, and those needed to implement 'tie'.
AUTHOR
------
Nick Ing-Simmons <[email protected]>
perl Test::Builder::Tester Test::Builder::Tester
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Functions](#Functions)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [MAINTAINERS](#MAINTAINERS)
* [NOTES](#NOTES)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Test::Builder::Tester - test testsuites that have been built with Test::Builder
SYNOPSIS
--------
```
use Test::Builder::Tester tests => 1;
use Test::More;
test_out("not ok 1 - foo");
test_fail(+1);
fail("foo");
test_test("fail works");
```
DESCRIPTION
-----------
A module that helps you test testing modules that are built with <Test::Builder>.
The testing system is designed to be used by performing a three step process for each test you wish to test. This process starts with using `test_out` and `test_err` in advance to declare what the testsuite you are testing will output with <Test::Builder> to stdout and stderr.
You then can run the test(s) from your test suite that call <Test::Builder>. At this point the output of <Test::Builder> is safely captured by <Test::Builder::Tester> rather than being interpreted as real test output.
The final stage is to call `test_test` that will simply compare what you predeclared to what <Test::Builder> actually outputted, and report the results back with a "ok" or "not ok" (with debugging) to the normal output.
### Functions
These are the six methods that are exported as default.
test\_out test\_err Procedures for predeclaring the output that your test suite is expected to produce until `test_test` is called. These procedures automatically assume that each line terminates with "\n". So
```
test_out("ok 1","ok 2");
```
is the same as
```
test_out("ok 1\nok 2");
```
which is even the same as
```
test_out("ok 1");
test_out("ok 2");
```
Once `test_out` or `test_err` (or `test_fail` or `test_diag`) have been called, all further output from <Test::Builder> will be captured by <Test::Builder::Tester>. This means that you will not be able perform further tests to the normal output in the normal way until you call `test_test` (well, unless you manually meddle with the output filehandles)
test\_fail Because the standard failure message that <Test::Builder> produces whenever a test fails will be a common occurrence in your test error output, and because it has changed between Test::Builder versions, rather than forcing you to call `test_err` with the string all the time like so
```
test_err("# Failed test ($0 at line ".line_num(+1).")");
```
`test_fail` exists as a convenience function that can be called instead. It takes one argument, the offset from the current line that the line that causes the fail is on.
```
test_fail(+1);
```
This means that the example in the synopsis could be rewritten more simply as:
```
test_out("not ok 1 - foo");
test_fail(+1);
fail("foo");
test_test("fail works");
```
test\_diag As most of the remaining expected output to the error stream will be created by <Test::Builder>'s `diag` function, <Test::Builder::Tester> provides a convenience function `test_diag` that you can use instead of `test_err`.
The `test_diag` function prepends comment hashes and spacing to the start and newlines to the end of the expected output passed to it and adds it to the list of expected error output. So, instead of writing
```
test_err("# Couldn't open file");
```
you can write
```
test_diag("Couldn't open file");
```
Remember that <Test::Builder>'s diag function will not add newlines to the end of output and test\_diag will. So to check
```
Test::Builder->new->diag("foo\n","bar\n");
```
You would do
```
test_diag("foo","bar")
```
without the newlines.
test\_test Actually performs the output check testing the tests, comparing the data (with `eq`) that we have captured from <Test::Builder> against what was declared with `test_out` and `test_err`.
This takes name/value pairs that effect how the test is run.
title (synonym 'name', 'label') The name of the test that will be displayed after the `ok` or `not ok`.
skip\_out Setting this to a true value will cause the test to ignore if the output sent by the test to the output stream does not match that declared with `test_out`.
skip\_err Setting this to a true value will cause the test to ignore if the output sent by the test to the error stream does not match that declared with `test_err`.
As a convenience, if only one argument is passed then this argument is assumed to be the name of the test (as in the above examples.)
Once `test_test` has been run test output will be redirected back to the original filehandles that <Test::Builder> was connected to (probably STDOUT and STDERR,) meaning any further tests you run will function normally and cause success/errors for <Test::Harness>.
line\_num A utility function that returns the line number that the function was called on. You can pass it an offset which will be added to the result. This is very useful for working out the correct text of diagnostic functions that contain line numbers.
Essentially this is the same as the `__LINE__` macro, but the `line_num(+3)` idiom is arguably nicer.
In addition to the six exported functions there exists one function that can only be accessed with a fully qualified function call.
color When `test_test` is called and the output that your tests generate does not match that which you declared, `test_test` will print out debug information showing the two conflicting versions. As this output itself is debug information it can be confusing which part of the output is from `test_test` and which was the original output from your original tests. Also, it may be hard to spot things like extraneous whitespace at the end of lines that may cause your test to fail even though the output looks similar.
To assist you `test_test` can colour the background of the debug information to disambiguate the different types of output. The debug output will have its background coloured green and red. The green part represents the text which is the same between the executed and actual output, the red shows which part differs.
The `color` function determines if colouring should occur or not. Passing it a true or false value will enable or disable colouring respectively, and the function called with no argument will return the current setting.
To enable colouring from the command line, you can use the <Text::Builder::Tester::Color> module like so:
```
perl -Mlib=Text::Builder::Tester::Color test.t
```
Or by including the <Test::Builder::Tester::Color> module directly in the PERL5LIB.
BUGS
----
Test::Builder::Tester does not handle plans well. It has never done anything special with plans. This means that plans from outside Test::Builder::Tester will effect Test::Builder::Tester, worse plans when using Test::Builder::Tester will effect overall testing. At this point there are no plans to fix this bug as people have come to depend on it, and Test::Builder::Tester is now discouraged in favor of `Test2::API::intercept()`. See <https://github.com/Test-More/test-more/issues/667>
Calls `Test::Builder->no_ending` turning off the ending tests. This is needed as otherwise it will trip out because we've run more tests than we strictly should have and it'll register any failures we had that we were testing for as real failures.
The color function doesn't work unless <Term::ANSIColor> is compatible with your terminal. Additionally, <Win32::Console::ANSI> must be installed on windows platforms for color output.
Bugs (and requests for new features) can be reported to the author though GitHub: <https://github.com/Test-More/test-more/issues>
AUTHOR
------
Copyright Mark Fowler <[email protected]> 2002, 2004.
Some code taken from <Test::More> and <Test::Catch>, written by Michael G Schwern <[email protected]>. Hence, those parts Copyright Micheal G Schwern 2001. Used and distributed with permission.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
MAINTAINERS
-----------
Chad Granum <[email protected]> NOTES
-----
Thanks to Richard Clamp <[email protected]> for letting me use his testing system to try this module out on.
SEE ALSO
---------
<Test::Builder>, <Test::Builder::Tester::Color>, <Test::More>.
perl ExtUtils::Constant::XS ExtUtils::Constant::XS
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Constant::XS - generate C code for XS modules' constants.
SYNOPSIS
--------
```
require ExtUtils::Constant::XS;
```
DESCRIPTION
-----------
ExtUtils::Constant::XS overrides ExtUtils::Constant::Base to generate C code for XS modules' constants.
BUGS
----
Nothing is documented.
Probably others.
AUTHOR
------
Nicholas Clark <[email protected]> based on the code in `h2xs` by Larry Wall and others
perl Pod::Functions Pod::Functions
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Pod::Functions - Group Perl's functions a la perlfunc.pod
SYNOPSIS
--------
```
use Pod::Functions;
my @misc_ops = @{ $Kinds{ 'Misc' } };
my $misc_dsc = $Type_Description{ 'Misc' };
```
or
```
perl /path/to/lib/Pod/Functions.pm
```
This will print a grouped list of Perl's functions, like the ["Perl Functions by Category" in perlfunc](perlfunc#Perl-Functions-by-Category) section.
DESCRIPTION
-----------
It exports the following variables:
%Kinds This holds a hash-of-lists. Each list contains the functions in the category the key denotes.
%Type In this hash each key represents a function and the value is the category. The category can be a comma separated list.
%Flavor In this hash each key represents a function and the value is a short description of that function.
%Type\_Description In this hash each key represents a category of functions and the value is a short description of that category.
@Type\_Order This list of categories is used to produce the same order as the ["Perl Functions by Category" in perlfunc](perlfunc#Perl-Functions-by-Category) section.
perl TAP::Parser::Grammar TAP::Parser::Grammar
====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [set\_version](#set_version)
- [tokenize](#tokenize)
- [token\_types](#token_types)
- [syntax\_for](#syntax_for)
- [handler\_for](#handler_for)
* [TAP GRAMMAR](#TAP-GRAMMAR)
* [SUBCLASSING](#SUBCLASSING)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Grammar - A grammar for the Test Anything Protocol.
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Grammar;
my $grammar = $self->make_grammar({
iterator => $tap_parser_iterator,
parser => $tap_parser,
version => 12,
});
my $result = $grammar->tokenize;
```
DESCRIPTION
-----------
`TAP::Parser::Grammar` tokenizes lines from a <TAP::Parser::Iterator> and constructs <TAP::Parser::Result> subclasses to represent the tokens.
Do not attempt to use this class directly. It won't make sense. It's mainly here to ensure that we will be able to have pluggable grammars when TAP is expanded at some future date (plus, this stuff was really cluttering the parser).
METHODS
-------
###
Class Methods
#### `new`
```
my $grammar = TAP::Parser::Grammar->new({
iterator => $iterator,
parser => $parser,
version => $version,
});
```
Returns <TAP::Parser> grammar object that will parse the TAP stream from the specified iterator. Both `iterator` and `parser` are required arguments. If `version` is not set it defaults to `12` (see ["set\_version"](#set_version) for more details).
###
Instance Methods
#### `set_version`
```
$grammar->set_version(13);
```
Tell the grammar which TAP syntax version to support. The lowest supported version is 12. Although 'TAP version' isn't valid version 12 syntax it is accepted so that higher version numbers may be parsed.
#### `tokenize`
```
my $token = $grammar->tokenize;
```
This method will return a <TAP::Parser::Result> object representing the current line of TAP.
#### `token_types`
```
my @types = $grammar->token_types;
```
Returns the different types of tokens which this grammar can parse.
#### `syntax_for`
```
my $syntax = $grammar->syntax_for($token_type);
```
Returns a pre-compiled regular expression which will match a chunk of TAP corresponding to the token type. For example (not that you should really pay attention to this, `$grammar->syntax_for('comment')` will return `qr/^#(.*)/`.
#### `handler_for`
```
my $handler = $grammar->handler_for($token_type);
```
Returns a code reference which, when passed an appropriate line of TAP, returns the lexed token corresponding to that line. As a result, the basic TAP parsing loop looks similar to the following:
```
my @tokens;
my $grammar = TAP::Grammar->new;
LINE: while ( defined( my $line = $parser->_next_chunk_of_tap ) ) {
for my $type ( $grammar->token_types ) {
my $syntax = $grammar->syntax_for($type);
if ( $line =~ $syntax ) {
my $handler = $grammar->handler_for($type);
push @tokens => $grammar->$handler($line);
next LINE;
}
}
push @tokens => $grammar->_make_unknown_token($line);
}
```
TAP GRAMMAR
------------
**NOTE:** This grammar is slightly out of date. There's still some discussion about it and a new one will be provided when we have things better defined.
The <TAP::Parser> does not use a formal grammar because TAP is essentially a stream-based protocol. In fact, it's quite legal to have an infinite stream. For the same reason that we don't apply regexes to streams, we're not using a formal grammar here. Instead, we parse the TAP in lines.
For purposes for forward compatibility, any result which does not match the following grammar is currently referred to as <TAP::Parser::Result::Unknown>. It is *not* a parse error.
A formal grammar would look similar to the following:
```
(*
For the time being, I'm cheating on the EBNF by allowing
certain terms to be defined by POSIX character classes by
using the following syntax:
digit ::= [:digit:]
As far as I am aware, that's not valid EBNF. Sue me. I
didn't know how to write "char" otherwise (Unicode issues).
Suggestions welcome.
*)
tap ::= version? { comment | unknown } leading_plan lines
|
lines trailing_plan {comment}
version ::= 'TAP version ' positiveInteger {positiveInteger} "\n"
leading_plan ::= plan skip_directive? "\n"
trailing_plan ::= plan "\n"
plan ::= '1..' nonNegativeInteger
lines ::= line {line}
line ::= (comment | test | unknown | bailout ) "\n"
test ::= status positiveInteger? description? directive?
status ::= 'not '? 'ok '
description ::= (character - (digit | '#')) {character - '#'}
directive ::= todo_directive | skip_directive
todo_directive ::= hash_mark 'TODO' ' ' {character}
skip_directive ::= hash_mark 'SKIP' ' ' {character}
comment ::= hash_mark {character}
hash_mark ::= '#' {' '}
bailout ::= 'Bail out!' {character}
unknown ::= { (character - "\n") }
(* POSIX character classes and other terminals *)
digit ::= [:digit:]
character ::= ([:print:] - "\n")
positiveInteger ::= ( digit - '0' ) {digit}
nonNegativeInteger ::= digit {digit}
```
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
If you *really* want to subclass <TAP::Parser>'s grammar the best thing to do is read through the code. There's no easy way of summarizing it here.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Iterator>, <TAP::Parser::Result>,
| programming_docs |
perl IO::Compress::Bzip2 IO::Compress::Bzip2
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [bzip2 $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#bzip2-%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))
* [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::Bzip2 - Write bzip2 files/buffers
SYNOPSIS
--------
```
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error) ;
my $status = bzip2 $input => $output [,OPTS]
or die "bzip2 failed: $Bzip2Error\n";
my $z = IO::Compress::Bzip2->new( $output [,OPTS] )
or die "bzip2 failed: $Bzip2Error\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->close() ;
$Bzip2Error ;
# 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 bzip2 compressed data to files or buffer.
For reading bzip2 files/buffers, see the companion module <IO::Uncompress::Bunzip2>.
Functional Interface
---------------------
A top-level function, `bzip2`, 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::Bzip2 qw(bzip2 $Bzip2Error) ;
bzip2 $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "bzip2 failed: $Bzip2Error\n";
```
The functional interface needs Perl5.005 or better.
###
bzip2 $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`bzip2` 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 ">" `bzip2` 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 ">" `bzip2` 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 `bzip2` 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 `bzip2` 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 `bzip2` 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::Bzip2=bzip2 -e 'bzip2 \*STDIN => \*STDOUT' >output.bz2
```
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::Bzip2=bzip2 -e 'bzip2 "-" => "-"' >output.bz2
```
####
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.bz2`.
```
use strict ;
use warnings ;
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error) ;
my $input = "file1.txt";
bzip2 $input => "$input.bz2"
or die "bzip2 failed: $Bzip2Error\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::Bzip2 qw(bzip2 $Bzip2Error) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt" )
or die "Cannot open 'file1.txt': $!\n" ;
my $buffer ;
bzip2 $input => \$buffer
or die "bzip2 failed: $Bzip2Error\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::Bzip2 qw(bzip2 $Bzip2Error) ;
bzip2 '</my/home/*.txt>' => '<*.bz2>'
or die "bzip2 failed: $Bzip2Error\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::Bzip2 qw(bzip2 $Bzip2Error) ;
for my $input ( glob "/my/home/*.txt" )
{
my $output = "$input.bz2" ;
bzip2 $input => $output
or die "Error compressing '$input': $Bzip2Error\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for `IO::Compress::Bzip2` is shown below
```
my $z = IO::Compress::Bzip2->new( $output [,OPTS] )
or die "IO::Compress::Bzip2 failed: $Bzip2Error\n";
```
It returns an `IO::Compress::Bzip2` object on success and undef on failure. The variable `$Bzip2Error` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Compress::Bzip2 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::Bzip2`::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::Bzip2` 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.
`BlockSize100K => number`
Specify the number of 100K blocks bzip2 uses during compression.
Valid values are from 1 to 9, where 9 is best compression.
The default is 1.
`WorkFactor => number`
Specifies how much effort bzip2 should take before resorting to a slower fallback compression algorithm.
Valid values range from 0 to 250, where 0 means use the default value 30.
The default is 0.
`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;
```
Flushes any pending compressed data to the output file/buffer.
TODO
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::Bzip2 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::Bzip2 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.
Importing
---------
No symbolic constants are required by IO::Compress::Bzip2 at present.
:all Imports `bzip2` and `$Bzip2Error`. Same as doing this
```
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error) ;
```
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::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <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 Sys::Hostname Sys::Hostname
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
NAME
----
Sys::Hostname - Try every conceivable way to get hostname
SYNOPSIS
--------
```
use Sys::Hostname;
$host = hostname;
```
DESCRIPTION
-----------
Attempts several methods of getting the system hostname and then caches the result. It tries the first available of the C library's gethostname(), ``$Config{aphostname}``, uname(2), `syscall(SYS_gethostname)`, ``hostname``, ``uname -n``, and the file */com/host*. If all that fails it `croak`s.
All NULs, returns, and newlines are removed from the result.
AUTHOR
------
David Sundstrom <*[email protected]*>
Texas Instruments
XS code added by Greg Bacon <*[email protected]*>
| programming_docs |
perl Pod::Simple::Methody Pod::Simple::Methody
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHOD CALLING](#METHOD-CALLING)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Methody -- turn Pod::Simple events into method calls
SYNOPSIS
--------
```
require 5;
use strict;
package SomePodFormatter;
use base qw(Pod::Simple::Methody);
sub handle_text {
my($self, $text) = @_;
...
}
sub start_head1 {
my($self, $attrs) = @_;
...
}
sub end_head1 {
my($self) = @_;
...
}
```
...and start\_/end\_ methods for whatever other events you want to catch.
DESCRIPTION
-----------
This class is of interest to people writing Pod formatters based on Pod::Simple.
This class (which is very small -- read the source) overrides Pod::Simple's \_handle\_element\_start, \_handle\_text, and \_handle\_element\_end methods so that parser events are turned into method calls. (Otherwise, this is a subclass of <Pod::Simple> and inherits all its methods.)
You can use this class as the base class for a Pod formatter/processor.
METHOD CALLING
---------------
When Pod::Simple sees a "=head1 Hi there", for example, it basically does this:
```
$parser->_handle_element_start( "head1", \%attributes );
$parser->_handle_text( "Hi there" );
$parser->_handle_element_end( "head1" );
```
But if you subclass Pod::Simple::Methody, it will instead do this when it sees a "=head1 Hi there":
```
$parser->start_head1( \%attributes ) if $parser->can('start_head1');
$parser->handle_text( "Hi there" ) if $parser->can('handle_text');
$parser->end_head1() if $parser->can('end_head1');
```
If Pod::Simple sends an event where the element name has a dash, period, or colon, the corresponding method name will have a underscore in its place. For example, "foo.bar:baz" becomes start\_foo\_bar\_baz and end\_foo\_bar\_baz.
See the source for Pod::Simple::Text for an example of using this class.
SEE ALSO
---------
<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 IO::Uncompress::AnyInflate IO::Uncompress::AnyInflate
==========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [anyinflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#anyinflate-%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::AnyInflate - Uncompress zlib-based (zip, gzip) file/buffer
SYNOPSIS
--------
```
use IO::Uncompress::AnyInflate qw(anyinflate $AnyInflateError) ;
my $status = anyinflate $input => $output [,OPTS]
or die "anyinflate failed: $AnyInflateError\n";
my $z = IO::Uncompress::AnyInflate->new( $input [OPTS] )
or die "anyinflate failed: $AnyInflateError\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()
$AnyInflateError ;
# 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 in a number of formats that use the zlib compression library.
The formats supported are
RFC 1950
RFC 1951 (optionally)
gzip (RFC 1952) zip The module will auto-detect which, if any, of the supported compression formats is being used.
Functional Interface
---------------------
A top-level function, `anyinflate`, 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::AnyInflate qw(anyinflate $AnyInflateError) ;
anyinflate $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "anyinflate failed: $AnyInflateError\n";
```
The functional interface needs Perl5.005 or better.
###
anyinflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`anyinflate` 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 ">" `anyinflate` 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 ">" `anyinflate` 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 `anyinflate` 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 `anyinflate` 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 `anyinflate` 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::AnyInflate qw(anyinflate $AnyInflateError) ;
my $input = "file1.txt.Compressed";
my $output = "file1.txt";
anyinflate $input => $output
or die "anyinflate failed: $AnyInflateError\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::AnyInflate qw(anyinflate $AnyInflateError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.Compressed" )
or die "Cannot open 'file1.txt.Compressed': $!\n" ;
my $buffer ;
anyinflate $input => \$buffer
or die "anyinflate failed: $AnyInflateError\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::AnyInflate qw(anyinflate $AnyInflateError) ;
anyinflate '</my/home/*.txt.Compressed>' => '</my/home/#1.txt>'
or die "anyinflate failed: $AnyInflateError\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::AnyInflate qw(anyinflate $AnyInflateError) ;
for my $input ( glob "/my/home/*.txt.Compressed" )
{
my $output = $input;
$output =~ s/.Compressed// ;
anyinflate $input => $output
or die "Error compressing '$input': $AnyInflateError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::AnyInflate is shown below
```
my $z = IO::Uncompress::AnyInflate->new( $input [OPTS] )
or die "IO::Uncompress::AnyInflate failed: $AnyInflateError\n";
```
Returns an `IO::Uncompress::AnyInflate` object on success and undef on failure. The variable `$AnyInflateError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::AnyInflate 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::AnyInflate 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::AnyInflate 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.
If the input is an RFC 1950 data stream, the following will be checked:
1. The ADLER32 checksum field must be present.
2. The value of the ADLER32 field read must match the adler32 value of the uncompressed data actually contained in the file.
If the input is a gzip (RFC 1952) data stream, the following will be checked:
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.
`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.
`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).
### 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::AnyInflate 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::AnyInflate 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::AnyInflate at present.
:all Imports `anyinflate` and `$AnyInflateError`. Same as doing this
```
use IO::Uncompress::AnyInflate qw(anyinflate $AnyInflateError) ;
```
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::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::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::MY ExtUtils::MY
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::MY - ExtUtils::MakeMaker subclass for customization
SYNOPSIS
--------
```
# in your Makefile.PL
sub MY::whatever {
...
}
```
DESCRIPTION
-----------
**FOR INTERNAL USE ONLY**
ExtUtils::MY is a subclass of <ExtUtils::MM>. Its provided in your Makefile.PL for you to add and override MakeMaker functionality.
It also provides a convenient alias via the MY class.
ExtUtils::MY might turn out to be a temporary solution, but MY won't go away.
perl Pod::Text::Overstrike Pod::Text::Overstrike
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Text::Overstrike - Convert POD data to formatted overstrike text
SYNOPSIS
--------
```
use Pod::Text::Overstrike;
my $parser = Pod::Text::Overstrike->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::Overstrike is a simple subclass of Pod::Text that highlights output text using overstrike sequences, in a manner similar to nroff. Characters in bold text are overstruck (character, backspace, character) and characters in underlined text are converted to overstruck underscores (underscore, backspace, character). This format was originally designed for hard-copy terminals and/or line printers, yet is readable on soft-copy (CRT) terminals.
Overstruck text is best viewed by page-at-a-time programs that take advantage of the terminal's **stand-out** and *underline* capabilities, such as the less program on Unix.
Apart from the overstrike, it in all ways functions like Pod::Text. See <Pod::Text> for details and available options.
BUGS
----
Currently, the outermost formatting instruction wins, so for example underlined text inside a region of bold text is displayed as simply bold. There may be some better approach possible.
AUTHOR
------
Originally written by Joe Smith <[email protected]>, using the framework created by Russ Allbery <[email protected]>. Subsequently updated by Russ Allbery.
COPYRIGHT AND LICENSE
----------------------
Copyright 2000 by Joe Smith <[email protected]>
Copyright 2001, 2004, 2008, 2014, 2018-2019 by 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 Time::Local Time::Local
===========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [timelocal\_posix() and timegm\_posix()](#timelocal_posix()-and-timegm_posix())
+ [timelocal\_modern() and timegm\_modern()](#timelocal_modern()-and-timegm_modern())
+ [timelocal() and timegm()](#timelocal()-and-timegm())
+ [timelocal\_nocheck() and timegm\_nocheck()](#timelocal_nocheck()-and-timegm_nocheck())
+ [Year Value Interpretation](#Year-Value-Interpretation)
+ [Limits of time\_t](#Limits-of-time_t)
+ [Ambiguous Local Times (DST)](#Ambiguous-Local-Times-(DST))
+ [Non-Existent Local Times (DST)](#Non-Existent-Local-Times-(DST))
+ [Negative Epoch Values](#Negative-Epoch-Values)
* [IMPLEMENTATION](#IMPLEMENTATION)
* [AUTHORS EMERITUS](#AUTHORS-EMERITUS)
* [BUGS](#BUGS)
* [SOURCE](#SOURCE)
* [AUTHOR](#AUTHOR)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Time::Local - Efficiently compute time from local and GMT time
VERSION
-------
version 1.30
SYNOPSIS
--------
```
use Time::Local qw( timelocal_posix timegm_posix );
my $time = timelocal_posix( $sec, $min, $hour, $mday, $mon, $year );
my $time = timegm_posix( $sec, $min, $hour, $mday, $mon, $year );
```
DESCRIPTION
-----------
This module provides functions that are the inverse of built-in perl functions `localtime()` and `gmtime()`. They accept a date as a six-element array, and return the corresponding `time(2)` value in seconds since the system epoch (Midnight, January 1, 1970 GMT on Unix, for example). This value can be positive or negative, though POSIX only requires support for positive values, so dates before the system's epoch may not work on all operating systems.
It is worth drawing particular attention to the expected ranges for the values provided. The value for the day of the month is the actual day (i.e. 1..31), while the month is the number of months since January (0..11). This is consistent with the values returned from `localtime()` and `gmtime()`.
FUNCTIONS
---------
###
`timelocal_posix()` and `timegm_posix()`
These functions are the exact inverse of Perl's built-in `localtime` and `gmtime` functions. That means that calling `timelocal_posix( localtime($value) )` will always give you the same `$value` you started with. The same applies to `timegm_posix( gmtime($value) )`.
The one exception is when the value returned from `localtime()` represents an ambiguous local time because of a DST change. See the documentation below for more details.
These functions expect the year value to be the number of years since 1900, which is what the `localtime()` and `gmtime()` built-ins returns.
They perform range checking by default on the input `$sec`, `$min`, `$hour`, `$mday`, and `$mon` values and will croak (using `Carp::croak()`) if given a value outside the allowed ranges.
While it would be nice to make this the default behavior, that would almost certainly break a lot of code, so you must explicitly import these functions and use them instead of the default `timelocal()` and `timegm()`.
You are **strongly** encouraged to use these functions in any new code which uses this module. It will almost certainly make your code's behavior less surprising.
###
`timelocal_modern()` and `timegm_modern()`
When `Time::Local` was first written, it was a common practice to represent years as a two-digit value like `99` for `1999` or `1` for `2001`. This caused all sorts of problems (google "Y2K problem" if you're very young) and developers eventually realized that this was a terrible idea.
The default exports of `timelocal()` and `timegm()` do a complicated calculation when given a year value less than 1000. This leads to surprising results in many cases. See ["Year Value Interpretation"](#Year-Value-Interpretation) for details.
The `time*_modern()` functions do not do this year munging and simply take the year value as provided.
They perform range checking by default on the input `$sec`, `$min`, `$hour`, `$mday`, and `$mon` values and will croak (using `Carp::croak()`) if given a value outside the allowed ranges.
###
`timelocal()` and `timegm()`
This module exports two functions by default, `timelocal()` and `timegm()`.
They perform range checking by default on the input `$sec`, `$min`, `$hour`, `$mday`, and `$mon` values and will croak (using `Carp::croak()`) if given a value outside the allowed ranges.
**Warning: The year value interpretation that these functions and their nocheck variants use will almost certainly lead to bugs in your code, if not now, then in the future. You are strongly discouraged from using these in new code, and you should convert old code to using either the `*_posix` or `*_modern` functions if possible.**
###
`timelocal_nocheck()` and `timegm_nocheck()`
If you are working with data you know to be valid, you can use the "nocheck" variants, `timelocal_nocheck()` and `timegm_nocheck()`. These variants must be explicitly imported.
If you supply data which is not valid (month 27, second 1,000) the results will be unpredictable (so don't do that).
Note that my benchmarks show that this is just a 3% speed increase over the checked versions, so unless calling `Time::Local` is the hottest spot in your application, using these nocheck variants is unlikely to have much impact on your application.
###
Year Value Interpretation
**This does not apply to the `*_posix` or `*_modern` functions. Use those exports if you want to ensure consistent behavior as your code ages.**
Strictly speaking, the year should be specified in a form consistent with `localtime()`, i.e. the offset from 1900. In order to make the interpretation of the year easier for humans, however, who are more accustomed to seeing years as two-digit or four-digit values, the following conventions are followed:
* Years greater than 999 are interpreted as being the actual year, rather than the offset from 1900. Thus, 1964 would indicate the year Martin Luther King won the Nobel prize, not the year 3864.
* Years in the range 100..999 are interpreted as offset from 1900, so that 112 indicates 2012. This rule also applies to years less than zero (but see note below regarding date range).
* Years in the range 0..99 are interpreted as shorthand for years in the rolling "current century," defined as 50 years on either side of the current year. Thus, today, in 1999, 0 would refer to 2000, and 45 to 2045, but 55 would refer to 1955. Twenty years from now, 55 would instead refer to 2055. This is messy, but matches the way people currently think about two digit dates. Whenever possible, use an absolute four digit year instead.
The scheme above allows interpretation of a wide range of dates, particularly if 4-digit years are used. But it also means that the behavior of your code changes as time passes, because the rolling "current century" changes each year.
###
Limits of time\_t
On perl versions older than 5.12.0, the range of dates that can be actually be handled depends on the size of `time_t` (usually a signed integer) on the given platform. Currently, this is 32 bits for most systems, yielding an approximate range from Dec 1901 to Jan 2038.
Both `timelocal()` and `timegm()` croak if given dates outside the supported range.
As of version 5.12.0, perl has stopped using the time implementation of the operating system it's running on. Instead, it has its own implementation of those routines with a safe range of at least +/- 2\*\*52 (about 142 million years)
###
Ambiguous Local Times (DST)
Because of DST changes, there are many time zones where the same local time occurs for two different GMT times on the same day. For example, in the "Europe/Paris" time zone, the local time of 2001-10-28 02:30:00 can represent either 2001-10-28 00:30:00 GMT, **or** 2001-10-28 01:30:00 GMT.
When given an ambiguous local time, the timelocal() function will always return the epoch for the *earlier* of the two possible GMT times.
###
Non-Existent Local Times (DST)
When a DST change causes a locale clock to skip one hour forward, there will be an hour's worth of local times that don't exist. Again, for the "Europe/Paris" time zone, the local clock jumped from 2001-03-25 01:59:59 to 2001-03-25 03:00:00.
If the `timelocal()` function is given a non-existent local time, it will simply return an epoch value for the time one hour later.
###
Negative Epoch Values
On perl version 5.12.0 and newer, negative epoch values are fully supported.
On older versions of perl, negative epoch (`time_t`) values, which are not officially supported by the POSIX standards, are known not to work on some systems. These include MacOS (pre-OSX) and Win32.
On systems which do support negative epoch values, this module should be able to cope with dates before the start of the epoch, down the minimum value of time\_t for the system.
IMPLEMENTATION
--------------
These routines are quite efficient and yet are always guaranteed to agree with `localtime()` and `gmtime()`. We manage this by caching the start times of any months we've seen before. If we know the start time of the month, we can always calculate any time within the month. The start times are calculated using a mathematical formula. Unlike other algorithms that do multiple calls to `gmtime()`.
The `timelocal()` function is implemented using the same cache. We just assume that we're translating a GMT time, and then fudge it when we're done for the timezone and daylight savings arguments. Note that the timezone is evaluated for each date because countries occasionally change their official timezones. Assuming that `localtime()` corrects for these changes, this routine will also be correct.
AUTHORS EMERITUS
-----------------
This module is based on a Perl 4 library, timelocal.pl, that was included with Perl 4.036, and was most likely written by Tom Christiansen.
The current version was written by Graham Barr.
BUGS
----
The whole scheme for interpreting two-digit years can be considered a bug.
Bugs may be submitted at <https://github.com/houseabsolute/Time-Local/issues>.
There is a mailing list available for users of this distribution, <mailto:[email protected]>.
I am also usually active on IRC as 'autarch' on `irc://irc.perl.org`.
SOURCE
------
The source code repository for Time-Local can be found at <https://github.com/houseabsolute/Time-Local>.
AUTHOR
------
Dave Rolsky <[email protected]>
CONTRIBUTORS
------------
* Florian Ragwitz <[email protected]>
* J. Nick Koston <[email protected]>
* Unknown <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 1997 - 2020 by Graham Barr & Dave Rolsky.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
The full text of the license can be found in the *LICENSE* file included with this distribution.
perl perlhaiku perlhaiku
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [BUILD AND INSTALL](#BUILD-AND-INSTALL)
* [KNOWN PROBLEMS](#KNOWN-PROBLEMS)
* [CONTACT](#CONTACT)
NAME
----
perlhaiku - Perl version 5.10+ on Haiku
DESCRIPTION
-----------
This file contains instructions how to build Perl for Haiku and lists known problems.
BUILD AND INSTALL
------------------
The build procedure is completely standard:
```
./Configure -de
make
make install
```
Make perl executable and create a symlink for libperl:
```
chmod a+x /boot/common/bin/perl
cd /boot/common/lib; ln -s perl5/5.36.0/BePC-haiku/CORE/libperl.so .
```
Replace `5.36.0` with your respective version of Perl.
KNOWN PROBLEMS
---------------
The following problems are encountered with Haiku revision 28311:
* Perl cannot be compiled with threading support ATM.
* The *cpan/Socket/t/socketpair.t* test fails. More precisely: the subtests using datagram sockets fail. Unix datagram sockets aren't implemented in Haiku yet.
* A subtest of the *cpan/Sys-Syslog/t/syslog.t* test fails. This is due to Haiku not implementing */dev/log* support yet.
* The tests *dist/Net-Ping/t/450\_service.t* and *dist/Net-Ping/t/510\_ping\_udp.t* fail. This is due to bugs in Haiku's network stack implementation.
CONTACT
-------
For Haiku specific problems contact the HaikuPorts developers: <http://ports.haiku-files.org/>
The initial Haiku port was done by Ingo Weinhold <ingo\[email protected]>.
Last update: 2008-10-29
perl File::Spec::Epoc File::Spec::Epoc
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::Epoc - methods for Epoc file specs
SYNOPSIS
--------
```
require File::Spec::Epoc; # 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.
This package is still a work in progress. ;-)
canonpath() No physical check on the filesystem, but a logical cleanup of a path. On UNIX eliminated successive slashes and successive "/.".
AUTHOR
------
[email protected]
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.
SEE ALSO
---------
See <File::Spec> and <File::Spec::Unix>. This package overrides the implementation of these methods, not the semantics.
perl CPAN::Meta::Spec CPAN::Meta::Spec
================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [TERMINOLOGY](#TERMINOLOGY)
* [DATA TYPES](#DATA-TYPES)
+ [Boolean](#Boolean)
+ [String](#String)
+ [List](#List)
+ [Map](#Map)
+ [License String](#License-String)
+ [URL](#URL)
+ [Version](#Version)
+ [Version Range](#Version-Range)
* [STRUCTURE](#STRUCTURE)
+ [REQUIRED FIELDS](#REQUIRED-FIELDS)
- [abstract](#abstract)
- [author](#author)
- [dynamic\_config](#dynamic_config)
- [generated\_by](#generated_by)
- [license](#license)
- [meta-spec](#meta-spec)
- [name](#name)
- [release\_status](#release_status)
- [version](#version1)
+ [OPTIONAL FIELDS](#OPTIONAL-FIELDS)
- [description](#description)
- [keywords](#keywords)
- [no\_index](#no_index)
- [optional\_features](#optional_features)
- [prereqs](#prereqs1)
- [provides](#provides)
- [resources](#resources)
+ [DEPRECATED FIELDS](#DEPRECATED-FIELDS)
- [build\_requires](#build_requires)
- [configure\_requires](#configure_requires)
- [conflicts](#conflicts)
- [distribution\_type](#distribution_type)
- [license\_uri](#license_uri)
- [private](#private)
- [recommends](#recommends)
- [requires](#requires)
* [VERSION NUMBERS](#VERSION-NUMBERS)
+ [Version Formats](#Version-Formats)
+ [Version Ranges](#Version-Ranges)
* [PREREQUISITES](#PREREQUISITES)
+ [Prereq Spec](#Prereq-Spec)
- [Phases](#Phases)
- [Relationships](#Relationships)
+ [Merging and Resolving Prerequisites](#Merging-and-Resolving-Prerequisites)
* [SERIALIZATION](#SERIALIZATION)
* [NOTES FOR IMPLEMENTORS](#NOTES-FOR-IMPLEMENTORS)
+ [Extracting Version Numbers from Perl Modules](#Extracting-Version-Numbers-from-Perl-Modules)
+ [Comparing Version Numbers](#Comparing-Version-Numbers)
+ [Prerequisites for dynamically configured distributions](#Prerequisites-for-dynamically-configured-distributions)
+ [Indexing distributions a la PAUSE](#Indexing-distributions-a-la-PAUSE)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Spec - specification for CPAN distribution metadata
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
my $distmeta = {
name => 'Module-Build',
abstract => 'Build and install Perl modules',
description => "Module::Build is a system for "
. "building, testing, and installing Perl modules. "
. "It is meant to ... blah blah blah ...",
version => '0.36',
release_status => 'stable',
author => [
'Ken Williams <[email protected]>',
'Module-Build List <[email protected]>', # additional contact
],
license => [ 'perl_5' ],
prereqs => {
runtime => {
requires => {
'perl' => '5.006',
'ExtUtils::Install' => '0',
'File::Basename' => '0',
'File::Compare' => '0',
'IO::File' => '0',
},
recommends => {
'Archive::Tar' => '1.00',
'ExtUtils::Install' => '0.3',
'ExtUtils::ParseXS' => '2.02',
},
},
build => {
requires => {
'Test::More' => '0',
},
}
},
resources => {
license => ['http://dev.perl.org/licenses/'],
},
optional_features => {
domination => {
description => 'Take over the world',
prereqs => {
develop => { requires => { 'Genius::Evil' => '1.234' } },
runtime => { requires => { 'Machine::Weather' => '2.0' } },
},
},
},
dynamic_config => 1,
keywords => [ qw/ toolchain cpan dual-life / ],
'meta-spec' => {
version => '2',
url => 'https://metacpan.org/pod/CPAN::Meta::Spec',
},
generated_by => 'Module::Build version 0.36',
};
```
DESCRIPTION
-----------
This document describes version 2 of the CPAN distribution metadata specification, also known as the "CPAN Meta Spec".
Revisions of this specification for typo corrections and prose clarifications may be issued as CPAN::Meta::Spec 2.*x*. These revisions will never change semantics or add or remove specified behavior.
Distribution metadata describe important properties of Perl distributions. Distribution building tools like Module::Build, Module::Install, ExtUtils::MakeMaker or Dist::Zilla should create a metadata file in accordance with this specification and include it with the distribution for use by automated tools that index, examine, package or install Perl distributions.
TERMINOLOGY
-----------
distribution This is the primary object described by the metadata. 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 contained in a single file. Modules usually contain one or more packages and are often referred to by the name of a primary package that can be mapped to the file name. For example, one might refer to `File::Spec` instead of *File/Spec.pm*
package This refers to a namespace declared with the Perl `package` statement. In Perl, packages often have a version number property given by the `$VERSION` variable in the namespace.
consumer This refers to code that reads a metadata file, deserializes it into a data structure in memory, or interprets a data structure of metadata elements.
producer This refers to code that constructs a metadata data structure, serializes into a bytestream and/or writes it to disk.
must, should, may, etc. These terms are interpreted as described in IETF RFC 2119.
DATA TYPES
-----------
Fields in the ["STRUCTURE"](#STRUCTURE) section describe data elements, each of which has an associated data type as described herein. There are four primitive types: Boolean, String, List and Map. Other types are subtypes of primitives and define compound data structures or define constraints on the values of a data element.
### Boolean
A *Boolean* is used to provide a true or false value. It **must** be represented as a defined value that is either "1" or "0" or stringifies to those values.
### String
A *String* is data element containing a non-zero length sequence of Unicode characters, such as an ordinary Perl scalar that is not a reference.
### List
A *List* is an ordered collection of zero or more data elements. Elements of a List may be of mixed types.
Producers **must** represent List elements using a data structure which unambiguously indicates that multiple values are possible, such as a reference to a Perl array (an "arrayref").
Consumers expecting a List **must** consider a String as equivalent to a List of length 1.
### Map
A *Map* is an unordered collection of zero or more data elements ("values"), indexed by associated String elements ("keys"). The Map's value elements may be of mixed types.
###
License String
A *License String* is a subtype of String with a restricted set of values. Valid values are described in detail in the description of the ["license"](#license) field.
### URL
*URL* is a subtype of String containing a Uniform Resource Locator or Identifier. [ This type is called URL and not URI for historical reasons. ]
### Version
A *Version* is a subtype of String containing a value that describes the version number of packages or distributions. Restrictions on format are described in detail in the ["Version Formats"](#Version-Formats) section.
###
Version Range
The *Version Range* type is a subtype of String. It describes a range of Versions that may be present or installed to fulfill prerequisites. It is specified in detail in the ["Version Ranges"](#Version-Ranges) section.
STRUCTURE
---------
The metadata structure is a data element of type Map. This section describes valid keys within the Map.
Any keys not described in this specification document (whether top-level or within compound data structures described herein) are considered *custom keys* and **must** begin with an "x" or "X" and be followed by an underscore; i.e. they must match the pattern: `qr{\Ax_}i`. If a custom key refers to a compound data structure, subkeys within it do not need an "x\_" or "X\_" prefix.
Consumers of metadata may ignore any or all custom keys. All other keys not described herein are invalid and should be ignored by consumers. Producers must not generate or output invalid keys.
For each key, an example is provided followed by a description. The description begins with the version of spec in which the key was added or in which the definition was modified, whether the key is *required* or *optional* and the data type of the corresponding data element. These items are in parentheses, brackets and braces, respectively.
If a data type is a Map or Map subtype, valid subkeys will be described as well.
Some fields are marked *Deprecated*. These are shown for historical context and must not be produced in or consumed from any metadata structure of version 2 or higher.
###
REQUIRED FIELDS
#### abstract
Example:
```
abstract => 'Build and install Perl modules'
```
(Spec 1.2) [required] {String}
This is a short description of the purpose of the distribution.
#### author
Example:
```
author => [ 'Ken Williams <[email protected]>' ]
```
(Spec 1.2) [required] {List of one or more Strings}
This List indicates the person(s) to contact concerning the distribution. The preferred form of the contact string is:
```
contact-name <email-address>
```
This field provides a general contact list independent of other structured fields provided within the ["resources"](#resources) field, such as `bugtracker`. The addressee(s) can be contacted for any purpose including but not limited to (security) problems with the distribution, questions about the distribution or bugs in the distribution.
A distribution's original author is usually the contact listed within this field. Co-maintainers, successor maintainers or mailing lists devoted to the distribution may also be listed in addition to or instead of the original author.
#### dynamic\_config
Example:
```
dynamic_config => 1
```
(Spec 2) [required] {Boolean}
A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed to determine prerequisites.
This field should be set to a true value if the distribution performs some dynamic configuration (asking questions, sensing the environment, etc.) as part of its configuration. This field should be set to a false value to indicate that prerequisites included in metadata may be considered final and valid for static analysis.
Note: when this field is true, post-configuration prerequisites are not guaranteed to bear any relation whatsoever to those stated in the metadata, and relying on them doing so is an error. See also ["Prerequisites for dynamically configured distributions"](#Prerequisites-for-dynamically-configured-distributions) in the implementors' notes.
This field explicitly **does not** indicate whether installation may be safely performed without using a Makefile or Build file, as there may be special files to install or custom installation targets (e.g. for dual-life modules that exist on CPAN as well as in the Perl core). This field only defines whether or not prerequisites are exactly as given in the metadata.
#### generated\_by
Example:
```
generated_by => 'Module::Build version 0.36'
```
(Spec 1.0) [required] {String}
This field indicates the tool that was used to create this metadata. There are no defined semantics for this field, but it is traditional to use a string in the form "Generating::Package version 1.23" or the author's name, if the file was generated by hand.
#### license
Example:
```
license => [ 'perl_5' ]
license => [ 'apache_2_0', 'mozilla_1_0' ]
```
(Spec 2) [required] {List of one or more License Strings}
One or more licenses that apply to some or all of the files in the distribution. If multiple licenses are listed, the distribution documentation should be consulted to clarify the interpretation of multiple licenses.
The following list of license strings are valid:
```
string description
------------- -----------------------------------------------
agpl_3 GNU Affero General Public License, Version 3
apache_1_1 Apache Software License, Version 1.1
apache_2_0 Apache License, Version 2.0
artistic_1 Artistic License, (Version 1)
artistic_2 Artistic License, Version 2.0
bsd BSD License (three-clause)
freebsd FreeBSD License (two-clause)
gfdl_1_2 GNU Free Documentation License, Version 1.2
gfdl_1_3 GNU Free Documentation License, Version 1.3
gpl_1 GNU General Public License, Version 1
gpl_2 GNU General Public License, Version 2
gpl_3 GNU General Public License, Version 3
lgpl_2_1 GNU Lesser General Public License, Version 2.1
lgpl_3_0 GNU Lesser General Public License, Version 3.0
mit MIT (aka X11) License
mozilla_1_0 Mozilla Public License, Version 1.0
mozilla_1_1 Mozilla Public License, Version 1.1
openssl OpenSSL License
perl_5 The Perl 5 License (Artistic 1 & GPL 1 or later)
qpl_1_0 Q Public License, Version 1.0
ssleay Original SSLeay License
sun Sun Internet Standards Source License (SISSL)
zlib zlib License
```
The following license strings are also valid and indicate other licensing not described above:
```
string description
------------- -----------------------------------------------
open_source Other Open Source Initiative (OSI) approved license
restricted Requires special permission from copyright holder
unrestricted Not an OSI approved license, but not restricted
unknown License not provided in metadata
```
All other strings are invalid in the license field.
####
meta-spec
Example:
```
'meta-spec' => {
version => '2',
url => 'http://search.cpan.org/perldoc?CPAN::Meta::Spec',
}
```
(Spec 1.2) [required] {Map}
This field indicates the version of the CPAN Meta Spec that should be used to interpret the metadata. Consumers must check this key as soon as possible and abort further metadata processing if the meta-spec version is not supported by the consumer.
The following keys are valid, but only `version` is required.
version This subkey gives the integer *Version* of the CPAN Meta Spec against which the document was generated.
url This is a *URL* of the metadata specification document corresponding to the given version. This is strictly for human-consumption and should not impact the interpretation of the document.
For the version 2 spec, either of these are recommended:
* `https://metacpan.org/pod/CPAN::Meta::Spec`
* `http://search.cpan.org/perldoc?CPAN::Meta::Spec`
#### name
Example:
```
name => 'Module-Build'
```
(Spec 1.0) [required] {String}
This field is the name of the distribution. This is often created by taking the "main package" in the distribution and changing `::` to `-`, but the name may be completely unrelated to the packages within the distribution. For example, <LWP::UserAgent> is distributed as part of the distribution name "libwww-perl".
#### release\_status
Example:
```
release_status => 'stable'
```
(Spec 2) [required] {String}
This field provides the release status of this distribution. If the `version` field contains an underscore character, then `release_status` **must not** be "stable."
The `release_status` field **must** have one of the following values:
stable This indicates an ordinary, "final" release that should be indexed by PAUSE or other indexers.
testing This indicates a "beta" release that is substantially complete, but has an elevated risk of bugs and requires additional testing. The distribution should not be installed over a stable release without an explicit request or other confirmation from a user. This release status may also be used for "release candidate" versions of a distribution.
unstable This indicates an "alpha" release that is under active development, but has been released for early feedback or testing and may be missing features or may have serious bugs. The distribution should not be installed over a stable release without an explicit request or other confirmation from a user.
Consumers **may** use this field to determine how to index the distribution for CPAN or other repositories in addition to or in replacement of heuristics based on version number or file name.
#### version
Example:
```
version => '0.36'
```
(Spec 1.0) [required] {Version}
This field gives the version of the distribution to which the metadata structure refers.
###
OPTIONAL FIELDS
#### description
Example:
```
description => "Module::Build is a system for "
. "building, testing, and installing Perl modules. "
. "It is meant to ... blah blah blah ...",
```
(Spec 2) [optional] {String}
A longer, more complete description of the purpose or intended use of the distribution than the one provided by the `abstract` key.
#### keywords
Example:
```
keywords => [ qw/ toolchain cpan dual-life / ]
```
(Spec 1.1) [optional] {List of zero or more Strings}
A List of keywords that describe this distribution. Keywords **must not** include whitespace.
#### no\_index
Example:
```
no_index => {
file => [ 'My/Module.pm' ],
directory => [ 'My/Private' ],
package => [ 'My::Module::Secret' ],
namespace => [ 'My::Module::Sample' ],
}
```
(Spec 1.2) [optional] {Map}
This Map describes any files, directories, packages, and namespaces that are private to the packaging or implementation of the distribution and should be ignored by indexing or search tools. Note that this is a list of exclusions, and the spec does not define what to *include* - see ["Indexing distributions a la PAUSE"](#Indexing-distributions-a-la-PAUSE) in the implementors notes for more information.
Valid subkeys are as follows:
file A *List* of relative paths to files. Paths **must be** specified with unix conventions.
directory A *List* of relative paths to directories. Paths **must be** specified with unix conventions.
[ Note: previous editions of the spec had `dir` instead of `directory` ]
package A *List* of package names.
namespace A *List* of package namespaces, where anything below the namespace must be ignored, but *not* the namespace itself.
In the example above for `no_index`, `My::Module::Sample::Foo` would be ignored, but `My::Module::Sample` would not.
#### optional\_features
Example:
```
optional_features => {
sqlite => {
description => 'Provides SQLite support',
prereqs => {
runtime => {
requires => {
'DBD::SQLite' => '1.25'
}
}
}
}
}
```
(Spec 2) [optional] {Map}
This Map describes optional features with incremental prerequisites. Each key of the `optional_features` Map is a String used to identify the feature and each value is a Map with additional information about the feature. Valid subkeys include:
description This is a String describing the feature. Every optional feature should provide a description
prereqs This entry is required and has the same structure as that of the `["prereqs"](#prereqs)` key. It provides a list of package requirements that must be satisfied for the feature to be supported or enabled.
There is one crucial restriction: the prereqs of an optional feature **must not** include `configure` phase prereqs.
Consumers **must not** include optional features as prerequisites without explicit instruction from users (whether via interactive prompting, a function parameter or a configuration value, etc. ).
If an optional feature is used by a consumer to add additional prerequisites, the consumer should merge the optional feature prerequisites into those given by the `prereqs` key using the same semantics. See ["Merging and Resolving Prerequisites"](#Merging-and-Resolving-Prerequisites) for details on merging prerequisites.
*Suggestion for disuse:* Because there is currently no way for a distribution to specify a dependency on an optional feature of another dependency, the use of `optional_feature` is discouraged. Instead, create a separate, installable distribution that ensures the desired feature is available. For example, if `Foo::Bar` has a `Baz` feature, release a separate `Foo-Bar-Baz` distribution that satisfies requirements for the feature.
#### prereqs
Example:
```
prereqs => {
runtime => {
requires => {
'perl' => '5.006',
'File::Spec' => '0.86',
'JSON' => '2.16',
},
recommends => {
'JSON::XS' => '2.26',
},
suggests => {
'Archive::Tar' => '0',
},
},
build => {
requires => {
'Alien::SDL' => '1.00',
},
},
test => {
recommends => {
'Test::Deep' => '0.10',
},
}
}
```
(Spec 2) [optional] {Map}
This is a Map that describes all the prerequisites of the distribution. The keys are phases of activity, such as `configure`, `build`, `test` or `runtime`. Values are Maps in which the keys name the type of prerequisite relationship such as `requires`, `recommends`, or `suggests` and the value provides a set of prerequisite relations. The set of relations **must** be specified as a Map of package names to version ranges.
The full definition for this field is given in the ["Prereq Spec"](#Prereq-Spec) section.
#### 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.2) [optional] {Map}
This describes all packages provided by this distribution. This information is used by distribution and automation mechanisms like PAUSE, CPAN, metacpan.org and search.cpan.org to build indexes saying in which distribution various packages can be found.
The keys of `provides` are package names that can be found within the distribution. If a package name key is provided, it must have a Map with the following valid subkeys:
file This field is required. It must contain a Unix-style relative file path from the root of the distribution directory to a file that contains or generates the package. It may be given as `META.yml` or `META.json` to claim a package for indexing without needing a `*.pm`.
version If it exists, this field must contains a *Version* String for the package. If the package does not have a `$VERSION`, this field must be omitted.
#### resources
Example:
```
resources => {
license => [ 'http://dev.perl.org/licenses/' ],
homepage => 'http://sourceforge.net/projects/module-build',
bugtracker => {
web => 'http://rt.cpan.org/Public/Dist/Display.html?Name=CPAN-Meta',
mailto => '[email protected]',
},
repository => {
url => 'git://github.com/dagolden/cpan-meta.git',
web => 'http://github.com/dagolden/cpan-meta',
type => 'git',
},
x_twitter => 'http://twitter.com/cpan_linked/',
}
```
(Spec 2) [optional] {Map}
This field describes resources related to this distribution.
Valid subkeys include:
homepage The official home of this project on the web.
license A List of *URL*'s that relate to this distribution's license. As with the top-level `license` field, distribution documentation should be consulted to clarify the interpretation of multiple licenses provided here.
bugtracker This entry describes the bug tracking system for this distribution. It is a Map with the following valid keys:
```
web - a URL pointing to a web front-end for the bug tracker
mailto - an email address to which bugs can be sent
```
repository This entry describes the source control repository for this distribution. It is a Map with the following valid keys:
```
url - a URL pointing to the repository itself
web - a URL pointing to a web front-end for the repository
type - a lowercase string indicating the VCS used
```
Because a url like `http://myrepo.example.com/` is ambiguous as to type, producers should provide a `type` whenever a `url` key is given. The `type` field should be the name of the most common program used to work with the repository, e.g. `git`, `svn`, `cvs`, `darcs`, `bzr` or `hg`.
###
DEPRECATED FIELDS
#### build\_requires
*(Deprecated in Spec 2)* [optional] {String}
Replaced by `prereqs`
#### configure\_requires
*(Deprecated in Spec 2)* [optional] {String}
Replaced by `prereqs`
#### conflicts
*(Deprecated in Spec 2)* [optional] {String}
Replaced by `prereqs`
#### distribution\_type
*(Deprecated in Spec 2)* [optional] {String}
This field indicated 'module' or 'script' but was considered meaningless, since many distributions are hybrids of several kinds of things.
#### license\_uri
*(Deprecated in Spec 1.2)* [optional] {URL}
Replaced by `license` in `resources`
#### private
*(Deprecated in Spec 1.2)* [optional] {Map}
This field has been renamed to ["no\_index"](#no_index).
#### recommends
*(Deprecated in Spec 2)* [optional] {String}
Replaced by `prereqs`
#### requires
*(Deprecated in Spec 2)* [optional] {String}
Replaced by `prereqs`
VERSION NUMBERS
----------------
###
Version Formats
This section defines the Version type, used by several fields in the CPAN Meta Spec.
Version numbers must be treated as strings, not numbers. For example, `1.200` **must not** be serialized as `1.2`. Version comparison should be delegated to the Perl <version> module, version 0.80 or newer.
Unless otherwise specified, version numbers **must** appear in one of two formats:
Decimal versions Decimal versions are regular "decimal numbers", with some limitations. They **must** be non-negative and **must** begin and end with a digit. A single underscore **may** be included, but **must** be between two digits. They **must not** use exponential notation ("1.23e-2").
```
version => '1.234' # OK
version => '1.23_04' # OK
version => '1.23_04_05' # Illegal
version => '1.' # Illegal
version => '.1' # Illegal
```
Dotted-integer versions Dotted-integer (also known as dotted-decimal) versions consist of positive integers separated by full stop characters (i.e. "dots", "periods" or "decimal points"). This are equivalent in format to Perl "v-strings", with some additional restrictions on form. They must be given in "normal" form, which has a leading "v" character and at least three integer components. To retain a one-to-one mapping with decimal versions, all components after the first **should** be restricted to the range 0 to 999. The final component **may** be separated by an underscore character instead of a period.
```
version => 'v1.2.3' # OK
version => 'v1.2_3' # OK
version => 'v1.2.3.4' # OK
version => 'v1.2.3_4' # OK
version => 'v2009.10.31' # OK
version => 'v1.2' # Illegal
version => '1.2.3' # Illegal
version => 'v1.2_3_4' # Illegal
version => 'v1.2009.10.31' # Not recommended
```
###
Version Ranges
Some fields (prereq, optional\_features) indicate the particular version(s) of some other module that may be required as a prerequisite. This section details the Version Range type used to provide this information.
The simplest format for a Version Range 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`.
Alternatively, a version range **may** 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.
PREREQUISITES
-------------
###
Prereq Spec
The `prereqs` key in the top-level metadata and within `optional_features` define the relationship between a distribution and other packages. The prereq spec structure is a hierarchical data structure which divides prerequisites into *Phases* of activity in the installation process and *Relationships* that indicate how prerequisites should be resolved.
For example, to specify that `Data::Dumper` is `required` during the `test` phase, this entry would appear in the distribution metadata:
```
prereqs => {
test => {
requires => {
'Data::Dumper' => '2.00'
}
}
}
```
#### Phases
Requirements for regular use must be listed in the `runtime` phase. Other requirements should be listed in the earliest stage in which they are required and consumers must accumulate and satisfy requirements across phases before executing the activity. For example, `build` requirements must also be available during the `test` phase.
```
before action requirements that must be met
---------------- --------------------------------
perl Build.PL configure
perl Makefile.PL
make configure, runtime, build
Build
make test configure, runtime, build, test
Build test
```
Consumers that install the distribution must ensure that *runtime* requirements are also installed and may install dependencies from other phases.
```
after action requirements that must be met
---------------- --------------------------------
make install runtime
Build install
```
configure The configure phase occurs before any dynamic configuration has been attempted. Libraries required by the configure phase **must** be available for use before the distribution building tool has been executed.
build The build phase is when the distribution's source code is compiled (if necessary) and otherwise made ready for installation.
test The test phase is when the distribution's automated test suite is run. Any library that is needed only for testing and not for subsequent use should be listed here.
runtime The runtime phase refers not only to when the distribution's contents are installed, but also to its continued use. Any library that is a prerequisite for regular use of this distribution should be indicated here.
develop The develop phase's prereqs are libraries needed to work on the distribution's source code as its author does. These tools might be needed to build a release tarball, to run author-only tests, or to perform other tasks related to developing new versions of the distribution.
#### Relationships
requires These dependencies **must** be installed for proper completion of the phase.
recommends Recommended dependencies are *strongly* encouraged and should be satisfied except in resource constrained environments.
suggests These dependencies are optional, but are suggested for enhanced operation of the described distribution.
conflicts These libraries cannot be installed when the phase is in operation. This is a very rare situation, and the `conflicts` relationship should be used with great caution, or not at all.
###
Merging and Resolving Prerequisites
Whenever metadata consumers merge prerequisites, either from different phases or from `optional_features`, they should merged in a way which preserves the intended semantics of the prerequisite structure. Generally, this means concatenating the version specifications using commas, as described in the ["Version Ranges"](#Version-Ranges) section.
Another subtle error that can occur in resolving prerequisites comes from the way that modules in prerequisites are indexed to distribution files on CPAN. When a module is deleted from a distribution, prerequisites calling for that module could indicate an older distribution should be installed, potentially overwriting files from a newer distribution.
For example, as of Oct 31, 2009, the CPAN index file contained these module-distribution mappings:
```
Class::MOP 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz
Class::MOP::Class 0.94 D/DR/DROLSKY/Class-MOP-0.94.tar.gz
Class::MOP::Class::Immutable 0.04 S/ST/STEVAN/Class-MOP-0.36.tar.gz
```
Consider the case where "Class::MOP" 0.94 is installed. If a distribution specified "Class::MOP::Class::Immutable" as a prerequisite, it could result in Class-MOP-0.36.tar.gz being installed, overwriting any files from Class-MOP-0.94.tar.gz.
Consumers of metadata **should** test whether prerequisites would result in installed module files being "downgraded" to an older version and **may** warn users or ignore the prerequisite that would cause such a result.
SERIALIZATION
-------------
Distribution metadata should be serialized (as a hashref) as JSON-encoded data and packaged with distributions as the file *META.json*.
In the past, the distribution metadata structure had been packed with distributions as *META.yml*, a file in the YAML Tiny format (for which, see <YAML::Tiny>). Tools that consume distribution metadata from disk should be capable of loading *META.yml*, but should prefer *META.json* if both are found.
NOTES FOR IMPLEMENTORS
-----------------------
###
Extracting Version Numbers from Perl Modules
To get the version number from a Perl module, consumers should use the `MM->parse_version($file)` method provided by <ExtUtils::MakeMaker> or <Module::Metadata>. For example, for the module given by `$mod`, the version may be retrieved in one of the following ways:
```
# via ExtUtils::MakeMaker
my $file = MM->_installed_file_for_module($mod);
my $version = MM->parse_version($file)
```
The private `_installed_file_for_module` method may be replaced with other methods for locating a module in `@INC`.
```
# via Module::Metadata
my $info = Module::Metadata->new_from_module($mod);
my $version = $info->version;
```
If only a filename is available, the following approach may be used:
```
# via Module::Build
my $info = Module::Metadata->new_from_file($file);
my $version = $info->version;
```
###
Comparing Version Numbers
The <version> module provides the most reliable way to compare version numbers in all the various ways they might be provided or might exist within modules. Given two strings containing version numbers, `$v1` and `$v2`, they should be converted to `version` objects before using ordinary comparison operators. For example:
```
use version;
if ( version->new($v1) <=> version->new($v2) ) {
print "Versions are not equal\n";
}
```
If the only comparison needed is whether an installed module is of a sufficiently high version, a direct test may be done using the string form of `eval` and the `use` function. For example, for module `$mod` and version prerequisite `$prereq`:
```
if ( eval "use $mod $prereq (); 1" ) {
print "Module $mod version is OK.\n";
}
```
If the values of `$mod` and `$prereq` have not been scrubbed, however, this presents security implications.
###
Prerequisites for dynamically configured distributions
When `dynamic_config` is true, it is an error to presume that the prerequisites given in distribution metadata will have any relationship whatsoever to the actual prerequisites of the distribution.
In practice, however, one can generally expect such prerequisites to be one of two things:
* The minimum prerequisites for the distribution, to which dynamic configuration will only add items
* Whatever the distribution configured with on the releaser's machine at release time
The second case often turns out to have identical results to the first case, albeit only by accident.
As such, consumers may use this data for informational analysis, but presenting it to the user as canonical or relying on it as such is invariably the height of folly.
###
Indexing distributions a la PAUSE
While no\_index tells you what must be ignored when indexing, this spec holds no opinion on how you should get your initial candidate list of things to possibly index. For "normal" distributions you might consider simply indexing the contents of lib/, but there are many fascinating oddities on CPAN and many dists from the days when it was normal to put the main .pm file in the root of the distribution archive - so PAUSE currently indexes all .pm and .PL files that are not either (a) specifically excluded by no\_index (b) in `inc`, `xt`, or `t` directories, or common 'mistake' directories such as `perl5`.
Or: If you're trying to be PAUSE-like, make sure you skip `inc`, `xt` and `t` as well as anything marked as no\_index.
Also remember: If the META file contains a provides field, you shouldn't be indexing anything in the first place - just use that.
SEE ALSO
---------
* CPAN, <http://www.cpan.org/>
* JSON, <http://json.org/>
* YAML, <http://www.yaml.org/>
* [CPAN](cpan)
* [CPANPLUS](cpanplus)
* <ExtUtils::MakeMaker>
* <Module::Build>
* <Module::Install>
* <CPAN::Meta::History::Meta_1_4>
HISTORY
-------
Ken Williams wrote the original CPAN Meta Spec (also known as the "META.yml spec") in 2003 and maintained it through several revisions with input from various members of the community. In 2005, Randy Sims redrafted it from HTML to POD for the version 1.2 release. Ken continued to maintain the spec through version 1.4.
In late 2009, David Golden organized the version 2 proposal review process. David and Ricardo Signes drafted the final version 2 spec in April 2010 based on the version 1.4 spec and patches contributed during the proposal process.
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.
| programming_docs |
perl Test::use::ok Test::use::ok
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [MAINTAINER](#MAINTAINER)
* [CC0 1.0 Universal](#CC0-1.0-Universal)
NAME
----
Test::use::ok - Alternative to Test::More::use\_ok
SYNOPSIS
--------
```
use ok 'Some::Module';
```
DESCRIPTION
-----------
According to the **Test::More** documentation, it is recommended to run `use_ok()` inside a `BEGIN` block, so functions are exported at compile-time and prototypes are properly honored.
That is, instead of writing this:
```
use_ok( 'Some::Module' );
use_ok( 'Other::Module' );
```
One should write this:
```
BEGIN { use_ok( 'Some::Module' ); }
BEGIN { use_ok( 'Other::Module' ); }
```
However, people often either forget to add `BEGIN`, or mistakenly group `use_ok` with other tests in a single `BEGIN` block, which can create subtle differences in execution order.
With this module, simply change all `use_ok` in test scripts to `use ok`, and they will be executed at `BEGIN` time. The explicit space after `use` makes it clear that this is a single compile-time action.
SEE ALSO
---------
<Test::More>
MAINTAINER
----------
Chad Granum <[email protected]>
CC0 1.0 Universal
------------------
To the extent possible under law, ๅ้ณณ has waived all copyright and related or neighboring rights to [Test-use-ok](test-use-ok).
This work is published from Taiwan.
<http://creativecommons.org/publicdomain/zero/1.0>
perl Pod::Perldoc::GetOptsOO Pod::Perldoc::GetOptsOO
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::GetOptsOO - Customized option parser for Pod::Perldoc
SYNOPSIS
--------
```
use Pod::Perldoc::GetOptsOO ();
Pod::Perldoc::GetOptsOO::getopts( $obj, \@args, $truth )
or die "wrong usage";
```
DESCRIPTION
-----------
Implements a customized option parser used for <Pod::Perldoc>.
Rather like Getopt::Std's getopts:
Call Pod::Perldoc::GetOptsOO::getopts($object, \@ARGV, $truth)
Given -n, if there's a opt\_n\_with, it'll call $object->opt\_n\_with( ARGUMENT ) (e.g., "-n foo" => $object->opt\_n\_with('foo'). Ditto "-nfoo")
Otherwise (given -n) if there's an opt\_n, we'll call it $object->opt\_n($truth) (Truth defaults to 1)
Otherwise we try calling $object->handle\_unknown\_option('n') (and we increment the error count by the return value of it)
If there's no handle\_unknown\_option, then we just warn, and then increment the error counter The return value of Pod::Perldoc::GetOptsOO::getopts is true if no errors, otherwise it's false.
SEE ALSO
---------
<Pod::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 DBM_Filter::encode DBM\_Filter::encode
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter::encode - 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('encode' => 'iso-8859-16');
```
DESCRIPTION
-----------
This DBM filter allows you to choose the character encoding will be store in the DBM file. The usage is
```
$db->Filter_Push('encode' => ENCODING);
```
where "ENCODING" must be a valid encoding name that the Encode module recognises.
A fatal error will be thrown if:
1. The Encode module is not available.
2. The encoding requested is not supported by the Encode module.
SEE ALSO
---------
[DBM\_Filter](dbm_filter), <perldbmfilter>, [Encode](encode)
AUTHOR
------
Paul Marquess [email protected]
perl perllocale perllocale
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [WHAT IS A LOCALE](#WHAT-IS-A-LOCALE)
* [PREPARING TO USE LOCALES](#PREPARING-TO-USE-LOCALES)
* [USING LOCALES](#USING-LOCALES)
+ [The "use locale" pragma](#The-%22use-locale%22-pragma)
+ [The setlocale function](#The-setlocale-function)
+ [Multi-threaded operation](#Multi-threaded-operation)
+ [Finding locales](#Finding-locales)
+ [LOCALE PROBLEMS](#LOCALE-PROBLEMS)
+ [Testing for broken locales](#Testing-for-broken-locales)
+ [Temporarily fixing locale problems](#Temporarily-fixing-locale-problems)
+ [Permanently fixing locale problems](#Permanently-fixing-locale-problems)
+ [Permanently fixing your system's locale configuration](#Permanently-fixing-your-system's-locale-configuration)
+ [Fixing system locale configuration](#Fixing-system-locale-configuration)
+ [The localeconv function](#The-localeconv-function)
+ [I18N::Langinfo](#I18N::Langinfo)
* [LOCALE CATEGORIES](#LOCALE-CATEGORIES)
+ [Category LC\_COLLATE: Collation: Text Comparisons and Sorting](#Category-LC_COLLATE:-Collation:-Text-Comparisons-and-Sorting)
+ [Category LC\_CTYPE: Character Types](#Category-LC_CTYPE:-Character-Types1)
+ [Category LC\_NUMERIC: Numeric Formatting](#Category-LC_NUMERIC:-Numeric-Formatting)
+ [Category LC\_MONETARY: Formatting of monetary amounts](#Category-LC_MONETARY:-Formatting-of-monetary-amounts1)
+ [Category LC\_TIME: Respresentation of time](#Category-LC_TIME:-Respresentation-of-time)
+ [Other categories](#Other-categories1)
* [SECURITY](#SECURITY)
* [ENVIRONMENT](#ENVIRONMENT)
+ [Examples](#Examples)
* [NOTES](#NOTES)
+ [String eval and LC\_NUMERIC](#String-eval-and-LC_NUMERIC)
+ [Backward compatibility](#Backward-compatibility)
+ [I18N:Collate obsolete](#I18N:Collate-obsolete)
+ [Sort speed and memory use impacts](#Sort-speed-and-memory-use-impacts)
+ [Freely available locale definitions](#Freely-available-locale-definitions)
+ [I18n and l10n](#I18n-and-l10n)
+ [An imperfect standard](#An-imperfect-standard)
* [Unicode and UTF-8](#Unicode-and-UTF-8)
* [BUGS](#BUGS)
+ [Collation of strings containing embedded NUL characters](#Collation-of-strings-containing-embedded-NUL-characters)
+ [Multi-threaded](#Multi-threaded)
+ [Broken systems](#Broken-systems)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
perllocale - Perl locale handling (internationalization and localization)
DESCRIPTION
-----------
In the beginning there was ASCII, the "American Standard Code for Information Interchange", which works quite well for Americans with their English alphabet and dollar-denominated currency. But it doesn't work so well even for other English speakers, who may use different currencies, such as the pound sterling (as the symbol for that currency is not in ASCII); and it's hopelessly inadequate for many of the thousands of the world's other languages.
To address these deficiencies, the concept of locales was invented (formally the ISO C, XPG4, POSIX 1.c "locale system"). And applications were and are being written that use the locale mechanism. The process of making such an application take account of its users' preferences in these kinds of matters is called **internationalization** (often abbreviated as **i18n**); telling such an application about a particular set of preferences is known as **localization** (**l10n**).
Perl has been extended to support certain types of locales available in the locale system. This is controlled per application by using one pragma, one function call, and several environment variables.
Perl supports single-byte locales that are supersets of ASCII, such as the ISO 8859 ones, and one multi-byte-type locale, UTF-8 ones, described in the next paragraph. Perl doesn't support any other multi-byte locales, such as the ones for East Asian languages.
Unfortunately, there are quite a few deficiencies with the design (and often, the implementations) of locales. Unicode was invented (see <perlunitut> for an introduction to that) in part to address these design deficiencies, and nowadays, there is a series of "UTF-8 locales", based on Unicode. These are locales whose character set is Unicode, encoded in UTF-8. Starting in v5.20, Perl fully supports UTF-8 locales, except for sorting and string comparisons like `lt` and `ge`. Starting in v5.26, Perl can handle these reasonably as well, depending on the platform's implementation. However, for earlier releases or for better control, use <Unicode::Collate>. There are actually two slightly different types of UTF-8 locales: one for Turkic languages and one for everything else.
Starting in Perl v5.30, Perl detects Turkic locales by their behaviour, and seamlessly handles both types; previously only the non-Turkic one was supported. The name of the locale is ignored, if your system has a `tr_TR.UTF-8` locale and it doesn't behave like a Turkic locale, perl will treat it like a non-Turkic locale.
Perl continues to support the old non UTF-8 locales as well. There are currently no UTF-8 locales for EBCDIC platforms.
(Unicode is also creating `CLDR`, the "Common Locale Data Repository", <http://cldr.unicode.org/> which includes more types of information than are available in the POSIX locale system. At the time of this writing, there was no CPAN module that provides access to this XML-encoded data. However, it is possible to compute the POSIX locale data from them, and earlier CLDR versions had these already extracted for you as UTF-8 locales <http://unicode.org/Public/cldr/2.0.1/>.)
WHAT IS A LOCALE
-----------------
A locale is a set of data that describes various aspects of how various communities in the world categorize their world. These categories are broken down into the following types (some of which include a brief note here):
Category `LC_NUMERIC`: Numeric formatting This indicates how numbers should be formatted for human readability, for example the character used as the decimal point.
Category `LC_MONETARY`: Formatting of monetary amounts
Category `LC_TIME`: Date/Time formatting
Category `LC_MESSAGES`: Error and other messages This is used by Perl itself only for accessing operating system error messages via [`$!`](perlvar#%24ERRNO) and [`$^E`](perlvar#%24EXTENDED_OS_ERROR).
Category `LC_COLLATE`: Collation This indicates the ordering of letters for comparison and sorting. In Latin alphabets, for example, "b", generally follows "a".
Category `LC_CTYPE`: Character Types This indicates, for example if a character is an uppercase letter.
Other categories Some platforms have other categories, dealing with such things as measurement units and paper sizes. None of these are used directly by Perl, but outside operations that Perl interacts with may use these. See ["Not within the scope of "use locale""](#Not-within-the-scope-of-%22use-locale%22) below.
More details on the categories used by Perl are given below in ["LOCALE CATEGORIES"](#LOCALE-CATEGORIES).
Together, these categories go a long way towards being able to customize a single program to run in many different locations. But there are deficiencies, so keep reading.
PREPARING TO USE LOCALES
-------------------------
Perl itself (outside the [POSIX](posix) module) will not use locales unless specifically requested to (but again note that Perl may interact with code that does use them). Even if there is such a request, **all** of the following must be true for it to work properly:
* **Your operating system must support the locale system**. If it does, you should find that the `setlocale()` function is a documented part of its C library.
* **Definitions for locales that you use must be installed**. You, or your system administrator, must make sure that this is the case. The available locales, the location in which they are kept, and the manner in which they are installed all vary from system to system. Some systems provide only a few, hard-wired locales and do not allow more to be added. Others allow you to add "canned" locales provided by the system supplier. Still others allow you or the system administrator to define and add arbitrary locales. (You may have to ask your supplier to provide canned locales that are not delivered with your operating system.) Read your system documentation for further illumination.
* **Perl must believe that the locale system is supported**. If it does, `perl -V:d_setlocale` will say that the value for `d_setlocale` is `define`.
If you want a Perl application to process and present your data according to a particular locale, the application code should include the `use locale` pragma (see ["The "use locale" pragma"](#The-%22use-locale%22-pragma)) where appropriate, and **at least one** of the following must be true:
1. **The locale-determining environment variables (see ["ENVIRONMENT"](#ENVIRONMENT)) must be correctly set up** at the time the application is started, either by yourself or by whomever set up your system account; or
2. **The application must set its own locale** using the method described in ["The setlocale function"](#The-setlocale-function).
USING LOCALES
--------------
###
The `"use locale"` pragma
Starting in Perl 5.28, this pragma may be used in [multi-threaded](threads) applications on systems that have thread-safe locale ability. Some caveats apply, see ["Multi-threaded"](#Multi-threaded) below. On systems without this capability, or in earlier Perls, do NOT use this pragma in scripts that have multiple <threads> active. The locale in these cases is not local to a single thread. Another thread may change the locale at any time, which could cause at a minimum that a given thread is operating in a locale it isn't expecting to be in. On some platforms, segfaults can also occur. The locale change need not be explicit; some operations cause perl itself to change the locale. You are vulnerable simply by having done a `"use locale"`.
By default, Perl itself (outside the [POSIX](posix) module) ignores the current locale. The `use locale` pragma tells Perl to use the current locale for some operations. Starting in v5.16, there are optional parameters to this pragma, described below, which restrict which operations are affected by it.
The current locale is set at execution time by [setlocale()](#The-setlocale-function) described below. If that function hasn't yet been called in the course of the program's execution, the current locale is that which was determined by the ["ENVIRONMENT"](#ENVIRONMENT) in effect at the start of the program. If there is no valid environment, the current locale is whatever the system default has been set to. On POSIX systems, it is likely, but not necessarily, the "C" locale. On Windows, the default is set via the computer's `Control Panel->Regional and Language Options` (or its current equivalent).
The operations that are affected by locale are:
**Not within the scope of `"use locale"`**
Only certain operations (all originating outside Perl) should be affected, as follows:
* The current locale is used when going outside of Perl with operations like [system()](perlfunc#system-LIST) or [qx//](perlop#qx%2FSTRING%2F), if those operations are locale-sensitive.
* Also Perl gives access to various C library functions through the [POSIX](posix) module. Some of those functions are always affected by the current locale. For example, `POSIX::strftime()` uses `LC_TIME`; `POSIX::strtod()` uses `LC_NUMERIC`; `POSIX::strcoll()` and `POSIX::strxfrm()` use `LC_COLLATE`. All such functions will behave according to the current underlying locale, even if that locale isn't exposed to Perl space.
This applies as well to <I18N::Langinfo>.
* XS modules for all categories but `LC_NUMERIC` get the underlying locale, and hence any C library functions they call will use that underlying locale. For more discussion, see ["CAVEATS" in perlxs](perlxs#CAVEATS).
Note that all C programs (including the perl interpreter, which is written in C) always have an underlying locale. That locale is the "C" locale unless changed by a call to [setlocale()](#The-setlocale-function). When Perl starts up, it changes the underlying locale to the one which is indicated by the ["ENVIRONMENT"](#ENVIRONMENT). When using the [POSIX](posix) module or writing XS code, it is important to keep in mind that the underlying locale may be something other than "C", even if the program hasn't explicitly changed it.
**Lingering effects of `use locale`**
Certain Perl operations that are set-up within the scope of a `use locale` retain that effect even outside the scope. These include:
* The output format of a [write()](perlfunc#write) is determined by an earlier format declaration (["format" in perlfunc](perlfunc#format)), so whether or not the output is affected by locale is determined by if the `format()` is within the scope of a `use locale`, not whether the `write()` is.
* Regular expression patterns can be compiled using [qr//](perlop#qr%2FSTRING%2Fmsixpodualn) with actual matching deferred to later. Again, it is whether or not the compilation was done within the scope of `use locale` that determines the match behavior, not if the matches are done within such a scope or not.
**Under `"use locale";`**
* All the above operations
* **Format declarations** (["format" in perlfunc](perlfunc#format)) and hence any subsequent `write()`s use `LC_NUMERIC`.
* **stringification and output** use `LC_NUMERIC`. These include the results of `print()`, `printf()`, `say()`, and `sprintf()`.
* **The comparison operators** (`lt`, `le`, `cmp`, `ge`, and `gt`) use `LC_COLLATE`. `sort()` is also affected if used without an explicit comparison function, because it uses `cmp` by default.
**Note:** `eq` and `ne` are unaffected by locale: they always perform a char-by-char comparison of their scalar operands. What's more, if `cmp` finds that its operands are equal according to the collation sequence specified by the current locale, it goes on to perform a char-by-char comparison, and only returns *0* (equal) if the operands are char-for-char identical. If you really want to know whether two strings--which `eq` and `cmp` may consider different--are equal as far as collation in the locale is concerned, see the discussion in ["Category `LC_COLLATE`: Collation"](#Category-LC_COLLATE%3A-Collation).
* **Regular expressions and case-modification functions** (`uc()`, `lc()`, `ucfirst()`, and `lcfirst()`) use `LC_CTYPE`
* **The variables [`$!`](perlvar#%24ERRNO)** (and its synonyms `$ERRNO` and `$OS_ERROR`) **and** [`$^E`](perlvar#%24EXTENDED_OS_ERROR)> (and its synonym `$EXTENDED_OS_ERROR`) when used as strings use `LC_MESSAGES`.
The default behavior is restored with the `no locale` pragma, or upon reaching the end of the block enclosing `use locale`. Note that `use locale` calls may be nested, and that what is in effect within an inner scope will revert to the outer scope's rules at the end of the inner scope.
The string result of any operation that uses locale information is tainted (if your perl supports taint checking), as it is possible for a locale to be untrustworthy. See ["SECURITY"](#SECURITY).
Starting in Perl v5.16 in a very limited way, and more generally in v5.22, you can restrict which category or categories are enabled by this particular instance of the pragma by adding parameters to it. For example,
```
use locale qw(:ctype :numeric);
```
enables locale awareness within its scope of only those operations (listed above) that are affected by `LC_CTYPE` and `LC_NUMERIC`.
The possible categories are: `:collate`, `:ctype`, `:messages`, `:monetary`, `:numeric`, `:time`, and the pseudo category `:characters` (described below).
Thus you can say
```
use locale ':messages';
```
and only [`$!`](perlvar#%24ERRNO) and [`$^E`](perlvar#%24EXTENDED_OS_ERROR) will be locale aware. Everything else is unaffected.
Since Perl doesn't currently do anything with the `LC_MONETARY` category, specifying `:monetary` does effectively nothing. Some systems have other categories, such as `LC_PAPER`, but Perl also doesn't do anything with them, and there is no way to specify them in this pragma's arguments.
You can also easily say to use all categories but one, by either, for example,
```
use locale ':!ctype';
use locale ':not_ctype';
```
both of which mean to enable locale awareness of all categories but `LC_CTYPE`. Only one category argument may be specified in a `use locale` if it is of the negated form.
Prior to v5.22 only one form of the pragma with arguments is available:
```
use locale ':not_characters';
```
(and you have to say `not_`; you can't use the bang `!` form). This pseudo category is a shorthand for specifying both `:collate` and `:ctype`. Hence, in the negated form, it is nearly the same thing as saying
```
use locale qw(:messages :monetary :numeric :time);
```
We use the term "nearly", because `:not_characters` also turns on `use feature 'unicode_strings'` within its scope. This form is less useful in v5.20 and later, and is described fully in ["Unicode and UTF-8"](#Unicode-and-UTF-8), but briefly, it tells Perl to not use the character portions of the locale definition, that is the `LC_CTYPE` and `LC_COLLATE` categories. Instead it will use the native character set (extended by Unicode). When using this parameter, you are responsible for getting the external character set translated into the native/Unicode one (which it already will be if it is one of the increasingly popular UTF-8 locales). There are convenient ways of doing this, as described in ["Unicode and UTF-8"](#Unicode-and-UTF-8).
###
The setlocale function
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 unthreaded or compiled to be locale-thread-safe. On z/OS systems, this function becomes a no-op once any thread is started. Thus, on that system, you can set up the locale before creating any threads, and that locale will be the one in effect for the entire program.
Otherwise, you can switch locales as often as you wish at run time with the `POSIX::setlocale()` function:
```
# Import locale-handling tool set from POSIX module.
# This example uses: setlocale -- the function call
# LC_CTYPE -- explained below
# (Showing the testing for success/failure of operations is
# omitted in these examples to avoid distracting from the main
# point)
use POSIX qw(locale_h);
use locale;
my $old_locale;
# query and save the old locale
$old_locale = setlocale(LC_CTYPE);
setlocale(LC_CTYPE, "fr_CA.ISO8859-1");
# LC_CTYPE now in locale "French, Canada, codeset ISO 8859-1"
setlocale(LC_CTYPE, "");
# LC_CTYPE now reset to the default defined by the
# LC_ALL/LC_CTYPE/LANG environment variables, or to the system
# default. See below for documentation.
# restore the old locale
setlocale(LC_CTYPE, $old_locale);
```
The first argument of `setlocale()` gives the **category**, the second the **locale**. The category tells in what aspect of data processing you want to apply locale-specific rules. Category names are discussed in ["LOCALE CATEGORIES"](#LOCALE-CATEGORIES) and ["ENVIRONMENT"](#ENVIRONMENT). The locale is the name of a collection of customization information corresponding to a particular combination of language, country or territory, and codeset. Read on for hints on the naming of locales: not all systems name locales as in the example.
If no second argument is provided and the category is something other than `LC_ALL`, the function returns a string naming the current locale for the category. You can use this value as the second argument in a subsequent call to `setlocale()`, **but** on some platforms the string is opaque, not something that most people would be able to decipher as to what locale it means.
If no second argument is provided and the category is `LC_ALL`, the result is implementation-dependent. It may be a string of concatenated locale names (separator also implementation-dependent) or a single locale name. Please consult your [setlocale(3)](http://man.he.net/man3/setlocale) man page for details.
If a second argument is given and it corresponds to a valid locale, the locale for the category is set to that value, and the function returns the now-current locale value. You can then use this in yet another call to `setlocale()`. (In some implementations, the return value may sometimes differ from the value you gave as the second argument--think of it as an alias for the value you gave.)
As the example shows, if the second argument is an empty string, the category's locale is returned to the default specified by the corresponding environment variables. Generally, this results in a return to the default that was in force when Perl started up: changes to the environment made by the application after startup may or may not be noticed, depending on your system's C library.
Note that when a form of `use locale` that doesn't include all categories is specified, Perl ignores the excluded categories.
If `setlocale()` fails for some reason (for example, an attempt to set to a locale unknown to the system), the locale for the category is not changed, and the function returns `undef`.
Starting in Perl 5.28, on multi-threaded perls compiled on systems that implement POSIX 2008 thread-safe locale operations, this function doesn't actually call the system `setlocale`. Instead those thread-safe operations are used to emulate the `setlocale` function, but in a thread-safe manner.
You can force the thread-safe locale operations to always be used (if available) by recompiling perl with
```
-Accflags='-DUSE_THREAD_SAFE_LOCALE'
```
added to your call to *Configure*.
For further information about the categories, consult [setlocale(3)](http://man.he.net/man3/setlocale).
###
Multi-threaded operation
Beginning in Perl 5.28, multi-threaded locale operation is supported on systems that implement either the POSIX 2008 or Windows-specific thread-safe locale operations. Many modern systems, such as various Unix variants and Darwin do have this.
You can tell if using locales is safe on your system by looking at the read-only boolean variable `${^SAFE_LOCALES}`. The value is 1 if the perl is not threaded, or if it is using thread-safe locale operations.
Thread-safe operations are supported in Windows starting in Visual Studio 2005, and in systems compatible with POSIX 2008. Some platforms claim to support POSIX 2008, but have buggy implementations, so that the hints files for compiling to run on them turn off attempting to use thread-safety. `${^SAFE_LOCALES}` will be 0 on them.
Be aware that writing a multi-threaded application will not be portable to a platform which lacks the native thread-safe locale support. On systems that do have it, you automatically get this behavior for threaded perls, without having to do anything. If for some reason, you don't want to use this capability (perhaps the POSIX 2008 support is buggy on your system), you can manually compile Perl to use the old non-thread-safe implementation by passing the argument `-Accflags='-DNO_THREAD_SAFE_LOCALE'` to *Configure*. Except on Windows, this will continue to use certain of the POSIX 2008 functions in some situations. If these are buggy, you can pass the following to *Configure* instead or additionally: `-Accflags='-DNO_POSIX_2008_LOCALE'`. This will also keep the code from using thread-safe locales. `${^SAFE_LOCALES}` will be 0 on systems that turn off the thread-safe operations.
Normally on unthreaded builds, the traditional `setlocale()` is used and not the thread-safe locale functions. You can force the use of these on systems that have them by adding the `-Accflags='-DUSE_THREAD_SAFE_LOCALE'` to *Configure*.
The initial program is started up using the locale specified from the environment, as currently, described in ["ENVIRONMENT"](#ENVIRONMENT). All newly created threads start with `LC_ALL` set to `"C"`. Each thread may use `POSIX::setlocale()` to query or switch its locale at any time, without affecting any other thread. All locale-dependent operations automatically use their thread's locale.
This should be completely transparent to any applications written entirely in Perl (minus a few rarely encountered caveats given in the ["Multi-threaded"](#Multi-threaded) section). Information for XS module writers is given in ["Locale-aware XS code" in perlxs](perlxs#Locale-aware-XS-code).
###
Finding locales
For locales available in your system, consult also [setlocale(3)](http://man.he.net/man3/setlocale) to see whether it leads to the list of available locales (search for the *SEE ALSO* section). If that fails, try the following command lines:
```
locale -a
nlsinfo
ls /usr/lib/nls/loc
ls /usr/lib/locale
ls /usr/lib/nls
ls /usr/share/locale
```
and see whether they list something resembling these
```
en_US.ISO8859-1 de_DE.ISO8859-1 ru_RU.ISO8859-5
en_US.iso88591 de_DE.iso88591 ru_RU.iso88595
en_US de_DE ru_RU
en de ru
english german russian
english.iso88591 german.iso88591 russian.iso88595
english.roman8 russian.koi8r
```
Sadly, even though the calling interface for `setlocale()` has been standardized, names of locales and the directories where the configuration resides have not been. The basic form of the name is *language\_territory***.***codeset*, but the latter parts after *language* are not always present. The *language* and *country* are usually from the standards **ISO 3166** and **ISO 639**, the two-letter abbreviations for the countries and the languages of the world, respectively. The *codeset* part often mentions some **ISO 8859** character set, the Latin codesets. For example, `ISO 8859-1` is the so-called "Western European codeset" that can be used to encode most Western European languages adequately. Again, there are several ways to write even the name of that one standard. Lamentably.
Two special locales are worth particular mention: "C" and "POSIX". Currently these are effectively the same locale: the difference is mainly that the first one is defined by the C standard, the second by the POSIX standard. They define the **default locale** in which every program starts in the absence of locale information in its environment. (The *default* default locale, if you will.) Its language is (American) English and its character codeset ASCII or, rarely, a superset thereof (such as the "DEC Multinational Character Set (DEC-MCS)"). **Warning**. The C locale delivered by some vendors may not actually exactly match what the C standard calls for. So beware.
**NOTE**: Not all systems have the "POSIX" locale (not all systems are POSIX-conformant), so use "C" when you need explicitly to specify this default locale.
###
LOCALE PROBLEMS
You may encounter the following warning message at Perl startup:
```
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LC_ALL = "En_US",
LANG = (unset)
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
```
This means that your locale settings had `LC_ALL` set to "En\_US" and LANG exists but has no value. Perl tried to believe you but could not. Instead, Perl gave up and fell back to the "C" locale, the default locale that is supposed to work no matter what. (On Windows, it first tries falling back to the system default locale.) This usually means your locale settings were wrong, they mention locales your system has never heard of, or the locale installation in your system has problems (for example, some system files are broken or missing). There are quick and temporary fixes to these problems, as well as more thorough and lasting fixes.
###
Testing for broken locales
If you are building Perl from source, the Perl test suite file *lib/locale.t* can be used to test the locales on your system. Setting the environment variable `PERL_DEBUG_FULL_TEST` to 1 will cause it to output detailed results. For example, on Linux, you could say
```
PERL_DEBUG_FULL_TEST=1 ./perl -T -Ilib lib/locale.t > locale.log 2>&1
```
Besides many other tests, it will test every locale it finds on your system to see if they conform to the POSIX standard. If any have errors, it will include a summary near the end of the output of which locales passed all its tests, and which failed, and why.
###
Temporarily fixing locale problems
The two quickest fixes are either to render Perl silent about any locale inconsistencies or to run Perl under the default locale "C".
Perl's moaning about locale problems can be silenced by setting the environment variable `PERL_BADLANG` to "0" or "". This method really just sweeps the problem under the carpet: you tell Perl to shut up even when Perl sees that something is wrong. Do not be surprised if later something locale-dependent misbehaves.
Perl can be run under the "C" locale by setting the environment variable `LC_ALL` to "C". This method is perhaps a bit more civilized than the `PERL_BADLANG` approach, but setting `LC_ALL` (or other locale variables) may affect other programs as well, not just Perl. In particular, external programs run from within Perl will see these changes. If you make the new settings permanent (read on), all programs you run see the changes. See ["ENVIRONMENT"](#ENVIRONMENT) for the full list of relevant environment variables and ["USING LOCALES"](#USING-LOCALES) for their effects in Perl. Effects in other programs are easily deducible. For example, the variable `LC_COLLATE` may well affect your **sort** program (or whatever the program that arranges "records" alphabetically in your system is called).
You can test out changing these variables temporarily, and if the new settings seem to help, put those settings into your shell startup files. Consult your local documentation for the exact details. For Bourne-like shells (**sh**, **ksh**, **bash**, **zsh**):
```
LC_ALL=en_US.ISO8859-1
export LC_ALL
```
This assumes that we saw the locale "en\_US.ISO8859-1" using the commands discussed above. We decided to try that instead of the above faulty locale "En\_US"--and in Cshish shells (**csh**, **tcsh**)
```
setenv LC_ALL en_US.ISO8859-1
```
or if you have the "env" application you can do (in any shell)
```
env LC_ALL=en_US.ISO8859-1 perl ...
```
If you do not know what shell you have, consult your local helpdesk or the equivalent.
###
Permanently fixing locale problems
The slower but superior fixes are when you may be able to yourself fix the misconfiguration of your own environment variables. The mis(sing)configuration of the whole system's locales usually requires the help of your friendly system administrator.
First, see earlier in this document about ["Finding locales"](#Finding-locales). That tells how to find which locales are really supported--and more importantly, installed--on your system. In our example error message, environment variables affecting the locale are listed in the order of decreasing importance (and unset variables do not matter). Therefore, having LC\_ALL set to "En\_US" must have been the bad choice, as shown by the error message. First try fixing locale settings listed first.
Second, if using the listed commands you see something **exactly** (prefix matches do not count and case usually counts) like "En\_US" without the quotes, then you should be okay because you are using a locale name that should be installed and available in your system. In this case, see ["Permanently fixing your system's locale configuration"](#Permanently-fixing-your-system%27s-locale-configuration).
###
Permanently fixing your system's locale configuration
This is when you see something like:
```
perl: warning: Please check that your locale settings:
LC_ALL = "En_US",
LANG = (unset)
are supported and installed on your system.
```
but then cannot see that "En\_US" listed by the above-mentioned commands. You may see things like "en\_US.ISO8859-1", but that isn't the same. In this case, try running under a locale that you can list and which somehow matches what you tried. The rules for matching locale names are a bit vague because standardization is weak in this area. See again the ["Finding locales"](#Finding-locales) about general rules.
###
Fixing system locale configuration
Contact a system administrator (preferably your own) and report the exact error message you get, and ask them to read this same documentation you are now reading. They should be able to check whether there is something wrong with the locale configuration of the system. The ["Finding locales"](#Finding-locales) section is unfortunately a bit vague about the exact commands and places because these things are not that standardized.
###
The localeconv function
The `POSIX::localeconv()` function allows you to get particulars of the locale-dependent numeric formatting information specified by the current underlying `LC_NUMERIC` and `LC_MONETARY` locales (regardless of whether called from within the scope of `use locale` or not). (If you just want the name of the current locale for a particular category, use `POSIX::setlocale()` with a single parameter--see ["The setlocale function"](#The-setlocale-function).)
```
use POSIX qw(locale_h);
# Get a reference to a hash of locale-dependent info
$locale_values = localeconv();
# Output sorted list of the values
for (sort keys %$locale_values) {
printf "%-20s = %s\n", $_, $locale_values->{$_}
}
```
`localeconv()` takes no arguments, and returns **a reference to** a hash. The keys of this hash are variable names for formatting, such as `decimal_point` and `thousands_sep`. The values are the corresponding, er, values. See ["localeconv" in POSIX](posix#localeconv) for a longer example listing the categories an implementation might be expected to provide; some provide more and others fewer. You don't need an explicit `use locale`, because `localeconv()` always observes the current locale.
Here's a simple-minded example program that rewrites its command-line parameters as integers correctly formatted in the current locale:
```
use POSIX qw(locale_h);
# Get some of locale's numeric formatting parameters
my ($thousands_sep, $grouping) =
@{localeconv()}{'thousands_sep', 'grouping'};
# Apply defaults if values are missing
$thousands_sep = ',' unless $thousands_sep;
# grouping and mon_grouping are packed lists
# of small integers (characters) telling the
# grouping (thousand_seps and mon_thousand_seps
# being the group dividers) of numbers and
# monetary quantities. The integers' meanings:
# 255 means no more grouping, 0 means repeat
# the previous grouping, 1-254 means use that
# as the current grouping. Grouping goes from
# right to left (low to high digits). In the
# below we cheat slightly by never using anything
# else than the first grouping (whatever that is).
if ($grouping) {
@grouping = unpack("C*", $grouping);
} else {
@grouping = (3);
}
# Format command line params for current locale
for (@ARGV) {
$_ = int; # Chop non-integer part
1 while
s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_sep$2/;
print "$_";
}
print "\n";
```
Note that if the platform doesn't have `LC_NUMERIC` and/or `LC_MONETARY` available or enabled, the corresponding elements of the hash will be missing.
###
I18N::Langinfo
Another interface for querying locale-dependent information is the `I18N::Langinfo::langinfo()` function.
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 } qw(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]
```
See <I18N::Langinfo> for more information.
LOCALE CATEGORIES
------------------
The following subsections describe basic locale categories. Beyond these, some combination categories allow manipulation of more than one basic category at a time. See ["ENVIRONMENT"](#ENVIRONMENT) for a discussion of these.
###
Category `LC_COLLATE`: Collation: Text Comparisons and Sorting
In the scope of a `use locale` form that includes collation, Perl looks to the `LC_COLLATE` environment variable to determine the application's notions on collation (ordering) of characters. For example, "b" follows "a" in Latin alphabets, but where do "รก" and "รฅ" belong? And while "color" follows "chocolate" in English, what about in traditional Spanish?
The following collations all make sense and you may meet any of them if you `"use locale"`.
```
A B C D E a b c d e
A a B b C c D d E e
a A b B c C d D e E
a b c d e A B C D E
```
Here is a code snippet to tell what "word" characters are in the current locale, in that locale's order:
```
use locale;
print +(sort grep /\w/, map { chr } 0..255), "\n";
```
Compare this with the characters that you see and their order if you state explicitly that the locale should be ignored:
```
no locale;
print +(sort grep /\w/, map { chr } 0..255), "\n";
```
This machine-native collation (which is what you get unless `use locale` has appeared earlier in the same block) must be used for sorting raw binary data, whereas the locale-dependent collation of the first example is useful for natural text.
As noted in ["USING LOCALES"](#USING-LOCALES), `cmp` compares according to the current collation locale when `use locale` is in effect, but falls back to a char-by-char comparison for strings that the locale says are equal. You can use `POSIX::strcoll()` if you don't want this fall-back:
```
use POSIX qw(strcoll);
$equal_in_locale =
!strcoll("space and case ignored", "SpaceAndCaseIgnored");
```
`$equal_in_locale` will be true if the collation locale specifies a dictionary-like ordering that ignores space characters completely and which folds case.
Perl uses the platform's C library collation functions `strcoll()` and `strxfrm()`. That means you get whatever they give. On some platforms, these functions work well on UTF-8 locales, giving a reasonable default collation for the code points that are important in that locale. (And if they aren't working well, the problem may only be that the locale definition is deficient, so can be fixed by using a better definition file. Unicode's definitions (see ["Freely available locale definitions"](#Freely-available-locale-definitions)) provide reasonable UTF-8 locale collation definitions.) Starting in Perl v5.26, Perl's use of these functions has been made more seamless. This may be sufficient for your needs. For more control, and to make sure strings containing any code point (not just the ones important in the locale) collate properly, the <Unicode::Collate> module is suggested.
In non-UTF-8 locales (hence single byte), code points above 0xFF are technically invalid. But if present, again starting in v5.26, they will collate to the same position as the highest valid code point does. This generally gives good results, but the collation order may be skewed if the valid code point gets special treatment when it forms particular sequences with other characters as defined by the locale. When two strings collate identically, the code point order is used as a tie breaker.
If Perl detects that there are problems with the locale collation order, it reverts to using non-locale collation rules for that locale.
If you have a single string that you want to check for "equality in locale" against several others, you might think you could gain a little efficiency by using `POSIX::strxfrm()` in conjunction with `eq`:
```
use POSIX qw(strxfrm);
$xfrm_string = strxfrm("Mixed-case string");
print "locale collation ignores spaces\n"
if $xfrm_string eq strxfrm("Mixed-casestring");
print "locale collation ignores hyphens\n"
if $xfrm_string eq strxfrm("Mixedcase string");
print "locale collation ignores case\n"
if $xfrm_string eq strxfrm("mixed-case string");
```
`strxfrm()` takes a string and maps it into a transformed string for use in char-by-char comparisons against other transformed strings during collation. "Under the hood", locale-affected Perl comparison operators call `strxfrm()` for both operands, then do a char-by-char comparison of the transformed strings. By calling `strxfrm()` explicitly and using a non locale-affected comparison, the example attempts to save a couple of transformations. But in fact, it doesn't save anything: Perl magic (see ["Magic Variables" in perlguts](perlguts#Magic-Variables)) creates the transformed version of a string the first time it's needed in a comparison, then keeps this version around in case it's needed again. An example rewritten the easy way with `cmp` runs just about as fast. It also copes with null characters embedded in strings; if you call `strxfrm()` directly, it treats the first null it finds as a terminator. Don't expect the transformed strings it produces to be portable across systems--or even from one revision of your operating system to the next. In short, don't call `strxfrm()` directly: let Perl do it for you.
Note: `use locale` isn't shown in some of these examples because it isn't needed: `strcoll()` and `strxfrm()` are POSIX functions which use the standard system-supplied `libc` functions that always obey the current `LC_COLLATE` locale.
###
Category `LC_CTYPE`: Character Types
In the scope of a `use locale` form that includes `LC_CTYPE`, Perl obeys the `LC_CTYPE` locale setting. This controls the application's notion of which characters are alphabetic, numeric, punctuation, *etc*. This affects Perl's `\w` regular expression metanotation, which stands for alphanumeric characters--that is, alphabetic, numeric, and the platform's native underscore. (Consult <perlre> for more information about regular expressions.) Thanks to `LC_CTYPE`, depending on your locale setting, characters like "รฆ", "รฐ", "ร", and "รธ" may be understood as `\w` characters. It also affects things like `\s`, `\D`, and the POSIX character classes, like `[[:graph:]]`. (See <perlrecharclass> for more information on all these.)
The `LC_CTYPE` locale also provides the map used in transliterating characters between lower and uppercase. This affects the case-mapping functions--`fc()`, `lc()`, `lcfirst()`, `uc()`, and `ucfirst()`; case-mapping interpolation with `\F`, `\l`, `\L`, `\u`, or `\U` in double-quoted strings and `s///` substitutions; and case-insensitive regular expression pattern matching using the `i` modifier.
Starting in v5.20, Perl supports UTF-8 locales for `LC_CTYPE`, but otherwise Perl only supports single-byte locales, such as the ISO 8859 series. This means that wide character locales, for example for Asian languages, are not well-supported. Use of these locales may cause core dumps. If the platform has the capability for Perl to detect such a locale, starting in Perl v5.22, [Perl will warn, default enabled](warnings#Category-Hierarchy), using the `locale` warning category, whenever such a locale is switched into. The UTF-8 locale support is actually a superset of POSIX locales, because it is really full Unicode behavior as if no `LC_CTYPE` locale were in effect at all (except for tainting; see ["SECURITY"](#SECURITY)). POSIX locales, even UTF-8 ones, are lacking certain concepts in Unicode, such as the idea that changing the case of a character could expand to be more than one character. Perl in a UTF-8 locale, will give you that expansion. Prior to v5.20, Perl treated a UTF-8 locale on some platforms like an ISO 8859-1 one, with some restrictions, and on other platforms more like the "C" locale. For releases v5.16 and v5.18, `use locale 'not\_characters` could be used as a workaround for this (see ["Unicode and UTF-8"](#Unicode-and-UTF-8)).
Note that there are quite a few things that are unaffected by the current locale. Any literal character is the native character for the given platform. Hence 'A' means the character at code point 65 on ASCII platforms, and 193 on EBCDIC. That may or may not be an 'A' in the current locale, if that locale even has an 'A'. Similarly, all the escape sequences for particular characters, `\n` for example, always mean the platform's native one. This means, for example, that `\N` in regular expressions (every character but new-line) works on the platform character set.
Starting in v5.22, Perl will by default warn when switching into a locale that redefines any ASCII printable character (plus `\t` and `\n`) into a different class than expected. This is likely to happen on modern locales only on EBCDIC platforms, where, for example, a CCSID 0037 locale on a CCSID 1047 machine moves `"["`, but it can happen on ASCII platforms with the ISO 646 and other 7-bit locales that are essentially obsolete. Things may still work, depending on what features of Perl are used by the program. For example, in the example from above where `"|"` becomes a `\w`, and there are no regular expressions where this matters, the program may still work properly. The warning lists all the characters that it can determine could be adversely affected.
**Note:** A broken or malicious `LC_CTYPE` locale definition may result in clearly ineligible characters being considered to be alphanumeric by your application. For strict matching of (mundane) ASCII letters and digits--for example, in command strings--locale-aware applications should use `\w` with the `/a` regular expression modifier. See ["SECURITY"](#SECURITY).
###
Category `LC_NUMERIC`: Numeric Formatting
After a proper `POSIX::setlocale()` call, and within the scope of a `use locale` form that includes numerics, Perl obeys the `LC_NUMERIC` locale information, which controls an application's idea of how numbers should be formatted for human readability. In most implementations the only effect is to change the character used for the decimal point--perhaps from "." to ",". The functions aren't aware of such niceties as thousands separation and so on. (See ["The localeconv function"](#The-localeconv-function) if you care about these things.)
```
use POSIX qw(strtod setlocale LC_NUMERIC);
use locale;
setlocale LC_NUMERIC, "";
$n = 5/2; # Assign numeric 2.5 to $n
$a = " $n"; # Locale-dependent conversion to string
print "half five is $n\n"; # Locale-dependent output
printf "half five is %g\n", $n; # Locale-dependent output
print "DECIMAL POINT IS COMMA\n"
if $n == (strtod("2,5"))[0]; # Locale-dependent conversion
```
See also <I18N::Langinfo> and `RADIXCHAR`.
###
Category `LC_MONETARY`: Formatting of monetary amounts
The C standard defines the `LC_MONETARY` category, but not a function that is affected by its contents. (Those with experience of standards committees will recognize that the working group decided to punt on the issue.) Consequently, Perl essentially takes no notice of it. If you really want to use `LC_MONETARY`, you can query its contents--see ["The localeconv function"](#The-localeconv-function)--and use the information that it returns in your application's own formatting of currency amounts. However, you may well find that the information, voluminous and complex though it may be, still does not quite meet your requirements: currency formatting is a hard nut to crack.
See also <I18N::Langinfo> and `CRNCYSTR`.
###
Category `LC_TIME`: Respresentation of time
Output produced by `POSIX::strftime()`, which builds a formatted human-readable date/time string, is affected by the current `LC_TIME` locale. Thus, in a French locale, the output produced by the `%B` format element (full month name) for the first month of the year would be "janvier". Here's how to get a list of long month names in the current locale:
```
use POSIX qw(strftime);
for (0..11) {
$long_month_name[$_] =
strftime("%B", 0, 0, 0, 1, $_, 96);
}
```
Note: `use locale` isn't needed in this example: `strftime()` is a POSIX function which uses the standard system-supplied `libc` function that always obeys the current `LC_TIME` locale.
See also <I18N::Langinfo> and `ABDAY_1`..`ABDAY_7`, `DAY_1`..`DAY_7`, `ABMON_1`..`ABMON_12`, and `ABMON_1`..`ABMON_12`.
###
Other categories
The remaining locale categories are not currently used by Perl itself. But again note that things Perl interacts with may use these, including extensions outside the standard Perl distribution, and by the operating system and its utilities. Note especially that the string value of `$!` and the error messages given by external utilities may be changed by `LC_MESSAGES`. If you want to have portable error codes, use `%!`. See [Errno](errno).
SECURITY
--------
Although the main discussion of Perl security issues can be found in <perlsec>, a discussion of Perl's locale handling would be incomplete if it did not draw your attention to locale-dependent security issues. Locales--particularly on systems that allow unprivileged users to build their own locales--are untrustworthy. A malicious (or just plain broken) locale can make a locale-aware application give unexpected results. Here are a few possibilities:
* Regular expression checks for safe file names or mail addresses using `\w` may be spoofed by an `LC_CTYPE` locale that claims that characters such as `">"` and `"|"` are alphanumeric.
* String interpolation with case-mapping, as in, say, `$dest = "C:\U$name.$ext"`, may produce dangerous results if a bogus `LC_CTYPE` case-mapping table is in effect.
* A sneaky `LC_COLLATE` locale could result in the names of students with "D" grades appearing ahead of those with "A"s.
* An application that takes the trouble to use information in `LC_MONETARY` may format debits as if they were credits and vice versa if that locale has been subverted. Or it might make payments in US dollars instead of Hong Kong dollars.
* The date and day names in dates formatted by `strftime()` could be manipulated to advantage by a malicious user able to subvert the `LC_DATE` locale. ("Look--it says I wasn't in the building on Sunday.")
Such dangers are not peculiar to the locale system: any aspect of an application's environment which may be modified maliciously presents similar challenges. Similarly, they are not specific to Perl: any programming language that allows you to write programs that take account of their environment exposes you to these issues.
Perl cannot protect you from all possibilities shown in the examples--there is no substitute for your own vigilance--but, when `use locale` is in effect, Perl uses the tainting mechanism (see <perlsec>) to mark string results that become locale-dependent, and which may be untrustworthy in consequence.
Note that it is possible to compile Perl without taint support, in which case all taint features silently do nothing.
Here is a summary of the tainting behavior of operators and functions that may be affected by the locale:
* **Comparison operators** (`lt`, `le`, `ge`, `gt` and `cmp`):
Scalar true/false (or less/equal/greater) result is never tainted.
* **Case-mapping interpolation** (with `\l`, `\L`, `\u`, `\U`, or `\F`)
The result string containing interpolated material is tainted if a `use locale` form that includes `LC_CTYPE` is in effect.
* **Matching operator** (`m//`):
Scalar true/false result never tainted.
All subpatterns, either delivered as a list-context result or as `$1` *etc*., are tainted if a `use locale` form that includes `LC_CTYPE` is in effect, and the subpattern regular expression contains a locale-dependent construct. These constructs include `\w` (to match an alphanumeric character), `\W` (non-alphanumeric character), `\b` and `\B` (word-boundary and non-boundardy, which depend on what `\w` and `\W` match), `\s` (whitespace character), `\S` (non whitespace character), `\d` and `\D` (digits and non-digits), and the POSIX character classes, such as `[:alpha:]` (see ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes)).
Tainting is also likely if the pattern is to be matched case-insensitively (via `/i`). The exception is if all the code points to be matched this way are above 255 and do not have folds under Unicode rules to below 256. Tainting is not done for these because Perl only uses Unicode rules for such code points, and those rules are the same no matter what the current locale.
The matched-pattern variables, `$&`, `$`` (pre-match), `$'` (post-match), and `$+` (last match) also are tainted.
* **Substitution operator** (`s///`):
Has the same behavior as the match operator. Also, the left operand of `=~` becomes tainted when a `use locale` form that includes `LC_CTYPE` is in effect, if modified as a result of a substitution based on a regular expression match involving any of the things mentioned in the previous item, or of case-mapping, such as `\l`, `\L`,`\u`, `\U`, or `\F`.
* **Output formatting functions** (`printf()` and `write()`):
Results are never tainted because otherwise even output from print, for example `print(1/7)`, should be tainted if `use locale` is in effect.
* **Case-mapping functions** (`lc()`, `lcfirst()`, `uc()`, `ucfirst()`):
Results are tainted if a `use locale` form that includes `LC_CTYPE` is in effect.
* **POSIX locale-dependent functions** (`localeconv()`, `strcoll()`, `strftime()`, `strxfrm()`):
Results are never tainted.
Three examples illustrate locale-dependent tainting. The first program, which ignores its locale, won't run: a value taken directly from the command line may not be used to name an output file when taint checks are enabled.
```
#/usr/local/bin/perl -T
# Run with taint checking
# Command line sanity check omitted...
$tainted_output_file = shift;
open(F, ">$tainted_output_file")
or warn "Open of $tainted_output_file failed: $!\n";
```
The program can be made to run by "laundering" the tainted value through a regular expression: the second example--which still ignores locale information--runs, creating the file named on its command line if it can.
```
#/usr/local/bin/perl -T
$tainted_output_file = shift;
$tainted_output_file =~ m%[\w/]+%;
$untainted_output_file = $&;
open(F, ">$untainted_output_file")
or warn "Open of $untainted_output_file failed: $!\n";
```
Compare this with a similar but locale-aware program:
```
#/usr/local/bin/perl -T
$tainted_output_file = shift;
use locale;
$tainted_output_file =~ m%[\w/]+%;
$localized_output_file = $&;
open(F, ">$localized_output_file")
or warn "Open of $localized_output_file failed: $!\n";
```
This third program fails to run because `$&` is tainted: it is the result of a match involving `\w` while `use locale` is in effect.
ENVIRONMENT
-----------
PERL\_SKIP\_LOCALE\_INIT This environment variable, available starting in Perl v5.20, if set (to any value), tells Perl to not use the rest of the environment variables to initialize with. Instead, Perl uses whatever the current locale settings are. This is particularly useful in embedded environments, see ["Using embedded Perl with POSIX locales" in perlembed](perlembed#Using-embedded-Perl-with-POSIX-locales).
PERL\_BADLANG A string that can suppress Perl's warning about failed locale settings at startup. Failure can occur if the locale support in the operating system is lacking (broken) in some way--or if you mistyped the name of a locale when you set up your environment. If this environment variable is absent, or has a value other than "0" or "", Perl will complain about locale setting failures.
**NOTE**: `PERL_BADLANG` only gives you a way to hide the warning message. The message tells about some problem in your system's locale support, and you should investigate what the problem is.
The following environment variables are not specific to Perl: They are part of the standardized (ISO C, XPG4, POSIX 1.c) `setlocale()` method for controlling an application's opinion on data. Windows is non-POSIX, but Perl arranges for the following to work as described anyway. If the locale given by an environment variable is not valid, Perl tries the next lower one in priority. If none are valid, on Windows, the system default locale is then tried. If all else fails, the `"C"` locale is used. If even that doesn't work, something is badly broken, but Perl tries to forge ahead with whatever the locale settings might be.
`LC_ALL` `LC_ALL` is the "override-all" locale environment variable. If set, it overrides all the rest of the locale environment variables.
`LANGUAGE` **NOTE**: `LANGUAGE` is a GNU extension, it affects you only if you are using the GNU libc. This is the case if you are using e.g. Linux. If you are using "commercial" Unixes you are most probably *not* using GNU libc and you can ignore `LANGUAGE`.
However, in the case you are using `LANGUAGE`: it affects the language of informational, warning, and error messages output by commands (in other words, it's like `LC_MESSAGES`) but it has higher priority than `LC_ALL`. Moreover, it's not a single value but instead a "path" (":"-separated list) of *languages* (not locales). See the GNU `gettext` library documentation for more information.
`LC_CTYPE` In the absence of `LC_ALL`, `LC_CTYPE` chooses the character type locale. In the absence of both `LC_ALL` and `LC_CTYPE`, `LANG` chooses the character type locale.
`LC_COLLATE` In the absence of `LC_ALL`, `LC_COLLATE` chooses the collation (sorting) locale. In the absence of both `LC_ALL` and `LC_COLLATE`, `LANG` chooses the collation locale.
`LC_MONETARY` In the absence of `LC_ALL`, `LC_MONETARY` chooses the monetary formatting locale. In the absence of both `LC_ALL` and `LC_MONETARY`, `LANG` chooses the monetary formatting locale.
`LC_NUMERIC` In the absence of `LC_ALL`, `LC_NUMERIC` chooses the numeric format locale. In the absence of both `LC_ALL` and `LC_NUMERIC`, `LANG` chooses the numeric format.
`LC_TIME` In the absence of `LC_ALL`, `LC_TIME` chooses the date and time formatting locale. In the absence of both `LC_ALL` and `LC_TIME`, `LANG` chooses the date and time formatting locale.
`LANG` `LANG` is the "catch-all" locale environment variable. If it is set, it is used as the last resort after the overall `LC_ALL` and the category-specific `LC_*foo*`.
### Examples
The `LC_NUMERIC` controls the numeric output:
```
use locale;
use POSIX qw(locale_h); # Imports setlocale() and the LC_ constants.
setlocale(LC_NUMERIC, "fr_FR") or die "Pardon";
printf "%g\n", 1.23; # If the "fr_FR" succeeded, probably shows 1,23.
```
and also how strings are parsed by `POSIX::strtod()` as numbers:
```
use locale;
use POSIX qw(locale_h strtod);
setlocale(LC_NUMERIC, "de_DE") or die "Entschuldigung";
my $x = strtod("2,34") + 5;
print $x, "\n"; # Probably shows 7,34.
```
NOTES
-----
###
String `eval` and `LC_NUMERIC`
A string [eval](perlfunc#eval-EXPR) parses its expression as standard Perl. It is therefore expecting the decimal point to be a dot. If `LC_NUMERIC` is set to have this be a comma instead, the parsing will be confused, perhaps silently.
```
use locale;
use POSIX qw(locale_h);
setlocale(LC_NUMERIC, "fr_FR") or die "Pardon";
my $a = 1.2;
print eval "$a + 1.5";
print "\n";
```
prints `13,5`. This is because in that locale, the comma is the decimal point character. The `eval` thus expands to:
```
eval "1,2 + 1.5"
```
and the result is not what you likely expected. No warnings are generated. If you do string `eval`'s within the scope of `use locale`, you should instead change the `eval` line to do something like:
```
print eval "no locale; $a + 1.5";
```
This prints `2.7`.
You could also exclude `LC_NUMERIC`, if you don't need it, by
```
use locale ':!numeric';
```
###
Backward compatibility
Versions of Perl prior to 5.004 **mostly** ignored locale information, generally behaving as if something similar to the `"C"` locale were always in force, even if the program environment suggested otherwise (see ["The setlocale function"](#The-setlocale-function)). By default, Perl still behaves this way for backward compatibility. If you want a Perl application to pay attention to locale information, you **must** use the `use locale` pragma (see ["The "use locale" pragma"](#The-%22use-locale%22-pragma)) or, in the unlikely event that you want to do so for just pattern matching, the `/l` regular expression modifier (see ["Character set modifiers" in perlre](perlre#Character-set-modifiers)) to instruct it to do so.
Versions of Perl from 5.002 to 5.003 did use the `LC_CTYPE` information if available; that is, `\w` did understand what were the letters according to the locale environment variables. The problem was that the user had no control over the feature: if the C library supported locales, Perl used them.
###
I18N:Collate obsolete
In versions of Perl prior to 5.004, per-locale collation was possible using the `I18N::Collate` library module. This module is now mildly obsolete and should be avoided in new applications. The `LC_COLLATE` functionality is now integrated into the Perl core language: One can use locale-specific scalar data completely normally with `use locale`, so there is no longer any need to juggle with the scalar references of `I18N::Collate`.
###
Sort speed and memory use impacts
Comparing and sorting by locale is usually slower than the default sorting; slow-downs of two to four times have been observed. It will also consume more memory: once a Perl scalar variable has participated in any string comparison or sorting operation obeying the locale collation rules, it will take 3-15 times more memory than before. (The exact multiplier depends on the string's contents, the operating system and the locale.) These downsides are dictated more by the operating system's implementation of the locale system than by Perl.
###
Freely available locale definitions
The Unicode CLDR project extracts the POSIX portion of many of its locales, available at
```
https://unicode.org/Public/cldr/2.0.1/
```
(Newer versions of CLDR require you to compute the POSIX data yourself. See <http://unicode.org/Public/cldr/latest/>.)
There is a large collection of locale definitions at:
```
http://std.dkuug.dk/i18n/WG15-collection/locales/
```
You should be aware that it is unsupported, and is not claimed to be fit for any purpose. If your system allows installation of arbitrary locales, you may find the definitions useful as they are, or as a basis for the development of your own locales.
###
I18n and l10n
"Internationalization" is often abbreviated as **i18n** because its first and last letters are separated by eighteen others. (You may guess why the internalin ... internaliti ... i18n tends to get abbreviated.) In the same way, "localization" is often abbreviated to **l10n**.
###
An imperfect standard
Internationalization, as defined in the C and POSIX standards, can be criticized as incomplete and ungainly. They also have a tendency, like standards groups, to divide the world into nations, when we all know that the world can equally well be divided into bankers, bikers, gamers, and so on.
Unicode and UTF-8
------------------
The support of Unicode is new starting from Perl version v5.6, and more fully implemented in versions v5.8 and later. See <perluniintro>.
Starting in Perl v5.20, UTF-8 locales are supported in Perl, except `LC_COLLATE` is only partially supported; collation support is improved in Perl v5.26 to a level that may be sufficient for your needs (see ["Category `LC_COLLATE`: Collation: Text Comparisons and Sorting"](#Category-LC_COLLATE%3A-Collation%3A-Text-Comparisons-and-Sorting)).
If you have Perl v5.16 or v5.18 and can't upgrade, you can use
```
use locale ':not_characters';
```
When this form of the pragma is used, only the non-character portions of locales are used by Perl, for example `LC_NUMERIC`. Perl assumes that you have translated all the characters it is to operate on into Unicode (actually the platform's native character set (ASCII or EBCDIC) plus Unicode). For data in files, this can conveniently be done by also specifying
```
use open ':locale';
```
This pragma arranges for all inputs from files to be translated into Unicode from the current locale as specified in the environment (see ["ENVIRONMENT"](#ENVIRONMENT)), and all outputs to files to be translated back into the locale. (See <open>). On a per-filehandle basis, you can instead use the <PerlIO::locale> module, or the <Encode::Locale> module, both available from CPAN. The latter module also has methods to ease the handling of `ARGV` and environment variables, and can be used on individual strings. If you know that all your locales will be UTF-8, as many are these days, you can use the [**-C**](perlrun#-C-%5Bnumber%2Flist%5D) command line switch.
This form of the pragma allows essentially seamless handling of locales with Unicode. The collation order will be by Unicode code point order. <Unicode::Collate> can be used to get Unicode rules collation.
All the modules and switches just described can be used in v5.20 with just plain `use locale`, and, should the input locales not be UTF-8, you'll get the less than ideal behavior, described below, that you get with pre-v5.16 Perls, or when you use the locale pragma without the `:not_characters` parameter in v5.16 and v5.18. If you are using exclusively UTF-8 locales in v5.20 and higher, the rest of this section does not apply to you.
There are two cases, multi-byte and single-byte locales. First multi-byte:
The only multi-byte (or wide character) locale that Perl is ever likely to support is UTF-8. This is due to the difficulty of implementation, the fact that high quality UTF-8 locales are now published for every area of the world (<https://unicode.org/Public/cldr/2.0.1/> for ones that are already set-up, but from an earlier version; <https://unicode.org/Public/cldr/latest/> for the most up-to-date, but you have to extract the POSIX information yourself), and failing all that, you can use the [Encode](encode) module to translate to/from your locale. So, you'll have to do one of those things if you're using one of these locales, such as Big5 or Shift JIS. For UTF-8 locales, in Perls (pre v5.20) that don't have full UTF-8 locale support, they may work reasonably well (depending on your C library implementation) simply because both they and Perl store characters that take up multiple bytes the same way. However, some, if not most, C library implementations may not process the characters in the upper half of the Latin-1 range (128 - 255) properly under `LC_CTYPE`. To see if a character is a particular type under a locale, Perl uses the functions like `isalnum()`. Your C library may not work for UTF-8 locales with those functions, instead only working under the newer wide library functions like `iswalnum()`, which Perl does not use. These multi-byte locales are treated like single-byte locales, and will have the restrictions described below. Starting in Perl v5.22 a warning message is raised when Perl detects a multi-byte locale that it doesn't fully support.
For single-byte locales, Perl generally takes the tack to use locale rules on code points that can fit in a single byte, and Unicode rules for those that can't (though this isn't uniformly applied, see the note at the end of this section). This prevents many problems in locales that aren't UTF-8. Suppose the locale is ISO8859-7, Greek. The character at 0xD7 there is a capital Chi. But in the ISO8859-1 locale, Latin1, it is a multiplication sign. The POSIX regular expression character class `[[:alpha:]]` will magically match 0xD7 in the Greek locale but not in the Latin one.
However, there are places where this breaks down. Certain Perl constructs are for Unicode only, such as `\p{Alpha}`. They assume that 0xD7 always has its Unicode meaning (or the equivalent on EBCDIC platforms). Since Latin1 is a subset of Unicode and 0xD7 is the multiplication sign in both Latin1 and Unicode, `\p{Alpha}` will never match it, regardless of locale. A similar issue occurs with `\N{...}`. Prior to v5.20, it is therefore a bad idea to use `\p{}` or `\N{}` under plain `use locale`--*unless* you can guarantee that the locale will be ISO8859-1. Use POSIX character classes instead.
Another problem with this approach is that operations that cross the single byte/multiple byte boundary are not well-defined, and so are disallowed. (This boundary is between the codepoints at 255/256.) For example, lower casing LATIN CAPITAL LETTER Y WITH DIAERESIS (U+0178) should return LATIN SMALL LETTER Y WITH DIAERESIS (U+00FF). But in the Greek locale, for example, there is no character at 0xFF, and Perl has no way of knowing what the character at 0xFF is really supposed to represent. Thus it disallows the operation. In this mode, the lowercase of U+0178 is itself.
The same problems ensue if you enable automatic UTF-8-ification of your standard file handles, default `open()` layer, and `@ARGV` on non-ISO8859-1, non-UTF-8 locales (by using either the **-C** command line switch or the `PERL_UNICODE` environment variable; see [perlrun](perlrun#-C-%5Bnumber%2Flist%5D)). Things are read in as UTF-8, which would normally imply a Unicode interpretation, but the presence of a locale causes them to be interpreted in that locale instead. For example, a 0xD7 code point in the Unicode input, which should mean the multiplication sign, won't be interpreted by Perl that way under the Greek locale. This is not a problem *provided* you make certain that all locales will always and only be either an ISO8859-1, or, if you don't have a deficient C library, a UTF-8 locale.
Still another problem is that this approach can lead to two code points meaning the same character. Thus in a Greek locale, both U+03A7 and U+00D7 are GREEK CAPITAL LETTER CHI.
Because of all these problems, starting in v5.22, Perl will raise a warning if a multi-byte (hence Unicode) code point is used when a single-byte locale is in effect. (Although it doesn't check for this if doing so would unreasonably slow execution down.)
Vendor locales are notoriously buggy, and it is difficult for Perl to test its locale-handling code because this interacts with code that Perl has no control over; therefore the locale-handling code in Perl may be buggy as well. (However, the Unicode-supplied locales should be better, and there is a feed back mechanism to correct any problems. See ["Freely available locale definitions"](#Freely-available-locale-definitions).)
If you have Perl v5.16, the problems mentioned above go away if you use the `:not_characters` parameter to the locale pragma (except for vendor bugs in the non-character portions). If you don't have v5.16, and you *do* have locales that work, using them may be worthwhile for certain specific purposes, as long as you keep in mind the gotchas already mentioned. For example, if the collation for your locales works, it runs faster under locales than under <Unicode::Collate>; and you gain access to such things as the local currency symbol and the names of the months and days of the week. (But to hammer home the point, in v5.16, you get this access without the downsides of locales by using the `:not_characters` form of the pragma.)
Note: The policy of using locale rules for code points that can fit in a byte, and Unicode rules for those that can't is not uniformly applied. Pre-v5.12, it was somewhat haphazard; in v5.12 it was applied fairly consistently to regular expression matching except for bracketed character classes; in v5.14 it was extended to all regex matches; and in v5.16 to the casing operations such as `\L` and `uc()`. For collation, in all releases so far, the system's `strxfrm()` function is called, and whatever it does is what you get. Starting in v5.26, various bugs are fixed with the way perl uses this function.
BUGS
----
###
Collation of strings containing embedded `NUL` characters
`NUL` characters will sort the same as the lowest collating control character does, or to `"\001"` in the unlikely event that there are no control characters at all in the locale. In cases where the strings don't contain this non-`NUL` control, the results will be correct, and in many locales, this control, whatever it might be, will rarely be encountered. But there are cases where a `NUL` should sort before this control, but doesn't. If two strings do collate identically, the one containing the `NUL` will sort to earlier. Prior to 5.26, there were more bugs.
###
Multi-threaded
XS code or C-language libraries called from it that use the system [`setlocale(3)`](setlocale(3)) function (except on Windows) likely will not work from a multi-threaded application without changes. See ["Locale-aware XS code" in perlxs](perlxs#Locale-aware-XS-code).
An XS module that is locale-dependent could have been written under the assumption that it will never be called in a multi-threaded environment, and so uses other non-locale constructs that aren't multi-thread-safe. See ["Thread-aware system interfaces" in perlxs](perlxs#Thread-aware-system-interfaces).
POSIX does not define a way to get the name of the current per-thread locale. Some systems, such as Darwin and NetBSD do implement a function, [querylocale(3)](http://man.he.net/man3/querylocale) to do this. On non-Windows systems without it, such as Linux, there are some additional caveats:
* An embedded perl needs to be started up while the global locale is in effect. See ["Using embedded Perl with POSIX locales" in perlembed](perlembed#Using-embedded-Perl-with-POSIX-locales).
* It becomes more important for perl to know about all the possible locale categories on the platform, even if they aren't apparently used in your program. Perl knows all of the Linux ones. If your platform has others, you can submit an issue at <https://github.com/Perl/perl5/issues> for inclusion of it in the next release. In the meantime, it is possible to edit the Perl source to teach it about the category, and then recompile. Search for instances of, say, `LC_PAPER` in the source, and use that as a template to add the omitted one.
* It is possible, though hard to do, to call `POSIX::setlocale` with a locale that it doesn't recognize as syntactically legal, but actually is legal on that system. This should happen only with embedded perls, or if you hand-craft a locale name yourself.
###
Broken systems
In certain systems, the operating system's locale support is broken and cannot be fixed or used by Perl. Such deficiencies can and will result in mysterious hangs and/or Perl core dumps when `use locale` is in effect. When confronted with such a system, please report in excruciating detail to <<https://github.com/Perl/perl5/issues>>, and also contact your vendor: bug fixes may exist for these problems in your operating system. Sometimes such bug fixes are called an operating system upgrade. If you have the source for Perl, include in the bug report the output of the test described above in ["Testing for broken locales"](#Testing-for-broken-locales).
SEE ALSO
---------
<I18N::Langinfo>, <perluniintro>, <perlunicode>, <open>, ["localeconv" in POSIX](posix#localeconv), ["setlocale" in POSIX](posix#setlocale), ["strcoll" in POSIX](posix#strcoll), ["strftime" in POSIX](posix#strftime), ["strtod" in POSIX](posix#strtod), ["strxfrm" in POSIX](posix#strxfrm).
For special considerations when Perl is embedded in a C program, see ["Using embedded Perl with POSIX locales" in perlembed](perlembed#Using-embedded-Perl-with-POSIX-locales).
HISTORY
-------
Jarkko Hietaniemi's original *perli18n.pod* heavily hacked by Dominic Dunlop, assisted by the perl5-porters. Prose worked over a bit by Tom Christiansen, and now maintained by Perl 5 porters.
| programming_docs |
perl perlrequick perlrequick
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [The Guide](#The-Guide)
+ [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)
+ [Matching repetitions](#Matching-repetitions)
+ [More matching](#More-matching)
+ [Search and replace](#Search-and-replace)
+ [The split operator](#The-split-operator)
+ [use re 'strict'](#use-re-'strict')
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
+ [Acknowledgments](#Acknowledgments)
NAME
----
perlrequick - Perl regular expressions quick start
DESCRIPTION
-----------
This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.
The Guide
----------
This page assumes you already know things, like what a "pattern" is, and the basic syntax of using them. If you don't, see <perlretut>.
###
Simple word matching
The simplest regex is simply a word, or more generally, a string of characters. A regex consisting of a word matches any string that contains that word:
```
"Hello World" =~ /World/; # matches
```
In this statement, `World` is a regex and the `//` enclosing `/World/` tells Perl to search a string for a match. The operator `=~` associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, `World` matches the second word in `"Hello World"`, so the expression is true. This idea has several variations.
Expressions like this are useful in conditionals:
```
print "It matches\n" if "Hello World" =~ /World/;
```
The sense of the match can be reversed by using `!~` operator:
```
print "It doesn't match\n" if "Hello World" !~ /World/;
```
The literal string in the regex can be replaced by a variable:
```
$greeting = "World";
print "It matches\n" if "Hello World" =~ /$greeting/;
```
If you're matching against `$_`, the `$_ =~` part can be omitted:
```
$_ = "Hello World";
print "It matches\n" if /World/;
```
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 matching '{}'
"/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
# '/' becomes an ordinary char
```
Regexes must match a part of the string *exactly* in order for the statement to be true:
```
"Hello World" =~ /world/; # doesn't match, case sensitive
"Hello World" =~ /o W/; # matches, ' ' is an ordinary char
"Hello World" =~ /World /; # doesn't match, no ' ' at end
```
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'
```
Not all characters can be used 'as is' in a match. Some characters, called **metacharacters**, are considered special, and reserved for use in regex notation. The metacharacters are
```
{}[]()^$.|*+?\
```
A metacharacter can be matched literally 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 +
'C:\WIN32' =~ /C:\\WIN/; # matches
"/usr/bin/perl" =~ /\/usr\/bin\/perl/; # matches
```
In the last regex, the forward slash `'/'` is also backslashed, because it is used to delimit the regex.
Most of the metacharacters aren't always special, and other characters (such as the ones delimiting the pattern) become special under various circumstances. This can be confusing and lead to unexpected results. [`use re 'strict'`](re#%27strict%27-mode) can notify you of potential pitfalls.
Non-printable ASCII characters are represented by **escape sequences**. Common examples are `\t` for a tab, `\n` for a newline, and `\r` for a carriage return. Arbitrary bytes are represented by octal escape sequences, e.g., `\033`, or hexadecimal escape sequences, e.g., `\x1B`:
```
"1000\t2000" =~ m(0\t2) # matches
"cat" =~ /\143\x61\x74/ # matches in ASCII, but
# a weird way to spell cat
```
Regexes are treated mostly as double-quoted strings, so variable substitution works:
```
$foo = 'house';
'cathouse' =~ /cat$foo/; # matches
'housecat' =~ /${foo}cat/; # matches
```
With all of the regexes above, if the regex matched anywhere in the string, it was considered a match. To specify *where* it should match, 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. Some examples:
```
"housekeeper" =~ /keeper/; # matches
"housekeeper" =~ /^keeper/; # doesn't match
"housekeeper" =~ /keeper$/; # matches
"housekeeper\n" =~ /keeper$/; # matches
"housekeeper" =~ /^housekeeper$/; # matches
```
###
Using character classes
A **character class** allows a set of possible characters, rather than just a single character, to match at a particular point in a regex. There are a number of different types of character classes, but usually when people use this term, they are referring to the type described in this section, which are technically called "Bracketed character classes", because they are denoted by brackets `[...]`, with the set of characters to be possibly matched inside. But we'll drop the "bracketed" below to correspond with common usage. Here are some examples of (bracketed) character classes:
```
/cat/; # matches 'cat'
/[bcr]at/; # matches 'bat', 'cat', or 'rat'
"abc" =~ /[cab]/; # matches 'a'
```
In the last statement, even though `'c'` is the first character in the class, the earliest point at which the regex can match is `'a'`.
```
/[yY][eE][sS]/; # match 'yes' in a case-insensitive way
# 'yes', 'Yes', 'YES', etc.
/yes/i; # also match 'yes' in a case-insensitive way
```
The last example shows a match with an `'i'` **modifier**, which makes the match case-insensitive.
Character classes also have ordinary and special characters, 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 are matched using an escape:
```
/[\]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 special character `'-'` acts as a range operator within character classes, so that the unwieldy `[0123456789]` and `[abc...xyz]` become the svelte `[0-9]` and `[a-z]`:
```
/item[0-9]/; # matches 'item0' or ... or 'item9'
/[0-9a-fA-F]/; # matches a hexadecimal digit
```
If `'-'` is the first or last character in a character class, it is treated as an ordinary character.
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
```
Perl has several abbreviations for common character classes. (These definitions are those that Perl uses in ASCII-safe mode with the `/a` modifier. Otherwise they could match many more non-ASCII Unicode characters as well. See ["Backslash sequences" in perlrecharclass](perlrecharclass#Backslash-sequences) for details.)
* \d is a digit and represents
```
[0-9]
```
* \s is a whitespace character and represents
```
[\ \t\r\n\f]
```
* \w is a word character (alphanumeric or \_) and represents
```
[0-9a-zA-Z_]
```
* \D is a negated \d; it represents any character but a digit
```
[^0-9]
```
* \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"
The `\d\s\w\D\S\W` abbreviations can be used both inside and outside of 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.'
```
The **word anchor** `\b` matches a boundary between a word character and a non-word character `\w\W` or `\W\w`:
```
$x = "Housecat catenates house and cat";
$x =~ /\bcat/; # matches cat in 'catenates'
$x =~ /cat\b/; # matches cat in 'housecat'
$x =~ /\bcat\b/; # matches 'cat' at end of string
```
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
```
###
Matching this or that
We can match different character strings with the **alternation** metacharacter `'|'`. To match `dog` or `cat`, we form the regex `dog|cat`. As before, Perl will try to match the regex 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 regex, `cat` is able to match earlier in the string.
```
"cats" =~ /c|ca|cat|cats/; # matches "c"
"cats" =~ /cats|cat|ca|c/; # matches "cats"
```
At a given character position, the first alternative that allows the regex match to succeed will be the one that matches. Here, all the alternatives match at the first string position, so the first matches.
###
Grouping things and hierarchical matching
The **grouping** metacharacters `()` allow a part of a regex to be treated as a single unit. Parts of a regex are grouped by enclosing them in parentheses. The regex `house(cat|keeper)` means match `house` followed by either `cat` or `keeper`. Some more examples are
```
/(a|b)b/; # matches 'ab' or 'bb'
/(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
/house(cat|)/; # matches either 'housecat' or 'house'
/house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
# 'house'. Note groups can be nested.
"20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
# because '20\d\d' can't match
```
###
Extracting matches
The grouping metacharacters `()` also allow the extraction of the parts of a string that matched. 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
$time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;
```
In list context, a match `/regex/` with groupings will return the list of matched values `($1,$2,...)`. So we could rewrite it as
```
($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
```
If the groupings in a regex are nested, `$1` gets the group with the leftmost opening parenthesis, `$2` the next opening parenthesis, etc. For example, here is a complex regex and the matching variables indicated below it:
```
/(ab(cd|ef)((gi)|j))/;
1 2 34
```
Associated with the matching variables `$1`, `$2`, ... are the **backreferences** `\g1`, `\g2`, ... Backreferences are matching variables that can be used *inside* a regex:
```
/(\w\w\w)\s\g1/; # find sequences like 'the the' in string
```
`$1`, `$2`, ... should only be used outside of a regex, and `\g1`, `\g2`, ... only inside a regex.
###
Matching repetitions
The **quantifier** metacharacters `?`, `*`, `+`, and `{}` allow us to determine the number of repeats of a portion of a regex 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?` = match 'a' 1 or 0 times
* `a*` = match 'a' 0 or more times, i.e., any number of times
* `a+` = match 'a' 1 or more times, i.e., at least once
* `a{n,m}` = match at least `n` times, but not more than `m` times.
* `a{n,}` = match at least `n` or more times
* `a{,n}` = match `n` times or fewer
* `a{n}` = match exactly `n` times
Here are some examples:
```
/[a-z]+\s+\d*/; # match a lowercase word, at least some space, and
# any number of digits
/(\w+)\s+\g1/; # match doubled words of arbitrary length
$year =~ /^\d{2,4}$/; # make sure year is at least 2 but not more
# than 4 digits
$year =~ /^\d{ 4 }$|^\d{2}$/; # better match; throw out 3 digit dates
```
These quantifiers will try to match as much of the string as possible, while still allowing the regex to match. So we have
```
$x = 'the cat in the hat';
$x =~ /^(.*)(at)(.*)$/; # matches,
# $1 = 'the cat in the h'
# $2 = 'at'
# $3 = '' (0 matches)
```
The first quantifier `.*` grabs as much of the string as possible while still having the regex match. The second quantifier `.*` has no string left to it, so it matches 0 times.
###
More matching
There are a few more things you might want to know about matching operators. The global modifier `/g` allows the matching operator to match within a string as many times as possible. In scalar context, successive matches 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. For example,
```
$x = "cat dog house"; # 3 words
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 `/regex/gc`.
In list context, `/g` returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex. So
```
@words = ($x =~ /(\w+)/g); # matches,
# $word[0] = 'cat'
# $word[1] = 'dog'
# $word[2] = 'house'
```
###
Search and replace
Search and replace is performed using `s/regex/replacement/modifiers`. The `replacement` is a Perl double-quoted string that replaces in the string whatever is matched with the `regex`. 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!"
$y = "'quoted words'";
$y =~ s/^'(.*)'$/$1/; # strip single quotes,
# $y contains "quoted words"
```
With the `s///` operator, the matched variables `$1`, `$2`, etc. are immediately available for use in the replacement expression. With the global modifier, `s///g` will search and replace all occurrences of the regex in the string:
```
$x = "I batted 4 for 4";
$x =~ s/4/four/; # $x contains "I batted four for 4"
$x = "I batted 4 for 4";
$x =~ s/4/four/g; # $x contains "I batted four for four"
```
The non-destructive modifier `s///r` causes the result of the substitution to be returned instead of modifying `$_` (or whatever variable the substitute was bound to with `=~`):
```
$x = "I like dogs.";
$y = $x =~ s/dogs/cats/r;
print "$x $y\n"; # prints "I like dogs. I like cats."
$x = "Cats are great.";
print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
s/Frogs/Hedgehogs/r, "\n";
# prints "Hedgehogs are great."
@foo = map { s/[a-z]/X/r } qw(a b c 1 2 3);
# @foo is now qw(X X X 1 2 3)
```
The evaluation modifier `s///e` wraps an `eval{...}` around the replacement string and the evaluated result is substituted for the matched substring. Some examples:
```
# reverse all the words in a string
$x = "the cat in the hat";
$x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah"
# convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"
```
The last example shows that `s///` can use other delimiters, such as `s!!!` and `s{}{}`, and even `s{}//`. If single quotes are used `s'''`, then the regex and replacement are treated as single-quoted strings.
###
The split operator
`split /regex/, string` splits `string` into a list of substrings and returns that list. The regex determines the character sequence that `string` is split with respect to. For example, to split a string into words, use
```
$x = "Calvin and Hobbes";
@word = split /\s+/, $x; # $word[0] = 'Calvin'
# $word[1] = 'and'
# $word[2] = 'Hobbes'
```
To extract a comma-delimited list of numbers, use
```
$x = "1.618,2.718, 3.142";
@const = split /,\s*/, $x; # $const[0] = '1.618'
# $const[1] = '2.718'
# $const[2] = '3.142'
```
If the empty regex `//` is used, the string is split into individual characters. If the regex has groupings, then the list produced contains the matched substrings from the groupings as well:
```
$x = "/usr/bin";
@parts = split m!(/)!, $x; # $parts[0] = ''
# $parts[1] = '/'
# $parts[2] = 'usr'
# $parts[3] = '/'
# $parts[4] = 'bin'
```
Since the first character of $x matched the regex, `split` prepended an empty initial element to the list.
###
`use re 'strict'`
New in v5.22, this applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended.
See ['strict' in re](re#%27strict%27-mode).
BUGS
----
None.
SEE ALSO
---------
This is just a quick start guide. For a more in-depth tutorial on regexes, see <perlretut> and for the reference page, see <perlre>.
AUTHOR AND COPYRIGHT
---------------------
Copyright (c) 2000 Mark Kvale All rights reserved.
This document may be distributed under the same terms as Perl itself.
### Acknowledgments
The author would like to thank Mark-Jason Dominus, Tom Christiansen, Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful comments.
perl perlunitut perlunitut
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Definitions](#Definitions)
- [Unicode](#Unicode)
- [UTF-8](#UTF-8)
- [Text strings (character strings)](#Text-strings-(character-strings))
- [Binary strings (byte strings)](#Binary-strings-(byte-strings))
- [Encoding](#Encoding)
- [Decoding](#Decoding)
- [Internal format](#Internal-format)
+ [Your new toolkit](#Your-new-toolkit)
+ [I/O flow (the actual 5 minute tutorial)](#I/O-flow-(the-actual-5-minute-tutorial))
* [SUMMARY](#SUMMARY)
* [Q and A (or FAQ)](#Q-and-A-(or-FAQ))
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlunitut - Perl Unicode Tutorial
DESCRIPTION
-----------
The days of just flinging strings around are over. It's well established that modern programs need to be capable of communicating funny accented letters, and things like euro symbols. This means that programmers need new habits. It's easy to program Unicode capable software, but it does require discipline to do it right.
There's a lot to know about character sets, and text encodings. It's probably best to spend a full day learning all this, but the basics can be learned in minutes.
These are not the very basics, though. It is assumed that you already know the difference between bytes and characters, and realise (and accept!) that there are many different character sets and encodings, and that your program has to be explicit about them. Recommended reading is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" by Joel Spolsky, at <http://joelonsoftware.com/articles/Unicode.html>.
This tutorial speaks in rather absolute terms, and provides only a limited view of the wealth of character string related features that Perl has to offer. For most projects, this information will probably suffice.
### Definitions
It's important to set a few things straight first. This is the most important part of this tutorial. This view may conflict with other information that you may have found on the web, but that's mostly because many sources are wrong.
You may have to re-read this entire section a few times...
#### Unicode
**Unicode** is a character set with room for lots of characters. The ordinal value of a character is called a **code point**. (But in practice, the distinction between code point and character is blurred, so the terms often are used interchangeably.)
There are many, many code points, but computers work with bytes, and a byte has room for only 256 values. Unicode has many more characters than that, so you need a method to make these accessible.
Unicode is encoded using several competing encodings, of which UTF-8 is the most used. In a Unicode encoding, multiple subsequent bytes can be used to store a single code point, or simply: character.
####
UTF-8
**UTF-8** is a Unicode encoding. Many people think that Unicode and UTF-8 are the same thing, but they're not. There are more Unicode encodings, but much of the world has standardized on UTF-8.
UTF-8 treats the first 128 codepoints, 0..127, the same as ASCII. They take only one byte per character. All other characters are encoded as two to four bytes using a complex scheme. Fortunately, Perl handles this for us, so we don't have to worry about this.
####
Text strings (character strings)
**Text strings**, or **character strings** are made of characters. Bytes are irrelevant here, and so are encodings. Each character is just that: the character.
On a text string, you would do things like:
```
$text =~ s/foo/bar/;
if ($string =~ /^\d+$/) { ... }
$text = ucfirst $text;
my $character_count = length $text;
```
The value of a character (`ord`, `chr`) is the corresponding Unicode code point.
####
Binary strings (byte strings)
**Binary strings**, or **byte strings** are made of bytes. Here, you don't have characters, just bytes. All communication with the outside world (anything outside of your current Perl process) is done in binary.
On a binary string, you would do things like:
```
my (@length_content) = unpack "(V/a)*", $binary;
$binary =~ s/\x00\x0F/\xFF\xF0/; # for the brave :)
print {$fh} $binary;
my $byte_count = length $binary;
```
#### Encoding
**Encoding** (as a verb) is the conversion from *text* to *binary*. To encode, you have to supply the target encoding, for example `iso-8859-1` or `UTF-8`. Some encodings, like the `iso-8859` ("latin") range, do not support the full Unicode standard; characters that can't be represented are lost in the conversion.
#### Decoding
**Decoding** is the conversion from *binary* to *text*. To decode, you have to know what encoding was used during the encoding phase. And most of all, it must be something decodable. It doesn't make much sense to decode a PNG image into a text string.
####
Internal format
Perl has an **internal format**, an encoding that it uses to encode text strings so it can store them in memory. All text strings are in this internal format. In fact, text strings are never in any other format!
You shouldn't worry about what this format is, because conversion is automatically done when you decode or encode.
###
Your new toolkit
Add to your standard heading the following line:
```
use Encode qw(encode decode);
```
Or, if you're lazy, just:
```
use Encode;
```
###
I/O flow (the actual 5 minute tutorial)
The typical input/output flow of a program is:
```
1. Receive and decode
2. Process
3. Encode and output
```
If your input is binary, and is supposed to remain binary, you shouldn't decode it to a text string, of course. But in all other cases, you should decode it.
Decoding can't happen reliably if you don't know how the data was encoded. If you get to choose, it's a good idea to standardize on UTF-8.
```
my $foo = decode('UTF-8', get 'http://example.com/');
my $bar = decode('ISO-8859-1', readline STDIN);
my $xyzzy = decode('Windows-1251', $cgi->param('foo'));
```
Processing happens as you knew before. The only difference is that you're now using characters instead of bytes. That's very useful if you use things like `substr`, or `length`.
It's important to realize that there are no bytes in a text string. Of course, Perl has its internal encoding to store the string in memory, but ignore that. If you have to do anything with the number of bytes, it's probably best to move that part to step 3, just after you've encoded the string. Then you know exactly how many bytes it will be in the destination string.
The syntax for encoding text strings to binary strings is as simple as decoding:
```
$body = encode('UTF-8', $body);
```
If you needed to know the length of the string in bytes, now's the perfect time for that. Because `$body` is now a byte string, `length` will report the number of bytes, instead of the number of characters. The number of characters is no longer known, because characters only exist in text strings.
```
my $byte_count = length $body;
```
And if the protocol you're using supports a way of letting the recipient know which character encoding you used, please help the receiving end by using that feature! For example, E-mail and HTTP support MIME headers, so you can use the `Content-Type` header. They can also have `Content-Length` to indicate the number of *bytes*, which is always a good idea to supply if the number is known.
```
"Content-Type: text/plain; charset=UTF-8",
"Content-Length: $byte_count"
```
SUMMARY
-------
Decode everything you receive, encode everything you send out. (If it's text data.)
Q and A (or FAQ)
-----------------
After reading this document, you ought to read <perlunifaq> too, then <perluniintro>.
ACKNOWLEDGEMENTS
----------------
Thanks to Johan Vromans from Squirrel Consultancy. His UTF-8 rants during the Amsterdam Perl Mongers meetings got me interested and determined to find out how to use character encodings in Perl in ways that don't break easily.
Thanks to Gerard Goossen from TTY. His presentation "UTF-8 in the wild" (Dutch Perl Workshop 2006) inspired me to publish my thoughts and write this tutorial.
Thanks to the people who asked about this kind of stuff in several Perl IRC channels, and have constantly reminded me that a simpler explanation was needed.
Thanks to the people who reviewed this document for me, before it went public. They are: Benjamin Smith, Jan-Pieter Cornet, Johan Vromans, Lukas Mai, Nathan Gray.
AUTHOR
------
Juerd Waalboer <#####@juerd.nl>
SEE ALSO
---------
<perlunifaq>, <perlunicode>, <perluniintro>, [Encode](encode)
| programming_docs |
perl perldoc perldoc
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [SECURITY](#SECURITY)
* [ENVIRONMENT](#ENVIRONMENT)
* [CHANGES](#CHANGES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perldoc - Look up Perl documentation in Pod format.
SYNOPSIS
--------
```
perldoc [-h] [-D] [-t] [-u] [-m] [-l] [-U] [-F]
[-i] [-V] [-T] [-r]
[-d destination_file]
[-o formatname]
[-M FormatterClassName]
[-w formatteroption:value]
[-n nroff-replacement]
[-X]
[-L language_code]
PageName|ModuleName|ProgramName|URL
```
Examples:
```
perldoc -f BuiltinFunction
perldoc -L it -f BuiltinFunction
perldoc -q FAQ Keyword
perldoc -L fr -q FAQ Keyword
perldoc -v PerlVariable
perldoc -a PerlAPI
```
See below for more description of the switches.
DESCRIPTION
-----------
**perldoc** looks up documentation in .pod format that is embedded in the perl installation tree or in a perl script, and displays it using a variety of formatters. This is primarily used for the documentation for the perl library modules.
Your system may also have man pages installed for those modules, in which case you can probably just use the man(1) command.
If you are looking for a table of contents to the Perl library modules documentation, see the <perltoc> page.
OPTIONS
-------
**-h**
Prints out a brief **h**elp message.
**-D**
**D**escribes search for the item in **d**etail.
**-t**
Display docs using plain **t**ext converter, instead of nroff. This may be faster, but it probably won't look as nice.
**-u**
Skip the real Pod formatting, and just show the raw Pod source (**U**nformatted)
**-m** *module*
Display the entire module: both code and unformatted pod documentation. This may be useful if the docs don't explain a function in the detail you need, and you'd like to inspect the code directly; perldoc will find the file for you and simply hand it off for display.
**-l**
Display on**l**y the file name of the module found.
**-U**
When running as the superuser, don't attempt drop privileges for security. This option is implied with **-F**.
**NOTE**: Please see the heading SECURITY below for more information.
**-F**
Consider arguments as file names; no search in directories will be performed. Implies **-U** if run as the superuser.
**-f** *perlfunc*
The **-f** option followed by the name of a perl built-in function will extract the documentation of this function from <perlfunc>.
Example:
```
perldoc -f sprintf
```
**-q** *perlfaq-search-regexp*
The **-q** option takes a regular expression as an argument. It will search the **q**uestion headings in perlfaq[1-9] and print the entries matching the regular expression.
Example:
```
perldoc -q shuffle
```
**-a** *perlapifunc*
The **-a** option followed by the name of a perl api function will extract the documentation of this function from <perlapi>.
Example:
```
perldoc -a newHV
```
**-v** *perlvar*
The **-v** option followed by the name of a Perl predefined variable will extract the documentation of this variable from <perlvar>.
Examples:
```
perldoc -v '$"'
perldoc -v @+
perldoc -v DATA
```
**-T**
This specifies that the output is not to be sent to a pager, but is to be sent directly to STDOUT.
**-d** *destination-filename*
This specifies that the output is to be sent neither to a pager nor to STDOUT, but is to be saved to the specified filename. Example: `perldoc -oLaTeX -dtextwrapdocs.tex Text::Wrap`
**-o** *output-formatname*
This specifies that you want Perldoc to try using a Pod-formatting class for the output format that you specify. For example: `-oman`. This is actually just a wrapper around the `-M` switch; using `-o*formatname*` just looks for a loadable class by adding that format name (with different capitalizations) to the end of different classname prefixes.
For example, `-oLaTeX` currently tries all of the following classes: Pod::Perldoc::ToLaTeX Pod::Perldoc::Tolatex Pod::Perldoc::ToLatex Pod::Perldoc::ToLATEX Pod::Simple::LaTeX Pod::Simple::latex Pod::Simple::Latex Pod::Simple::LATEX Pod::LaTeX Pod::latex Pod::Latex Pod::LATEX.
**-M** *module-name*
This specifies the module that you want to try using for formatting the pod. The class must at least provide a `parse_from_file` method. For example: `perldoc -MPod::Perldoc::ToChecker`.
You can specify several classes to try by joining them with commas or semicolons, as in `-MTk::SuperPod;Tk::Pod`.
**-w** *option:value* or **-w** *option*
This specifies an option to call the formatter **w**ith. For example, `-w textsize:15` will call `$formatter->textsize(15)` on the formatter object before it is used to format the object. For this to be valid, the formatter class must provide such a method, and the value you pass should be valid. (So if `textsize` expects an integer, and you do `-w textsize:big`, expect trouble.)
You can use `-w optionname` (without a value) as shorthand for `-w optionname:*TRUE*`. This is presumably useful in cases of on/off features like: `-w page_numbering`.
You can use an "=" instead of the ":", as in: `-w textsize=15`. This might be more (or less) convenient, depending on what shell you use.
**-X**
Use an index if it is present. The **-X** option looks for an entry whose basename matches the name given on the command line in the file `$Config{archlib}/pod.idx`. The *pod.idx* file should contain fully qualified filenames, one per line.
**-L** *language\_code*
This allows one to specify the *language code* for the desired language translation. If the `POD2::<language_code>` package isn't installed in your system, the switch is ignored. All available translation packages are to be found under the `POD2::` namespace. See <POD2::IT> (or <POD2::FR>) to see how to create new localized `POD2::*` documentation packages and integrate them into <Pod::Perldoc>.
**PageName|ModuleName|ProgramName|URL**
The item you want to look up. Nested modules (such as `File::Basename`) are specified either as `File::Basename` or `File/Basename`. You may also give a descriptive name of a page, such as `perlfunc`. For URLs, HTTP and HTTPS are the only kind currently supported.
For simple names like 'foo', when the normal search fails to find a matching page, a search with the "perl" prefix is tried as well. So "perldoc intro" is enough to find/render "perlintro.pod".
**-n** *some-formatter*
Specify replacement for groff
**-r**
Recursive search.
**-i**
Ignore case.
**-V**
Displays the version of perldoc you're running.
SECURITY
--------
Because **perldoc** does not run properly tainted, and is known to have security issues, when run as the superuser it will attempt to drop privileges by setting the effective and real IDs to nobody's or nouser's account, or -2 if unavailable. If it cannot relinquish its privileges, it will not run.
See the `-U` option if you do not want this behavior but **beware** that there are significant security risks if you choose to use `-U`.
Since 3.26, using `-F` as the superuser also implies `-U` as opening most files and traversing directories requires privileges that are above the nobody/nogroup level.
ENVIRONMENT
-----------
Any switches in the `PERLDOC` environment variable will be used before the command line arguments.
Useful values for `PERLDOC` include `-oterm`, `-otext`, `-ortf`, `-oxml`, and so on, depending on what modules you have on hand; or the formatter class may be specified exactly with `-MPod::Perldoc::ToTerm` or the like.
`perldoc` also searches directories specified by the `PERL5LIB` (or `PERLLIB` if `PERL5LIB` is not defined) and `PATH` environment variables. (The latter is so that embedded pods for executables, such as `perldoc` itself, are available.)
In directories where either `Makefile.PL` or `Build.PL` exist, `perldoc` will add `.` and `lib` first to its search path, and as long as you're not the superuser will add `blib` too. This is really helpful if you're working inside of a build directory and want to read through the docs even if you have a version of a module previously installed.
`perldoc` will use, in order of preference, the pager defined in `PERLDOC_PAGER`, `MANPAGER`, or `PAGER` before trying to find a pager on its own. (`MANPAGER` is not used if `perldoc` was told to display plain text or unformatted pod.)
When using perldoc in it's `-m` mode (display module source code), `perldoc` will attempt to use the pager set in `PERLDOC_SRC_PAGER`. A useful setting for this command is your favorite editor as in `/usr/bin/nano`. (Don't judge me.)
One useful value for `PERLDOC_PAGER` is `less -+C -E`.
Having PERLDOCDEBUG set to a positive integer will make perldoc emit even more descriptive output than the `-D` switch does; the higher the number, the more it emits.
CHANGES
-------
Up to 3.14\_05, the switch **-v** was used to produce verbose messages of **perldoc** operation, which is now enabled by **-D**.
SEE ALSO
---------
<perlpod>, <Pod::Perldoc>
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributors are: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`, Kenneth Albanowski `<[email protected]>`, Andy Dougherty `<[email protected]>`, and many others.
perl Test2::Formatter Test2::Formatter
================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [CREATING FORMATTERS](#CREATING-FORMATTERS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Formatter - Namespace for formatters.
DESCRIPTION
-----------
This is the namespace for formatters. This is an empty package.
CREATING FORMATTERS
--------------------
A formatter is any package or object with a `write($event, $num)` method.
```
package Test2::Formatter::Foo;
use strict;
use warnings;
sub write {
my $self_or_class = shift;
my ($event, $assert_num) = @_;
...
}
sub hide_buffered { 1 }
sub terminate { }
sub finalize { }
sub supports_tables { return $BOOL }
sub new_root {
my $class = shift;
...
$class->new(@_);
}
1;
```
The `write` method is a method, so it either gets a class or instance. The two arguments are the `$event` object it should record, and the `$assert_num` which is the number of the current assertion (ok), or the last assertion if this event is not itself an assertion. The assertion number may be any integer 0 or greater, and may be undefined in some cases.
The `hide_buffered()` method must return a boolean. This is used to tell buffered subtests whether or not to send it events as they are being buffered. See ["run\_subtest(...)" in Test2::API](Test2::API#run_subtest%28...%29) for more information.
The `terminate` and `finalize` methods are optional methods called that you can implement if the format you're generating needs to handle these cases, for example if you are generating XML and need close open tags.
The `terminate` method is called when an event's `terminate` method returns true, for example when a <Test2::Event::Plan> has a `'skip_all'` plan, or when a <Test2::Event::Bail> event is sent. The `terminate` method is passed a single argument, the <Test2::Event> object which triggered the terminate.
The `finalize` method is always the last thing called on the formatter, *except when `terminate` is called for a Bail event*. It is passed the following arguments:
The `supports_tables` method should be true if the formatter supports directly rendering table data from the `info` facets. This is a newer feature and many older formatters may not support it. When not supported the formatter falls back to rendering `detail` instead of the `table` data.
The `new_root` method is used when constructing a root formatter. The default is to just delegate to the regular `new()` method, most formatters can ignore this.
* The number of tests that were planned
* The number of tests actually seen
* The number of tests which failed
* A boolean indicating whether or not the test suite passed
* A boolean indicating whether or not this call is for a subtest
The `new_root` method is called when `Test2::API::Stack` Initializes the root hub for the first time. Most formatters will simply have this call `$class->new`, which is the default behavior. Some formatters however may want to take extra action during construction of the root formatter, this is where they can do that.
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::CBuilder ExtUtils::CBuilder
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [TO DO](#TO-DO)
* [HISTORY](#HISTORY)
* [SUPPORT](#SUPPORT)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::CBuilder - Compile and link C code for Perl modules
SYNOPSIS
--------
```
use ExtUtils::CBuilder;
my $b = ExtUtils::CBuilder->new(%options);
$obj_file = $b->compile(source => 'MyModule.c');
$lib_file = $b->link(objects => $obj_file);
```
DESCRIPTION
-----------
This module can build the C portions of Perl modules by invoking the appropriate compilers and linkers in a cross-platform manner. It was motivated by the `Module::Build` project, but may be useful for other purposes as well. However, it is *not* intended as a general cross-platform interface to all your C building needs. That would have been a much more ambitious goal!
METHODS
-------
new Returns a new `ExtUtils::CBuilder` object. A `config` parameter lets you override `Config.pm` settings for all operations performed by the object, as in the following example:
```
# Use a different compiler than Config.pm says
my $b = ExtUtils::CBuilder->new( config =>
{ ld => 'gcc' } );
```
A `quiet` parameter tells `CBuilder` to not print its `system()` commands before executing them:
```
# Be quieter than normal
my $b = ExtUtils::CBuilder->new( quiet => 1 );
```
have\_compiler Returns true if the current system has a working C compiler and linker, false otherwise. To determine this, we actually compile and link a sample C library. The sample will be compiled in the system tempdir or, if that fails for some reason, in the current directory.
have\_cplusplus Just like have\_compiler but for C++ instead of C.
compile Compiles a C source file and produces an object file. The name of the object file is returned. The source file is specified in a `source` parameter, which is required; the other parameters listed below are optional.
`object_file` Specifies the name of the output file to create. Otherwise the `object_file()` method will be consulted, passing it the name of the `source` file.
`include_dirs` Specifies any additional directories in which to search for header files. May be given as a string indicating a single directory, or as a list reference indicating multiple directories.
`extra_compiler_flags` Specifies any additional arguments to pass to the compiler. Should be given as a list reference containing the arguments individually, or if this is not possible, as a string containing all the arguments together.
`C++`
Specifies that the source file is a C++ source file and sets appropriate compiler flags
The operation of this method is also affected by the `archlibexp`, `cccdlflags`, `ccflags`, `optimize`, and `cc` entries in `Config.pm`.
link Invokes the linker to produce a library file from object files. In scalar context, the name of the library file is returned. In list context, the library file and any temporary files created are returned. A required `objects` parameter contains the name of the object files to process, either in a string (for one object file) or list reference (for one or more files). The following parameters are optional:
lib\_file Specifies the name of the output library file to create. Otherwise the `lib_file()` method will be consulted, passing it the name of the first entry in `objects`.
module\_name Specifies the name of the Perl module that will be created by linking. On platforms that need to do prelinking (Win32, OS/2, etc.) this is a required parameter.
extra\_linker\_flags Any additional flags you wish to pass to the linker.
On platforms where `need_prelink()` returns true, `prelink()` will be called automatically.
The operation of this method is also affected by the `lddlflags`, `shrpenv`, and `ld` entries in `Config.pm`.
link\_executable Invokes the linker to produce an executable file from object files. In scalar context, the name of the executable file is returned. In list context, the executable file and any temporary files created are returned. A required `objects` parameter contains the name of the object files to process, either in a string (for one object file) or list reference (for one or more files). The optional parameters are the same as `link` with exception for
exe\_file Specifies the name of the output executable file to create. Otherwise the `exe_file()` method will be consulted, passing it the name of the first entry in `objects`.
object\_file
```
my $object_file = $b->object_file($source_file);
```
Converts the name of a C source file to the most natural name of an output object file to create from it. For instance, on Unix the source file *foo.c* would result in the object file *foo.o*.
lib\_file
```
my $lib_file = $b->lib_file($object_file);
```
Converts the name of an object file to the most natural name of a output library file to create from it. For instance, on Mac OS X the object file *foo.o* would result in the library file *foo.bundle*.
exe\_file
```
my $exe_file = $b->exe_file($object_file);
```
Converts the name of an object file to the most natural name of an executable file to create from it. For instance, on Mac OS X the object file *foo.o* would result in the executable file *foo*, and on Windows it would result in *foo.exe*.
prelink On certain platforms like Win32, OS/2, VMS, and AIX, it is necessary to perform some actions before invoking the linker. The `ExtUtils::Mksymlists` module does this, writing files used by the linker during the creation of shared libraries for dynamic extensions. The names of any files written will be returned as a list.
Several parameters correspond to `ExtUtils::Mksymlists::Mksymlists()` options, as follows:
```
Mksymlists() prelink() type
-------------|-------------------|-------------------
NAME | dl_name | string (required)
DLBASE | dl_base | string
FILE | dl_file | string
DL_VARS | dl_vars | array reference
DL_FUNCS | dl_funcs | hash reference
FUNCLIST | dl_func_list | array reference
IMPORTS | dl_imports | hash reference
VERSION | dl_version | string
```
Please see the documentation for `ExtUtils::Mksymlists` for the details of what these parameters do.
need\_prelink Returns true on platforms where `prelink()` should be called during linking, and false otherwise.
extra\_link\_args\_after\_prelink Returns list of extra arguments to give to the link command; the arguments are the same as for prelink(), with addition of array reference to the results of prelink(); this reference is indexed by key `prelink_res`.
TO DO
------
Currently this has only been tested on Unix and doesn't contain any of the Windows-specific code from the `Module::Build` project. I'll do that next.
HISTORY
-------
This module is an outgrowth of the `Module::Build` project, to which there have been many contributors. Notably, Randy W. Sims submitted lots of code to support 3 compilers on Windows and helped with various other platform-specific issues. Ilya Zakharevich has contributed fixes for OS/2; John E. Malmberg and Peter Prymmer have done likewise for VMS.
SUPPORT
-------
ExtUtils::CBuilder is maintained as part of the Perl 5 core. Please submit any bug reports via the *perlbug* tool included with Perl 5. Bug reports will be included in the Perl 5 ticket system at <https://rt.perl.org>.
The Perl 5 source code is available at <https://perl5.git.perl.org/perl.git> and ExtUtils-CBuilder may be found in the *dist/ExtUtils-CBuilder* directory of the repository.
AUTHOR
------
Ken Williams, [email protected]
Additional contributions by The Perl 5 Porters.
COPYRIGHT
---------
Copyright (c) 2003-2005 Ken Williams. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
perl(1), Module::Build(3)
| programming_docs |
perl perlos400 perlos400
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Compiling Perl for OS/400 PASE](#Compiling-Perl-for-OS/400-PASE)
+ [Installing Perl in OS/400 PASE](#Installing-Perl-in-OS/400-PASE)
+ [Using Perl in OS/400 PASE](#Using-Perl-in-OS/400-PASE)
+ [Known Problems](#Known-Problems)
+ [Perl on ILE](#Perl-on-ILE)
* [AUTHORS](#AUTHORS)
NAME
----
perlos400 - Perl version 5 on OS/400
**This document needs to be updated, but we don't know what it should say. Please submit comments to <https://github.com/Perl/perl5/issues>.**
DESCRIPTION
-----------
This document describes various features of IBM's OS/400 operating system that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
By far the easiest way to build Perl for OS/400 is to use the PASE (Portable Application Solutions Environment), for more information see <http://www.iseries.ibm.com/developer/factory/pase/index.html> This environment allows one to use AIX APIs while programming, and it provides a runtime that allows AIX binaries to execute directly on the PowerPC iSeries.
###
Compiling Perl for OS/400 PASE
The recommended way to build Perl for the OS/400 PASE is to build the Perl 5 source code (release 5.8.1 or later) under AIX.
The trick is to give a special parameter to the Configure shell script when running it on AIX:
```
sh Configure -DPASE ...
```
The default installation directory of Perl under PASE is /QOpenSys/perl. This can be modified if needed with Configure parameter -Dprefix=/some/dir.
Starting from OS/400 V5R2 the IBM Visual Age compiler is supported on OS/400 PASE, so it is possible to build Perl natively on OS/400. The easier way, however, is to compile in AIX, as just described.
If you don't want to install the compiled Perl in AIX into /QOpenSys (for packaging it before copying it to PASE), you can use a Configure parameter: -Dinstallprefix=/tmp/QOpenSys/perl. This will cause the "make install" to install everything into that directory, while the installed files still think they are (will be) in /QOpenSys/perl.
If building natively on PASE, please do the build under the /QOpenSys directory, since Perl is happier when built on a case sensitive filesystem.
###
Installing Perl in OS/400 PASE
If you are compiling on AIX, simply do a "make install" on the AIX box. Once the install finishes, tar up the /QOpenSys/perl directory. Transfer the tarball to the OS/400 using FTP with the following commands:
```
> binary
> site namefmt 1
> put perl.tar /QOpenSys
```
Once you have it on, simply bring up a PASE shell and extract the tarball.
If you are compiling in PASE, then "make install" is the only thing you will need to do.
The default path for perl binary is /QOpenSys/perl/bin/perl. You'll want to symlink /QOpenSys/usr/bin/perl to this file so you don't have to modify your path.
###
Using Perl in OS/400 PASE
Perl in PASE may be used in the same manner as you would use Perl on AIX.
Scripts starting with #!/usr/bin/perl should work if you have /QOpenSys/usr/bin/perl symlinked to your perl binary. This will not work if you've done a setuid/setgid or have environment variable PASE\_EXEC\_QOPENSYS="N". If you have V5R1, you'll need to get the latest PTFs to have this feature. Scripts starting with #!/QOpenSys/perl/bin/perl should always work.
###
Known Problems
When compiling in PASE, there is no "oslevel" command. Therefore, you may want to create a script called "oslevel" that echoes the level of AIX that your version of PASE runtime supports. If you're unsure, consult your documentation or use "4.3.3.0".
If you have test cases that fail, check for the existence of spool files. The test case may be trying to use a syscall that is not implemented in PASE. To avoid the SIGILL, try setting the PASE\_SYSCALL\_NOSIGILL environment variable or have a handler for the SIGILL. If you can compile programs for PASE, run the config script and edit config.sh when it gives you the option. If you want to remove fchdir(), which isn't implement in V5R1, simply change the line that says:
d\_fchdir='define'
to
d\_fchdir='undef'
and then compile Perl. The places where fchdir() is used have alternatives for systems that do not have fchdir() available.
###
Perl on ILE
There exists a port of Perl to the ILE environment. This port, however, is based quite an old release of Perl, Perl 5.00502 (August 1998). (As of July 2002 the latest release of Perl is 5.8.0, and even 5.6.1 has been out since April 2001.) If you need to run Perl on ILE, though, you may need this older port: <http://www.cpan.org/ports/#os400> Note that any Perl release later than 5.00502 has not been ported to ILE.
If you need to use Perl in the ILE environment, you may want to consider using Qp2RunPase() to call the PASE version of Perl.
AUTHORS
-------
Jarkko Hietaniemi <[email protected]> Bryan Logan <[email protected]> David Larson <[email protected]>
perl perlaix perlaix
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Compiling Perl 5 on AIX](#Compiling-Perl-5-on-AIX)
+ [Supported Compilers](#Supported-Compilers)
+ [Incompatibility with AIX Toolbox lib gdbm](#Incompatibility-with-AIX-Toolbox-lib-gdbm)
+ [Perl 5 was successfully compiled and tested on:](#Perl-5-was-successfully-compiled-and-tested-on:)
+ [Building Dynamic Extensions on AIX](#Building-Dynamic-Extensions-on-AIX)
+ [Using Large Files with Perl](#Using-Large-Files-with-Perl)
+ [Threaded Perl](#Threaded-Perl)
+ [64-bit Perl](#64-bit-Perl)
+ [Long doubles](#Long-doubles)
+ [Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/32-bit)](#Recommended-Options-AIX-5.1/5.2/5.3/6.1-and-7.1-(threaded/32-bit))
+ [Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (32-bit)](#Recommended-Options-AIX-5.1/5.2/5.3/6.1-and-7.1-(32-bit))
+ [Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/64-bit)](#Recommended-Options-AIX-5.1/5.2/5.3/6.1-and-7.1-(threaded/64-bit))
+ [Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (64-bit)](#Recommended-Options-AIX-5.1/5.2/5.3/6.1-and-7.1-(64-bit))
+ [Compiling Perl 5 on AIX 7.1.0](#Compiling-Perl-5-on-AIX-7.1.0)
+ [Compiling Perl 5 on older AIX versions up to 4.3.3](#Compiling-Perl-5-on-older-AIX-versions-up-to-4.3.3)
+ [OS level](#OS-level)
+ [Building Dynamic Extensions on AIX < 5L](#Building-Dynamic-Extensions-on-AIX-%3C-5L)
+ [The IBM ANSI C Compiler](#The-IBM-ANSI-C-Compiler)
+ [The usenm option](#The-usenm-option)
+ [Using GNU's gcc for building Perl](#Using-GNU's-gcc-for-building-Perl)
+ [Using Large Files with Perl < 5L](#Using-Large-Files-with-Perl-%3C-5L)
+ [Threaded Perl < 5L](#Threaded-Perl-%3C-5L)
+ [64-bit Perl < 5L](#64-bit-Perl-%3C-5L)
+ [AIX 4.2 and extensions using C++ with statics](#AIX-4.2-and-extensions-using-C++-with-statics)
* [AUTHORS](#AUTHORS)
NAME
----
perlaix - Perl version 5 on IBM AIX (UNIX) systems
DESCRIPTION
-----------
This document describes various features of IBM's UNIX operating system AIX that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
Compiling Perl 5 on AIX
For information on compilers on older versions of AIX, see ["Compiling Perl 5 on older AIX versions up to 4.3.3"](#Compiling-Perl-5-on-older-AIX-versions-up-to-4.3.3).
When compiling Perl, you must use an ANSI C compiler. AIX does not ship an ANSI compliant C compiler with AIX by default, but binary builds of gcc for AIX are widely available. A version of gcc is also included in the AIX Toolbox which is shipped with AIX.
###
Supported Compilers
Currently all versions of IBM's "xlc", "xlc\_r", "cc", "cc\_r" or "vac" ANSI/C compiler will work for building Perl if that compiler works on your system.
If you plan to link Perl to any module that requires thread-support, like DBD::Oracle, it is better to use the \_r version of the compiler. This will not build a threaded Perl, but a thread-enabled Perl. See also ["Threaded Perl"](#Threaded-Perl) later on.
As of writing (2010-09) only the *IBM XL C for AIX* or *IBM XL C/C++ for AIX* compiler is supported by IBM on AIX 5L/6.1/7.1.
The following compiler versions are currently supported by IBM:
```
IBM XL C and IBM XL C/C++ V8, V9, V10, V11
```
The XL C for AIX is integrated in the XL C/C++ for AIX compiler and therefore also supported.
If you choose XL C/C++ V9 you need APAR IZ35785 installed otherwise the integrated SDBM\_File do not compile correctly due to an optimization bug. You can circumvent this problem by adding -qipa to the optimization flags (-Doptimize='-O -qipa'). The PTF for APAR IZ35785 which solves this problem is available from IBM (April 2009 PTF for XL C/C++ Enterprise Edition for AIX, V9.0).
If you choose XL C/C++ V11 you need the April 2010 PTF (or newer) installed otherwise you will not get a working Perl version.
Perl can be compiled with either IBM's ANSI C compiler or with gcc. The former is recommended, as not only it can compile Perl with no difficulty, but also can take advantage of features listed later that require the use of IBM 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. Please report any hoops you had to jump through to the development team.
###
Incompatibility with AIX Toolbox lib gdbm
If the AIX Toolbox version of lib gdbm < 1.8.3-5 is installed on your system then Perl will not work. This library contains the header files /opt/freeware/include/gdbm/dbm.h|ndbm.h which conflict with the AIX system versions. The lib gdbm will be automatically removed from the wanted libraries if the presence of one of these two header files is detected. If you want to build Perl with GDBM support then please install at least gdbm-devel-1.8.3-5 (or higher).
###
Perl 5 was successfully compiled and tested on:
```
Perl | AIX Level | Compiler Level | w th | w/o th
-------+---------------------+-------------------------+------+-------
5.12.2 |5.1 TL9 32 bit | XL C/C++ V7 | OK | OK
5.12.2 |5.1 TL9 64 bit | XL C/C++ V7 | OK | OK
5.12.2 |5.2 TL10 SP8 32 bit | XL C/C++ V8 | OK | OK
5.12.2 |5.2 TL10 SP8 32 bit | gcc 3.2.2 | OK | OK
5.12.2 |5.2 TL10 SP8 64 bit | XL C/C++ V8 | OK | OK
5.12.2 |5.3 TL8 SP8 32 bit | XL C/C++ V9 + IZ35785 | OK | OK
5.12.2 |5.3 TL8 SP8 32 bit | gcc 4.2.4 | OK | OK
5.12.2 |5.3 TL8 SP8 64 bit | XL C/C++ V9 + IZ35785 | OK | OK
5.12.2 |5.3 TL10 SP3 32 bit | XL C/C++ V11 + Apr 2010 | OK | OK
5.12.2 |5.3 TL10 SP3 64 bit | XL C/C++ V11 + Apr 2010 | OK | OK
5.12.2 |6.1 TL1 SP7 32 bit | XL C/C++ V10 | OK | OK
5.12.2 |6.1 TL1 SP7 64 bit | XL C/C++ V10 | OK | OK
5.13 |7.1 TL0 SP1 32 bit | XL C/C++ V11 + Jul 2010 | OK | OK
5.13 |7.1 TL0 SP1 64 bit | XL C/C++ V11 + Jul 2010 | OK | OK
w th = with thread support
w/o th = without thread support
OK = tested
```
Successfully tested means that all "make test" runs finish with a result of 100% OK. All tests were conducted with -Duseshrplib set.
All tests were conducted on the oldest supported AIX technology level with the latest support package applied. If the tested AIX version is out of support (AIX 4.3.3, 5.1, 5.2) then the last available support level was used.
###
Building Dynamic Extensions on AIX
Starting from Perl 5.7.2 (and consequently 5.8.x / 5.10.x / 5.12.x) and AIX 4.3 or newer Perl uses the AIX native dynamic loading interface in the so called runtime linking mode instead of the emulated interface that was used in Perl releases 5.6.1 and earlier or, for AIX releases 4.2 and earlier. This change does break backward compatibility with compiled modules from earlier Perl releases. The change was made to make Perl more compliant with other applications like Apache/mod\_perl which are using the AIX native interface. This change also enables the use of C++ code with static constructors and destructors in Perl extensions, which was not possible using the emulated interface.
It is highly recommended to use the new interface.
###
Using Large Files with Perl
Should yield no problems.
###
Threaded Perl
Should yield no problems with AIX 5.1 / 5.2 / 5.3 / 6.1 / 7.1.
IBM uses the AIX system Perl (V5.6.0 on AIX 5.1 and V5.8.2 on AIX 5.2 / 5.3 and 6.1; V5.8.8 on AIX 5.3 TL11 and AIX 6.1 TL4; V5.10.1 on AIX 7.1) for some AIX system scripts. If you switch the links in /usr/bin from the AIX system Perl (/usr/opt/perl5) to the newly build Perl then you get the same features as with the IBM AIX system Perl if the threaded options are used.
The threaded Perl build works also on AIX 5.1 but the IBM Perl build (Perl v5.6.0) is not threaded on AIX 5.1.
Perl 5.12 an newer is not compatible with the IBM fileset perl.libext.
###
64-bit Perl
If your AIX system is installed with 64-bit support, you can expect 64-bit configurations to work. If you want to use 64-bit Perl on AIX 6.1 you need an APAR for a libc.a bug which affects (n)dbm\_XXX functions. The APAR number for this problem is IZ39077.
If you need more memory (larger data segment) for your Perl programs you can set:
```
/etc/security/limits
default: (or your user)
data = -1 (default is 262144 * 512 byte)
```
With the default setting the size is limited to 128MB. The -1 removes this limit. If the "make test" fails please change your /etc/security/limits as stated above.
###
Long doubles
IBM calls its implementation of long doubles 128-bit, but it is not the IEEE 128-bit ("quadruple precision") which would give 116 bit of mantissa (nor it is implemented in hardware), instead it's a special software implementation called "double-double", which gives 106 bits of mantissa.
There seem to be various problems in this long double implementation. If Configure detects this brokenness, it will disable the long double support. This can be overridden with explicit `-Duselongdouble` (or `-Dusemorebits`, which enables both long doubles and 64 bit integers). If you decide to enable long doubles, for most of the broken things Perl has implemented workarounds, but the handling of the special values infinity and NaN remains badly broken: for example infinity plus zero results in NaN.
###
Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/32-bit)
With the following options you get a threaded Perl version which passes all make tests in threaded 32-bit mode, which is the default configuration for the Perl builds that AIX ships with.
```
rm config.sh
./Configure \
-d \
-Dcc=cc_r \
-Duseshrplib \
-Dusethreads \
-Dprefix=/usr/opt/perl5_32
```
The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation.
###
Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (32-bit)
With the following options you get a Perl version which passes all make tests in 32-bit mode.
```
rm config.sh
./Configure \
-d \
-Dcc=cc_r \
-Duseshrplib \
-Dprefix=/usr/opt/perl5_32
```
The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation.
###
Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (threaded/64-bit)
With the following options you get a threaded Perl version which passes all make tests in 64-bit mode.
```
export OBJECT_MODE=64 / setenv OBJECT_MODE 64 (depending on your shell)
rm config.sh
./Configure \
-d \
-Dcc=cc_r \
-Duseshrplib \
-Dusethreads \
-Duse64bitall \
-Dprefix=/usr/opt/perl5_64
```
###
Recommended Options AIX 5.1/5.2/5.3/6.1 and 7.1 (64-bit)
With the following options you get a Perl version which passes all make tests in 64-bit mode.
```
export OBJECT_MODE=64 / setenv OBJECT_MODE 64 (depending on your shell)
rm config.sh
./Configure \
-d \
-Dcc=cc_r \
-Duseshrplib \
-Duse64bitall \
-Dprefix=/usr/opt/perl5_64
```
The -Dprefix option will install Perl in a directory parallel to the IBM AIX system Perl installation.
If you choose gcc to compile 64-bit Perl then you need to add the following option:
```
-Dcc='gcc -maix64'
```
###
Compiling Perl 5 on AIX 7.1.0
A regression in AIX 7 causes a failure in make test in Time::Piece during daylight savings time. APAR IV16514 provides the fix for this. A quick test to see if it's required, assuming it is currently daylight savings in Eastern Time, would be to run `TZ=EST5 date +%Z` . This will come back with `EST` normally, but nothing if you have the problem.
###
Compiling Perl 5 on older AIX versions up to 4.3.3
Due to the fact that AIX 4.3.3 reached end-of-service in December 31, 2003 this information is provided as is. The Perl versions prior to Perl 5.8.9 could be compiled on AIX up to 4.3.3 with the following settings (your mileage may vary):
When compiling Perl, you must use an ANSI C compiler. AIX does not ship an ANSI compliant C-compiler with AIX by default, but binary builds of gcc for AIX are widely available.
At the moment of writing, AIX supports two different native C compilers, for which you have to pay: **xlC** and **vac**. If you decide to use either of these two (which is quite a lot easier than using gcc), be sure to upgrade to the latest available patch level. Currently:
```
xlC.C 3.1.4.10 or 3.6.6.0 or 4.0.2.2 or 5.0.2.9 or 6.0.0.3
vac.C 4.4.0.3 or 5.0.2.6 or 6.0.0.1
```
note that xlC has the OS version in the name as of version 4.0.2.0, so you will find xlC.C for AIX-5.0 as package
```
xlC.aix50.rte 5.0.2.0 or 6.0.0.3
```
subversions are not the same "latest" on all OS versions. For example, the latest xlC-5 on aix41 is 5.0.2.9, while on aix43, it is 5.0.2.7.
Perl can be compiled with either IBM'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 IBM compiler-specific command-line flags.
The IBM's compiler patch levels 5.0.0.0 and 5.0.1.0 have compiler optimization bugs that affect compiling perl.c and regcomp.c, respectively. If Perl's configuration detects those compiler patch levels, optimization is turned off for the said source code files. Upgrading to at least 5.0.2.0 is recommended.
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. Please report any hoops you had to jump through to the development team.
###
OS level
Before installing the patches to the IBM C-compiler you need to know the level of patching for the Operating System. IBM's command 'oslevel' will show the base, but is not always complete (in this example oslevel shows 4.3.NULL, whereas the system might run most of 4.3.THREE):
```
# oslevel
4.3.0.0
# lslpp -l | grep 'bos.rte '
bos.rte 4.3.3.75 COMMITTED Base Operating System Runtime
bos.rte 4.3.2.0 COMMITTED Base Operating System Runtime
#
```
The same might happen to AIX 5.1 or other OS levels. As a side note, Perl cannot be built without bos.adt.syscalls and bos.adt.libm installed
```
# lslpp -l | egrep "syscalls|libm"
bos.adt.libm 5.1.0.25 COMMITTED Base Application Development
bos.adt.syscalls 5.1.0.36 COMMITTED System Calls Application
#
```
###
Building Dynamic Extensions on AIX < 5L
AIX supports dynamically loadable objects as well as shared libraries. Shared libraries by convention end with the suffix .a, which is a bit misleading, as an archive can contain static as well as dynamic members. For Perl dynamically loaded objects we use the .so suffix also used on many other platforms.
Note that starting from Perl 5.7.2 (and consequently 5.8.0) and AIX 4.3 or newer Perl uses the AIX native dynamic loading interface in the so called runtime linking mode instead of the emulated interface that was used in Perl releases 5.6.1 and earlier or, for AIX releases 4.2 and earlier. This change does break backward compatibility with compiled modules from earlier Perl releases. The change was made to make Perl more compliant with other applications like Apache/mod\_perl which are using the AIX native interface. This change also enables the use of C++ code with static constructors and destructors in Perl extensions, which was not possible using the emulated interface.
###
The IBM ANSI C Compiler
All defaults for Configure can be used.
If you've chosen to use vac 4, be sure to run 4.4.0.3. Older versions will turn up nasty later on. For vac 5 be sure to run at least 5.0.1.0, but vac 5.0.2.6 or up is highly recommended. Note that since IBM has removed vac 5.0.2.1 through 5.0.2.5 from the software depot, these versions should be considered obsolete.
Here's a brief lead of how to upgrade the compiler to the latest level. Of course this is subject to changes. You can only upgrade versions from ftp-available updates if the first three digit groups are the same (in where you can skip intermediate unlike the patches in the developer snapshots of Perl), or to one version up where the "base" is available. In other words, the AIX compiler patches are cumulative.
```
vac.C.4.4.0.1 => vac.C.4.4.0.3 is OK (vac.C.4.4.0.2 not needed)
xlC.C.3.1.3.3 => xlC.C.3.1.4.10 is NOT OK (xlC.C.3.1.4.0 is not
available)
# ftp ftp.software.ibm.com
Connected to service.boulder.ibm.com.
: welcome message ...
Name (ftp.software.ibm.com:merijn): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
... accepted login stuff
ftp> cd /aix/fixes/v4/
ftp> dir other other.ll
output to local-file: other.ll? y
200 PORT command successful.
150 Opening ASCII mode data connection for /bin/ls.
226 Transfer complete.
ftp> dir xlc xlc.ll
output to local-file: xlc.ll? y
200 PORT command successful.
150 Opening ASCII mode data connection for /bin/ls.
226 Transfer complete.
ftp> bye
... goodbye messages
# ls -l *.ll
-rw-rw-rw- 1 merijn system 1169432 Nov 2 17:29 other.ll
-rw-rw-rw- 1 merijn system 29170 Nov 2 17:29 xlc.ll
```
On AIX 4.2 using xlC, we continue:
```
# lslpp -l | fgrep 'xlC.C '
xlC.C 3.1.4.9 COMMITTED C for AIX Compiler
xlC.C 3.1.4.0 COMMITTED C for AIX Compiler
# grep 'xlC.C.3.1.4.*.bff' xlc.ll
-rw-r--r-- 1 45776101 1 6286336 Jul 22 1996 xlC.C.3.1.4.1.bff
-rw-rw-r-- 1 45776101 1 6173696 Aug 24 1998 xlC.C.3.1.4.10.bff
-rw-r--r-- 1 45776101 1 6319104 Aug 14 1996 xlC.C.3.1.4.2.bff
-rw-r--r-- 1 45776101 1 6316032 Oct 21 1996 xlC.C.3.1.4.3.bff
-rw-r--r-- 1 45776101 1 6315008 Dec 20 1996 xlC.C.3.1.4.4.bff
-rw-rw-r-- 1 45776101 1 6178816 Mar 28 1997 xlC.C.3.1.4.5.bff
-rw-rw-r-- 1 45776101 1 6188032 May 22 1997 xlC.C.3.1.4.6.bff
-rw-rw-r-- 1 45776101 1 6191104 Sep 5 1997 xlC.C.3.1.4.7.bff
-rw-rw-r-- 1 45776101 1 6185984 Jan 13 1998 xlC.C.3.1.4.8.bff
-rw-rw-r-- 1 45776101 1 6169600 May 27 1998 xlC.C.3.1.4.9.bff
# wget ftp://ftp.software.ibm.com/aix/fixes/v4/xlc/xlC.C.3.1.4.10.bff
#
```
On AIX 4.3 using vac, we continue:
```
# lslpp -l | grep 'vac.C '
vac.C 5.0.2.2 COMMITTED C for AIX Compiler
vac.C 5.0.2.0 COMMITTED C for AIX Compiler
# grep 'vac.C.5.0.2.*.bff' other.ll
-rw-rw-r-- 1 45776101 1 13592576 Apr 16 2001 vac.C.5.0.2.0.bff
-rw-rw-r-- 1 45776101 1 14133248 Apr 9 2002 vac.C.5.0.2.3.bff
-rw-rw-r-- 1 45776101 1 14173184 May 20 2002 vac.C.5.0.2.4.bff
-rw-rw-r-- 1 45776101 1 14192640 Nov 22 2002 vac.C.5.0.2.6.bff
# wget ftp://ftp.software.ibm.com/aix/fixes/v4/other/vac.C.5.0.2.6.bff
#
```
Likewise on all other OS levels. Then execute the following command, and fill in its choices
```
# smit install_update
-> Install and Update from LATEST Available Software
* INPUT device / directory for software [ vac.C.5.0.2.6.bff ]
[ OK ]
[ OK ]
```
Follow the messages ... and you're done.
If you like a more web-like approach, a good start point can be <http://www14.software.ibm.com/webapp/download/downloadaz.jsp> and click "C for AIX", and follow the instructions.
###
The usenm option
If linking miniperl
```
cc -o miniperl ... miniperlmain.o opmini.o perl.o ... -lm -lc ...
```
causes error like this
```
ld: 0711-317 ERROR: Undefined symbol: .aintl
ld: 0711-317 ERROR: Undefined symbol: .copysignl
ld: 0711-317 ERROR: Undefined symbol: .syscall
ld: 0711-317 ERROR: Undefined symbol: .eaccess
ld: 0711-317 ERROR: Undefined symbol: .setresuid
ld: 0711-317 ERROR: Undefined symbol: .setresgid
ld: 0711-317 ERROR: Undefined symbol: .setproctitle
ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more
information.
```
you could retry with
```
make realclean
rm config.sh
./Configure -Dusenm ...
```
which makes Configure to use the `nm` tool when scanning for library symbols, which usually is not done in AIX.
Related to this, you probably should not use the `-r` option of Configure in AIX, because that affects of how the `nm` tool is used.
###
Using GNU's gcc for building Perl
Using gcc-3.x (tested with 3.0.4, 3.1, and 3.2) now works out of the box, as do recent gcc-2.9 builds available directly from IBM as part of their Linux compatibility packages, available here:
```
http://www.ibm.com/servers/aix/products/aixos/linux/
```
###
Using Large Files with Perl < 5L
Should yield no problems.
###
Threaded Perl < 5L
Threads seem to work OK, though at the moment not all tests pass when threads are used in combination with 64-bit configurations.
You may get a warning when doing a threaded build:
```
"pp_sys.c", line 4640.39: 1506-280 (W) Function argument assignment
between types "unsigned char*" and "const void*" is not allowed.
```
The exact line number may vary, but if the warning (W) comes from a line line this
```
hent = PerlSock_gethostbyaddr(addr, (Netdb_hlen_t) addrlen, addrtype);
```
in the "pp\_ghostent" function, you may ignore it safely. The warning is caused by the reentrant variant of gethostbyaddr() having a slightly different prototype than its non-reentrant variant, but the difference is not really significant here.
###
64-bit Perl < 5L
If your AIX is installed with 64-bit support, you can expect 64-bit configurations to work. In combination with threads some tests might still fail.
###
AIX 4.2 and extensions using C++ with statics
In AIX 4.2 Perl extensions that use C++ functions that use statics may have problems in that the statics are not getting initialized. In newer AIX releases this has been solved by linking Perl with the libC\_r library, but unfortunately in AIX 4.2 the said library has an obscure bug where the various functions related to time (such as time() and gettimeofday()) return broken values, and therefore in AIX 4.2 Perl is not linked against the libC\_r.
AUTHORS
-------
Rainer Tammer <[email protected]>
| programming_docs |
perl parent parent
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [HISTORY](#HISTORY)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS AND CONTRIBUTORS](#AUTHORS-AND-CONTRIBUTORS)
* [MAINTAINER](#MAINTAINER)
* [LICENSE](#LICENSE)
NAME
----
parent - Establish an ISA relationship with base classes at compile time
SYNOPSIS
--------
```
package Baz;
use parent qw(Foo Bar);
```
DESCRIPTION
-----------
Allows you to both load one or more modules, while setting up inheritance from those modules at the same time. Mostly similar in effect to
```
package Baz;
BEGIN {
require Foo;
require Bar;
push @ISA, qw(Foo Bar);
}
```
By default, every base class needs to live in a file of its own. If you want to have a subclass and its parent class in the same file, you can tell `parent` not to load any modules by using the `-norequire` switch:
```
package Foo;
sub exclaim { "I CAN HAS PERL" }
package DoesNotLoadFooBar;
use parent -norequire, 'Foo', 'Bar';
# will not go looking for Foo.pm or Bar.pm
```
This is equivalent to the following code:
```
package Foo;
sub exclaim { "I CAN HAS PERL" }
package DoesNotLoadFooBar;
push @DoesNotLoadFooBar::ISA, 'Foo', 'Bar';
```
This is also helpful for the case where a package lives within a differently named file:
```
package MyHash;
use Tie::Hash;
use parent -norequire, 'Tie::StdHash';
```
This is equivalent to the following code:
```
package MyHash;
require Tie::Hash;
push @ISA, 'Tie::StdHash';
```
If you want to load a subclass from a file that `require` would not consider an eligible filename (that is, it does not end in either `.pm` or `.pmc`), use the following code:
```
package MySecondPlugin;
require './plugins/custom.plugin'; # contains Plugin::Custom
use parent -norequire, 'Plugin::Custom';
```
HISTORY
-------
This module was forked from <base> to remove the cruft that had accumulated in it.
CAVEATS
-------
SEE ALSO
---------
<base>
<parent::versioned>
A fork of <parent> that provides version checking in parent class modules.
AUTHORS AND CONTRIBUTORS
-------------------------
Rafaรซl Garcia-Suarez, Bart Lateur, Max Maischein, Anno Siegel, Michael Schwern
MAINTAINER
----------
Max Maischein `[email protected]`
Copyright (c) 2007-2017 Max Maischein `<[email protected]>` Based on the idea of `base.pm`, which was introduced with Perl 5.004\_04.
LICENSE
-------
This module is released under the same terms as Perl itself.
perl ExtUtils::Typemaps::OutputMap ExtUtils::Typemaps::OutputMap
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [code](#code)
+ [xstype](#xstype)
+ [cleaned\_code](#cleaned_code)
+ [targetable](#targetable)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
ExtUtils::Typemaps::OutputMap - Entry in the OUTPUT section of a typemap
SYNOPSIS
--------
```
use ExtUtils::Typemaps;
...
my $output = $typemap->get_output_map('T_NV');
my $code = $output->code();
$output->code("...");
```
DESCRIPTION
-----------
Refer to <ExtUtils::Typemaps> for details.
METHODS
-------
### new
Requires `xstype` and `code` parameters.
### code
Returns or sets the OUTPUT mapping code for this entry.
### xstype
Returns the name of the XS type of the OUTPUT map.
### cleaned\_code
Returns a cleaned-up copy of the code to which certain transformations have been applied to make it more ANSI compliant.
### targetable
This is an obscure but effective optimization that used to live in `ExtUtils::ParseXS` directly. Not implementing it should never result in incorrect use of typemaps, just less efficient code.
In a nutshell, this will check whether the output code involves calling `sv_setiv`, `sv_setuv`, `sv_setnv`, `sv_setpv` or `sv_setpvn` to set the special `$arg` placeholder to a new value **AT THE END OF THE OUTPUT CODE**. If that is the case, the code is eligible for using the `TARG`-related macros to optimize this. Thus the name of the method: `targetable`.
If this optimization is applicable, `ExtUtils::ParseXS` will emit a `dXSTARG;` definition at the start of the generated XSUB code, and type (see below) dependent code to set `TARG` and push it on the stack at the end of the generated XSUB code.
If the optimization can not be applied, this returns undef. If it can be applied, this method returns a hash reference containing the following information:
```
type: Any of the characters i, u, n, p
with_size: Bool indicating whether this is the sv_setpvn variant
what: The code that actually evaluates to the output scalar
what_size: If "with_size", this has the string length (as code,
not constant, including leading comma)
```
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 FileHandle FileHandle
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
FileHandle - supply object methods for filehandles
SYNOPSIS
--------
```
use FileHandle;
$fh = FileHandle->new;
if ($fh->open("< file")) {
print <$fh>;
$fh->close;
}
$fh = FileHandle->new("> FOO");
if (defined $fh) {
print $fh "bar\n";
$fh->close;
}
$fh = FileHandle->new("file", "r");
if (defined $fh) {
print <$fh>;
undef $fh; # automatically closes the file
}
$fh = FileHandle->new("file", O_WRONLY|O_APPEND);
if (defined $fh) {
print $fh "corge\n";
undef $fh; # automatically closes the file
}
$pos = $fh->getpos;
$fh->setpos($pos);
$fh->setvbuf($buffer_var, _IOLBF, 1024);
($readfh, $writefh) = FileHandle::pipe;
autoflush STDOUT 1;
```
DESCRIPTION
-----------
NOTE: This class is now a front-end to the IO::\* classes.
`FileHandle::new` creates a `FileHandle`, which is a reference to a newly created symbol (see the `Symbol` package). If it receives any parameters, they are passed to `FileHandle::open`; if the open fails, the `FileHandle` object is destroyed. Otherwise, it is returned to the caller.
`FileHandle::new_from_fd` creates a `FileHandle` like `new` does. It requires two parameters, which are passed to `FileHandle::fdopen`; if the fdopen fails, the `FileHandle` object is destroyed. Otherwise, it is returned to the caller.
`FileHandle::open` accepts one parameter or two. With one parameter, it is just a front end for the built-in `open` function. With two parameters, the first parameter is a filename that may include whitespace or other special characters, and the second parameter is the open mode, optionally followed by a file permission value.
If `FileHandle::open` receives a Perl mode string (">", "+<", etc.) or a POSIX fopen() mode string ("w", "r+", etc.), it uses the basic Perl `open` operator.
If `FileHandle::open` is given a numeric mode, it passes that mode and the optional permissions value to the Perl `sysopen` operator. For convenience, `FileHandle::import` tries to import the O\_XXX constants from the Fcntl module. If dynamic loading is not available, this may fail, but the rest of FileHandle will still work.
`FileHandle::fdopen` is like `open` except that its first parameter is not a filename but rather a file handle name, a FileHandle object, or a file descriptor number.
If the C functions fgetpos() and fsetpos() are available, then `FileHandle::getpos` returns an opaque value that represents the current position of the FileHandle, and `FileHandle::setpos` uses that value to return to a previously visited position.
If the C function setvbuf() is available, then `FileHandle::setvbuf` sets the buffering policy for the FileHandle. The calling sequence for the Perl function is the same as its C counterpart, including the macros `_IOFBF`, `_IOLBF`, and `_IONBF`, except that the buffer parameter specifies a scalar variable to use as a buffer. WARNING: A variable used as a buffer by `FileHandle::setvbuf` must not be modified in any way until the FileHandle is closed or until `FileHandle::setvbuf` is called again, or memory corruption may result!
See <perlfunc> for complete descriptions of each of the following supported `FileHandle` methods, which are just front ends for the corresponding built-in functions:
```
close
fileno
getc
gets
eof
clearerr
seek
tell
```
See <perlvar> for complete descriptions of each of the following supported `FileHandle` methods:
```
autoflush
output_field_separator
output_record_separator
input_record_separator
input_line_number
format_page_number
format_lines_per_page
format_lines_left
format_name
format_top_name
format_line_break_characters
format_formfeed
```
Furthermore, for doing normal I/O you might need these:
$fh->print See ["print" in perlfunc](perlfunc#print).
$fh->printf See ["printf" in perlfunc](perlfunc#printf).
$fh->getline This works like <$fh> 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.
$fh->getlines This works like <$fh> 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.
There are many other functions available since FileHandle is descended from IO::File, IO::Seekable, and IO::Handle. Please see those respective pages for documentation on more functions.
SEE ALSO
---------
The **IO** extension, <perlfunc>, ["I/O Operators" in perlop](perlop#I%2FO-Operators).
perl Test2::Event::Diag Test2::Event::Diag
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ACCESSORS](#ACCESSORS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Diag - Diag event type
DESCRIPTION
-----------
Diagnostics messages, typically rendered to STDERR.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Diag;
my $ctx = context();
my $event = $ctx->diag($message);
```
ACCESSORS
---------
$diag->message The message for the diag.
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 Test::Builder::IO::Scalar Test::Builder::IO::Scalar
=========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [COPYRIGHT and LICENSE](#COPYRIGHT-and-LICENSE)
+ [Construction](#Construction)
+ [Input and output](#Input-and-output)
+ [Seeking/telling and other attributes](#Seeking/telling-and-other-attributes)
* [WARNINGS](#WARNINGS)
* [VERSION](#VERSION)
* [AUTHORS](#AUTHORS)
+ [Primary Maintainer](#Primary-Maintainer)
+ [Principal author](#Principal-author)
+ [Other contributors](#Other-contributors)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Test::Builder::IO::Scalar - A copy of IO::Scalar for Test::Builder
DESCRIPTION
-----------
This is a copy of <IO::Scalar> which ships with <Test::Builder> to support scalar references as filehandles on Perl 5.6. Newer versions of Perl simply use `open()`'s built in support.
<Test::Builder> can not have dependencies on other modules without careful consideration, so its simply been copied into the distribution.
COPYRIGHT and LICENSE
----------------------
This file came from the "IO-stringy" Perl5 toolkit.
Copyright (c) 1996 by Eryq. All rights reserved. Copyright (c) 1999,2001 by ZeeGee Software Inc. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
### Construction
new [ARGS...] *Class method.* Return a new, unattached scalar handle. If any arguments are given, they're sent to open().
open [SCALARREF] *Instance method.* Open the scalar handle on a new scalar, pointed to by SCALARREF. If no SCALARREF is given, a "private" scalar is created to hold the file data.
Returns the self object on success, undefined on error.
opened *Instance method.* Is the scalar handle opened on something?
close *Instance method.* Disassociate the scalar handle from its underlying scalar. Done automatically on destroy.
###
Input and output
flush *Instance method.* No-op, provided for OO compatibility.
getc *Instance method.* Return the next character, or undef if none remain.
getline *Instance method.* Return the next line, or undef on end of string. Can safely be called in an array context. Currently, lines are delimited by "\n".
getlines *Instance method.* Get all remaining lines. It will croak() if accidentally called in a scalar context.
print ARGS... *Instance method.* Print ARGS to the underlying scalar.
**Warning:** this continues to always cause a seek to the end of the string, but if you perform seek()s and tell()s, it is still safer to explicitly seek-to-end before subsequent print()s.
read BUF, NBYTES, [OFFSET] *Instance method.* Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error.
write BUF, NBYTES, [OFFSET] *Instance method.* Write some bytes to the scalar.
sysread BUF, LEN, [OFFSET] *Instance method.* Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error.
syswrite BUF, NBYTES, [OFFSET] *Instance method.* Write some bytes to the scalar.
###
Seeking/telling and other attributes
autoflush *Instance method.* No-op, provided for OO compatibility.
binmode *Instance method.* No-op, provided for OO compatibility.
clearerr *Instance method.* Clear the error and EOF flags. A no-op.
eof *Instance method.* Are we at end of file?
seek OFFSET, WHENCE *Instance method.* Seek to a given position in the stream.
sysseek OFFSET, WHENCE *Instance method.* Identical to `seek OFFSET, WHENCE`, *q.v.*
tell *Instance method.* Return the current position in the stream, as a numeric offset.
use\_RS [YESNO] *Instance method.* **Deprecated and ignored.** Obey the current setting of $/, like IO::Handle does? Default is false in 1.x, but cold-welded true in 2.x and later.
setpos POS *Instance method.* Set the current position, using the opaque value returned by `getpos()`.
getpos *Instance method.* Return the current position in the string, as an opaque object.
sref *Instance method.* Return a reference to the underlying scalar.
WARNINGS
--------
Perl's TIEHANDLE spec was incomplete prior to 5.005\_57; it was missing support for `seek()`, `tell()`, and `eof()`. Attempting to use these functions with an IO::Scalar will not work prior to 5.005\_57. IO::Scalar will not have the relevant methods invoked; and even worse, this kind of bug can lie dormant for a while. If you turn warnings on (via `$^W` or `perl -w`), and you see something like this...
```
attempt to seek on unopened filehandle
```
...then you are probably trying to use one of these functions on an IO::Scalar with an old Perl. The remedy is to simply use the OO version; e.g.:
```
$SH->seek(0,0); ### GOOD: will work on any 5.005
seek($SH,0,0); ### WARNING: will only work on 5.005_57 and beyond
```
VERSION
-------
$Id: Scalar.pm,v 1.6 2005/02/10 21:21:53 dfs Exp $
AUTHORS
-------
###
Primary Maintainer
David F. Skoll (*[email protected]*).
###
Principal author
Eryq (*[email protected]*). President, ZeeGee Software Inc (*http://www.zeegee.com*).
###
Other contributors
The full set of contributors always includes the folks mentioned in ["CHANGE LOG" in IO::Stringy](IO::Stringy#CHANGE-LOG). But just the same, special thanks to the following individuals for their invaluable contributions (if I've forgotten or misspelled your name, please email me!):
*Andy Glew,* for contributing `getc()`.
*Brandon Browning,* for suggesting `opened()`.
*David Richter,* for finding and fixing the bug in `PRINTF()`.
*Eric L. Brine,* for his offset-using read() and write() implementations.
*Richard Jones,* for his patches to massively improve the performance of `getline()` and add `sysread` and `syswrite`.
*B. K. Oxley (binkley),* for stringification and inheritance improvements, and sundry good ideas.
*Doug Wilson,* for the IO::Handle inheritance and automatic tie-ing.
SEE ALSO
---------
<IO::String>, which is quite similar but which was designed more-recently and with an IO::Handle-like interface in mind, so you could mix OO- and native-filehandle usage without using tied().
*Note:* as of version 2.x, these classes all work like their IO::Handle counterparts, so we have comparable functionality to IO::String.
perl perlebcdic perlebcdic
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [COMMON CHARACTER CODE SETS](#COMMON-CHARACTER-CODE-SETS)
+ [ASCII](#ASCII)
+ [ISO 8859](#ISO-8859)
+ [Latin 1 (ISO 8859-1)](#Latin-1-(ISO-8859-1))
+ [EBCDIC](#EBCDIC)
- [The 13 variant characters](#The-13-variant-characters)
- [EBCDIC code sets recognized by Perl](#EBCDIC-code-sets-recognized-by-Perl)
+ [Unicode code points versus EBCDIC code points](#Unicode-code-points-versus-EBCDIC-code-points)
+ [Unicode and UTF](#Unicode-and-UTF)
+ [Using Encode](#Using-Encode)
* [SINGLE OCTET TABLES](#SINGLE-OCTET-TABLES)
+ [Table in hex, sorted in 1047 order](#Table-in-hex,-sorted-in-1047-order)
* [IDENTIFYING CHARACTER CODE SETS](#IDENTIFYING-CHARACTER-CODE-SETS)
* [CONVERSIONS](#CONVERSIONS)
+ [utf8::unicode\_to\_native() and utf8::native\_to\_unicode()](#utf8::unicode_to_native()-and-utf8::native_to_unicode())
+ [tr///](#tr///)
+ [iconv](#iconv)
+ [C RTL](#C-RTL)
* [OPERATOR DIFFERENCES](#OPERATOR-DIFFERENCES)
* [FUNCTION DIFFERENCES](#FUNCTION-DIFFERENCES)
* [REGULAR EXPRESSION DIFFERENCES](#REGULAR-EXPRESSION-DIFFERENCES)
* [SOCKETS](#SOCKETS)
* [SORTING](#SORTING)
+ [Ignore ASCII vs. EBCDIC sort differences.](#Ignore-ASCII-vs.-EBCDIC-sort-differences.)
+ [Use a sort helper function](#Use-a-sort-helper-function)
+ [MONO CASE then sort data (for non-digits, non-underscore)](#MONO-CASE-then-sort-data-(for-non-digits,-non-underscore))
+ [Perform sorting on one type of platform only.](#Perform-sorting-on-one-type-of-platform-only.)
* [TRANSFORMATION FORMATS](#TRANSFORMATION-FORMATS)
+ [URL decoding and encoding](#URL-decoding-and-encoding)
+ [uu encoding and decoding](#uu-encoding-and-decoding)
+ [Quoted-Printable encoding and decoding](#Quoted-Printable-encoding-and-decoding)
+ [Caesarean ciphers](#Caesarean-ciphers)
* [Hashing order and checksums](#Hashing-order-and-checksums)
* [I18N AND L10N](#I18N-AND-L10N)
* [MULTI-OCTET CHARACTER SETS](#MULTI-OCTET-CHARACTER-SETS)
* [OS ISSUES](#OS-ISSUES)
+ [OS/400](#OS/400)
+ [OS/390, z/OS](#OS/390,-z/OS)
+ [POSIX-BC?](#POSIX-BC?)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [REFERENCES](#REFERENCES)
* [HISTORY](#HISTORY)
* [AUTHOR](#AUTHOR)
NAME
----
perlebcdic - Considerations for running Perl on EBCDIC platforms
DESCRIPTION
-----------
An exploration of some of the issues facing Perl programmers on EBCDIC based computers.
Portions of this document that are still incomplete are marked with XXX.
Early Perl versions worked on some EBCDIC machines, but the last known version that ran on EBCDIC was v5.8.7, until v5.22, when the Perl core again works on z/OS. Theoretically, it could work on OS/400 or Siemens' BS2000 (or their successors), but this is untested. In v5.22 and 5.24, not all the modules found on CPAN but shipped with core Perl work on z/OS.
If you want to use Perl on a non-z/OS EBCDIC machine, please let us know at <https://github.com/Perl/perl5/issues>.
Writing Perl on an EBCDIC platform is really no different than writing on an ["ASCII"](#ASCII) one, but with different underlying numbers, as we'll see shortly. You'll have to know something about those ["ASCII"](#ASCII) platforms because the documentation is biased and will frequently use example numbers that don't apply to EBCDIC. There are also very few CPAN modules that are written for EBCDIC and which don't work on ASCII; instead the vast majority of CPAN modules are written for ASCII, and some may happen to work on EBCDIC, while a few have been designed to portably work on both.
If your code just uses the 52 letters A-Z and a-z, plus SPACE, the digits 0-9, and the punctuation characters that Perl uses, plus a few controls that are denoted by escape sequences like `\n` and `\t`, then there's nothing special about using Perl, and your code may very well work on an ASCII machine without change.
But if you write code that uses `\005` to mean a TAB or `\xC1` to mean an "A", or `\xDF` to mean a "รฟ" (small `"y"` with a diaeresis), then your code may well work on your EBCDIC platform, but not on an ASCII one. That's fine to do if no one will ever want to run your code on an ASCII platform; but the bias in this document will be towards writing code portable between EBCDIC and ASCII systems. Again, if every character you care about is easily enterable from your keyboard, you don't have to know anything about ASCII, but many keyboards don't easily allow you to directly enter, say, the character `\xDF`, so you have to specify it indirectly, such as by using the `"\xDF"` escape sequence. In those cases it's easiest to know something about the ASCII/Unicode character sets. If you know that the small "รฟ" is `U+00FF`, then you can instead specify it as `"\N{U+FF}"`, and have the computer automatically translate it to `\xDF` on your platform, and leave it as `\xFF` on ASCII ones. Or you could specify it by name, `\N{LATIN SMALL LETTER Y WITH DIAERESIS` and not have to know the numbers. Either way works, but both require familiarity with Unicode.
COMMON CHARACTER CODE SETS
---------------------------
### ASCII
The American Standard Code for Information Interchange (ASCII or US-ASCII) is a set of integers running from 0 to 127 (decimal) that have standardized interpretations by the computers which use ASCII. For example, 65 means the letter "A". The range 0..127 can be covered by setting various bits in a 7-bit binary digit, hence the set is sometimes referred to as "7-bit ASCII". ASCII was described by the American National Standards Institute document ANSI X3.4-1986. It was also described by ISO 646:1991 (with localization for currency symbols). The full ASCII set is given in the table [below](#recipe-3) as the first 128 elements. Languages that can be written adequately with the characters in ASCII include English, Hawaiian, Indonesian, Swahili and some Native American languages.
Most non-EBCDIC character sets are supersets of ASCII. That is the integers 0-127 mean what ASCII says they mean. But integers 128 and above are specific to the character set.
Many of these fit entirely into 8 bits, using ASCII as 0-127, while specifying what 128-255 mean, and not using anything above 255. Thus, these are single-byte (or octet if you prefer) character sets. One important one (since Unicode is a superset of it) is the ISO 8859-1 character set.
###
ISO 8859
The ISO 8859-***$n*** are a collection of character code sets from the International Organization for Standardization (ISO), each of which adds characters to the ASCII set that are typically found in various languages, many of which are based on the Roman, or Latin, alphabet. Most are for European languages, but there are also ones for Arabic, Greek, Hebrew, and Thai. There are good references on the web about all these.
###
Latin 1 (ISO 8859-1)
A particular 8-bit extension to ASCII that includes grave and acute accented Latin characters. Languages that can employ ISO 8859-1 include all the languages covered by ASCII as well as Afrikaans, Albanian, Basque, Catalan, Danish, Faroese, Finnish, Norwegian, Portuguese, Spanish, and Swedish. Dutch is covered albeit without the ij ligature. French is covered too but without the oe ligature. German can use ISO 8859-1 but must do so without German-style quotation marks. This set is based on Western European extensions to ASCII and is commonly encountered in world wide web work. In IBM character code set identification terminology, ISO 8859-1 is also known as CCSID 819 (or sometimes 0819 or even 00819).
### EBCDIC
The Extended Binary Coded Decimal Interchange Code refers to a large collection of single- and multi-byte coded character sets that are quite different from ASCII and ISO 8859-1, and are all slightly different from each other; they typically run on host computers. The EBCDIC encodings derive from 8-bit byte extensions of Hollerith punched card encodings, which long predate ASCII. The layout on the cards was such that high bits were set for the upper and lower case alphabetic characters `[a-z]` and `[A-Z]`, but there were gaps within each Latin alphabet range, visible in the table [below](#recipe-3). These gaps can cause complications.
Some IBM EBCDIC character sets may be known by character code set identification numbers (CCSID numbers) or code page numbers.
Perl can be compiled on platforms that run any of three commonly used EBCDIC character sets, listed below.
####
The 13 variant characters
Among IBM EBCDIC character code sets there are 13 characters that are often mapped to different integer values. Those characters are known as the 13 "variant" characters and are:
```
\ [ ] { } ^ ~ ! # | $ @ `
```
When Perl is compiled for a platform, it looks at all of these characters to guess which EBCDIC character set the platform uses, and adapts itself accordingly to that platform. If the platform uses a character set that is not one of the three Perl knows about, Perl will either fail to compile, or mistakenly and silently choose one of the three.
The Line Feed (LF) character is actually a 14th variant character, and Perl checks for that as well.
####
EBCDIC code sets recognized by Perl
**0037**
Character code set ID 0037 is a mapping of the ASCII plus Latin-1 characters (i.e. ISO 8859-1) to an EBCDIC set. 0037 is used in North American English locales on the OS/400 operating system that runs on AS/400 computers. CCSID 0037 differs from ISO 8859-1 in 236 places; in other words they agree on only 20 code point values.
**1047**
Character code set ID 1047 is also a mapping of the ASCII plus Latin-1 characters (i.e. ISO 8859-1) to an EBCDIC set. 1047 is used under Unix System Services for OS/390 or z/OS, and OpenEdition for VM/ESA. CCSID 1047 differs from CCSID 0037 in eight places, and from ISO 8859-1 in 236.
**POSIX-BC**
The EBCDIC code page in use on Siemens' BS2000 system is distinct from 1047 and 0037. It is identified below as the POSIX-BC set. Like 0037 and 1047, it is the same as ISO 8859-1 in 20 code point values.
###
Unicode code points versus EBCDIC code points
In Unicode terminology a *code point* is the number assigned to a character: for example, in EBCDIC the character "A" is usually assigned the number 193. In Unicode, the character "A" is assigned the number 65. All the code points in ASCII and Latin-1 (ISO 8859-1) have the same meaning in Unicode. All three of the recognized EBCDIC code sets have 256 code points, and in each code set, all 256 code points are mapped to equivalent Latin1 code points. Obviously, "A" will map to "A", "B" => "B", "%" => "%", etc., for all printable characters in Latin1 and these code pages.
It also turns out that EBCDIC has nearly precise equivalents for the ASCII/Latin1 C0 controls and the DELETE control. (The C0 controls are those whose ASCII code points are 0..0x1F; things like TAB, ACK, BEL, etc.) A mapping is set up between these ASCII/EBCDIC controls. There isn't such a precise mapping between the C1 controls on ASCII platforms and the remaining EBCDIC controls. What has been done is to map these controls, mostly arbitrarily, to some otherwise unmatched character in the other character set. Most of these are very very rarely used nowadays in EBCDIC anyway, and their names have been dropped, without much complaint. For example the EO (Eight Ones) EBCDIC control (consisting of eight one bits = 0xFF) is mapped to the C1 APC control (0x9F), and you can't use the name "EO".
The EBCDIC controls provide three possible line terminator characters, CR (0x0D), LF (0x25), and NL (0x15). On ASCII platforms, the symbols "NL" and "LF" refer to the same character, but in strict EBCDIC terminology they are different ones. The EBCDIC NL is mapped to the C1 control called "NEL" ("Next Line"; here's a case where the mapping makes quite a bit of sense, and hence isn't just arbitrary). On some EBCDIC platforms, this NL or NEL is the typical line terminator. This is true of z/OS and BS2000. In these platforms, the C compilers will swap the LF and NEL code points, so that `"\n"` is 0x15, and refers to NL. Perl does that too; you can see it in the code chart [below](#recipe-3). This makes things generally "just work" without you even having to be aware that there is a swap.
###
Unicode and UTF
UTF stands for "Unicode Transformation Format". UTF-8 is an encoding of Unicode into a sequence of 8-bit byte chunks, based on ASCII and Latin-1. The length of a sequence required to represent a Unicode code point depends on the ordinal number of that code point, with larger numbers requiring more bytes. UTF-EBCDIC is like UTF-8, but based on EBCDIC. They are enough alike that often, casual usage will conflate the two terms, and use "UTF-8" to mean both the UTF-8 found on ASCII platforms, and the UTF-EBCDIC found on EBCDIC ones.
You may see the term "invariant" character or code point. This simply means that the character has the same numeric value and representation when encoded in UTF-8 (or UTF-EBCDIC) as when not. (Note that this is a very different concept from ["The 13 variant characters"](#The-13-variant-characters) mentioned above. Careful prose will use the term "UTF-8 invariant" instead of just "invariant", but most often you'll see just "invariant".) For example, the ordinal value of "A" is 193 in most EBCDIC code pages, and also is 193 when encoded in UTF-EBCDIC. All UTF-8 (or UTF-EBCDIC) variant code points occupy at least two bytes when encoded in UTF-8 (or UTF-EBCDIC); by definition, the UTF-8 (or UTF-EBCDIC) invariant code points are exactly one byte whether encoded in UTF-8 (or UTF-EBCDIC), or not. (By now you see why people typically just say "UTF-8" when they also mean "UTF-EBCDIC". For the rest of this document, we'll mostly be casual about it too.) In ASCII UTF-8, the code points corresponding to the lowest 128 ordinal numbers (0 - 127: the ASCII characters) are invariant. In UTF-EBCDIC, there are 160 invariant characters. (If you care, the EBCDIC invariants are those characters which have ASCII equivalents, plus those that correspond to the C1 controls (128 - 159 on ASCII platforms).)
A string encoded in UTF-EBCDIC may be longer (very rarely shorter) than one encoded in UTF-8. Perl extends both UTF-8 and UTF-EBCDIC so that they can encode code points above the Unicode maximum of U+10FFFF. Both extensions are constructed to allow encoding of any code point that fits in a 64-bit word.
UTF-EBCDIC is defined by [Unicode Technical Report #16](https://www.unicode.org/reports/tr16) (often referred to as just TR16). It is defined based on CCSID 1047, not allowing for the differences for other code pages. This allows for easy interchange of text between computers running different code pages, but makes it unusable, without adaptation, for Perl on those other code pages.
The reason for this unusability is that a fundamental assumption of Perl is that the characters it cares about for parsing and lexical analysis are the same whether or not the text is in UTF-8. For example, Perl expects the character `"["` to have the same representation, no matter if the string containing it (or program text) is UTF-8 encoded or not. To ensure this, Perl adapts UTF-EBCDIC to the particular code page so that all characters it expects to be UTF-8 invariant are in fact UTF-8 invariant. This means that text generated on a computer running one version of Perl's UTF-EBCDIC has to be translated to be intelligible to a computer running another.
TR16 implies a method to extend UTF-EBCDIC to encode points up through `2 ** 31 - 1`. Perl uses this method for code points up through `2 ** 30 - 1`, but uses an incompatible method for larger ones, to enable it to handle much larger code points than otherwise.
###
Using Encode
Starting from Perl 5.8 you can use the standard module Encode to translate from EBCDIC to Latin-1 code points. Encode knows about more EBCDIC character sets than Perl can currently be compiled to run on.
```
use Encode 'from_to';
my %ebcdic = ( 176 => 'cp37', 95 => 'cp1047', 106 => 'posix-bc' );
# $a is in EBCDIC code points
from_to($a, $ebcdic{ord '^'}, 'latin1');
# $a is ISO 8859-1 code points
```
and from Latin-1 code points to EBCDIC code points
```
use Encode 'from_to';
my %ebcdic = ( 176 => 'cp37', 95 => 'cp1047', 106 => 'posix-bc' );
# $a is ISO 8859-1 code points
from_to($a, 'latin1', $ebcdic{ord '^'});
# $a is in EBCDIC code points
```
For doing I/O it is suggested that you use the autotranslating features of PerlIO, see <perluniintro>.
Since version 5.8 Perl uses the PerlIO I/O library. This enables you to use different encodings per IO channel. For example you may use
```
use Encode;
open($f, ">:encoding(ascii)", "test.ascii");
print $f "Hello World!\n";
open($f, ">:encoding(cp37)", "test.ebcdic");
print $f "Hello World!\n";
open($f, ">:encoding(latin1)", "test.latin1");
print $f "Hello World!\n";
open($f, ">:encoding(utf8)", "test.utf8");
print $f "Hello World!\n";
```
to get four files containing "Hello World!\n" in ASCII, CP 0037 EBCDIC, ISO 8859-1 (Latin-1) (in this example identical to ASCII since only ASCII characters were printed), and UTF-EBCDIC (in this example identical to normal EBCDIC since only characters that don't differ between EBCDIC and UTF-EBCDIC were printed). See the documentation of <Encode::PerlIO> for details.
As the PerlIO layer uses raw IO (bytes) internally, all this totally ignores things like the type of your filesystem (ASCII or EBCDIC).
SINGLE OCTET TABLES
--------------------
The following tables list the ASCII and Latin 1 ordered sets including the subsets: C0 controls (0..31), ASCII graphics (32..7e), delete (7f), C1 controls (80..9f), and Latin-1 (a.k.a. ISO 8859-1) (a0..ff). In the table names of the Latin 1 extensions to ASCII have been labelled with character names roughly corresponding to *The Unicode Standard, Version 6.1* albeit with substitutions such as `s/LATIN//` and `s/VULGAR//` in all cases; `s/CAPITAL LETTER//` in some cases; and `s/SMALL LETTER ([A-Z])/\l$1/` in some other cases. Controls are listed using their Unicode 6.2 abbreviations. The differences between the 0037 and 1047 sets are flagged with `**`. The differences between the 1047 and POSIX-BC sets are flagged with `##.` All `ord()` numbers listed are decimal. If you would rather see this table listing octal values, then run the table (that is, the pod source text of this document, since this recipe may not work with a pod2\_other\_format translation) through:
recipe 0
```
perl -ne 'if(/(.{29})(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/)' \
-e '{printf("%s%-5.03o%-5.03o%-5.03o%.03o\n",$1,$2,$3,$4,$5)}' \
perlebcdic.pod
```
If you want to retain the UTF-x code points then in script form you might want to write:
recipe 1
```
open(FH,"<perlebcdic.pod") or die "Could not open perlebcdic.pod: $!";
while (<FH>) {
if (/(.{29})(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\.?(\d*)
\s+(\d+)\.?(\d*)/x)
{
if ($7 ne '' && $9 ne '') {
printf(
"%s%-5.03o%-5.03o%-5.03o%-5.03o%-3o.%-5o%-3o.%.03o\n",
$1,$2,$3,$4,$5,$6,$7,$8,$9);
}
elsif ($7 ne '') {
printf("%s%-5.03o%-5.03o%-5.03o%-5.03o%-3o.%-5o%.03o\n",
$1,$2,$3,$4,$5,$6,$7,$8);
}
else {
printf("%s%-5.03o%-5.03o%-5.03o%-5.03o%-5.03o%.03o\n",
$1,$2,$3,$4,$5,$6,$8);
}
}
}
```
If you would rather see this table listing hexadecimal values then run the table through:
recipe 2
```
perl -ne 'if(/(.{29})(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/)' \
-e '{printf("%s%-5.02X%-5.02X%-5.02X%.02X\n",$1,$2,$3,$4,$5)}' \
perlebcdic.pod
```
Or, in order to retain the UTF-x code points in hexadecimal:
recipe 3
```
open(FH,"<perlebcdic.pod") or die "Could not open perlebcdic.pod: $!";
while (<FH>) {
if (/(.{29})(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\.?(\d*)
\s+(\d+)\.?(\d*)/x)
{
if ($7 ne '' && $9 ne '') {
printf(
"%s%-5.02X%-5.02X%-5.02X%-5.02X%-2X.%-6.02X%02X.%02X\n",
$1,$2,$3,$4,$5,$6,$7,$8,$9);
}
elsif ($7 ne '') {
printf("%s%-5.02X%-5.02X%-5.02X%-5.02X%-2X.%-6.02X%02X\n",
$1,$2,$3,$4,$5,$6,$7,$8);
}
else {
printf("%s%-5.02X%-5.02X%-5.02X%-5.02X%-5.02X%02X\n",
$1,$2,$3,$4,$5,$6,$8);
}
}
}
ISO
8859-1 POS- CCSID
CCSID CCSID CCSID IX- 1047
chr 0819 0037 1047 BC UTF-8 UTF-EBCDIC
---------------------------------------------------------------------
<NUL> 0 0 0 0 0 0
<SOH> 1 1 1 1 1 1
<STX> 2 2 2 2 2 2
<ETX> 3 3 3 3 3 3
<EOT> 4 55 55 55 4 55
<ENQ> 5 45 45 45 5 45
<ACK> 6 46 46 46 6 46
<BEL> 7 47 47 47 7 47
<BS> 8 22 22 22 8 22
<HT> 9 5 5 5 9 5
<LF> 10 37 21 21 10 21 **
<VT> 11 11 11 11 11 11
<FF> 12 12 12 12 12 12
<CR> 13 13 13 13 13 13
<SO> 14 14 14 14 14 14
<SI> 15 15 15 15 15 15
<DLE> 16 16 16 16 16 16
<DC1> 17 17 17 17 17 17
<DC2> 18 18 18 18 18 18
<DC3> 19 19 19 19 19 19
<DC4> 20 60 60 60 20 60
<NAK> 21 61 61 61 21 61
<SYN> 22 50 50 50 22 50
<ETB> 23 38 38 38 23 38
<CAN> 24 24 24 24 24 24
<EOM> 25 25 25 25 25 25
<SUB> 26 63 63 63 26 63
<ESC> 27 39 39 39 27 39
<FS> 28 28 28 28 28 28
<GS> 29 29 29 29 29 29
<RS> 30 30 30 30 30 30
<US> 31 31 31 31 31 31
<SPACE> 32 64 64 64 32 64
! 33 90 90 90 33 90
" 34 127 127 127 34 127
# 35 123 123 123 35 123
$ 36 91 91 91 36 91
% 37 108 108 108 37 108
& 38 80 80 80 38 80
' 39 125 125 125 39 125
( 40 77 77 77 40 77
) 41 93 93 93 41 93
* 42 92 92 92 42 92
+ 43 78 78 78 43 78
, 44 107 107 107 44 107
- 45 96 96 96 45 96
. 46 75 75 75 46 75
/ 47 97 97 97 47 97
0 48 240 240 240 48 240
1 49 241 241 241 49 241
2 50 242 242 242 50 242
3 51 243 243 243 51 243
4 52 244 244 244 52 244
5 53 245 245 245 53 245
6 54 246 246 246 54 246
7 55 247 247 247 55 247
8 56 248 248 248 56 248
9 57 249 249 249 57 249
: 58 122 122 122 58 122
; 59 94 94 94 59 94
< 60 76 76 76 60 76
= 61 126 126 126 61 126
> 62 110 110 110 62 110
? 63 111 111 111 63 111
@ 64 124 124 124 64 124
A 65 193 193 193 65 193
B 66 194 194 194 66 194
C 67 195 195 195 67 195
D 68 196 196 196 68 196
E 69 197 197 197 69 197
F 70 198 198 198 70 198
G 71 199 199 199 71 199
H 72 200 200 200 72 200
I 73 201 201 201 73 201
J 74 209 209 209 74 209
K 75 210 210 210 75 210
L 76 211 211 211 76 211
M 77 212 212 212 77 212
N 78 213 213 213 78 213
O 79 214 214 214 79 214
P 80 215 215 215 80 215
Q 81 216 216 216 81 216
R 82 217 217 217 82 217
S 83 226 226 226 83 226
T 84 227 227 227 84 227
U 85 228 228 228 85 228
V 86 229 229 229 86 229
W 87 230 230 230 87 230
X 88 231 231 231 88 231
Y 89 232 232 232 89 232
Z 90 233 233 233 90 233
[ 91 186 173 187 91 173 ** ##
\ 92 224 224 188 92 224 ##
] 93 187 189 189 93 189 **
^ 94 176 95 106 94 95 ** ##
_ 95 109 109 109 95 109
` 96 121 121 74 96 121 ##
a 97 129 129 129 97 129
b 98 130 130 130 98 130
c 99 131 131 131 99 131
d 100 132 132 132 100 132
e 101 133 133 133 101 133
f 102 134 134 134 102 134
g 103 135 135 135 103 135
h 104 136 136 136 104 136
i 105 137 137 137 105 137
j 106 145 145 145 106 145
k 107 146 146 146 107 146
l 108 147 147 147 108 147
m 109 148 148 148 109 148
n 110 149 149 149 110 149
o 111 150 150 150 111 150
p 112 151 151 151 112 151
q 113 152 152 152 113 152
r 114 153 153 153 114 153
s 115 162 162 162 115 162
t 116 163 163 163 116 163
u 117 164 164 164 117 164
v 118 165 165 165 118 165
w 119 166 166 166 119 166
x 120 167 167 167 120 167
y 121 168 168 168 121 168
z 122 169 169 169 122 169
{ 123 192 192 251 123 192 ##
| 124 79 79 79 124 79
} 125 208 208 253 125 208 ##
~ 126 161 161 255 126 161 ##
<DEL> 127 7 7 7 127 7
<PAD> 128 32 32 32 194.128 32
<HOP> 129 33 33 33 194.129 33
<BPH> 130 34 34 34 194.130 34
<NBH> 131 35 35 35 194.131 35
<IND> 132 36 36 36 194.132 36
<NEL> 133 21 37 37 194.133 37 **
<SSA> 134 6 6 6 194.134 6
<ESA> 135 23 23 23 194.135 23
<HTS> 136 40 40 40 194.136 40
<HTJ> 137 41 41 41 194.137 41
<VTS> 138 42 42 42 194.138 42
<PLD> 139 43 43 43 194.139 43
<PLU> 140 44 44 44 194.140 44
<RI> 141 9 9 9 194.141 9
<SS2> 142 10 10 10 194.142 10
<SS3> 143 27 27 27 194.143 27
<DCS> 144 48 48 48 194.144 48
<PU1> 145 49 49 49 194.145 49
<PU2> 146 26 26 26 194.146 26
<STS> 147 51 51 51 194.147 51
<CCH> 148 52 52 52 194.148 52
<MW> 149 53 53 53 194.149 53
<SPA> 150 54 54 54 194.150 54
<EPA> 151 8 8 8 194.151 8
<SOS> 152 56 56 56 194.152 56
<SGC> 153 57 57 57 194.153 57
<SCI> 154 58 58 58 194.154 58
<CSI> 155 59 59 59 194.155 59
<ST> 156 4 4 4 194.156 4
<OSC> 157 20 20 20 194.157 20
<PM> 158 62 62 62 194.158 62
<APC> 159 255 255 95 194.159 255 ##
<NON-BREAKING SPACE> 160 65 65 65 194.160 128.65
<INVERTED "!" > 161 170 170 170 194.161 128.66
<CENT SIGN> 162 74 74 176 194.162 128.67 ##
<POUND SIGN> 163 177 177 177 194.163 128.68
<CURRENCY SIGN> 164 159 159 159 194.164 128.69
<YEN SIGN> 165 178 178 178 194.165 128.70
<BROKEN BAR> 166 106 106 208 194.166 128.71 ##
<SECTION SIGN> 167 181 181 181 194.167 128.72
<DIAERESIS> 168 189 187 121 194.168 128.73 ** ##
<COPYRIGHT SIGN> 169 180 180 180 194.169 128.74
<FEMININE ORDINAL> 170 154 154 154 194.170 128.81
<LEFT POINTING GUILLEMET> 171 138 138 138 194.171 128.82
<NOT SIGN> 172 95 176 186 194.172 128.83 ** ##
<SOFT HYPHEN> 173 202 202 202 194.173 128.84
<REGISTERED TRADE MARK> 174 175 175 175 194.174 128.85
<MACRON> 175 188 188 161 194.175 128.86 ##
<DEGREE SIGN> 176 144 144 144 194.176 128.87
<PLUS-OR-MINUS SIGN> 177 143 143 143 194.177 128.88
<SUPERSCRIPT TWO> 178 234 234 234 194.178 128.89
<SUPERSCRIPT THREE> 179 250 250 250 194.179 128.98
<ACUTE ACCENT> 180 190 190 190 194.180 128.99
<MICRO SIGN> 181 160 160 160 194.181 128.100
<PARAGRAPH SIGN> 182 182 182 182 194.182 128.101
<MIDDLE DOT> 183 179 179 179 194.183 128.102
<CEDILLA> 184 157 157 157 194.184 128.103
<SUPERSCRIPT ONE> 185 218 218 218 194.185 128.104
<MASC. ORDINAL INDICATOR> 186 155 155 155 194.186 128.105
<RIGHT POINTING GUILLEMET> 187 139 139 139 194.187 128.106
<FRACTION ONE QUARTER> 188 183 183 183 194.188 128.112
<FRACTION ONE HALF> 189 184 184 184 194.189 128.113
<FRACTION THREE QUARTERS> 190 185 185 185 194.190 128.114
<INVERTED QUESTION MARK> 191 171 171 171 194.191 128.115
<A WITH GRAVE> 192 100 100 100 195.128 138.65
<A WITH ACUTE> 193 101 101 101 195.129 138.66
<A WITH CIRCUMFLEX> 194 98 98 98 195.130 138.67
<A WITH TILDE> 195 102 102 102 195.131 138.68
<A WITH DIAERESIS> 196 99 99 99 195.132 138.69
<A WITH RING ABOVE> 197 103 103 103 195.133 138.70
<CAPITAL LIGATURE AE> 198 158 158 158 195.134 138.71
<C WITH CEDILLA> 199 104 104 104 195.135 138.72
<E WITH GRAVE> 200 116 116 116 195.136 138.73
<E WITH ACUTE> 201 113 113 113 195.137 138.74
<E WITH CIRCUMFLEX> 202 114 114 114 195.138 138.81
<E WITH DIAERESIS> 203 115 115 115 195.139 138.82
<I WITH GRAVE> 204 120 120 120 195.140 138.83
<I WITH ACUTE> 205 117 117 117 195.141 138.84
<I WITH CIRCUMFLEX> 206 118 118 118 195.142 138.85
<I WITH DIAERESIS> 207 119 119 119 195.143 138.86
<CAPITAL LETTER ETH> 208 172 172 172 195.144 138.87
<N WITH TILDE> 209 105 105 105 195.145 138.88
<O WITH GRAVE> 210 237 237 237 195.146 138.89
<O WITH ACUTE> 211 238 238 238 195.147 138.98
<O WITH CIRCUMFLEX> 212 235 235 235 195.148 138.99
<O WITH TILDE> 213 239 239 239 195.149 138.100
<O WITH DIAERESIS> 214 236 236 236 195.150 138.101
<MULTIPLICATION SIGN> 215 191 191 191 195.151 138.102
<O WITH STROKE> 216 128 128 128 195.152 138.103
<U WITH GRAVE> 217 253 253 224 195.153 138.104 ##
<U WITH ACUTE> 218 254 254 254 195.154 138.105
<U WITH CIRCUMFLEX> 219 251 251 221 195.155 138.106 ##
<U WITH DIAERESIS> 220 252 252 252 195.156 138.112
<Y WITH ACUTE> 221 173 186 173 195.157 138.113 ** ##
<CAPITAL LETTER THORN> 222 174 174 174 195.158 138.114
<SMALL LETTER SHARP S> 223 89 89 89 195.159 138.115
<a WITH GRAVE> 224 68 68 68 195.160 139.65
<a WITH ACUTE> 225 69 69 69 195.161 139.66
<a WITH CIRCUMFLEX> 226 66 66 66 195.162 139.67
<a WITH TILDE> 227 70 70 70 195.163 139.68
<a WITH DIAERESIS> 228 67 67 67 195.164 139.69
<a WITH RING ABOVE> 229 71 71 71 195.165 139.70
<SMALL LIGATURE ae> 230 156 156 156 195.166 139.71
<c WITH CEDILLA> 231 72 72 72 195.167 139.72
<e WITH GRAVE> 232 84 84 84 195.168 139.73
<e WITH ACUTE> 233 81 81 81 195.169 139.74
<e WITH CIRCUMFLEX> 234 82 82 82 195.170 139.81
<e WITH DIAERESIS> 235 83 83 83 195.171 139.82
<i WITH GRAVE> 236 88 88 88 195.172 139.83
<i WITH ACUTE> 237 85 85 85 195.173 139.84
<i WITH CIRCUMFLEX> 238 86 86 86 195.174 139.85
<i WITH DIAERESIS> 239 87 87 87 195.175 139.86
<SMALL LETTER eth> 240 140 140 140 195.176 139.87
<n WITH TILDE> 241 73 73 73 195.177 139.88
<o WITH GRAVE> 242 205 205 205 195.178 139.89
<o WITH ACUTE> 243 206 206 206 195.179 139.98
<o WITH CIRCUMFLEX> 244 203 203 203 195.180 139.99
<o WITH TILDE> 245 207 207 207 195.181 139.100
<o WITH DIAERESIS> 246 204 204 204 195.182 139.101
<DIVISION SIGN> 247 225 225 225 195.183 139.102
<o WITH STROKE> 248 112 112 112 195.184 139.103
<u WITH GRAVE> 249 221 221 192 195.185 139.104 ##
<u WITH ACUTE> 250 222 222 222 195.186 139.105
<u WITH CIRCUMFLEX> 251 219 219 219 195.187 139.106
<u WITH DIAERESIS> 252 220 220 220 195.188 139.112
<y WITH ACUTE> 253 141 141 141 195.189 139.113
<SMALL LETTER thorn> 254 142 142 142 195.190 139.114
<y WITH DIAERESIS> 255 223 223 223 195.191 139.115
```
If you would rather see the above table in CCSID 0037 order rather than ASCII + Latin-1 order then run the table through:
recipe 4
```
perl \
-ne 'if(/.{29}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}/)'\
-e '{push(@l,$_)}' \
-e 'END{print map{$_->[0]}' \
-e ' sort{$a->[1] <=> $b->[1]}' \
-e ' map{[$_,substr($_,34,3)]}@l;}' perlebcdic.pod
```
If you would rather see it in CCSID 1047 order then change the number 34 in the last line to 39, like this:
recipe 5
```
perl \
-ne 'if(/.{29}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}/)'\
-e '{push(@l,$_)}' \
-e 'END{print map{$_->[0]}' \
-e ' sort{$a->[1] <=> $b->[1]}' \
-e ' map{[$_,substr($_,39,3)]}@l;}' perlebcdic.pod
```
If you would rather see it in POSIX-BC order then change the number 34 in the last line to 44, like this:
recipe 6
```
perl \
-ne 'if(/.{29}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}\s{2,4}\d{1,3}/)'\
-e '{push(@l,$_)}' \
-e 'END{print map{$_->[0]}' \
-e ' sort{$a->[1] <=> $b->[1]}' \
-e ' map{[$_,substr($_,44,3)]}@l;}' perlebcdic.pod
```
###
Table in hex, sorted in 1047 order
Since this document was first written, the convention has become more and more to use hexadecimal notation for code points. To do this with the recipes and to also sort is a multi-step process, so here, for convenience, is the table from above, re-sorted to be in Code Page 1047 order, and using hex notation.
```
ISO
8859-1 POS- CCSID
CCSID CCSID CCSID IX- 1047
chr 0819 0037 1047 BC UTF-8 UTF-EBCDIC
---------------------------------------------------------------------
<NUL> 00 00 00 00 00 00
<SOH> 01 01 01 01 01 01
<STX> 02 02 02 02 02 02
<ETX> 03 03 03 03 03 03
<ST> 9C 04 04 04 C2.9C 04
<HT> 09 05 05 05 09 05
<SSA> 86 06 06 06 C2.86 06
<DEL> 7F 07 07 07 7F 07
<EPA> 97 08 08 08 C2.97 08
<RI> 8D 09 09 09 C2.8D 09
<SS2> 8E 0A 0A 0A C2.8E 0A
<VT> 0B 0B 0B 0B 0B 0B
<FF> 0C 0C 0C 0C 0C 0C
<CR> 0D 0D 0D 0D 0D 0D
<SO> 0E 0E 0E 0E 0E 0E
<SI> 0F 0F 0F 0F 0F 0F
<DLE> 10 10 10 10 10 10
<DC1> 11 11 11 11 11 11
<DC2> 12 12 12 12 12 12
<DC3> 13 13 13 13 13 13
<OSC> 9D 14 14 14 C2.9D 14
<LF> 0A 25 15 15 0A 15 **
<BS> 08 16 16 16 08 16
<ESA> 87 17 17 17 C2.87 17
<CAN> 18 18 18 18 18 18
<EOM> 19 19 19 19 19 19
<PU2> 92 1A 1A 1A C2.92 1A
<SS3> 8F 1B 1B 1B C2.8F 1B
<FS> 1C 1C 1C 1C 1C 1C
<GS> 1D 1D 1D 1D 1D 1D
<RS> 1E 1E 1E 1E 1E 1E
<US> 1F 1F 1F 1F 1F 1F
<PAD> 80 20 20 20 C2.80 20
<HOP> 81 21 21 21 C2.81 21
<BPH> 82 22 22 22 C2.82 22
<NBH> 83 23 23 23 C2.83 23
<IND> 84 24 24 24 C2.84 24
<NEL> 85 15 25 25 C2.85 25 **
<ETB> 17 26 26 26 17 26
<ESC> 1B 27 27 27 1B 27
<HTS> 88 28 28 28 C2.88 28
<HTJ> 89 29 29 29 C2.89 29
<VTS> 8A 2A 2A 2A C2.8A 2A
<PLD> 8B 2B 2B 2B C2.8B 2B
<PLU> 8C 2C 2C 2C C2.8C 2C
<ENQ> 05 2D 2D 2D 05 2D
<ACK> 06 2E 2E 2E 06 2E
<BEL> 07 2F 2F 2F 07 2F
<DCS> 90 30 30 30 C2.90 30
<PU1> 91 31 31 31 C2.91 31
<SYN> 16 32 32 32 16 32
<STS> 93 33 33 33 C2.93 33
<CCH> 94 34 34 34 C2.94 34
<MW> 95 35 35 35 C2.95 35
<SPA> 96 36 36 36 C2.96 36
<EOT> 04 37 37 37 04 37
<SOS> 98 38 38 38 C2.98 38
<SGC> 99 39 39 39 C2.99 39
<SCI> 9A 3A 3A 3A C2.9A 3A
<CSI> 9B 3B 3B 3B C2.9B 3B
<DC4> 14 3C 3C 3C 14 3C
<NAK> 15 3D 3D 3D 15 3D
<PM> 9E 3E 3E 3E C2.9E 3E
<SUB> 1A 3F 3F 3F 1A 3F
<SPACE> 20 40 40 40 20 40
<NON-BREAKING SPACE> A0 41 41 41 C2.A0 80.41
<a WITH CIRCUMFLEX> E2 42 42 42 C3.A2 8B.43
<a WITH DIAERESIS> E4 43 43 43 C3.A4 8B.45
<a WITH GRAVE> E0 44 44 44 C3.A0 8B.41
<a WITH ACUTE> E1 45 45 45 C3.A1 8B.42
<a WITH TILDE> E3 46 46 46 C3.A3 8B.44
<a WITH RING ABOVE> E5 47 47 47 C3.A5 8B.46
<c WITH CEDILLA> E7 48 48 48 C3.A7 8B.48
<n WITH TILDE> F1 49 49 49 C3.B1 8B.58
<CENT SIGN> A2 4A 4A B0 C2.A2 80.43 ##
. 2E 4B 4B 4B 2E 4B
< 3C 4C 4C 4C 3C 4C
( 28 4D 4D 4D 28 4D
+ 2B 4E 4E 4E 2B 4E
| 7C 4F 4F 4F 7C 4F
& 26 50 50 50 26 50
<e WITH ACUTE> E9 51 51 51 C3.A9 8B.4A
<e WITH CIRCUMFLEX> EA 52 52 52 C3.AA 8B.51
<e WITH DIAERESIS> EB 53 53 53 C3.AB 8B.52
<e WITH GRAVE> E8 54 54 54 C3.A8 8B.49
<i WITH ACUTE> ED 55 55 55 C3.AD 8B.54
<i WITH CIRCUMFLEX> EE 56 56 56 C3.AE 8B.55
<i WITH DIAERESIS> EF 57 57 57 C3.AF 8B.56
<i WITH GRAVE> EC 58 58 58 C3.AC 8B.53
<SMALL LETTER SHARP S> DF 59 59 59 C3.9F 8A.73
! 21 5A 5A 5A 21 5A
$ 24 5B 5B 5B 24 5B
* 2A 5C 5C 5C 2A 5C
) 29 5D 5D 5D 29 5D
; 3B 5E 5E 5E 3B 5E
^ 5E B0 5F 6A 5E 5F ** ##
- 2D 60 60 60 2D 60
/ 2F 61 61 61 2F 61
<A WITH CIRCUMFLEX> C2 62 62 62 C3.82 8A.43
<A WITH DIAERESIS> C4 63 63 63 C3.84 8A.45
<A WITH GRAVE> C0 64 64 64 C3.80 8A.41
<A WITH ACUTE> C1 65 65 65 C3.81 8A.42
<A WITH TILDE> C3 66 66 66 C3.83 8A.44
<A WITH RING ABOVE> C5 67 67 67 C3.85 8A.46
<C WITH CEDILLA> C7 68 68 68 C3.87 8A.48
<N WITH TILDE> D1 69 69 69 C3.91 8A.58
<BROKEN BAR> A6 6A 6A D0 C2.A6 80.47 ##
, 2C 6B 6B 6B 2C 6B
% 25 6C 6C 6C 25 6C
_ 5F 6D 6D 6D 5F 6D
> 3E 6E 6E 6E 3E 6E
? 3F 6F 6F 6F 3F 6F
<o WITH STROKE> F8 70 70 70 C3.B8 8B.67
<E WITH ACUTE> C9 71 71 71 C3.89 8A.4A
<E WITH CIRCUMFLEX> CA 72 72 72 C3.8A 8A.51
<E WITH DIAERESIS> CB 73 73 73 C3.8B 8A.52
<E WITH GRAVE> C8 74 74 74 C3.88 8A.49
<I WITH ACUTE> CD 75 75 75 C3.8D 8A.54
<I WITH CIRCUMFLEX> CE 76 76 76 C3.8E 8A.55
<I WITH DIAERESIS> CF 77 77 77 C3.8F 8A.56
<I WITH GRAVE> CC 78 78 78 C3.8C 8A.53
` 60 79 79 4A 60 79 ##
: 3A 7A 7A 7A 3A 7A
# 23 7B 7B 7B 23 7B
@ 40 7C 7C 7C 40 7C
' 27 7D 7D 7D 27 7D
= 3D 7E 7E 7E 3D 7E
" 22 7F 7F 7F 22 7F
<O WITH STROKE> D8 80 80 80 C3.98 8A.67
a 61 81 81 81 61 81
b 62 82 82 82 62 82
c 63 83 83 83 63 83
d 64 84 84 84 64 84
e 65 85 85 85 65 85
f 66 86 86 86 66 86
g 67 87 87 87 67 87
h 68 88 88 88 68 88
i 69 89 89 89 69 89
<LEFT POINTING GUILLEMET> AB 8A 8A 8A C2.AB 80.52
<RIGHT POINTING GUILLEMET> BB 8B 8B 8B C2.BB 80.6A
<SMALL LETTER eth> F0 8C 8C 8C C3.B0 8B.57
<y WITH ACUTE> FD 8D 8D 8D C3.BD 8B.71
<SMALL LETTER thorn> FE 8E 8E 8E C3.BE 8B.72
<PLUS-OR-MINUS SIGN> B1 8F 8F 8F C2.B1 80.58
<DEGREE SIGN> B0 90 90 90 C2.B0 80.57
j 6A 91 91 91 6A 91
k 6B 92 92 92 6B 92
l 6C 93 93 93 6C 93
m 6D 94 94 94 6D 94
n 6E 95 95 95 6E 95
o 6F 96 96 96 6F 96
p 70 97 97 97 70 97
q 71 98 98 98 71 98
r 72 99 99 99 72 99
<FEMININE ORDINAL> AA 9A 9A 9A C2.AA 80.51
<MASC. ORDINAL INDICATOR> BA 9B 9B 9B C2.BA 80.69
<SMALL LIGATURE ae> E6 9C 9C 9C C3.A6 8B.47
<CEDILLA> B8 9D 9D 9D C2.B8 80.67
<CAPITAL LIGATURE AE> C6 9E 9E 9E C3.86 8A.47
<CURRENCY SIGN> A4 9F 9F 9F C2.A4 80.45
<MICRO SIGN> B5 A0 A0 A0 C2.B5 80.64
~ 7E A1 A1 FF 7E A1 ##
s 73 A2 A2 A2 73 A2
t 74 A3 A3 A3 74 A3
u 75 A4 A4 A4 75 A4
v 76 A5 A5 A5 76 A5
w 77 A6 A6 A6 77 A6
x 78 A7 A7 A7 78 A7
y 79 A8 A8 A8 79 A8
z 7A A9 A9 A9 7A A9
<INVERTED "!" > A1 AA AA AA C2.A1 80.42
<INVERTED QUESTION MARK> BF AB AB AB C2.BF 80.73
<CAPITAL LETTER ETH> D0 AC AC AC C3.90 8A.57
[ 5B BA AD BB 5B AD ** ##
<CAPITAL LETTER THORN> DE AE AE AE C3.9E 8A.72
<REGISTERED TRADE MARK> AE AF AF AF C2.AE 80.55
<NOT SIGN> AC 5F B0 BA C2.AC 80.53 ** ##
<POUND SIGN> A3 B1 B1 B1 C2.A3 80.44
<YEN SIGN> A5 B2 B2 B2 C2.A5 80.46
<MIDDLE DOT> B7 B3 B3 B3 C2.B7 80.66
<COPYRIGHT SIGN> A9 B4 B4 B4 C2.A9 80.4A
<SECTION SIGN> A7 B5 B5 B5 C2.A7 80.48
<PARAGRAPH SIGN> B6 B6 B6 B6 C2.B6 80.65
<FRACTION ONE QUARTER> BC B7 B7 B7 C2.BC 80.70
<FRACTION ONE HALF> BD B8 B8 B8 C2.BD 80.71
<FRACTION THREE QUARTERS> BE B9 B9 B9 C2.BE 80.72
<Y WITH ACUTE> DD AD BA AD C3.9D 8A.71 ** ##
<DIAERESIS> A8 BD BB 79 C2.A8 80.49 ** ##
<MACRON> AF BC BC A1 C2.AF 80.56 ##
] 5D BB BD BD 5D BD **
<ACUTE ACCENT> B4 BE BE BE C2.B4 80.63
<MULTIPLICATION SIGN> D7 BF BF BF C3.97 8A.66
{ 7B C0 C0 FB 7B C0 ##
A 41 C1 C1 C1 41 C1
B 42 C2 C2 C2 42 C2
C 43 C3 C3 C3 43 C3
D 44 C4 C4 C4 44 C4
E 45 C5 C5 C5 45 C5
F 46 C6 C6 C6 46 C6
G 47 C7 C7 C7 47 C7
H 48 C8 C8 C8 48 C8
I 49 C9 C9 C9 49 C9
<SOFT HYPHEN> AD CA CA CA C2.AD 80.54
<o WITH CIRCUMFLEX> F4 CB CB CB C3.B4 8B.63
<o WITH DIAERESIS> F6 CC CC CC C3.B6 8B.65
<o WITH GRAVE> F2 CD CD CD C3.B2 8B.59
<o WITH ACUTE> F3 CE CE CE C3.B3 8B.62
<o WITH TILDE> F5 CF CF CF C3.B5 8B.64
} 7D D0 D0 FD 7D D0 ##
J 4A D1 D1 D1 4A D1
K 4B D2 D2 D2 4B D2
L 4C D3 D3 D3 4C D3
M 4D D4 D4 D4 4D D4
N 4E D5 D5 D5 4E D5
O 4F D6 D6 D6 4F D6
P 50 D7 D7 D7 50 D7
Q 51 D8 D8 D8 51 D8
R 52 D9 D9 D9 52 D9
<SUPERSCRIPT ONE> B9 DA DA DA C2.B9 80.68
<u WITH CIRCUMFLEX> FB DB DB DB C3.BB 8B.6A
<u WITH DIAERESIS> FC DC DC DC C3.BC 8B.70
<u WITH GRAVE> F9 DD DD C0 C3.B9 8B.68 ##
<u WITH ACUTE> FA DE DE DE C3.BA 8B.69
<y WITH DIAERESIS> FF DF DF DF C3.BF 8B.73
\ 5C E0 E0 BC 5C E0 ##
<DIVISION SIGN> F7 E1 E1 E1 C3.B7 8B.66
S 53 E2 E2 E2 53 E2
T 54 E3 E3 E3 54 E3
U 55 E4 E4 E4 55 E4
V 56 E5 E5 E5 56 E5
W 57 E6 E6 E6 57 E6
X 58 E7 E7 E7 58 E7
Y 59 E8 E8 E8 59 E8
Z 5A E9 E9 E9 5A E9
<SUPERSCRIPT TWO> B2 EA EA EA C2.B2 80.59
<O WITH CIRCUMFLEX> D4 EB EB EB C3.94 8A.63
<O WITH DIAERESIS> D6 EC EC EC C3.96 8A.65
<O WITH GRAVE> D2 ED ED ED C3.92 8A.59
<O WITH ACUTE> D3 EE EE EE C3.93 8A.62
<O WITH TILDE> D5 EF EF EF C3.95 8A.64
0 30 F0 F0 F0 30 F0
1 31 F1 F1 F1 31 F1
2 32 F2 F2 F2 32 F2
3 33 F3 F3 F3 33 F3
4 34 F4 F4 F4 34 F4
5 35 F5 F5 F5 35 F5
6 36 F6 F6 F6 36 F6
7 37 F7 F7 F7 37 F7
8 38 F8 F8 F8 38 F8
9 39 F9 F9 F9 39 F9
<SUPERSCRIPT THREE> B3 FA FA FA C2.B3 80.62
<U WITH CIRCUMFLEX> DB FB FB DD C3.9B 8A.6A ##
<U WITH DIAERESIS> DC FC FC FC C3.9C 8A.70
<U WITH GRAVE> D9 FD FD E0 C3.99 8A.68 ##
<U WITH ACUTE> DA FE FE FE C3.9A 8A.69
<APC> 9F FF FF 5F C2.9F FF ##
```
IDENTIFYING CHARACTER CODE SETS
--------------------------------
It is possible to determine which character set you are operating under. But first you need to be really really sure you need to do this. Your code will be simpler and probably just as portable if you don't have to test the character set and do different things, depending. There are actually only very few circumstances where it's not easy to write straight-line code portable to all character sets. See ["Unicode and EBCDIC" in perluniintro](perluniintro#Unicode-and-EBCDIC) for how to portably specify characters.
But there are some cases where you may want to know which character set you are running under. One possible example is doing [sorting](#SORTING) in inner loops where performance is critical.
To determine if you are running under ASCII or EBCDIC, you can use the return value of `ord()` or `chr()` to test one or more character values. For example:
```
$is_ascii = "A" eq chr(65);
$is_ebcdic = "A" eq chr(193);
$is_ascii = ord("A") == 65;
$is_ebcdic = ord("A") == 193;
```
There's even less need to distinguish between EBCDIC code pages, but to do so try looking at one or more of the characters that differ between them.
```
$is_ascii = ord('[') == 91;
$is_ebcdic_37 = ord('[') == 186;
$is_ebcdic_1047 = ord('[') == 173;
$is_ebcdic_POSIX_BC = ord('[') == 187;
```
However, it would be unwise to write tests such as:
```
$is_ascii = "\r" ne chr(13); # WRONG
$is_ascii = "\n" ne chr(10); # ILL ADVISED
```
Obviously the first of these will fail to distinguish most ASCII platforms from either a CCSID 0037, a 1047, or a POSIX-BC EBCDIC platform since `"\r" eq chr(13)` under all of those coded character sets. But note too that because `"\n"` is `chr(13)` and `"\r"` is `chr(10)` on old Macintosh (which is an ASCII platform) the second `$is_ascii` test will lead to trouble there.
To determine whether or not perl was built under an EBCDIC code page you can use the Config module like so:
```
use Config;
$is_ebcdic = $Config{'ebcdic'} eq 'define';
```
CONVERSIONS
-----------
###
`utf8::unicode_to_native()` and `utf8::native_to_unicode()`
These functions take an input numeric code point in one encoding and return what its equivalent value is in the other.
See <utf8>.
###
tr///
In order to convert a string of characters from one character set to another a simple list of numbers, such as in the right columns in the above table, along with Perl's `tr///` operator is all that is needed. The data in the table are in ASCII/Latin1 order, hence the EBCDIC columns provide easy-to-use ASCII/Latin1 to EBCDIC operations that are also easily reversed.
For example, to convert ASCII/Latin1 to code page 037 take the output of the second numbers column from the output of recipe 2 (modified to add `"\"` characters), and use it in `tr///` like so:
```
$cp_037 =
'\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' .
'\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
'\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
'\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
'\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
'\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBA\xE0\xBB\xB0\x6D' .
'\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
'\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
'\x20\x21\x22\x23\x24\x15\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
'\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
'\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBD\xB4\x9A\x8A\x5F\xCA\xAF\xBC' .
'\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
'\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
'\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xAD\xAE\x59' .
'\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
'\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
my $ebcdic_string = $ascii_string;
eval '$ebcdic_string =~ tr/\000-\377/' . $cp_037 . '/';
```
To convert from EBCDIC 037 to ASCII just reverse the order of the tr/// arguments like so:
```
my $ascii_string = $ebcdic_string;
eval '$ascii_string =~ tr/' . $cp_037 . '/\000-\377/';
```
Similarly one could take the output of the third numbers column from recipe 2 to obtain a `$cp_1047` table. The fourth numbers column of the output from recipe 2 could provide a `$cp_posix_bc` table suitable for transcoding as well.
If you wanted to see the inverse tables, you would first have to sort on the desired numbers column as in recipes 4, 5 or 6, then take the output of the first numbers column.
### iconv
XPG operability often implies the presence of an *iconv* utility available from the shell or from the C library. Consult your system's documentation for information on iconv.
On OS/390 or z/OS see the [iconv(1)](http://man.he.net/man1/iconv) manpage. One way to invoke the `iconv` shell utility from within perl would be to:
```
# OS/390 or z/OS example
$ascii_data = `echo '$ebcdic_data'| iconv -f IBM-1047 -t ISO8859-1`
```
or the inverse map:
```
# OS/390 or z/OS example
$ebcdic_data = `echo '$ascii_data'| iconv -f ISO8859-1 -t IBM-1047`
```
For other Perl-based conversion options see the `Convert::*` modules on CPAN.
###
C RTL
The OS/390 and z/OS C run-time libraries provide `_atoe()` and `_etoa()` functions.
OPERATOR DIFFERENCES
---------------------
The `..` range operator treats certain character ranges with care on EBCDIC platforms. For example the following array will have twenty six elements on either an EBCDIC platform or an ASCII platform:
```
@alphabet = ('A'..'Z'); # $#alphabet == 25
```
The bitwise operators such as & ^ | may return different results when operating on string or character data in a Perl program running on an EBCDIC platform than when run on an ASCII platform. Here is an example adapted from the one in <perlop>:
```
# EBCDIC-based examples
print "j p \n" ^ " a h"; # prints "JAPH\n"
print "JA" | " ph\n"; # prints "japh\n"
print "JAPH\nJunk" & "\277\277\277\277\277"; # prints "japh\n";
print 'p N$' ^ " E<H\n"; # prints "Perl\n";
```
An interesting property of the 32 C0 control characters in the ASCII table is that they can "literally" be constructed as control characters in Perl, e.g. `(chr(0)` eq `\c@`)> `(chr(1)` eq `\cA`)>, and so on. Perl on EBCDIC platforms has been ported to take `\c@` to `chr(0)` and `\cA` to `chr(1)`, etc. as well, but the characters that result depend on which code page you are using. The table below uses the standard acronyms for the controls. The POSIX-BC and 1047 sets are identical throughout this range and differ from the 0037 set at only one spot (21 decimal). Note that the line terminator character may be generated by `\cJ` on ASCII platforms but by `\cU` on 1047 or POSIX-BC platforms and cannot be generated as a `"\c.letter."` control character on 0037 platforms. Note also that `\c\` cannot be the final element in a string or regex, as it will absorb the terminator. But `\c\*X*` is a `FILE SEPARATOR` concatenated with *X* for all *X*. The outlier `\c?` on ASCII, which yields a non-C0 control `DEL`, yields the outlier control `APC` on EBCDIC, the one that isn't in the block of contiguous controls. Note that a subtlety of this is that `\c?` on ASCII platforms is an ASCII character, while it isn't equivalent to any ASCII character in EBCDIC platforms.
```
chr ord 8859-1 0037 1047 && POSIX-BC
-----------------------------------------------------------------------
\c@ 0 <NUL> <NUL> <NUL>
\cA 1 <SOH> <SOH> <SOH>
\cB 2 <STX> <STX> <STX>
\cC 3 <ETX> <ETX> <ETX>
\cD 4 <EOT> <ST> <ST>
\cE 5 <ENQ> <HT> <HT>
\cF 6 <ACK> <SSA> <SSA>
\cG 7 <BEL> <DEL> <DEL>
\cH 8 <BS> <EPA> <EPA>
\cI 9 <HT> <RI> <RI>
\cJ 10 <LF> <SS2> <SS2>
\cK 11 <VT> <VT> <VT>
\cL 12 <FF> <FF> <FF>
\cM 13 <CR> <CR> <CR>
\cN 14 <SO> <SO> <SO>
\cO 15 <SI> <SI> <SI>
\cP 16 <DLE> <DLE> <DLE>
\cQ 17 <DC1> <DC1> <DC1>
\cR 18 <DC2> <DC2> <DC2>
\cS 19 <DC3> <DC3> <DC3>
\cT 20 <DC4> <OSC> <OSC>
\cU 21 <NAK> <NEL> <LF> **
\cV 22 <SYN> <BS> <BS>
\cW 23 <ETB> <ESA> <ESA>
\cX 24 <CAN> <CAN> <CAN>
\cY 25 <EOM> <EOM> <EOM>
\cZ 26 <SUB> <PU2> <PU2>
\c[ 27 <ESC> <SS3> <SS3>
\c\X 28 <FS>X <FS>X <FS>X
\c] 29 <GS> <GS> <GS>
\c^ 30 <RS> <RS> <RS>
\c_ 31 <US> <US> <US>
\c? * <DEL> <APC> <APC>
```
`*` Note: `\c?` maps to ordinal 127 (`DEL`) on ASCII platforms, but since ordinal 127 is a not a control character on EBCDIC machines, `\c?` instead maps on them to `APC`, which is 255 in 0037 and 1047, and 95 in POSIX-BC.
FUNCTION DIFFERENCES
---------------------
`chr()`
`chr()` must be given an EBCDIC code number argument to yield a desired character return value on an EBCDIC platform. For example:
```
$CAPITAL_LETTER_A = chr(193);
```
`ord()`
`ord()` will return EBCDIC code number values on an EBCDIC platform. For example:
```
$the_number_193 = ord("A");
```
`pack()`
The `"c"` and `"C"` templates for `pack()` are dependent upon character set encoding. Examples of usage on EBCDIC include:
```
$foo = pack("CCCC",193,194,195,196);
# $foo eq "ABCD"
$foo = pack("C4",193,194,195,196);
# same thing
$foo = pack("ccxxcc",193,194,195,196);
# $foo eq "AB\0\0CD"
```
The `"U"` template has been ported to mean "Unicode" on all platforms so that
```
pack("U", 65) eq 'A'
```
is true on all platforms. If you want native code points for the low 256, use the `"W"` template. This means that the equivalences
```
pack("W", ord($character)) eq $character
unpack("W", $character) == ord $character
```
will hold.
`print()`
One must be careful with scalars and strings that are passed to print that contain ASCII encodings. One common place for this to occur is in the output of the MIME type header for CGI script writing. For example, many Perl programming guides recommend something similar to:
```
print "Content-type:\ttext/html\015\012\015\012";
# this may be wrong on EBCDIC
```
You can instead write
```
print "Content-type:\ttext/html\r\n\r\n"; # OK for DGW et al
```
and have it work portably.
That is because the translation from EBCDIC to ASCII is done by the web server in this case. Consult your web server's documentation for further details.
`printf()`
The formats that can convert characters to numbers and vice versa will be different from their ASCII counterparts when executed on an EBCDIC platform. Examples include:
```
printf("%c%c%c",193,194,195); # prints ABC
```
`sort()`
EBCDIC sort results may differ from ASCII sort results especially for mixed case strings. This is discussed in more detail [below](#SORTING).
`sprintf()`
See the discussion of `["printf()"](#printf%28%29)` above. An example of the use of sprintf would be:
```
$CAPITAL_LETTER_A = sprintf("%c",193);
```
`unpack()`
See the discussion of `["pack()"](#pack%28%29)` above.
Note that it is possible to write portable code for these by specifying things in Unicode numbers, and using a conversion function:
```
printf("%c",utf8::unicode_to_native(65)); # prints A on all
# platforms
print utf8::native_to_unicode(ord("A")); # Likewise, prints 65
```
See ["Unicode and EBCDIC" in perluniintro](perluniintro#Unicode-and-EBCDIC) and ["CONVERSIONS"](#CONVERSIONS) for other options.
REGULAR EXPRESSION DIFFERENCES
-------------------------------
You can write your regular expressions just like someone on an ASCII platform would do. But keep in mind that using octal or hex notation to specify a particular code point will give you the character that the EBCDIC code page natively maps to it. (This is also true of all double-quoted strings.) If you want to write portably, just use the `\N{U+...}` notation everywhere where you would have used `\x{...}`, and don't use octal notation at all.
Starting in Perl v5.22, this applies to ranges in bracketed character classes. If you say, for example, `qr/[\N{U+20}-\N{U+7F}]/`, it means the characters `\N{U+20}`, `\N{U+21}`, ..., `\N{U+7F}`. This range is all the printable characters that the ASCII character set contains.
Prior to v5.22, you couldn't specify any ranges portably, except (starting in Perl v5.5.3) all subsets of the `[A-Z]` and `[a-z]` ranges are specially coded to not pick up gap characters. For example, characters such as "รด" (`o WITH CIRCUMFLEX`) that lie between "I" and "J" would not be matched by the regular expression range `/[H-K]/`. But if either of the range end points is explicitly numeric (and neither is specified by `\N{U+...}`), the gap characters are matched:
```
/[\x89-\x91]/
```
will match `\x8e`, even though `\x89` is "i" and `\x91` is "j", and `\x8e` is a gap character, from the alphabetic viewpoint.
Another construct to be wary of is the inappropriate use of hex (unless you use `\N{U+...}`) or octal constants in regular expressions. Consider the following set of subs:
```
sub is_c0 {
my $char = substr(shift,0,1);
$char =~ /[\000-\037]/;
}
sub is_print_ascii {
my $char = substr(shift,0,1);
$char =~ /[\040-\176]/;
}
sub is_delete {
my $char = substr(shift,0,1);
$char eq "\177";
}
sub is_c1 {
my $char = substr(shift,0,1);
$char =~ /[\200-\237]/;
}
sub is_latin_1 { # But not ASCII; not C1
my $char = substr(shift,0,1);
$char =~ /[\240-\377]/;
}
```
These are valid only on ASCII platforms. Starting in Perl v5.22, simply changing the octal constants to equivalent `\N{U+...}` values makes them portable:
```
sub is_c0 {
my $char = substr(shift,0,1);
$char =~ /[\N{U+00}-\N{U+1F}]/;
}
sub is_print_ascii {
my $char = substr(shift,0,1);
$char =~ /[\N{U+20}-\N{U+7E}]/;
}
sub is_delete {
my $char = substr(shift,0,1);
$char eq "\N{U+7F}";
}
sub is_c1 {
my $char = substr(shift,0,1);
$char =~ /[\N{U+80}-\N{U+9F}]/;
}
sub is_latin_1 { # But not ASCII; not C1
my $char = substr(shift,0,1);
$char =~ /[\N{U+A0}-\N{U+FF}]/;
}
```
And here are some alternative portable ways to write them:
```
sub Is_c0 {
my $char = substr(shift,0,1);
return $char =~ /[[:cntrl:]]/a && ! Is_delete($char);
# Alternatively:
# return $char =~ /[[:cntrl:]]/
# && $char =~ /[[:ascii:]]/
# && ! Is_delete($char);
}
sub Is_print_ascii {
my $char = substr(shift,0,1);
return $char =~ /[[:print:]]/a;
# Alternatively:
# return $char =~ /[[:print:]]/ && $char =~ /[[:ascii:]]/;
# Or
# return $char
# =~ /[ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/;
}
sub Is_delete {
my $char = substr(shift,0,1);
return utf8::native_to_unicode(ord $char) == 0x7F;
}
sub Is_c1 {
use feature 'unicode_strings';
my $char = substr(shift,0,1);
return $char =~ /[[:cntrl:]]/ && $char !~ /[[:ascii:]]/;
}
sub Is_latin_1 { # But not ASCII; not C1
use feature 'unicode_strings';
my $char = substr(shift,0,1);
return ord($char) < 256
&& $char !~ /[[:ascii:]]/
&& $char !~ /[[:cntrl:]]/;
}
```
Another way to write `Is_latin_1()` would be to use the characters in the range explicitly:
```
sub Is_latin_1 {
my $char = substr(shift,0,1);
$char =~ /[ย ยกยขยฃยคยฅยฆยงยจยฉยชยซยฌยญยฎยฏยฐยฑยฒยณยดยตยถยทยธยนยบยปยผยฝยพยฟรรรรรร
รรรรรรรรรร]
[รรรรรรรรรรรรรรรรร รกรขรฃรครฅรฆรงรจรฉรชรซรฌรญรฎรฏรฐรฑรฒรณรดรตรถรทรธรนรบรปรผรฝรพรฟ]/x;
}
```
Although that form may run into trouble in network transit (due to the presence of 8 bit characters) or on non ISO-Latin character sets. But it does allow `Is_c1` to be rewritten so it works on Perls that don't have `'unicode_strings'` (earlier than v5.14):
```
sub Is_latin_1 { # But not ASCII; not C1
my $char = substr(shift,0,1);
return ord($char) < 256
&& $char !~ /[[:ascii:]]/
&& ! Is_latin1($char);
}
```
SOCKETS
-------
Most socket programming assumes ASCII character encodings in network byte order. Exceptions can include CGI script writing under a host web server where the server may take care of translation for you. Most host web servers convert EBCDIC data to ISO-8859-1 or Unicode on output.
SORTING
-------
One big difference between ASCII-based character sets and EBCDIC ones are the relative positions of the characters when sorted in native order. Of most concern are the upper- and lowercase letters, the digits, and the underscore (`"_"`). On ASCII platforms the native sort order has the digits come before the uppercase letters which come before the underscore which comes before the lowercase letters. On EBCDIC, the underscore comes first, then the lowercase letters, then the uppercase ones, and the digits last. If sorted on an ASCII-based platform, the two-letter abbreviation for a physician comes before the two letter abbreviation for drive; that is:
```
@sorted = sort(qw(Dr. dr.)); # @sorted holds ('Dr.','dr.') on ASCII,
# but ('dr.','Dr.') on EBCDIC
```
The property of lowercase before uppercase letters in EBCDIC is even carried to the Latin 1 EBCDIC pages such as 0037 and 1047. An example would be that "ร" (`E WITH DIAERESIS`, 203) comes before "รซ" (`e WITH DIAERESIS`, 235) on an ASCII platform, but the latter (83) comes before the former (115) on an EBCDIC platform. (Astute readers will note that the uppercase version of "ร" `SMALL LETTER SHARP S` is simply "SS" and that the upper case versions of "รฟ" (small `y WITH DIAERESIS`) and "ยต" (`MICRO SIGN`) are not in the 0..255 range but are in Unicode, in a Unicode enabled Perl).
The sort order will cause differences between results obtained on ASCII platforms versus EBCDIC platforms. What follows are some suggestions on how to deal with these differences.
###
Ignore ASCII vs. EBCDIC sort differences.
This is the least computationally expensive strategy. It may require some user education.
###
Use a sort helper function
This is completely general, but the most computationally expensive strategy. Choose one or the other character set and transform to that for every sort comparison. Here's a complete example that transforms to ASCII sort order:
```
sub native_to_uni($) {
my $string = shift;
# Saves time on an ASCII platform
return $string if ord 'A' == 65;
my $output = "";
for my $i (0 .. length($string) - 1) {
$output
.= chr(utf8::native_to_unicode(ord(substr($string, $i, 1))));
}
# Preserve utf8ness of input onto the output, even if it didn't need
# to be utf8
utf8::upgrade($output) if utf8::is_utf8($string);
return $output;
}
sub ascii_order { # Sort helper
return native_to_uni($a) cmp native_to_uni($b);
}
sort ascii_order @list;
```
###
MONO CASE then sort data (for non-digits, non-underscore)
If you don't care about where digits and underscore sort to, you can do something like this
```
sub case_insensitive_order { # Sort helper
return lc($a) cmp lc($b)
}
sort case_insensitive_order @list;
```
If performance is an issue, and you don't care if the output is in the same case as the input, Use `tr///` to transform to the case most employed within the data. If the data are primarily UPPERCASE non-Latin1, then apply `tr/[a-z]/[A-Z]/`, and then `sort()`. If the data are primarily lowercase non Latin1 then apply `tr/[A-Z]/[a-z]/` before sorting. If the data are primarily UPPERCASE and include Latin-1 characters then apply:
```
tr/[a-z]/[A-Z]/;
tr/[ร รกรขรฃรครฅรฆรงรจรฉรชรซรฌรญรฎรฏรฐรฑรฒรณรดรตรถรธรนรบรปรผรฝรพ]/[รรรรรร
รรรรรรรรรรรรรรรรรรรรรรรร/;
s/ร/SS/g;
```
then `sort()`. If you have a choice, it's better to lowercase things to avoid the problems of the two Latin-1 characters whose uppercase is outside Latin-1: "รฟ" (small `y WITH DIAERESIS`) and "ยต" (`MICRO SIGN`). If you do need to upppercase, you can; with a Unicode-enabled Perl, do:
```
tr/รฟ/\x{178}/;
tr/ยต/\x{39C}/;
```
###
Perform sorting on one type of platform only.
This strategy can employ a network connection. As such it would be computationally expensive.
TRANSFORMATION FORMATS
-----------------------
There are a variety of ways of transforming data with an intra character set mapping that serve a variety of purposes. Sorting was discussed in the previous section and a few of the other more popular mapping techniques are discussed next.
###
URL decoding and encoding
Note that some URLs have hexadecimal ASCII code points in them in an attempt to overcome character or protocol limitation issues. For example the tilde character is not on every keyboard hence a URL of the form:
```
http://www.pvhp.com/~pvhp/
```
may also be expressed as either of:
```
http://www.pvhp.com/%7Epvhp/
http://www.pvhp.com/%7epvhp/
```
where 7E is the hexadecimal ASCII code point for "~". Here is an example of decoding such a URL in any EBCDIC code page:
```
$url = 'http://www.pvhp.com/%7Epvhp/';
$url =~ s/%([0-9a-fA-F]{2})/
pack("c",utf8::unicode_to_native(hex($1)))/xge;
```
Conversely, here is a partial solution for the task of encoding such a URL in any EBCDIC code page:
```
$url = 'http://www.pvhp.com/~pvhp/';
# The following regular expression does not address the
# mappings for: ('.' => '%2E', '/' => '%2F', ':' => '%3A')
$url =~ s/([\t "#%&\(\),;<=>\?\@\[\\\]^`{|}~])/
sprintf("%%%02X",utf8::native_to_unicode(ord($1)))/xge;
```
where a more complete solution would split the URL into components and apply a full s/// substitution only to the appropriate parts.
###
uu encoding and decoding
The `u` template to `pack()` or `unpack()` will render EBCDIC data in EBCDIC characters equivalent to their ASCII counterparts. For example, the following will print "Yes indeed\n" on either an ASCII or EBCDIC computer:
```
$all_byte_chrs = '';
for (0..255) { $all_byte_chrs .= chr($_); }
$uuencode_byte_chrs = pack('u', $all_byte_chrs);
($uu = <<'ENDOFHEREDOC') =~ s/^\s*//gm;
M``$"`P0%!@<("0H+#`T.#Q`1$A,4%187&!D:&QP='A\@(2(C)"4F)R@I*BLL
M+2XO,#$R,S0U-C<X.3H[/#T^/T!!0D-$149'2$E*2TQ-3D]045)35%565UA9
M6EM<75Y?8&%B8V1E9F=H:6IK;&UN;W!Q<G-T=79W>'EZ>WQ]?G^`@8*#A(6&
MAXB)BHN,C8Z/D)&2DY25EI>8F9J;G)V>GZ"AHJ.DI::GJ*FJJZRMKJ^PL;*S
MM+6VM[BYNKN\O;Z_P,'"P\3%QL?(R<K+S,W.S]#1TM/4U=;7V-G:V]S=WM_@
?X>+CY.7FY^CIZNOL[>[O\/'R\_3U]O?X^?K[_/W^_P``
ENDOFHEREDOC
if ($uuencode_byte_chrs eq $uu) {
print "Yes ";
}
$uudecode_byte_chrs = unpack('u', $uuencode_byte_chrs);
if ($uudecode_byte_chrs eq $all_byte_chrs) {
print "indeed\n";
}
```
Here is a very spartan uudecoder that will work on EBCDIC:
```
#!/usr/local/bin/perl
$_ = <> until ($mode,$file) = /^begin\s*(\d*)\s*(\S*)/;
open(OUT, "> $file") if $file ne "";
while(<>) {
last if /^end/;
next if /[a-z]/;
next unless int((((utf8::native_to_unicode(ord()) - 32 ) & 077)
+ 2) / 3)
== int(length() / 4);
print OUT unpack("u", $_);
}
close(OUT);
chmod oct($mode), $file;
```
###
Quoted-Printable encoding and decoding
On ASCII-encoded platforms it is possible to strip characters outside of the printable set using:
```
# This QP encoder works on ASCII only
$qp_string =~ s/([=\x00-\x1F\x80-\xFF])/
sprintf("=%02X",ord($1))/xge;
```
Starting in Perl v5.22, this is trivially changeable to work portably on both ASCII and EBCDIC platforms.
```
# This QP encoder works on both ASCII and EBCDIC
$qp_string =~ s/([=\N{U+00}-\N{U+1F}\N{U+80}-\N{U+FF}])/
sprintf("=%02X",ord($1))/xge;
```
For earlier Perls, a QP encoder that works on both ASCII and EBCDIC platforms would look somewhat like the following:
```
$delete = utf8::unicode_to_native(ord("\x7F"));
$qp_string =~
s/([^[:print:]$delete])/
sprintf("=%02X",utf8::native_to_unicode(ord($1)))/xage;
```
(although in production code the substitutions might be done in the EBCDIC branch with the function call and separately in the ASCII branch without the expense of the identity map; in Perl v5.22, the identity map is optimized out so there is no expense, but the alternative above is simpler and is also available in v5.22).
Such QP strings can be decoded with:
```
# This QP decoder is limited to ASCII only
$string =~ s/=([[:xdigit:][[:xdigit:])/chr hex $1/ge;
$string =~ s/=[\n\r]+$//;
```
Whereas a QP decoder that works on both ASCII and EBCDIC platforms would look somewhat like the following:
```
$string =~ s/=([[:xdigit:][:xdigit:]])/
chr utf8::native_to_unicode(hex $1)/xge;
$string =~ s/=[\n\r]+$//;
```
###
Caesarean ciphers
The practice of shifting an alphabet one or more characters for encipherment dates back thousands of years and was explicitly detailed by Gaius Julius Caesar in his **Gallic Wars** text. A single alphabet shift is sometimes referred to as a rotation and the shift amount is given as a number $n after the string 'rot' or "rot$n". Rot0 and rot26 would designate identity maps on the 26-letter English version of the Latin alphabet. Rot13 has the interesting property that alternate subsequent invocations are identity maps (thus rot13 is its own non-trivial inverse in the group of 26 alphabet rotations). Hence the following is a rot13 encoder and decoder that will work on ASCII and EBCDIC platforms:
```
#!/usr/local/bin/perl
while(<>){
tr/n-za-mN-ZA-M/a-zA-Z/;
print;
}
```
In one-liner form:
```
perl -ne 'tr/n-za-mN-ZA-M/a-zA-Z/;print'
```
Hashing order and checksums
----------------------------
Perl deliberately randomizes hash order for security purposes on both ASCII and EBCDIC platforms.
EBCDIC checksums will differ for the same file translated into ASCII and vice versa.
I18N AND L10N
--------------
Internationalization (I18N) and localization (L10N) are supported at least in principle even on EBCDIC platforms. The details are system-dependent and discussed under the ["OS ISSUES"](#OS-ISSUES) section below.
MULTI-OCTET CHARACTER SETS
---------------------------
Perl works with UTF-EBCDIC, a multi-byte encoding. In Perls earlier than v5.22, there may be various bugs in this regard.
Legacy multi byte EBCDIC code pages XXX.
OS ISSUES
----------
There may be a few system-dependent issues of concern to EBCDIC Perl programmers.
###
OS/400
PASE The PASE environment is a runtime environment for OS/400 that can run executables built for PowerPC AIX in OS/400; see <perlos400>. PASE is ASCII-based, not EBCDIC-based as the ILE.
IFS access XXX.
###
OS/390, z/OS
Perl runs under Unix Systems Services or USS.
`sigaction` `SA_SIGINFO` can have segmentation faults.
`chcp` **chcp** is supported as a shell utility for displaying and changing one's code page. See also [chcp(1)](http://man.he.net/man1/chcp).
dataset access For sequential data set access try:
```
my @ds_records = `cat //DSNAME`;
```
or:
```
my @ds_records = `cat //'HLQ.DSNAME'`;
```
See also the OS390::Stdio module on CPAN.
`iconv` **iconv** is supported as both a shell utility and a C RTL routine. See also the [iconv(1)](http://man.he.net/man1/iconv) and [iconv(3)](http://man.he.net/man3/iconv) manual pages.
locales Locales are supported. There may be glitches when a locale is another EBCDIC code page which has some of the [code-page variant characters](#The-13-variant-characters) in other positions.
There aren't currently any real UTF-8 locales, even though some locale names contain the string "UTF-8".
See <perllocale> for information on locales. The L10N files are in */usr/nls/locale*. `$Config{d_setlocale}` is `'define'` on OS/390 or z/OS.
###
POSIX-BC?
XXX.
BUGS
----
* Not all shells will allow multiple `-e` string arguments to perl to be concatenated together properly as recipes in this document 0, 2, 4, 5, and 6 might seem to imply.
* There are a significant number of test failures in the CPAN modules shipped with Perl v5.22 and 5.24. These are only in modules not primarily maintained by Perl 5 porters. Some of these are failures in the tests only: they don't realize that it is proper to get different results on EBCDIC platforms. And some of the failures are real bugs. If you compile and do a `make test` on Perl, all tests on the `/cpan` directory are skipped.
[Encode](encode) partially works.
* In earlier Perl versions, when byte and character data were concatenated, the new string was sometimes created by decoding the byte strings as *ISO 8859-1 (Latin-1)*, even if the old Unicode string used EBCDIC.
SEE ALSO
---------
<perllocale>, <perlfunc>, <perlunicode>, <utf8>.
REFERENCES
----------
<http://std.dkuug.dk/i18n/charmaps>
<https://www.unicode.org/>
<https://www.unicode.org/reports/tr16/>
<https://www.sr-ix.com/Archive/CharCodeHist/index.html> **ASCII: American Standard Code for Information Infiltration** Tom Jennings, September 1999.
**The Unicode Standard, Version 3.0** The Unicode Consortium, Lisa Moore ed., ISBN 0-201-61633-5, Addison Wesley Developers Press, February 2000.
**CDRA: IBM - Character Data Representation Architecture - Reference and Registry**, IBM SC09-2190-00, December 1996.
"Demystifying Character Sets", Andrea Vine, Multilingual Computing & Technology, **#26 Vol. 10 Issue 4**, August/September 1999; ISSN 1523-0309; Multilingual Computing Inc. Sandpoint ID, USA.
**Codes, Ciphers, and Other Cryptic and Clandestine Communication** Fred B. Wrixon, ISBN 1-57912-040-7, Black Dog & Leventhal Publishers, 1998.
<http://www.bobbemer.com/P-BIT.HTM> **IBM - EBCDIC and the P-bit; The biggest Computer Goof Ever** Robert Bemer.
HISTORY
-------
15 April 2001: added UTF-8 and UTF-EBCDIC to main table, pvhp.
AUTHOR
------
Peter Prymmer [email protected] wrote this in 1999 and 2000 with CCSID 0819 and 0037 help from Chris Leach and Andrรฉ Pirard [email protected] as well as POSIX-BC help from Thomas Dorner [email protected]. Thanks also to Vickie Cooper, Philip Newton, William Raffloer, and Joe Smith. Trademarks, registered trademarks, service marks and registered service marks used in this document are the property of their respective owners.
Now maintained by Perl5 Porters.
| programming_docs |
perl Math::BigInt::FastCalc Math::BigInt::FastCalc
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [STORAGE](#STORAGE)
* [METHODS](#METHODS)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Math::BigInt::FastCalc - Math::BigInt::Calc with some XS for more speed
SYNOPSIS
--------
```
# to use it with Math::BigInt
use Math::BigInt lib => 'FastCalc';
# to use it with Math::BigFloat
use Math::BigFloat lib => 'FastCalc';
# to use it with Math::BigRat
use Math::BigRat lib => 'FastCalc';
```
DESCRIPTION
-----------
Math::BigInt::FastCalc inherits from Math::BigInt::Calc.
Provides support for big integer calculations. Not intended to be used by other modules. Other modules which sport the same functions can also be used to support Math::BigInt, like <Math::BigInt::GMP> or <Math::BigInt::Pari>.
In order to allow for multiple big integer libraries, Math::BigInt was rewritten to use library modules for core math routines. Any module which follows the same API as this can be used instead by using the following:
```
use Math::BigInt lib => 'libname';
```
'libname' is either the long name ('Math::BigInt::Pari'), or only the short version like 'Pari'. To use this library:
```
use Math::BigInt lib => 'FastCalc';
```
The default behaviour is to chose the best internal representation of big integers, but the base length used in the internal representation can be specified explicitly. Note that this must be done before Math::BigInt is loaded. For example,
```
use Math::BigInt::FastCalc base_len => 3;
use Math::BigInt lib => 'FastCalc';
```
STORAGE
-------
Math::BigInt::FastCalc works exactly like Math::BigInt::Calc. Numbers are stored in decimal form chopped into parts.
METHODS
-------
The following functions are now implemented in FastCalc.xs:
```
_is_odd _is_even _is_one _is_zero
_is_two _is_ten
_zero _one _two _ten
_acmp _len
_inc _dec
__strip_zeros _copy
```
BUGS
----
Please report any bugs or feature requests to `bug-math-bigint-fastcalc at rt.cpan.org`, or through the web interface at <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt-FastCalc> (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
-------
After installing, you can find documentation for this module with the perldoc command.
```
perldoc Math::BigInt::FastCalc
```
You can also look for information at:
GitHub <https://github.com/pjacklam/p5-Math-BigInt-FastCalc>
RT: CPAN's request tracker <https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt-FastCalc>
MetaCPAN <https://metacpan.org/release/Math-BigInt-FastCalc>
CPAN Testers Matrix <http://matrix.cpantesters.org/?dist=Math-BigInt-FastCalc>
CPAN Ratings <https://cpanratings.perl.org/dist/Math-BigInt-FastCalc>
LICENSE
-------
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
AUTHORS
-------
Original math code by Mark Biggar, rewritten by Tels <http://bloodgate.com/> in late 2000.
Separated from Math::BigInt and shaped API with the help of John Peacock.
Fixed, sped-up and enhanced by Tels http://bloodgate.com 2001-2003. Further streamlining (api\_version 1 etc.) by Tels 2004-2007.
Maintained by Peter John Acklam <[email protected]> 2010-2021.
SEE ALSO
---------
<Math::BigInt::Lib> for a description of the API.
Alternative libraries <Math::BigInt::Calc>, <Math::BigInt::GMP>, and <Math::BigInt::Pari>.
Some of the modules that use these libraries <Math::BigInt>, <Math::BigFloat>, and <Math::BigRat>.
perl Dumpvalue Dumpvalue
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Creation](#Creation)
+ [Methods](#Methods)
NAME
----
Dumpvalue - provides screen dump of Perl data.
SYNOPSIS
--------
```
use Dumpvalue;
my $dumper = Dumpvalue->new;
$dumper->set(globPrint => 1);
$dumper->dumpValue(\*::);
$dumper->dumpvars('main');
my $dump = $dumper->stringify($some_value);
```
DESCRIPTION
-----------
### Creation
A new dumper is created by a call
```
$d = Dumpvalue->new(option1 => value1, option2 => value2)
```
Recognized options:
`arrayDepth`, `hashDepth`
Print only first N elements of arrays and hashes. If false, prints all the elements.
`compactDump`, `veryCompact`
Change style of array and hash dump. If true, short array may be printed on one line.
`globPrint` Whether to print contents of globs.
`dumpDBFiles` Dump arrays holding contents of debugged files.
`dumpPackages` Dump symbol tables of packages.
`dumpReused` Dump contents of "reused" addresses.
`tick`, `quoteHighBit`, `printUndef`
Change style of string dump. Default value of `tick` is `auto`, one can enable either double-quotish dump, or single-quotish by setting it to `"` or `'`. By default, characters with high bit set are printed *as is*. If `quoteHighBit` is set, they will be quoted.
`usageOnly` rudimentary per-package memory usage dump. If set, `dumpvars` calculates total size of strings in variables in the package.
unctrl Changes the style of printout of strings. Possible values are `unctrl` and `quote`.
subdump Whether to try to find the subroutine name given the reference.
bareStringify Whether to write the non-overloaded form of the stringify-overloaded objects.
quoteHighBit Whether to print chars with high bit set in binary or "as is".
stopDbSignal Whether to abort printing if debugger signal flag is raised.
Later in the life of the object the methods may be queries with get() method and set() method (which accept multiple arguments).
### Methods
dumpValue
```
$dumper->dumpValue($value);
$dumper->dumpValue([$value1, $value2]);
```
Prints a dump to the currently selected filehandle.
dumpValues
```
$dumper->dumpValues($value1, $value2);
```
Same as `$dumper->dumpValue([$value1, $value2]);`.
stringify
```
my $dump = $dumper->stringify($value [,$noticks] );
```
Returns the dump of a single scalar without printing. If the second argument is true, the return value does not contain enclosing ticks. Does not handle data structures.
dumpvars
```
$dumper->dumpvars('my_package');
$dumper->dumpvars('my_package', 'foo', '~bar$', '!......');
```
The optional arguments are considered as literal strings unless they start with `~` or `!`, in which case they are interpreted as regular expressions (possibly negated).
The second example prints entries with names `foo`, and also entries with names which ends on `bar`, or are shorter than 5 chars.
set\_quote
```
$d->set_quote('"');
```
Sets `tick` and `unctrl` options to suitable values for printout with the given quote char. Possible values are `auto`, `'` and `"`.
set\_unctrl
```
$d->set_unctrl('unctrl');
```
Sets `unctrl` option with checking for an invalid argument. Possible values are `unctrl` and `quote`.
compactDump
```
$d->compactDump(1);
```
Sets `compactDump` option. If the value is 1, sets to a reasonable big number.
veryCompact
```
$d->veryCompact(1);
```
Sets `compactDump` and `veryCompact` options simultaneously.
set
```
$d->set(option1 => value1, option2 => value2);
```
get
```
@values = $d->get('option1', 'option2');
```
perl Test::Harness Test::Harness
=============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [runtests( @test\_files )](#runtests(-@test_files-))
+ [execute\_tests( tests => \@test\_files, out => \\*FH )](#execute_tests(-tests-=%3E-%5C@test_files,-out-=%3E-%5C*FH-))
* [EXPORT](#EXPORT)
* [ENVIRONMENT VARIABLES THAT TAP::HARNESS::COMPATIBLE SETS](#ENVIRONMENT-VARIABLES-THAT-TAP::HARNESS::COMPATIBLE-SETS)
* [ENVIRONMENT VARIABLES THAT AFFECT TEST::HARNESS](#ENVIRONMENT-VARIABLES-THAT-AFFECT-TEST::HARNESS)
* [Taint Mode](#Taint-Mode)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [LICENCE AND COPYRIGHT](#LICENCE-AND-COPYRIGHT)
NAME
----
Test::Harness - Run Perl standard test scripts with statistics
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use Test::Harness;
runtests(@test_files);
```
DESCRIPTION
-----------
Although, for historical reasons, the <Test::Harness> distribution takes its name from this module it now exists only to provide <TAP::Harness> with an interface that is somewhat backwards compatible with <Test::Harness> 2.xx. If you're writing new code consider using <TAP::Harness> directly instead.
Emulation is provided for `runtests` and `execute_tests` but the pluggable 'Straps' interface that previous versions of <Test::Harness> supported is not reproduced here. Straps is now available as a stand alone module: <Test::Harness::Straps>.
See <TAP::Parser>, <TAP::Harness> for the main documentation for this distribution.
FUNCTIONS
---------
The following functions are available.
###
runtests( @test\_files )
This runs all the given *@test\_files* and divines whether they passed or failed based on their output to STDOUT (details above). It prints out each individual test which failed along with a summary report and a how long it all took.
It returns true if everything was ok. Otherwise it will `die()` with one of the messages in the DIAGNOSTICS section.
###
execute\_tests( tests => \@test\_files, out => \\*FH )
Runs all the given `@test_files` (just like `runtests()`) but doesn't generate the final report. During testing, progress information will be written to the currently selected output filehandle (usually `STDOUT`), or to the filehandle given by the `out` parameter. The *out* is optional.
Returns a list of two values, `$total` and `$failed`, describing the results. `$total` is a hash ref summary of all the tests run. Its keys and values are this:
```
bonus Number of individual todo tests unexpectedly passed
max Number of individual tests ran
ok Number of individual tests passed
sub_skipped Number of individual tests skipped
todo Number of individual todo tests
files Number of test files ran
good Number of test files passed
bad Number of test files failed
tests Number of test files originally given
skipped Number of test files skipped
```
If `$total->{bad} == 0` and `$total->{max} > 0`, you've got a successful test.
`$failed` is a hash ref of all the test scripts that failed. Each key is the name of a test script, each value is another hash representing how that script failed. Its keys are these:
```
name Name of the test which failed
estat Script's exit value
wstat Script's wait status
max Number of individual tests
failed Number which failed
canon List of tests which failed (as string).
```
`$failed` should be empty if everything passed.
EXPORT
------
`&runtests` is exported by `Test::Harness` by default.
`&execute_tests`, `$verbose`, `$switches` and `$debug` are exported upon request.
ENVIRONMENT VARIABLES THAT TAP::HARNESS::COMPATIBLE SETS
---------------------------------------------------------
`Test::Harness` sets these before executing the individual tests.
`HARNESS_ACTIVE` This is set to a true value. It allows the tests to determine if they are being executed through the harness or by any other means.
`HARNESS_VERSION` This is the version of `Test::Harness`.
ENVIRONMENT VARIABLES THAT AFFECT TEST::HARNESS
------------------------------------------------
`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.
`-w` is always set. You can turn this off in the test with `BEGIN { $^W = 0 }`.
`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_VERBOSE` If true, `Test::Harness` will output the verbose results of running its tests. Setting `$Test::Harness::verbose` will override this, or you can use the `-v` switch in the *prove* utility.
`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_SUBCLASS` Specifies a TAP::Harness subclass to be used in place of TAP::Harness.
`HARNESS_SUMMARY_COLOR_SUCCESS` Determines the <Term::ANSIColor> for the summary in case it is successful. This color defaults to `'green'`.
`HARNESS_SUMMARY_COLOR_FAIL` Determines the <Term::ANSIColor> for the failure in case it is successful. This color defaults to `'red'`.
Taint Mode
-----------
Normally when a Perl program is run in taint mode the contents of the `PERL5LIB` environment variable do not appear in `@INC`.
Because `PERL5LIB` is often used during testing to add build directories to `@INC` `Test::Harness` passes the names of any directories found in `PERL5LIB` as -I switches. The net effect of this is that `PERL5LIB` is honoured even in taint mode.
SEE ALSO
---------
<TAP::Harness>
BUGS
----
Please report any bugs or feature requests to `bug-test-harness at rt.cpan.org`, or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Harness>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
AUTHORS
-------
Andy Armstrong `<[email protected]>`
<Test::Harness> 2.64 (maintained by Andy Lester and on which this module is based) has this attribution:
```
Either Tim Bunce or Andreas Koenig, we don't know. What we know for
sure is, that it was inspired by Larry Wall's F<TEST> script that came
with perl distributions for ages. Numerous anonymous contributors
exist. Andreas Koenig held the torch for many years, and then
Michael G Schwern.
```
LICENCE AND COPYRIGHT
----------------------
Copyright (c) 2007-2011, Andy Armstrong `<[email protected]>`. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See [perlartistic](https://perldoc.perl.org/5.36.0/perlartistic).
perl json_pp json\_pp
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
+ [-f](#-f)
+ [-t](#-t)
+ [-json\_opt](#-json_opt)
+ [-v](#-v)
+ [-V](#-V)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
json\_pp - JSON::PP command utility
SYNOPSIS
--------
```
json_pp [-v] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]]
```
DESCRIPTION
-----------
json\_pp converts between some input and output formats (one of them is JSON). This program was copied from <json_xs> and modified.
The default input format is json and the default output format is json with pretty option.
OPTIONS
-------
###
-f
```
-f from_format
```
Reads a data in the given format from STDIN.
Format types:
json as JSON
eval as Perl code
###
-t
Writes a data in the given format to STDOUT.
null no action.
json as JSON
dumper as Data::Dumper
###
-json\_opt
options to JSON::PP
Acceptable options are:
```
ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref
allow_singlequote allow_barekey allow_bignum loose escape_slash indent_length
```
Multiple options must be separated by commas:
```
Right: -json_opt pretty,canonical
Wrong: -json_opt pretty -json_opt canonical
```
###
-v
Verbose option, but currently no action in fact.
###
-V
Prints version and exits.
EXAMPLES
--------
```
$ perl -e'print q|{"foo":"ใใ","bar":1234567890000000000000000}|' |\
json_pp -f json -t dumper -json_opt pretty,utf8,allow_bignum
$VAR1 = {
'bar' => bless( {
'value' => [
'0000000',
'0000000',
'5678900',
'1234'
],
'sign' => '+'
}, 'Math::BigInt' ),
'foo' => "\x{3042}\x{3044}"
};
$ perl -e'print q|{"foo":"ใใ","bar":1234567890000000000000000}|' |\
json_pp -f json -t dumper -json_opt pretty
$VAR1 = {
'bar' => '1234567890000000000000000',
'foo' => "\x{e3}\x{81}\x{82}\x{e3}\x{81}\x{84}"
};
```
SEE ALSO
---------
<JSON::PP>, <json_xs>
AUTHOR
------
Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
COPYRIGHT AND LICENSE
----------------------
Copyright 2010 by Makamaka Hannyaharamitu
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl ExtUtils::Command::MM ExtUtils::Command::MM
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::Command::MM - Commands for the MM's to use in Makefiles
SYNOPSIS
--------
```
perl "-MExtUtils::Command::MM" -e "function" "--" arguments...
```
DESCRIPTION
-----------
**FOR INTERNAL USE ONLY!** The interface is not stable.
ExtUtils::Command::MM encapsulates code which would otherwise have to be done with large "one" liners.
Any $(FOO) used in the examples are make variables, not Perl.
**test\_harness**
```
test_harness($verbose, @test_libs);
```
Runs the tests on @ARGV via Test::Harness passing through the $verbose flag. Any @test\_libs will be unshifted onto the test's @INC.
@test\_libs are run in alphabetical order.
**pod2man**
```
pod2man( '--option=value',
$podfile1 => $manpage1,
$podfile2 => $manpage2,
...
);
# or args on @ARGV
```
pod2man() is a function performing most of the duties of the pod2man program. Its arguments are exactly the same as pod2man as of 5.8.0 with the addition of:
```
--perm_rw octal permission to set the resulting manpage to
```
And the removal of:
```
--verbose/-v
--help/-h
```
If no arguments are given to pod2man it will read from @ARGV.
If Pod::Man is unavailable, this function will warn and return undef.
**warn\_if\_old\_packlist**
```
perl "-MExtUtils::Command::MM" -e warn_if_old_packlist <somefile>
```
Displays a warning that an old packlist file was found. Reads the filename from @ARGV.
**perllocal\_install**
```
perl "-MExtUtils::Command::MM" -e perllocal_install
<type> <module name> <key> <value> ...
# VMS only, key|value pairs come on STDIN
perl "-MExtUtils::Command::MM" -e perllocal_install
<type> <module name> < <key>|<value> ...
```
Prints a fragment of POD suitable for appending to perllocal.pod. Arguments are read from @ARGV.
'type' is the type of what you're installing. Usually 'Module'.
'module name' is simply the name of your module. (Foo::Bar)
Key/value pairs are extra information about the module. Fields include:
```
installed into which directory your module was out into
LINKTYPE dynamic or static linking
VERSION module version number
EXE_FILES any executables installed in a space separated
list
```
**uninstall**
```
perl "-MExtUtils::Command::MM" -e uninstall <packlist>
```
A wrapper around ExtUtils::Install::uninstall(). Warns that uninstallation is deprecated and doesn't actually perform the uninstallation.
**test\_s**
```
perl "-MExtUtils::Command::MM" -e test_s <file>
```
Tests if a file exists and is not empty (size > 0). *Exits* with 0 if it does, 1 if it does not.
**cp\_nonempty**
```
perl "-MExtUtils::Command::MM" -e cp_nonempty <srcfile> <dstfile> <perm>
```
Tests if the source file exists and is not empty (size > 0). If it is not empty it copies it to the given destination with the given permissions.
| programming_docs |
perl ExtUtils::ParseXS::Eval ExtUtils::ParseXS::Eval
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [SUBROUTINES](#SUBROUTINES)
+ [$pxs->eval\_output\_typemap\_code($typemapcode, $other\_hashref)](#%24pxs-%3Eeval_output_typemap_code(%24typemapcode,-%24other_hashref))
+ [$pxs->eval\_input\_typemap\_code($typemapcode, $other\_hashref)](#%24pxs-%3Eeval_input_typemap_code(%24typemapcode,-%24other_hashref))
* [TODO](#TODO)
NAME
----
ExtUtils::ParseXS::Eval - Clean package to evaluate code in
SYNOPSIS
--------
```
use ExtUtils::ParseXS::Eval;
my $rv = ExtUtils::ParseXS::Eval::eval_typemap_code(
$parsexs_obj, "some Perl code"
);
```
SUBROUTINES
-----------
###
$pxs->eval\_output\_typemap\_code($typemapcode, $other\_hashref)
Sets up various bits of previously global state (formerly ExtUtils::ParseXS package variables) for eval'ing output typemap code that may refer to these variables.
Warns the contents of `$@` if any.
Not all these variables are necessarily considered "public" wrt. use in typemaps, so beware. Variables set up from the ExtUtils::ParseXS object:
```
$Package $ALIAS $func_name $Full_func_name $pname
```
Variables set up from `$other_hashref`:
```
$var $type $ntype $subtype $arg
```
###
$pxs->eval\_input\_typemap\_code($typemapcode, $other\_hashref)
Sets up various bits of previously global state (formerly ExtUtils::ParseXS package variables) for eval'ing output typemap code that may refer to these variables.
Warns the contents of `$@` if any.
Not all these variables are necessarily considered "public" wrt. use in typemaps, so beware. Variables set up from the ExtUtils::ParseXS object:
```
$Package $ALIAS $func_name $Full_func_name $pname
```
Variables set up from `$other_hashref`:
```
$var $type $ntype $subtype $num $init $printed_name $arg $argoff
```
TODO
----
Eventually, with better documentation and possible some cleanup, this could be part of `ExtUtils::Typemaps`.
perl bigfloat bigfloat
========
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
----
bigfloat - transparent big floating point number support for Perl
SYNOPSIS
--------
```
use bigfloat;
$x = 2 + 4.5; # Math::BigFloat 6.5
print 2 ** 512 * 0.1; # Math::BigFloat 134...09.6
print inf + 42; # Math::BigFloat inf
print NaN * 7; # Math::BigFloat NaN
print hex("0x1234567890123490"); # Perl v5.10.0 or later
{
no bigfloat;
print 2 ** 256; # a normal Perl scalar now
}
# for older Perls, import into current package:
use bigfloat qw/hex oct/;
print hex("0x1234567890123490");
print oct("01234567890123490");
```
DESCRIPTION
-----------
All numeric literals in the given scope are converted to Math::BigFloat objects.
All operators (including basic math operations) except the range operator `..` are overloaded.
So, the following:
```
use bigfloat;
$x = 1234;
```
creates a Math::BigFloat 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 -Mbigfloat -le 'print ref(1234)'
```
Since numbers are actually objects, you can call all the usual methods from Math::BigFloat on them. This even works to some extent on expressions:
```
perl -Mbigfloat -le '$x = 1234; print $x->bdec()'
perl -Mbigfloat -le 'print 1234->copy()->binc();'
perl -Mbigfloat -le 'print 1234->copy()->binc->badd(6);'
perl -Mbigfloat -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 -Mbigfloat -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 -Mbigfloat -le 'for (1..2) { print ref($_); }'
```
### Options
`bigfloat` recognizes some options that can be passed while loading it via 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 -Mbigfloat=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 -Mbigfloat=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 -Mbigfloat=l,GMP -e 'print 2 ** 512'
perl -Mbigfloat=lib,GMP -e 'print 2 ** 512'
perl -Mbigfloat=try,GMP -e 'print 2 ** 512'
perl -Mbigfloat=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 `bigfloat` 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 `bigfloat` pragma is active.
v or version this prints out the name and version of the modules and then exits.
```
perl -Mbigfloat=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 bigfloat lib => 'Calc';
```
you can change this by using:
```
use bigfloat 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 bigfloat 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 bigfloat try => 'GMP';
```
If you want the code to die instead of falling back, use `only` instead:
```
use bigfloat only => 'GMP';
```
Please see 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::BigFloat 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::BigFloat->binf(). Useful because Perl does not always handle bareword `inf` properly.
NaN() A shortcut to return Math::BigFloat->bnan(). Useful because Perl does not always handle bareword `NaN` properly.
e
```
# perl -Mbigfloat=e -wle 'print e'
```
Returns Euler's number `e`, aka exp(1)
PI
```
# perl -Mbigfloat=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 -Mbigfloat=bexp -wle 'print bexp(1,80)'
```
bpi()
```
bpi($accuracy);
```
Returns PI to the wanted accuracy.
Example:
```
# perl -Mbigfloat=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.
upgrade() Set or get the class that the downgrade class upgrades to, if any. Set the upgrade class to `undef` to disable upgrading.
Upgrading is disabled by default.
downgrade() Set or get the class that the upgrade class downgrades to, if any. Set the downgrade class to `undef` to disable upgrading.
Downgrading is disabled by default.
in\_effect()
```
use bigfloat;
print "in effect\n" if bigfloat::in_effect; # true
{
no bigfloat;
print "in effect\n" if bigfloat::in_effect; # false
}
```
Returns true or false if `bigfloat` 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 `bigfloat` never sees the string literals. To ensure the expression is all treated as `Math::BigFloat` 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 `bigfloat` endpoints, nor is the iterator variable a `Math::BigFloat`.
```
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() `bigfloat` 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 bigfloat`:
```
use bigfloat qw/hex oct/;
print hex("0x1234567890123456");
{
no bigfloat;
print hex("0x1234567890123456");
}
```
The second call to hex() will warn about a non-portable constant.
Compare this to:
```
use bigfloat;
# will warn only under Perl older than v5.9.4
print hex("0x1234567890123456");
```
EXAMPLES
--------
Some cool command line examples to impress the Python crowd ;)
```
perl -Mbigfloat -le 'print sqrt(33)'
perl -Mbigfloat -le 'print 2**255'
perl -Mbigfloat -le 'print 4.5+2**255'
perl -Mbigfloat -le 'print 3/7 + 5/7 + 8/3'
perl -Mbigfloat -le 'print 123->is_odd()'
perl -Mbigfloat -le 'print log(2)'
perl -Mbigfloat -le 'print exp(1)'
perl -Mbigfloat -le 'print 2 ** 0.5'
perl -Mbigfloat=a,65 -le 'print 2 ** 0.2'
perl -Mbigfloat=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 bigfloat
```
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
---------
<bigint> and <bigrat>.
<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-.
perl CPAN::Meta::Validator CPAN::Meta::Validator
=====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [is\_valid](#is_valid)
+ [errors](#errors)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Validator - validate CPAN distribution metadata structures
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
my $struct = decode_json_file('META.json');
my $cmv = CPAN::Meta::Validator->new( $struct );
unless ( $cmv->is_valid ) {
my $msg = "Invalid META structure. Errors found:\n";
$msg .= join( "\n", $cmv->errors );
die $msg;
}
```
DESCRIPTION
-----------
This module validates a CPAN Meta structure against the version of the the specification claimed in the `meta-spec` field of the structure.
METHODS
-------
### new
```
my $cmv = CPAN::Meta::Validator->new( $struct )
```
The constructor must be passed a metadata structure.
### is\_valid
```
if ( $cmv->is_valid ) {
...
}
```
Returns a boolean value indicating whether the metadata provided is valid.
### errors
```
warn( join "\n", $cmv->errors );
```
Returns a list of errors seen during validation.
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 perlfaq8 perlfaq8
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [How do I find out which operating system I'm running under?](#How-do-I-find-out-which-operating-system-I'm-running-under?)
+ [How come exec() doesn't return?](#How-come-exec()-doesn't-return?)
+ [How do I do fancy stuff with the keyboard/screen/mouse?](#How-do-I-do-fancy-stuff-with-the-keyboard/screen/mouse?)
+ [How do I print something out in color?](#How-do-I-print-something-out-in-color?)
+ [How do I read just one key without waiting for a return key?](#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-check-whether-input-is-ready-on-the-keyboard?)
+ [How do I clear the screen?](#How-do-I-clear-the-screen?)
+ [How do I get the screen size?](#How-do-I-get-the-screen-size?)
+ [How do I ask the user for a password?](#How-do-I-ask-the-user-for-a-password?)
+ [How do I read and write the serial port?](#How-do-I-read-and-write-the-serial-port?)
+ [How do I decode encrypted password files?](#How-do-I-decode-encrypted-password-files?)
+ [How do I start a process in the background?](#How-do-I-start-a-process-in-the-background?)
+ [How do I trap control characters/signals?](#How-do-I-trap-control-characters/signals?)
+ [How do I modify the shadow password file on a Unix system?](#How-do-I-modify-the-shadow-password-file-on-a-Unix-system?)
+ [How do I set the time and date?](#How-do-I-set-the-time-and-date?)
+ [How can I sleep() or alarm() for under a second?](#How-can-I-sleep()-or-alarm()-for-under-a-second?)
+ [How can I measure time under a second?](#How-can-I-measure-time-under-a-second?)
+ [How can I do an atexit() or setjmp()/longjmp()? (Exception handling)](#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?](#Why-doesn't-my-sockets-program-work-under-System-V-(Solaris)?-What-does-the-error-message-%22Protocol-not-supported%22-mean?)
+ [How can I call my system's unique C functions from Perl?](#How-can-I-call-my-system's-unique-C-functions-from-Perl?)
+ [Where do I get the include files to do ioctl() or syscall()?](#Where-do-I-get-the-include-files-to-do-ioctl()-or-syscall()?)
+ [Why do setuid perl scripts complain about kernel problems?](#Why-do-setuid-perl-scripts-complain-about-kernel-problems?)
+ [How can I open a pipe both to and from a command?](#How-can-I-open-a-pipe-both-to-and-from-a-command?)
+ [Why can't I get the output of a command with system()?](#Why-can't-I-get-the-output-of-a-command-with-system()?)
+ [How can I capture STDERR from an external command?](#How-can-I-capture-STDERR-from-an-external-command?)
+ [Why doesn't open() return an error when a pipe open fails?](#Why-doesn't-open()-return-an-error-when-a-pipe-open-fails?)
+ [What's wrong with using backticks in a void context?](#What's-wrong-with-using-backticks-in-a-void-context?)
+ [How can I call backticks without shell processing?](#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)?](#Why-can't-my-script-read-from-STDIN-after-I-gave-it-EOF-(%5ED-on-Unix,-%5EZ-on-MS-DOS)?)
+ [How can I convert my shell script to perl?](#How-can-I-convert-my-shell-script-to-perl?)
+ [Can I use perl to run a telnet or ftp session?](#Can-I-use-perl-to-run-a-telnet-or-ftp-session?)
+ [How can I write expect in Perl?](#How-can-I-write-expect-in-Perl?)
+ [Is there a way to hide perl's command line from programs such as "ps"?](#Is-there-a-way-to-hide-perl's-command-line-from-programs-such-as-%22ps%22?)
+ [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?](#I-%7Bchanged-directory,-modified-my-environment%7D-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-close-a-process's-filehandle-without-waiting-for-it-to-complete?)
+ [How do I fork a daemon process?](#How-do-I-fork-a-daemon-process?)
+ [How do I find out if I'm running interactively or not?](#How-do-I-find-out-if-I'm-running-interactively-or-not?)
+ [How do I timeout a slow event?](#How-do-I-timeout-a-slow-event?)
+ [How do I set CPU limits?](#How-do-I-set-CPU-limits?)
+ [How do I avoid zombies on a Unix system?](#How-do-I-avoid-zombies-on-a-Unix-system?)
+ [How do I use an SQL database?](#How-do-I-use-an-SQL-database?)
+ [How do I make a system() exit on control-C?](#How-do-I-make-a-system()-exit-on-control-C?)
+ [How do I open a file without blocking?](#How-do-I-open-a-file-without-blocking?)
+ [How do I tell the difference between errors from the shell and perl?](#How-do-I-tell-the-difference-between-errors-from-the-shell-and-perl?)
+ [How do I install a module from CPAN?](#How-do-I-install-a-module-from-CPAN?)
+ [What's the difference between require and use?](#What's-the-difference-between-require-and-use?)
+ [How do I keep my own module/library directory?](#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-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?](#How-do-I-add-a-directory-to-my-include-path-(@INC)-at-runtime?)
+ [Where are modules installed?](#Where-are-modules-installed?)
+ [What is socket.ph and where do I get it?](#What-is-socket.ph-and-where-do-I-get-it?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq8 - System Interaction
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
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.
Read the FAQs and documentation specific to the port of perl to your operating system (eg, <perlvms>, <perlplan9>, ...). These should contain more detailed information on the vagaries of your perl.
###
How do I find out which operating system I'm running under?
The `$^O` variable (`$OSNAME` if you use `English`) contains an indication of the name of the operating system (not its release number) that your perl binary was built for.
###
How come exec() doesn't return?
(contributed by brian d foy)
The `exec` function's job is to turn your process into another command and never to return. If that's not what you want to do, don't use `exec`. :)
If you want to run an external command and still keep your Perl process going, look at a piped `open`, `fork`, or `system`.
###
How do I do fancy stuff with the keyboard/screen/mouse?
How you access/control keyboards, screens, and pointing devices ("mice") is system-dependent. Try the following modules:
Keyboard
```
Term::Cap Standard perl distribution
Term::ReadKey CPAN
Term::ReadLine::Gnu CPAN
Term::ReadLine::Perl CPAN
Term::Screen CPAN
```
Screen
```
Term::Cap Standard perl distribution
Curses CPAN
Term::ANSIColor CPAN
```
Mouse
```
Tk CPAN
Wx CPAN
Gtk2 CPAN
Qt4 kdebindings4 package
```
Some of these specific cases are shown as examples in other answers in this section of the perlfaq.
###
How do I print something out in color?
In general, you don't, because you don't know whether the recipient has a color-aware display device. If you know that they have an ANSI terminal that understands color, you can use the <Term::ANSIColor> module from CPAN:
```
use Term::ANSIColor;
print color("red"), "Stop!\n", color("reset");
print color("green"), "Go!\n", color("reset");
```
Or like this:
```
use Term::ANSIColor qw(:constants);
print RED, "Stop!\n", RESET;
print GREEN, "Go!\n", RESET;
```
###
How do I read just one key without waiting for a return key?
Controlling input buffering is a remarkably system-dependent matter. On many systems, you can just use the **stty** command as shown in ["getc" in perlfunc](perlfunc#getc), but as you see, that's already getting you into portability snags.
```
open(TTY, "+</dev/tty") or die "no tty: $!";
system "stty cbreak </dev/tty >/dev/tty 2>&1";
$key = getc(TTY); # perhaps this works
# OR ELSE
sysread(TTY, $key, 1); # probably this does
system "stty -cbreak </dev/tty >/dev/tty 2>&1";
```
The <Term::ReadKey> module from CPAN offers an easy-to-use interface that should be more efficient than shelling out to **stty** for each key. It even includes limited support for Windows.
```
use Term::ReadKey;
ReadMode('cbreak');
$key = ReadKey(0);
ReadMode('normal');
```
However, using the code requires that you have a working C compiler and can use it to build and install a CPAN module. Here's a solution using the standard [POSIX](posix) module, which is already on your system (assuming your system supports POSIX).
```
use HotKey;
$key = readkey();
```
And here's the `HotKey` module, which hides the somewhat mystifying calls to manipulate the POSIX termios structures.
```
# HotKey.pm
package HotKey;
use strict;
use warnings;
use parent 'Exporter';
our @EXPORT = qw(cbreak cooked readkey);
use POSIX qw(:termios_h);
my ($term, $oterm, $echo, $noecho, $fd_stdin);
$fd_stdin = fileno(STDIN);
$term = POSIX::Termios->new();
$term->getattr($fd_stdin);
$oterm = $term->getlflag();
$echo = ECHO | ECHOK | ICANON;
$noecho = $oterm & ~$echo;
sub cbreak {
$term->setlflag($noecho); # ok, so i don't want echo either
$term->setcc(VTIME, 1);
$term->setattr($fd_stdin, TCSANOW);
}
sub cooked {
$term->setlflag($oterm);
$term->setcc(VTIME, 0);
$term->setattr($fd_stdin, TCSANOW);
}
sub readkey {
my $key = '';
cbreak();
sysread(STDIN, $key, 1);
cooked();
return $key;
}
END { cooked() }
1;
```
###
How do I check whether input is ready on the keyboard?
The easiest way to do this is to read a key in nonblocking mode with the <Term::ReadKey> module from CPAN, passing it an argument of -1 to indicate not to block:
```
use Term::ReadKey;
ReadMode('cbreak');
if (defined (my $char = ReadKey(-1)) ) {
# input was waiting and it was $char
} else {
# no input was waiting
}
ReadMode('normal'); # restore normal tty settings
```
###
How do I clear the screen?
(contributed by brian d foy)
To clear the screen, you just have to print the special sequence that tells the terminal to clear the screen. Once you have that sequence, output it when you want to clear the screen.
You can use the <Term::ANSIScreen> module to get the special sequence. Import the `cls` function (or the `:screen` tag):
```
use Term::ANSIScreen qw(cls);
my $clear_screen = cls();
print $clear_screen;
```
The <Term::Cap> module can also get the special sequence if you want to deal with the low-level details of terminal control. The `Tputs` method returns the string for the given capability:
```
use Term::Cap;
my $terminal = Term::Cap->Tgetent( { OSPEED => 9600 } );
my $clear_screen = $terminal->Tputs('cl');
print $clear_screen;
```
On Windows, you can use the <Win32::Console> module. After creating an object for the output filehandle you want to affect, call the `Cls` method:
```
Win32::Console;
my $OUT = Win32::Console->new(STD_OUTPUT_HANDLE);
my $clear_string = $OUT->Cls;
print $clear_screen;
```
If you have a command-line program that does the job, you can call it in backticks to capture whatever it outputs so you can use it later:
```
my $clear_string = `clear`;
print $clear_string;
```
###
How do I get the screen size?
If you have <Term::ReadKey> module installed from CPAN, you can use it to fetch the width and height in characters and in pixels:
```
use Term::ReadKey;
my ($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
```
This is more portable than the raw `ioctl`, but not as illustrative:
```
require './sys/ioctl.ph';
die "no TIOCGWINSZ " unless defined &TIOCGWINSZ;
open(my $tty_fh, "+</dev/tty") or die "No tty: $!";
unless (ioctl($tty_fh, &TIOCGWINSZ, $winsize='')) {
die sprintf "$0: ioctl TIOCGWINSZ (%08x: $!)\n", &TIOCGWINSZ;
}
my ($row, $col, $xpixel, $ypixel) = unpack('S4', $winsize);
print "(row,col) = ($row,$col)";
print " (xpixel,ypixel) = ($xpixel,$ypixel)" if $xpixel || $ypixel;
print "\n";
```
###
How do I ask the user for a password?
(This question has nothing to do with the web. See a different FAQ for that.)
There's an example of this in ["crypt" in perlfunc](perlfunc#crypt). First, you put the terminal into "no echo" mode, then just read the password normally. You may do this with an old-style `ioctl()` function, POSIX terminal control (see [POSIX](posix) or its documentation the Camel Book), or a call to the **stty** program, with varying degrees of portability.
You can also do this for most systems using the <Term::ReadKey> module from CPAN, which is easier to use and in theory more portable.
```
use Term::ReadKey;
ReadMode('noecho');
my $password = ReadLine(0);
```
###
How do I read and write the serial port?
This depends on which operating system your program is running on. In the case of Unix, the serial ports will be accessible through files in `/dev`; on other systems, device names will doubtless differ. Several problem areas common to all device interaction are the following:
lockfiles Your system may use lockfiles to control multiple access. Make sure you follow the correct protocol. Unpredictable behavior can result from multiple processes reading from one device.
open mode If you expect to use both read and write operations on the device, you'll have to open it for update (see ["open" in perlfunc](perlfunc#open) for details). You may wish to open it without running the risk of blocking by using `sysopen()` and `O_RDWR|O_NDELAY|O_NOCTTY` from the [Fcntl](fcntl) module (part of the standard perl distribution). See ["sysopen" in perlfunc](perlfunc#sysopen) for more on this approach.
end of line Some devices will be expecting a "\r" at the end of each line rather than a "\n". In some ports of perl, "\r" and "\n" are different from their usual (Unix) ASCII values of "\015" and "\012". You may have to give the numeric values you want directly, using octal ("\015"), hex ("0x0D"), or as a control-character specification ("\cM").
```
print DEV "atv1\012"; # wrong, for some devices
print DEV "atv1\015"; # right, for some devices
```
Even though with normal text files a "\n" will do the trick, there is still no unified scheme for terminating a line that is portable between Unix, DOS/Win, and Macintosh, except to terminate *ALL* line ends with "\015\012", and strip what you don't need from the output. This applies especially to socket I/O and autoflushing, discussed next.
flushing output If you expect characters to get to your device when you `print()` them, you'll want to autoflush that filehandle. You can use `select()` and the `$|` variable to control autoflushing (see ["$|" in perlvar](perlvar#%24%7C) and ["select" in perlfunc](perlfunc#select), or <perlfaq5>, "How do I flush/unbuffer an output filehandle? Why must I do this?"):
```
my $old_handle = select($dev_fh);
$| = 1;
select($old_handle);
```
You'll also see code that does this without a temporary variable, as in
```
select((select($deb_handle), $| = 1)[0]);
```
Or if you don't mind pulling in a few thousand lines of code just because you're afraid of a little `$|` variable:
```
use IO::Handle;
$dev_fh->autoflush(1);
```
As mentioned in the previous item, this still doesn't work when using socket I/O between Unix and Macintosh. You'll need to hard code your line terminators, in that case.
non-blocking input If you are doing a blocking `read()` or `sysread()`, you'll have to arrange for an alarm handler to provide a timeout (see ["alarm" in perlfunc](perlfunc#alarm)). If you have a non-blocking open, you'll likely have a non-blocking read, which means you may have to use a 4-arg `select()` to determine whether I/O is ready on that device (see ["select" in perlfunc](perlfunc#select).
While trying to read from his caller-id box, the notorious Jamie Zawinski `<[email protected]>`, after much gnashing of teeth and fighting with `sysread`, `sysopen`, POSIX's `tcgetattr` business, and various other functions that go bump in the night, finally came up with this:
```
sub open_modem {
use IPC::Open2;
my $stty = `/bin/stty -g`;
open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
# starting cu hoses /dev/tty's stty settings, even when it has
# been opened on a pipe...
system("/bin/stty $stty");
$_ = <MODEM_IN>;
chomp;
if ( !m/^Connected/ ) {
print STDERR "$0: cu printed `$_' instead of `Connected'\n";
}
}
```
###
How do I decode encrypted password files?
You spend lots and lots of money on dedicated hardware, but this is bound to get you talked about.
Seriously, you can't if they are Unix password files--the Unix password system employs one-way encryption. It's more like hashing than encryption. The best you can do is check whether something else hashes to the same string. You can't turn a hash back into the original string. Programs like Crack can forcibly (and intelligently) try to guess passwords, but don't (can't) guarantee quick success.
If you're worried about users selecting bad passwords, you should proactively check when they try to change their password (by modifying [passwd(1)](http://man.he.net/man1/passwd), for example).
###
How do I start a process in the background?
(contributed by brian d foy)
There's not a single way to run code in the background so you don't have to wait for it to finish before your program moves on to other tasks. Process management depends on your particular operating system, and many of the techniques are covered in <perlipc>.
Several CPAN modules may be able to help, including <IPC::Open2> or <IPC::Open3>, <IPC::Run>, <Parallel::Jobs>, <Parallel::ForkManager>, [POE](poe), <Proc::Background>, and <Win32::Process>. There are many other modules you might use, so check those namespaces for other options too.
If you are on a Unix-like system, you might be able to get away with a system call where you put an `&` on the end of the command:
```
system("cmd &")
```
You can also try using `fork`, as described in <perlfunc> (although this is the same thing that many of the modules will do for you).
STDIN, STDOUT, and STDERR are shared Both the main process and the backgrounded one (the "child" process) share the same STDIN, STDOUT and STDERR filehandles. If both try to access them at once, strange things can happen. You may want to close or reopen these for the child. You can get around this with `open`ing a pipe (see ["open" in perlfunc](perlfunc#open)) but on some systems this means that the child process cannot outlive the parent.
Signals You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too. SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is sent when you write to a filehandle whose child process has closed (an untrapped SIGPIPE can cause your program to silently die). This is not an issue with `system("cmd&")`.
Zombies You have to be prepared to "reap" the child process when it finishes.
```
$SIG{CHLD} = sub { wait };
$SIG{CHLD} = 'IGNORE';
```
You can also use a double fork. You immediately `wait()` for your first child, and the init daemon will `wait()` for your grandchild once it exits.
```
unless ($pid = fork) {
unless (fork) {
exec "what you really wanna do";
die "exec failed!";
}
exit 0;
}
waitpid($pid, 0);
```
See ["Signals" in perlipc](perlipc#Signals) for other examples of code to do this. Zombies are not an issue with `system("prog &")`.
###
How do I trap control characters/signals?
You don't actually "trap" a control character. Instead, that character generates a signal which is sent to your terminal's currently foregrounded process group, which you then trap in your process. Signals are documented in ["Signals" in perlipc](perlipc#Signals) and the section on "Signals" in the Camel.
You can set the values of the `%SIG` hash to be the functions you want to handle the signal. After perl catches the signal, it looks in `%SIG` for a key with the same name as the signal, then calls the subroutine value for that key.
```
# as an anonymous subroutine
$SIG{INT} = sub { syswrite(STDERR, "ouch\n", 5 ) };
# or a reference to a function
$SIG{INT} = \&ouch;
# or the name of the function as a string
$SIG{INT} = "ouch";
```
Perl versions before 5.8 had in its C source code signal handlers which would catch the signal and possibly run a Perl function that you had set in `%SIG`. This violated the rules of signal handling at that level causing perl to dump core. Since version 5.8.0, perl looks at `%SIG` **after** the signal has been caught, rather than while it is being caught. Previous versions of this answer were incorrect.
###
How do I modify the shadow password file on a Unix system?
If perl was installed correctly and your shadow library was written properly, the `getpw*()` functions described in <perlfunc> should in theory provide (read-only) access to entries in the shadow password file. To change the file, make a new shadow password file (the format varies from system to system--see [passwd(1)](http://man.he.net/man1/passwd) for specifics) and use `pwd_mkdb(8)` to install it (see [pwd\_mkdb(8)](http://man.he.net/man8/pwd_mkdb) for more details).
###
How do I set the time and date?
Assuming you're running under sufficient permissions, you should be able to set the system-wide date and time by running the `date(1)` program. (There is no way to set the time and date on a per-process basis.) This mechanism will work for Unix, MS-DOS, Windows, and NT; the VMS equivalent is `set time`.
However, if all you want to do is change your time zone, you can probably get away with setting an environment variable:
```
$ENV{TZ} = "MST7MDT"; # Unixish
$ENV{'SYS$TIMEZONE_DIFFERENTIAL'}="-5" # vms
system('trn', 'comp.lang.perl.misc');
```
###
How can I sleep() or alarm() for under a second?
If you want finer granularity than the 1 second that the `sleep()` function provides, the easiest way is to use the `select()` function as documented in ["select" in perlfunc](perlfunc#select). Try the <Time::HiRes> and the <BSD::Itimer> modules (available from CPAN, and starting from Perl 5.8 <Time::HiRes> is part of the standard distribution).
###
How can I measure time under a second?
(contributed by brian d foy)
The <Time::HiRes> module (part of the standard distribution as of Perl 5.8) measures time with the `gettimeofday()` system call, which returns the time in microseconds since the epoch. If you can't install <Time::HiRes> for older Perls and you are on a Unixish system, you may be able to call `gettimeofday(2)` directly. See ["syscall" in perlfunc](perlfunc#syscall).
###
How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
You can use the `END` block to simulate `atexit()`. Each package's `END` block is called when the program or thread ends. See the <perlmod> manpage for more details about `END` blocks.
For example, you can use this to make sure your filter program managed to finish its output without filling up the disk:
```
END {
close(STDOUT) || die "stdout close failed: $!";
}
```
The `END` block isn't called when untrapped signals kill the program, though, so if you use `END` blocks you should also use
```
use sigtrap qw(die normal-signals);
```
Perl's exception-handling mechanism is its `eval()` operator. You can use `eval()` as `setjmp` and `die()` as `longjmp`. For details of this, see the section on signals, especially the time-out handler for a blocking `flock()` in ["Signals" in perlipc](perlipc#Signals) or the section on "Signals" in *Programming Perl*.
If exception handling is all you're interested in, use one of the many CPAN modules that handle exceptions, such as <Try::Tiny>.
If you want the `atexit()` syntax (and an `rmexit()` as well), try the `AtExit` module available from CPAN.
###
Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
Some Sys-V based systems, notably Solaris 2.X, redefined some of the standard socket constants. Since these were constant across all architectures, they were often hardwired into perl code. The proper way to deal with this is to "use Socket" to get the correct values.
Note that even though SunOS and Solaris are binary compatible, these values are different. Go figure.
###
How can I call my system's unique C functions from Perl?
In most cases, you write an external module to do it--see the answer to "Where can I learn about linking C with Perl? [h2xs, xsubpp]". However, if the function is a system call, and your system supports `syscall()`, you can use the `syscall` function (documented in <perlfunc>).
Remember to check the modules that came with your distribution, and CPAN as well--someone may already have written a module to do it. On Windows, try <Win32::API>. On Macs, try <Mac::Carbon>. If no module has an interface to the C function, you can inline a bit of C in your Perl source with <Inline::C>.
###
Where do I get the include files to do ioctl() or syscall()?
Historically, these would be generated by the <h2ph> tool, part of the standard perl distribution. This program converts `cpp(1)` directives in C header files to files containing subroutine definitions, like `SYS_getitimer()`, which you can use as arguments to your functions. It doesn't work perfectly, but it usually gets most of the job done. Simple files like *errno.h*, *syscall.h*, and *socket.h* were fine, but the hard ones like *ioctl.h* nearly always need to be hand-edited. Here's how to install the \*.ph files:
```
1. Become the super-user
2. cd /usr/include
3. h2ph *.h */*.h
```
If your system supports dynamic loading, for reasons of portability and sanity you probably ought to use <h2xs> (also part of the standard perl distribution). This tool converts C header files to Perl extensions. See <perlxstut> for how to get started with <h2xs>.
If your system doesn't support dynamic loading, you still probably ought to use <h2xs>. See <perlxstut> and <ExtUtils::MakeMaker> for more information (in brief, just use **make perl** instead of a plain **make** to rebuild perl with a new static extension).
###
Why do setuid perl scripts complain about kernel problems?
Some operating systems have bugs in the kernel that make setuid scripts inherently insecure. Perl gives you a number of options (described in <perlsec>) to work around such systems.
###
How can I open a pipe both to and from a command?
The <IPC::Open2> module (part of the standard perl distribution) is an easy-to-use approach that internally uses `pipe()`, `fork()`, and `exec()` to do the job. Make sure you read the deadlock warnings in its documentation, though (see <IPC::Open2>). See ["Bidirectional Communication with Another Process" in perlipc](perlipc#Bidirectional-Communication-with-Another-Process) and ["Bidirectional Communication with Yourself" in perlipc](perlipc#Bidirectional-Communication-with-Yourself)
You may also use the <IPC::Open3> module (part of the standard perl distribution), but be warned that it has a different order of arguments from <IPC::Open2> (see <IPC::Open3>).
###
Why can't I get the output of a command with system()?
You're confusing the purpose of `system()` and backticks (``). `system()` runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.
```
my $exit_status = system("mail-users");
my $output_string = `ls`;
```
###
How can I capture STDERR from an external command?
There are three basic ways of running external commands:
```
system $cmd; # using system()
my $output = `$cmd`; # using backticks (``)
open (my $pipe_fh, "$cmd |"); # using open()
```
With `system()`, both STDOUT and STDERR will go the same place as the script's STDOUT and STDERR, unless the `system()` command redirects them. Backticks and `open()` read **only** the STDOUT of your command.
You can also use the `open3()` function from <IPC::Open3>. Benjamin Goldberg provides some sample code:
To capture a program's STDOUT, but discard its STDERR:
```
use IPC::Open3;
use File::Spec;
my $in = '';
open(NULL, ">", File::Spec->devnull);
my $pid = open3($in, \*PH, ">&NULL", "cmd");
while( <PH> ) { }
waitpid($pid, 0);
```
To capture a program's STDERR, but discard its STDOUT:
```
use IPC::Open3;
use File::Spec;
my $in = '';
open(NULL, ">", File::Spec->devnull);
my $pid = open3($in, ">&NULL", \*PH, "cmd");
while( <PH> ) { }
waitpid($pid, 0);
```
To capture a program's STDERR, and let its STDOUT go to our own STDERR:
```
use IPC::Open3;
my $in = '';
my $pid = open3($in, ">&STDERR", \*PH, "cmd");
while( <PH> ) { }
waitpid($pid, 0);
```
To read both a command's STDOUT and its STDERR separately, you can redirect them to temp files, let the command run, then read the temp files:
```
use IPC::Open3;
use IO::File;
my $in = '';
local *CATCHOUT = IO::File->new_tmpfile;
local *CATCHERR = IO::File->new_tmpfile;
my $pid = open3($in, ">&CATCHOUT", ">&CATCHERR", "cmd");
waitpid($pid, 0);
seek $_, 0, 0 for \*CATCHOUT, \*CATCHERR;
while( <CATCHOUT> ) {}
while( <CATCHERR> ) {}
```
But there's no real need for **both** to be tempfiles... the following should work just as well, without deadlocking:
```
use IPC::Open3;
my $in = '';
use IO::File;
local *CATCHERR = IO::File->new_tmpfile;
my $pid = open3($in, \*CATCHOUT, ">&CATCHERR", "cmd");
while( <CATCHOUT> ) {}
waitpid($pid, 0);
seek CATCHERR, 0, 0;
while( <CATCHERR> ) {}
```
And it'll be faster, too, since we can begin processing the program's stdout immediately, rather than waiting for the program to finish.
With any of these, you can change file descriptors before the call:
```
open(STDOUT, ">logfile");
system("ls");
```
or you can use Bourne shell file-descriptor redirection:
```
$output = `$cmd 2>some_file`;
open (PIPE, "cmd 2>some_file |");
```
You can also use file-descriptor redirection to make STDERR a duplicate of STDOUT:
```
$output = `$cmd 2>&1`;
open (PIPE, "cmd 2>&1 |");
```
Note that you *cannot* simply open STDERR to be a dup of STDOUT in your Perl program and avoid calling the shell to do the redirection. This doesn't work:
```
open(STDERR, ">&STDOUT");
$alloutput = `cmd args`; # stderr still escapes
```
This fails because the `open()` makes STDERR go to where STDOUT was going at the time of the `open()`. The backticks then make STDOUT go to a string, but don't change STDERR (which still goes to the old STDOUT).
Note that you *must* use Bourne shell (`sh(1)`) redirection syntax in backticks, not `csh(1)`! Details on why Perl's `system()` and backtick and pipe opens all use the Bourne shell are in the *versus/csh.whynot* article in the "Far More Than You Ever Wanted To Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> . To capture a command's STDERR and STDOUT together:
```
$output = `cmd 2>&1`; # either with backticks
$pid = open(PH, "cmd 2>&1 |"); # or with an open pipe
while (<PH>) { } # plus a read
```
To capture a command's STDOUT but discard its STDERR:
```
$output = `cmd 2>/dev/null`; # either with backticks
$pid = open(PH, "cmd 2>/dev/null |"); # or with an open pipe
while (<PH>) { } # plus a read
```
To capture a command's STDERR but discard its STDOUT:
```
$output = `cmd 2>&1 1>/dev/null`; # either with backticks
$pid = open(PH, "cmd 2>&1 1>/dev/null |"); # or with an open pipe
while (<PH>) { } # plus a read
```
To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out our old STDERR:
```
$output = `cmd 3>&1 1>&2 2>&3 3>&-`; # either with backticks
$pid = open(PH, "cmd 3>&1 1>&2 2>&3 3>&-|");# or with an open pipe
while (<PH>) { } # plus a read
```
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");
```
Ordering is important in all these examples. That's because the shell processes file descriptor redirections in strictly left to right order.
```
system("prog args 1>tmpfile 2>&1");
system("prog args 2>&1 1>tmpfile");
```
The first command sends both standard out and standard error to the temporary file. The second command sends only the old standard output there, and the old standard error shows up on the old standard out.
###
Why doesn't open() return an error when a pipe open fails?
If the second argument to a piped `open()` contains shell metacharacters, perl `fork()`s, then `exec()`s a shell to decode the metacharacters and eventually run the desired program. If the program couldn't be run, it's the shell that gets the message, not Perl. All your Perl program can find out is whether the shell itself could be successfully started. You can still capture the shell's STDERR and check it for error messages. See ["How can I capture STDERR from an external command?"](#How-can-I-capture-STDERR-from-an-external-command%3F) elsewhere in this document, or use the <IPC::Open3> module.
If there are no shell metacharacters in the argument of `open()`, Perl runs the command directly, without using the shell, and can correctly report whether the command started.
###
What's wrong with using backticks in a void context?
Strictly speaking, nothing. Stylistically speaking, it's not a good way to write maintainable code. Perl has several operators for running external commands. Backticks are one; they collect the output from the command for use in your program. The `system` function is another; it doesn't do this.
Writing backticks in your program sends a clear message to the readers of your code that you wanted to collect the output of the command. Why send a clear message that isn't true?
Consider this line:
```
`cat /etc/termcap`;
```
You forgot to check `$?` to see whether the program even ran correctly. Even if you wrote
```
print `cat /etc/termcap`;
```
this code could and probably should be written as
```
system("cat /etc/termcap") == 0
or die "cat program failed!";
```
which will echo the cat command's output as it is generated, instead of waiting until the program has completed to print it out. It also checks the return value.
`system` also provides direct control over whether shell wildcard processing may take place, whereas backticks do not.
###
How can I call backticks without shell processing?
This is a bit tricky. You can't simply write the command like this:
```
@ok = `grep @opts '$search_string' @filenames`;
```
As of Perl 5.8.0, you can use `open()` with multiple arguments. Just like the list forms of `system()` and `exec()`, no shell escapes happen.
```
open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
chomp(@ok = <GREP>);
close GREP;
```
You can also:
```
my @ok = ();
if (open(GREP, "-|")) {
while (<GREP>) {
chomp;
push(@ok, $_);
}
close GREP;
} else {
exec 'grep', @opts, $search_string, @filenames;
}
```
Just as with `system()`, no shell escapes happen when you `exec()` a list. Further examples of this can be found in ["Safe Pipe Opens" in perlipc](perlipc#Safe-Pipe-Opens).
Note that if you're using Windows, no solution to this vexing issue is even possible. Even though Perl emulates `fork()`, you'll still be stuck, because Windows does not have an argc/argv-style API.
###
Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
This happens only if your perl is compiled to use stdio instead of perlio, which is the default. Some (maybe all?) stdios set error and eof flags that you may need to clear. The [POSIX](posix) module defines `clearerr()` that you can use. That is the technically correct way to do it. Here are some less reliable workarounds:
1. Try keeping around the seekpointer and go there, like this:
```
my $where = tell($log_fh);
seek($log_fh, $where, 0);
```
2. If that doesn't work, try seeking to a different part of the file and then back.
3. If that doesn't work, try seeking to a different part of the file, reading something, and then seeking back.
4. If that doesn't work, give up on your stdio package and use sysread.
###
How can I convert my shell script to perl?
Learn Perl and rewrite it. Seriously, there's no simple converter. Things that are awkward to do in the shell are easy to do in Perl, and this very awkwardness is what would make a shell->perl converter nigh-on impossible to write. By rewriting it, you'll think about what you're really trying to do, and hopefully will escape the shell's pipeline datastream paradigm, which while convenient for some matters, causes many inefficiencies.
###
Can I use perl to run a telnet or ftp session?
Try the <Net::FTP>, <TCP::Client>, and <Net::Telnet> modules (available from CPAN). <http://www.cpan.org/scripts/netstuff/telnet.emul.shar> will also help for emulating the telnet protocol, but <Net::Telnet> is quite probably easier to use.
If all you want to do is pretend to be telnet but don't need the initial telnet handshaking, then the standard dual-process approach will suffice:
```
use IO::Socket; # new in 5.004
my $handle = IO::Socket::INET->new('www.perl.com:80')
or die "can't connect to port 80 on www.perl.com $!";
$handle->autoflush(1);
if (fork()) { # XXX: undef means failure
select($handle);
print while <STDIN>; # everything from stdin to socket
} else {
print while <$handle>; # everything from socket to stdout
}
close $handle;
exit;
```
###
How can I write expect in Perl?
Once upon a time, there was a library called *chat2.pl* (part of the standard perl distribution), which never really got finished. If you find it somewhere, *don't use it*. These days, your best bet is to look at the [Expect](expect) module available from CPAN, which also requires two other modules from CPAN, <IO::Pty> and <IO::Stty>.
###
Is there a way to hide perl's command line from programs such as "ps"?
First of all note that if you're doing this for security reasons (to avoid people seeing passwords, for example) then you should rewrite your program so that critical information is never given as an argument. Hiding the arguments won't make your program completely secure.
To actually alter the visible command line, you can assign to the variable $0 as documented in <perlvar>. This won't work on all operating systems, though. Daemon programs like sendmail place their state there, as in:
```
$0 = "orcus [accepting connections]";
```
###
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?
Unix In the strictest sense, it can't be done--the script executes as a different process from the shell it was started from. Changes to a process are not reflected in its parent--only in any children created after the change. There is shell magic that may allow you to fake it by `eval()`ing the script's output in your shell; check out the comp.unix.questions FAQ for details.
###
How do I close a process's filehandle without waiting for it to complete?
Assuming your system supports such things, just send an appropriate signal to the process (see ["kill" in perlfunc](perlfunc#kill)). It's common to first send a TERM signal, wait a little bit, and then send a KILL signal to finish it off.
###
How do I fork a daemon process?
If by daemon process you mean one that's detached (disassociated from its tty), then the following process is reported to work on most Unixish systems. Non-Unix users should check their Your\_OS::Process module for other solutions.
* Open /dev/tty and use the TIOCNOTTY ioctl on it. See [tty(1)](http://man.he.net/man1/tty) for details. Or better yet, you can just use the `POSIX::setsid()` function, so you don't have to worry about process groups.
* Change directory to /
* Reopen STDIN, STDOUT, and STDERR so they're not connected to the old tty.
* Background yourself like this:
```
fork && exit;
```
The <Proc::Daemon> module, available from CPAN, provides a function to perform these actions for you.
###
How do I find out if I'm running interactively or not?
(contributed by brian d foy)
This is a difficult question to answer, and the best answer is only a guess.
What do you really want to know? If you merely want to know if one of your filehandles is connected to a terminal, you can try the `-t` file test:
```
if( -t STDOUT ) {
print "I'm connected to a terminal!\n";
}
```
However, you might be out of luck if you expect that means there is a real person on the other side. With the [Expect](expect) module, another program can pretend to be a person. The program might even come close to passing the Turing test.
The <IO::Interactive> module does the best it can to give you an answer. Its `is_interactive` function returns an output filehandle; that filehandle points to standard output if the module thinks the session is interactive. Otherwise, the filehandle is a null handle that simply discards the output:
```
use IO::Interactive;
print { is_interactive } "I might go to standard output!\n";
```
This still doesn't guarantee that a real person is answering your prompts or reading your output.
If you want to know how to handle automated testing for your distribution, you can check the environment. The CPAN Testers, for instance, set the value of `AUTOMATED_TESTING`:
```
unless( $ENV{AUTOMATED_TESTING} ) {
print "Hello interactive tester!\n";
}
```
###
How do I timeout a slow event?
Use the `alarm()` function, probably in conjunction with a signal handler, as documented in ["Signals" in perlipc](perlipc#Signals) and the section on "Signals" in the Camel. You may instead use the more flexible <Sys::AlarmCall> module available from CPAN.
The `alarm()` function is not implemented on all versions of Windows. Check the documentation for your specific version of Perl.
###
How do I set CPU limits?
(contributed by Xho)
Use the <BSD::Resource> module from CPAN. As an example:
```
use BSD::Resource;
setrlimit(RLIMIT_CPU,10,20) or die $!;
```
This sets the soft and hard limits to 10 and 20 seconds, respectively. After 10 seconds of time spent running on the CPU (not "wall" time), the process will be sent a signal (XCPU on some systems) which, if not trapped, will cause the process to terminate. If that signal is trapped, then after 10 more seconds (20 seconds in total) the process will be killed with a non-trappable signal.
See the <BSD::Resource> and your systems documentation for the gory details.
###
How do I avoid zombies on a Unix system?
Use the reaper code from ["Signals" in perlipc](perlipc#Signals) to call `wait()` when a SIGCHLD is received, or else use the double-fork technique described in ["How do I start a process in the background?" in perlfaq8](perlfaq8#How-do-I-start-a-process-in-the-background%3F).
###
How do I use an SQL database?
The [DBI](dbi) module provides an abstract interface to most database servers and types, including Oracle, DB2, Sybase, mysql, Postgresql, ODBC, and flat files. The DBI module accesses each database type through a database driver, or DBD. You can see a complete list of available drivers on CPAN: <http://www.cpan.org/modules/by-module/DBD/> . You can read more about DBI on <http://dbi.perl.org/> .
Other modules provide more specific access: <Win32::ODBC>, [Alzabo](alzabo), `iodbc`, and others found on CPAN Search: <https://metacpan.org/> .
###
How do I make a system() exit on control-C?
You can't. You need to imitate the `system()` call (see <perlipc> for sample code) and then have a signal handler for the INT signal that passes the signal on to the subprocess. Or you can check for it:
```
$rc = system($cmd);
if ($rc & 127) { die "signal death" }
```
###
How do I open a file without blocking?
If you're lucky enough to be using a system that supports non-blocking reads (most Unixish systems do), you need only to use the `O_NDELAY` or `O_NONBLOCK` flag from the `Fcntl` module in conjunction with `sysopen()`:
```
use Fcntl;
sysopen(my $fh, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT, 0644)
or die "can't open /foo/somefile: $!":
```
###
How do I tell the difference between errors from the shell and perl?
(answer contributed by brian d foy)
When you run a Perl script, something else is running the script for you, and that something else may output error messages. The script might emit its own warnings and error messages. Most of the time you cannot tell who said what.
You probably cannot fix the thing that runs perl, but you can change how perl outputs its warnings by defining a custom warning and die functions.
Consider this script, which has an error you may not notice immediately.
```
#!/usr/locl/bin/perl
print "Hello World\n";
```
I get an error when I run this from my shell (which happens to be bash). That may look like perl forgot it has a `print()` function, but my shebang line is not the path to perl, so the shell runs the script, and I get the error.
```
$ ./test
./test: line 3: print: command not found
```
A quick and dirty fix involves a little bit of code, but this may be all you need to figure out the problem.
```
#!/usr/bin/perl -w
BEGIN {
$SIG{__WARN__} = sub{ print STDERR "Perl: ", @_; };
$SIG{__DIE__} = sub{ print STDERR "Perl: ", @_; exit 1};
}
$a = 1 + undef;
$x / 0;
__END__
```
The perl message comes out with "Perl" in front. The `BEGIN` block works at compile time so all of the compilation errors and warnings get the "Perl:" prefix too.
```
Perl: Useless use of division (/) in void context at ./test line 9.
Perl: Name "main::a" used only once: possible typo at ./test line 8.
Perl: Name "main::x" used only once: possible typo at ./test line 9.
Perl: Use of uninitialized value in addition (+) at ./test line 8.
Perl: Use of uninitialized value in division (/) at ./test line 9.
Perl: Illegal division by zero at ./test line 9.
Perl: Illegal division by zero at -e line 3.
```
If I don't see that "Perl:", it's not from perl.
You could also just know all the perl errors, and although there are some people who may know all of them, you probably don't. However, they all should be in the <perldiag> manpage. If you don't find the error in there, it probably isn't a perl error.
Looking up every message is not the easiest way, so let perl to do it for you. Use the diagnostics pragma with turns perl's normal messages into longer discussions on the topic.
```
use diagnostics;
```
If you don't get a paragraph or two of expanded discussion, it might not be perl's message.
###
How do I install a module from CPAN?
(contributed by brian d foy)
The easiest way is to have a module also named CPAN do it for you by using the `cpan` command that comes with Perl. You can give it a list of modules to install:
```
$ cpan IO::Interactive Getopt::Whatever
```
If you prefer `CPANPLUS`, it's just as easy:
```
$ cpanp i IO::Interactive Getopt::Whatever
```
If you want to install a distribution from the current directory, you can tell `CPAN.pm` to install `.` (the full stop):
```
$ cpan .
```
See the documentation for either of those commands to see what else you can do.
If you want to try to install a distribution by yourself, resolving all dependencies on your own, you follow one of two possible build paths.
For distributions that use *Makefile.PL*:
```
$ perl Makefile.PL
$ make test install
```
For distributions that use *Build.PL*:
```
$ perl Build.PL
$ ./Build test
$ ./Build install
```
Some distributions may need to link to libraries or other third-party code and their build and installation sequences may be more complicated. Check any *README* or *INSTALL* files that you may find.
###
What's the difference between require and use?
(contributed by brian d foy)
Perl runs `require` statement at run-time. Once Perl loads, compiles, and runs the file, it doesn't do anything else. The `use` statement is the same as a `require` run at compile-time, but Perl also calls the `import` method for the loaded package. These two are the same:
```
use MODULE qw(import list);
BEGIN {
require MODULE;
MODULE->import(import list);
}
```
However, you can suppress the `import` by using an explicit, empty import list. Both of these still happen at compile-time:
```
use MODULE ();
BEGIN {
require MODULE;
}
```
Since `use` will also call the `import` method, the actual value for `MODULE` must be a bareword. That is, `use` cannot load files by name, although `require` can:
```
require "$ENV{HOME}/lib/Foo.pm"; # no @INC searching!
```
See the entry for `use` in <perlfunc> for more details.
###
How do I keep my own module/library directory?
When you build modules, tell Perl where to install the modules.
If you want to install modules for your own use, the easiest way might be <local::lib>, which you can download from CPAN. It sets various installation settings for you, and uses those same settings within your programs.
If you want more flexibility, you need to configure your CPAN client for your particular situation.
For `Makefile.PL`-based distributions, use the INSTALL\_BASE option when generating Makefiles:
```
perl Makefile.PL INSTALL_BASE=/mydir/perl
```
You can set this in your `CPAN.pm` configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:
```
% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
```
For `Build.PL`-based distributions, use the --install\_base option:
```
perl Build.PL --install_base /mydir/perl
```
You can configure `CPAN.pm` to automatically use this option too:
```
% cpan
cpan> o conf mbuild_arg "--install_base /mydir/perl"
cpan> o conf commit
```
INSTALL\_BASE tells these tools to put your modules into */mydir/perl/lib/perl5*. See ["How do I add a directory to my include path (@INC) at runtime?"](#How-do-I-add-a-directory-to-my-include-path-%28%40INC%29-at-runtime%3F) for details on how to run your newly installed modules.
There is one caveat with INSTALL\_BASE, though, since it acts differently from the PREFIX and LIB settings that older versions of <ExtUtils::MakeMaker> advocated. INSTALL\_BASE does not support installing modules for multiple versions of Perl or different architectures under the same directory. You should consider whether you really want that and, if you do, use the older PREFIX and LIB settings. See the <ExtUtils::Makemaker> documentation for more details.
###
How do I add the directory my program lives in to the module/library search path?
(contributed by brian d foy)
If you know the directory already, you can add it to `@INC` as you would for any other directory. You might `use lib` if you know the directory at compile time:
```
use lib $directory;
```
The trick in this task is to find the directory. Before your script does anything else (such as a `chdir`), you can get the current working directory with the `Cwd` module, which comes with Perl:
```
BEGIN {
use Cwd;
our $directory = cwd;
}
use lib $directory;
```
You can do a similar thing with the value of `$0`, which holds the script name. That might hold a relative path, but `rel2abs` can turn it into an absolute path. Once you have the
```
BEGIN {
use File::Spec::Functions qw(rel2abs);
use File::Basename qw(dirname);
my $path = rel2abs( $0 );
our $directory = dirname( $path );
}
use lib $directory;
```
The [FindBin](findbin) module, which comes with Perl, might work. It finds the directory of the currently running script and puts it in `$Bin`, which you can then use to construct the right library path:
```
use FindBin qw($Bin);
```
You can also use <local::lib> to do much of the same thing. Install modules using <local::lib>'s settings then use the module in your program:
```
use local::lib; # sets up a local lib at ~/perl5
```
See the <local::lib> documentation for more details.
###
How do I add a directory to my include path (@INC) at runtime?
Here are the suggested ways of modifying your include path, including environment variables, run-time switches, and in-code statements:
the `PERLLIB` environment variable
```
$ export PERLLIB=/path/to/my/dir
$ perl program.pl
```
the `PERL5LIB` environment variable
```
$ export PERL5LIB=/path/to/my/dir
$ perl program.pl
```
the `perl -Idir` command line flag
```
$ perl -I/path/to/my/dir program.pl
```
the `lib` pragma:
```
use lib "$ENV{HOME}/myown_perllib";
```
the <local::lib> module:
```
use local::lib;
use local::lib "~/myown_perllib";
```
###
Where are modules installed?
Modules are installed on a case-by-case basis (as provided by the methods described in the previous section), and in the operating system. All of these paths are stored in @INC, which you can display with the one-liner
```
perl -e 'print join("\n",@INC,"")'
```
The same information is displayed at the end of the output from the command
```
perl -V
```
To find out where a module's source code is located, use
```
perldoc -l Encode
```
to display the path to the module. In some cases (for example, the `AutoLoader` module), this command will show the path to a separate `pod` file; the module itself should be in the same directory, with a 'pm' file extension.
###
What is socket.ph and where do I get it?
It's a Perl 4 style file defining values for system networking constants. Sometimes it is built using <h2ph> when Perl is installed, but other times it is not. Modern programs should use `use Socket;` instead.
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 ExtUtils::MM_Unix ExtUtils::MM\_Unix
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Methods](#Methods)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MM\_Unix - methods used by ExtUtils::MakeMaker
SYNOPSIS
--------
```
require ExtUtils::MM_Unix;
```
DESCRIPTION
-----------
The methods provided by this package are designed to be used in conjunction with <ExtUtils::MakeMaker>. When MakeMaker writes a Makefile, it creates one or more objects that inherit their methods from a package [MM](ExtUtils::MM). MM itself doesn't provide any methods, but it ISA ExtUtils::MM\_Unix class. The inheritance tree of MM lets operating specific packages take the responsibility for all the methods provided by MM\_Unix. We are trying to reduce the number of the necessary overrides by defining rather primitive operations within ExtUtils::MM\_Unix.
If you are going to write a platform specific MM package, please try to limit the necessary overrides to primitive methods, and if it is not possible to do so, let's work out how to achieve that gain.
If you are overriding any of these methods in your Makefile.PL (in the MY class), please report that to the makemaker mailing list. We are trying to minimize the necessary method overrides and switch to data driven Makefile.PLs wherever possible. In the long run less methods will be overridable via the MY class.
METHODS
-------
The following description of methods is still under development. Please refer to the code for not suitably documented sections and complain loudly to the [email protected] mailing list. Better yet, provide a patch.
Not all of the methods below are overridable in a Makefile.PL. Overridable methods are marked as (o). All methods are overridable by a platform specific MM\_\*.pm file.
Cross-platform methods are being moved into [MM\_Any](ExtUtils::MM_Any). If you can't find something that used to be in here, look in MM\_Any.
### Methods
os\_flavor Simply says that we're Unix.
c\_o (o) Defines the suffix rules to compile different flavors of C files to object files.
xs\_obj\_opt Takes the object file as an argument, and returns the portion of compile command-line that will output to the specified object file.
dbgoutflag Returns a CC flag that tells the CC to emit a separate debugging symbol file when compiling an object file.
cflags (o) Does very much the same as the cflags script in the perl distribution. It doesn't return the whole compiler command line, but initializes all of its parts. The const\_cccmd method then actually returns the definition of the CCCMD macro which uses these parts.
const\_cccmd (o) Returns the full compiler call for C programs and stores the definition in CONST\_CCCMD.
const\_config (o) Sets SHELL if needed, then defines a couple of constants in the Makefile that are imported from %Config.
const\_loadlibs (o) Defines EXTRALIBS, LDLOADLIBS, BSLOADLIBS, LD\_RUN\_PATH. See <ExtUtils::Liblist> for details.
constants (o)
```
my $make_frag = $mm->constants;
```
Prints out macros for lots of constants.
depend (o) Same as macro for the depend attribute.
init\_DEST
```
$mm->init_DEST
```
Defines the DESTDIR and DEST\* variables paralleling the INSTALL\*.
init\_dist
```
$mm->init_dist;
```
Defines a lot of macros for distribution support.
```
macro description default
TAR tar command to use tar
TARFLAGS flags to pass to TAR cvf
ZIP zip command to use zip
ZIPFLAGS flags to pass to ZIP -r
COMPRESS compression command to gzip --best
use for tarfiles
SUFFIX suffix to put on .gz
compressed files
SHAR shar command to use shar
PREOP extra commands to run before
making the archive
POSTOP extra commands to run after
making the archive
TO_UNIX a command to convert linefeeds
to Unix style in your archive
CI command to checkin your ci -u
sources to version control
RCS_LABEL command to label your sources rcs -Nv$(VERSION_SYM): -q
just after CI is run
DIST_CP $how argument to manicopy() best
when the distdir is created
DIST_DEFAULT default target to use to tardist
create a distribution
DISTVNAME name of the resulting archive $(DISTNAME)-$(VERSION)
(minus suffixes)
```
dist (o)
```
my $dist_macros = $mm->dist(%overrides);
```
Generates a make fragment defining all the macros initialized in init\_dist.
%overrides can be used to override any of the above.
dist\_basics (o) Defines the targets distclean, distcheck, skipcheck, manifest, veryclean.
dist\_ci (o) Defines a check in target for RCS.
dist\_core (o)
```
my $dist_make_fragment = $MM->dist_core;
```
Puts the targets necessary for 'make dist' together into one make fragment.
**dist\_target**
```
my $make_frag = $MM->dist_target;
```
Returns the 'dist' target to make an archive for distribution. This target simply checks to make sure the Makefile is up-to-date and depends on $(DIST\_DEFAULT).
**tardist\_target**
```
my $make_frag = $MM->tardist_target;
```
Returns the 'tardist' target which is simply so 'make tardist' works. The real work is done by the dynamically named tardistfile\_target() method, tardist should have that as a dependency.
**zipdist\_target**
```
my $make_frag = $MM->zipdist_target;
```
Returns the 'zipdist' target which is simply so 'make zipdist' works. The real work is done by the dynamically named zipdistfile\_target() method, zipdist should have that as a dependency.
**tarfile\_target**
```
my $make_frag = $MM->tarfile_target;
```
The name of this target is the name of the tarball generated by tardist. This target does the actual work of turning the distdir into a tarball.
zipfile\_target
```
my $make_frag = $MM->zipfile_target;
```
The name of this target is the name of the zip file generated by zipdist. This target does the actual work of turning the distdir into a zip file.
uutardist\_target
```
my $make_frag = $MM->uutardist_target;
```
Converts the tarfile into a uuencoded file
shdist\_target
```
my $make_frag = $MM->shdist_target;
```
Converts the distdir into a shell archive.
dlsyms (o) Used by some OS' to define DL\_FUNCS and DL\_VARS and write the \*.exp files.
Normally just returns an empty string.
dynamic\_bs (o) Defines targets for bootstrap files.
dynamic\_lib (o) Defines how to produce the \*.so (or equivalent) files.
xs\_dynamic\_lib\_macros Defines the macros for the `dynamic_lib` section.
xs\_make\_dynamic\_lib Defines the recipes for the `dynamic_lib` section.
exescan Deprecated method. Use libscan instead.
extliblist Called by init\_others, and calls ext ExtUtils::Liblist. See <ExtUtils::Liblist> for details.
find\_perl Finds the executables PERL and FULLPERL
fixin
```
$mm->fixin(@files);
```
Inserts the sharpbang or equivalent magic number to a set of @files.
force (o) Writes an empty FORCE: target.
guess\_name Guess the name of this package by examining the working directory's name. MakeMaker calls this only if the developer has not supplied a NAME attribute.
has\_link\_code Returns true if C, XS, MYEXTLIB or similar objects exist within this object that need a compiler. Does not descend into subdirectories as needs\_linking() does.
init\_dirscan Scans the directory structure and initializes DIR, XS, XS\_FILES, C, C\_FILES, O\_FILES, H, H\_FILES, PL\_FILES, EXE\_FILES.
Called by init\_main.
init\_MANPODS Determines if man pages should be generated and initializes MAN1PODS and MAN3PODS as appropriate.
init\_MAN1PODS Initializes MAN1PODS from the list of EXE\_FILES.
init\_MAN3PODS Initializes MAN3PODS from the list of PM files.
init\_PM Initializes PMLIBDIRS and PM from PMLIBDIRS.
init\_DIRFILESEP Using / for Unix. Called by init\_main.
init\_main Initializes AR, AR\_STATIC\_ARGS, BASEEXT, CONFIG, DISTNAME, DLBASE, EXE\_EXT, FULLEXT, FULLPERL, FULLPERLRUN, FULLPERLRUNINST, INST\_\*, INSTALL\*, INSTALLDIRS, LIB\_EXT, LIBPERL\_A, MAP\_TARGET, NAME, OBJ\_EXT, PARENT\_NAME, PERL, PERL\_ARCHLIB, PERL\_INC, PERL\_LIB, PERL\_SRC, PERLRUN, PERLRUNINST, PREFIX, VERSION, VERSION\_SYM, XS\_VERSION.
init\_tools Initializes tools to use their common (and faster) Unix commands.
init\_linker Unix has no need of special linker flags.
init\_PERL
```
$mm->init_PERL;
```
Called by init\_main. Sets up ABSPERL, PERL, FULLPERL and all the \*PERLRUN\* permutations.
```
PERL is allowed to be miniperl
FULLPERL must be a complete perl
ABSPERL is PERL converted to an absolute path
*PERLRUN contains everything necessary to run perl, find it's
libraries, etc...
*PERLRUNINST is *PERLRUN + everything necessary to find the
modules being built.
```
init\_platform platform\_constants Add MM\_Unix\_VERSION.
init\_PERM
```
$mm->init_PERM
```
Called by init\_main. Initializes PERL\_\*
init\_xs
```
$mm->init_xs
```
Sets up macros having to do with XS code. Currently just INST\_STATIC, INST\_DYNAMIC and INST\_BOOT.
install (o) Defines the install target.
installbin (o) Defines targets to make and to install EXE\_FILES.
linkext (o) Defines the linkext target which in turn defines the LINKTYPE.
lsdir Takes as arguments a directory name and a regular expression. Returns all entries in the directory that match the regular expression.
macro (o) Simple subroutine to insert the macros defined by the macro attribute into the Makefile.
makeaperl (o) Called by staticmake. Defines how to write the Makefile to produce a static new perl.
By default the Makefile produced includes all the static extensions in the perl library. (Purified versions of library files, e.g., DynaLoader\_pure\_p1\_c0\_032.a are automatically ignored to avoid link errors.)
xs\_static\_lib\_is\_xs (o) Called by a utility method of makeaperl. Checks whether a given file is an XS library by seeing whether it defines any symbols starting with `boot_` (with an optional leading underscore - needed on MacOS).
makefile (o) Defines how to rewrite the Makefile.
maybe\_command Returns true, if the argument is likely to be a command.
needs\_linking (o) Does this module need linking? Looks into subdirectory objects (see also has\_link\_code())
parse\_abstract parse a file and return what you think is the ABSTRACT
parse\_version
```
my $version = MM->parse_version($file);
```
Parse a $file and return what $VERSION is set to by the first assignment. It will return the string "undef" if it can't figure out what $VERSION is. $VERSION should be for all to see, so `our $VERSION` or plain $VERSION are okay, but `my $VERSION` is not.
`package Foo VERSION` is also checked for. The first version declaration found is used, but this may change as it differs from how Perl does it.
parse\_version() will try to `use version` before checking for `$VERSION` so the following will work.
```
$VERSION = qv(1.2.3);
```
pasthru (o) Defines the string that is passed to recursive make calls in subdirectories. The variables like `PASTHRU_DEFINE` are used in each level, and passed downwards on the command-line with e.g. the value of that level's DEFINE. Example:
```
# Level 0 has DEFINE = -Dfunky
# This code will define level 0's PASTHRU=PASTHRU_DEFINE="$(DEFINE)
# $(PASTHRU_DEFINE)"
# Level 0's $(CCCMD) will include macros $(DEFINE) and $(PASTHRU_DEFINE)
# So will level 1's, so when level 1 compiles, it will get right values
# And so ad infinitum
```
perl\_script Takes one argument, a file name, and returns the file name, if the argument is likely to be a perl script. On MM\_Unix this is true for any ordinary, readable file.
perldepend (o) Defines the dependency from all \*.h files that come with the perl distribution.
pm\_to\_blib Defines target that copies all files in the hash PM to their destination and autosplits them. See ["DESCRIPTION" in ExtUtils::Install](ExtUtils::Install#DESCRIPTION)
ppd Defines target that creates a PPD (Perl Package Description) file for a binary distribution.
prefixify
```
$MM->prefixify($var, $prefix, $new_prefix, $default);
```
Using either $MM->{uc $var} || $Config{lc $var}, it will attempt to replace it's $prefix with a $new\_prefix.
Should the $prefix fail to match *AND* a PREFIX was given as an argument to WriteMakefile() it will set it to the $new\_prefix + $default. This is for systems whose file layouts don't neatly fit into our ideas of prefixes.
This is for heuristics which attempt to create directory structures that mirror those of the installed perl.
For example:
```
$MM->prefixify('installman1dir', '/usr', '/home/foo', 'man/man1');
```
this will attempt to remove '/usr' from the front of the $MM->{INSTALLMAN1DIR} path (initializing it to $Config{installman1dir} if necessary) and replace it with '/home/foo'. If this fails it will simply use '/home/foo/man/man1'.
processPL (o) Defines targets to run \*.PL files.
specify\_shell Specify SHELL if needed - not done on Unix.
quote\_paren Backslashes parentheses `()` in command line arguments. Doesn't handle recursive Makefile `$(...)` constructs, but handles simple ones.
replace\_manpage\_separator
```
my $man_name = $MM->replace_manpage_separator($file_path);
```
Takes the name of a package, which may be a nested package, in the form 'Foo/Bar.pm' and replaces the slash with `::` or something else safe for a man page file name. Returns the replacement.
cd oneliner quote\_literal Quotes macro literal value suitable for being used on a command line so that when expanded by make, will be received by command as given to this method:
```
my $quoted = $mm->quote_literal(q{it isn't});
# returns:
# 'it isn'\''t'
print MAKEFILE "target:\n\techo $quoted\n";
# when run "make target", will output:
# it isn't
```
escape\_newlines max\_exec\_len Using [POSIX](posix)::ARG\_MAX. Otherwise falling back to 4096.
static (o) Defines the static target.
xs\_make\_static\_lib Defines the recipes for the `static_lib` section.
static\_lib\_closures Records `$(EXTRALIBS)` in *extralibs.ld* and *$(PERL\_SRC)/ext.libs*.
static\_lib\_fixtures Handles copying `$(MYEXTLIB)` as starter for final static library that then gets added to.
static\_lib\_pure\_cmd Defines how to run the archive utility.
staticmake (o) Calls makeaperl.
subdir\_x (o) Helper subroutine for subdirs
subdirs (o) Defines targets to process subdirectories.
test (o) Defines the test targets.
test\_via\_harness (override) For some reason which I forget, Unix machines like to have PERL\_DL\_NONLAZY set for tests.
test\_via\_script (override) Again, the PERL\_DL\_NONLAZY thing.
tool\_xsubpp (o) Determines typemaps, xsubpp version, prototype behaviour.
all\_target Build man pages, too
top\_targets (o) Defines the targets all, subdirs, config, and O\_FILES
writedoc Obsolete, deprecated method. Not used since Version 5.21.
xs\_c (o) Defines the suffix rules to compile XS files to C.
xs\_cpp (o) Defines the suffix rules to compile XS files to C++.
xs\_o (o) Defines suffix rules to go from XS to object files directly. This was originally only intended for broken make implementations, but is now necessary for per-XS file under `XSMULTI`, since each XS file might have an individual `$(VERSION)`.
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl MIME::QuotedPrint MIME::QuotedPrint
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
MIME::QuotedPrint - Encoding and decoding of quoted-printable strings
SYNOPSIS
--------
```
use MIME::QuotedPrint;
$encoded = encode_qp($decoded);
$decoded = decode_qp($encoded);
```
DESCRIPTION
-----------
This module provides functions to encode and decode strings into and from the quoted-printable encoding specified in RFC 2045 - *MIME (Multipurpose Internet Mail Extensions)*. The quoted-printable encoding is intended to represent data that largely consists of bytes that correspond to printable characters in the ASCII character set. Each non-printable character (as defined by English Americans) is represented by a triplet consisting of the character "=" followed by two hexadecimal digits.
The following functions are provided:
encode\_qp( $str)
encode\_qp( $str, $eol)
encode\_qp( $str, $eol, $binmode ) This function returns an encoded version of the string ($str) given as argument.
The second argument ($eol) is the line-ending sequence to use. It is optional and defaults to "\n". Every occurrence of "\n" is replaced with this string, and it is also used for additional "soft line breaks" to ensure that no line end up longer than 76 characters. Pass it as "\015\012" to produce data suitable for external consumption. The string "\r\n" produces the same result on many platforms, but not all.
The third argument ($binmode) will select binary mode if passed as a TRUE value. In binary mode "\n" will be encoded in the same way as any other non-printable character. This ensures that a decoder will end up with exactly the same string whatever line ending sequence it uses. In general it is preferable to use the base64 encoding for binary data; see <MIME::Base64>.
An $eol of "" (the empty string) is special. In this case, no "soft line breaks" are introduced and binary mode is effectively enabled so that any "\n" in the original data is encoded as well.
decode\_qp( $str ) This function returns the plain text version of the string given as argument. The lines of the result are "\n" terminated, even if the $str argument contains "\r\n" terminated lines.
If you prefer not to import these routines into your namespace, you can call them as:
```
use MIME::QuotedPrint ();
$encoded = MIME::QuotedPrint::encode($decoded);
$decoded = MIME::QuotedPrint::decode($encoded);
```
Perl v5.8 and better allow extended Unicode characters in strings. Such strings cannot be encoded directly, as the quoted-printable encoding is only defined for single-byte characters. The solution is to use the Encode module to select the byte encoding you want. For example:
```
use MIME::QuotedPrint qw(encode_qp);
use Encode qw(encode);
$encoded = encode_qp(encode("UTF-8", "\x{FFFF}\n"));
print $encoded;
```
COPYRIGHT
---------
Copyright 1995-1997,2002-2004 Gisle Aas.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<MIME::Base64>
perl open open
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [IMPLEMENTATION DETAILS](#IMPLEMENTATION-DETAILS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
open - perl pragma to set default PerlIO layers for input and output
SYNOPSIS
--------
```
use open IN => ':crlf', OUT => ':raw';
open my $in, '<', 'foo.txt' or die "open failed: $!";
my $line = <$in>; # CRLF translated
close $in;
open my $out, '>', 'bar.txt' or die "open failed: $!";
print $out $line; # no translation of bytes
close $out;
use open OUT => ':encoding(UTF-8)';
use open IN => ':encoding(iso-8859-7)';
use open IO => ':locale';
# IO implicit only for :utf8, :encoding, :locale
use open ':encoding(UTF-8)';
use open ':encoding(iso-8859-7)';
use open ':locale';
# with :std, also affect global standard handles
use open ':std', ':encoding(UTF-8)';
use open ':std', OUT => ':encoding(cp1252)';
use open ':std', IO => ':raw :encoding(UTF-16LE)';
```
DESCRIPTION
-----------
Full-fledged support for I/O layers is now implemented provided Perl is configured to use PerlIO as its IO system (which has been the default since 5.8, and the only supported configuration since 5.16).
The `open` pragma serves as one of the interfaces to declare default "layers" (previously known as "disciplines") for all I/O. Any open(), readpipe() (aka qx//) and similar operators found within the lexical scope of this pragma will use the declared defaults via the [`${^OPEN}`](perlvar#%24%7B%5EOPEN%7D) variable.
Layers are specified with a leading colon by convention. You can specify a stack of multiple layers as a space-separated string. See [PerlIO](perlio) for more information on the available layers.
With the `IN` subpragma you can declare the default layers of input streams, and with the `OUT` subpragma you can declare the default layers of output streams. With the `IO` subpragma (may be omitted for `:utf8`, `:locale`, or `:encoding`) you can control both input and output streams simultaneously.
When open() is given an explicit list of layers (with the three-arg syntax), they override the list declared using this pragma. open() can also be given a single colon (:) for a layer name, to override this pragma and use the default as detailed in ["Defaults and how to override them" in PerlIO](perlio#Defaults-and-how-to-override-them).
To translate from and to an arbitrary text encoding, use the `:encoding` layer. The matching of encoding names in `:encoding` is loose: case does not matter, and many encodings have several aliases. See <Encode::Supported> for details and the list of supported locales.
If you want to set your encoding layers based on your locale environment variables, you can use the `:locale` pseudo-layer. For example:
```
$ENV{LANG} = 'ru_RU.KOI8-R';
# the :locale will probe the locale environment variables like LANG
use open OUT => ':locale';
open(my $out, '>', 'koi8') or die "open failed: $!";
print $out chr(0x430); # CYRILLIC SMALL LETTER A = KOI8-R 0xc1
close $out;
open(my $in, '<', 'koi8') or die "open failed: $!";
printf "%#x\n", ord(<$in>); # this should print 0xc1
close $in;
```
The logic of `:locale` is described in full in ["The `:locale` sub-pragma" in encoding](encoding#The-%3Alocale-sub-pragma), but in short it is first trying nl\_langinfo(CODESET) and then guessing from the LC\_ALL and LANG locale environment variables. `:locale` also implicitly turns on `:std`.
`:std` is not a layer but an additional subpragma. When specified in the import list, it activates an additional functionality of pushing the layers selected for input/output handles to the standard filehandles (STDIN, STDOUT, STDERR). If the new layers and existing layer stack both end with an `:encoding` layer, the existing `:encoding` layer will also be removed.
For example, if both input and out are chosen to be `:encoding(UTF-8)`, a `:std` will mean that STDIN, STDOUT, and STDERR will also have `:encoding(UTF-8)` set. On the other hand, if only output is chosen to be in `:encoding(koi8r)`, a `:std` will cause only the STDOUT and STDERR to be in `koi8r`.
The effect of `:std` is not lexical as it modifies the layer stack of the global handles. If you wish to apply only this global effect and not the effect on handles that are opened in that scope, you can isolate the call to this pragma in its own lexical scope.
```
{ use open ':std', IO => ':encoding(UTF-8)' }
```
Before Perl 5.34, `:std` would only apply the first layer provided that is either `:utf8` or has a layer argument, e.g. `:encoding(UTF-8)`. Since Perl 5.34 it will apply the same layer stack it provides to `${^OPEN}`.
IMPLEMENTATION DETAILS
-----------------------
There is a class method in `PerlIO::Layer` `find` which is implemented as XS code. It is called by `import` to validate the layers:
```
PerlIO::Layer::->find("perlio")
```
The return value (if defined) is a Perl object, of class `PerlIO::Layer` which is created by the C code in *perlio.c*. As yet there is nothing useful you can do with the object at the perl level.
SEE ALSO
---------
["binmode" in perlfunc](perlfunc#binmode), ["open" in perlfunc](perlfunc#open), <perlunicode>, [PerlIO](perlio), <encoding>
| programming_docs |
perl Devel::Peek Devel::Peek
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Runtime debugging](#Runtime-debugging)
+ [Memory footprint debugging](#Memory-footprint-debugging)
* [EXAMPLES](#EXAMPLES)
+ [A simple scalar string](#A-simple-scalar-string)
+ [A simple scalar number](#A-simple-scalar-number)
+ [A simple scalar with an extra reference](#A-simple-scalar-with-an-extra-reference)
+ [A reference to a simple scalar](#A-reference-to-a-simple-scalar)
+ [A reference to an array](#A-reference-to-an-array)
+ [A reference to a hash](#A-reference-to-a-hash)
+ [Dumping a large array or hash](#Dumping-a-large-array-or-hash)
+ [A reference to an SV which holds a C pointer](#A-reference-to-an-SV-which-holds-a-C-pointer)
+ [A reference to a subroutine](#A-reference-to-a-subroutine)
* [EXPORTS](#EXPORTS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Devel::Peek - A data debugging tool for the XS programmer
SYNOPSIS
--------
```
use Devel::Peek;
Dump( $a );
Dump( $a, 5 );
Dump( @a );
Dump( %h );
DumpArray( 5, $a, $b, ... );
mstat "Point 5";
use Devel::Peek ':opd=st';
```
DESCRIPTION
-----------
Devel::Peek contains functions which allows raw Perl datatypes to be manipulated from a Perl script. This is used by those who do XS programming to check that the data they are sending from C to Perl looks as they think it should look. The trick, then, is to know what the raw datatype is supposed to look like when it gets to Perl. This document offers some tips and hints to describe good and bad raw data.
It is very possible that this document will fall far short of being useful to the casual reader. The reader is expected to understand the material in the first few sections of <perlguts>.
Devel::Peek supplies a `Dump()` function which can dump a raw Perl datatype, and `mstat("marker")` function to report on memory usage (if perl is compiled with corresponding option). The function DeadCode() provides statistics on the data "frozen" into inactive `CV`. Devel::Peek also supplies `SvREFCNT()` which can query reference counts on SVs. This document will take a passive, and safe, approach to data debugging and for that it will describe only the `Dump()` function.
All output is to STDERR.
The `Dump()` function takes one or two arguments: something to dump, and an optional limit for recursion and array elements (default is 4). The first argument is evaluated in rvalue scalar context, with exceptions for @array and %hash, which dump the array or hash itself. So `Dump @array` works, as does `Dump $foo`. And `Dump pos` will call `pos` in rvalue context, whereas `Dump ${\pos}` will call it in lvalue context.
Function `DumpArray()` allows dumping of multiple values (useful when you need to analyze returns of functions).
The global variable $Devel::Peek::pv\_limit can be set to limit the number of character printed in various string values. Setting it to 0 means no limit.
If `use Devel::Peek` directive has a `:opd=FLAGS` argument, this switches on debugging of opcode dispatch. `FLAGS` should be a combination of `s`, `t`, and `P` (see [**-D** flags in perlrun](perlrun#-Dletters)).
`:opd` is a shortcut for `:opd=st`.
###
Runtime debugging
`CvGV($cv)` return one of the globs associated to a subroutine reference $cv.
debug\_flags() returns a string representation of `$^D` (similar to what is allowed for **-D** flag). When called with a numeric argument, sets $^D to the corresponding value. When called with an argument of the form `"flags-flags"`, set on/off bits of `$^D` corresponding to letters before/after `-`. (The returned value is for `$^D` before the modification.)
runops\_debug() returns true if the current *opcode dispatcher* is the debugging one. When called with an argument, switches to debugging or non-debugging dispatcher depending on the argument (active for newly-entered subs/etc only). (The returned value is for the dispatcher before the modification.)
###
Memory footprint debugging
When perl is compiled with support for memory footprint debugging (default with Perl's malloc()), Devel::Peek provides an access to this API.
Use mstat() function to emit a memory state statistic to the terminal. For more information on the format of output of mstat() see ["Using $ENV{PERL\_DEBUG\_MSTATS}" in perldebguts](perldebguts#Using-%24ENV%7BPERL_DEBUG_MSTATS%7D).
Three additional functions allow access to this statistic from Perl. First, use `mstats_fillhash(%hash)` to get the information contained in the output of mstat() into %hash. The field of this hash are
```
minbucket nbuckets sbrk_good sbrk_slack sbrked_remains sbrks
start_slack topbucket topbucket_ev topbucket_odd total total_chain
total_sbrk totfree
```
Two additional fields `free`, `used` contain array references which provide per-bucket count of free and used chunks. Two other fields `mem_size`, `available_size` contain array references which provide the information about the allocated size and usable size of chunks in each bucket. Again, see ["Using $ENV{PERL\_DEBUG\_MSTATS}" in perldebguts](perldebguts#Using-%24ENV%7BPERL_DEBUG_MSTATS%7D) for details.
Keep in mind that only the first several "odd-numbered" buckets are used, so the information on size of the "odd-numbered" buckets which are not used is probably meaningless.
The information in
```
mem_size available_size minbucket nbuckets
```
is the property of a particular build of perl, and does not depend on the current process. If you do not provide the optional argument to the functions mstats\_fillhash(), fill\_mstats(), mstats2hash(), then the information in fields `mem_size`, `available_size` is not updated.
`fill_mstats($buf)` is a much cheaper call (both speedwise and memory-wise) which collects the statistic into $buf in machine-readable form. At a later moment you may need to call `mstats2hash($buf, %hash)` to use this information to fill %hash.
All three APIs `fill_mstats($buf)`, `mstats_fillhash(%hash)`, and `mstats2hash($buf, %hash)` are designed to allocate no memory if used *the second time* on the same $buf and/or %hash.
So, if you want to collect memory info in a cycle, you may call
```
$#buf = 999;
fill_mstats($_) for @buf;
mstats_fillhash(%report, 1); # Static info too
foreach (@buf) {
# Do something...
fill_mstats $_; # Collect statistic
}
foreach (@buf) {
mstats2hash($_, %report); # Preserve static info
# Do something with %report
}
```
EXAMPLES
--------
The following examples don't attempt to show everything as that would be a monumental task, and, frankly, we don't want this manpage to be an internals document for Perl. The examples do demonstrate some basics of the raw Perl datatypes, and should suffice to get most determined people on their way. There are no guidewires or safety nets, nor blazed trails, so be prepared to travel alone from this point and on and, if at all possible, don't fall into the quicksand (it's bad for business).
Oh, one final bit of advice: take <perlguts> with you. When you return we expect to see it well-thumbed.
###
A simple scalar string
Let's begin by looking a simple scalar which is holding a string.
```
use Devel::Peek;
$a = 42; $a = "hello";
Dump $a;
```
The output:
```
SV = PVIV(0xbc288) at 0xbe9a8
REFCNT = 1
FLAGS = (POK,pPOK)
IV = 42
PV = 0xb2048 "hello"\0
CUR = 5
LEN = 8
```
This says `$a` is an SV, a scalar. The scalar type is a PVIV, which is capable of holding an integer (IV) and/or a string (PV) value. The scalar's head is allocated at address 0xbe9a8, while the body is at 0xbc288. Its reference count is 1. It has the `POK` flag set, meaning its current PV field is valid. Because POK is set we look at the PV item to see what is in the scalar. The \0 at the end indicate that this PV is properly NUL-terminated. Note that the IV field still contains its old numeric value, but because FLAGS doesn't have IOK set, we must ignore the IV item. CUR indicates the number of characters in the PV. LEN indicates the number of bytes allocated for the PV (at least one more than CUR, because LEN includes an extra byte for the end-of-string marker, then usually rounded up to some efficient allocation unit).
###
A simple scalar number
If the scalar contains a number the raw SV will be leaner.
```
use Devel::Peek;
$a = 42;
Dump $a;
```
The output:
```
SV = IV(0xbc818) at 0xbe9a8
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 42
```
This says `$a` is an SV, a scalar. The scalar is an IV, a number. Its reference count is 1. It has the `IOK` flag set, meaning it is currently being evaluated as a number. Because IOK is set we look at the IV item to see what is in the scalar.
###
A simple scalar with an extra reference
If the scalar from the previous example had an extra reference:
```
use Devel::Peek;
$a = 42;
$b = \$a;
Dump $a;
```
The output:
```
SV = IV(0xbe860) at 0xbe9a8
REFCNT = 2
FLAGS = (IOK,pIOK)
IV = 42
```
Notice that this example differs from the previous example only in its reference count. Compare this to the next example, where we dump `$b` instead of `$a`.
###
A reference to a simple scalar
This shows what a reference looks like when it references a simple scalar.
```
use Devel::Peek;
$a = 42;
$b = \$a;
Dump $b;
```
The output:
```
SV = IV(0xf041c) at 0xbe9a0
REFCNT = 1
FLAGS = (ROK)
RV = 0xbab08
SV = IV(0xbe860) at 0xbe9a8
REFCNT = 2
FLAGS = (IOK,pIOK)
IV = 42
```
Starting from the top, this says `$b` is an SV. The scalar is an IV, which is capable of holding an integer or reference value. It has the `ROK` flag set, meaning it is a reference (rather than an integer or string). Notice that Dump follows the reference and shows us what `$b` was referencing. We see the same `$a` that we found in the previous example.
Note that the value of `RV` coincides with the numbers we see when we stringify $b. The addresses inside IV() are addresses of `X***` structures which hold the current state of an `SV`. This address may change during lifetime of an SV.
###
A reference to an array
This shows what a reference to an array looks like.
```
use Devel::Peek;
$a = [42];
Dump $a;
```
The output:
```
SV = IV(0xc85998) at 0xc859a8
REFCNT = 1
FLAGS = (ROK)
RV = 0xc70de8
SV = PVAV(0xc71e10) at 0xc70de8
REFCNT = 1
FLAGS = ()
ARRAY = 0xc7e820
FILL = 0
MAX = 0
FLAGS = (REAL)
Elt No. 0
SV = IV(0xc70f88) at 0xc70f98
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 42
```
This says `$a` is a reference (ROK), which points to another SV which is a PVAV, an array. The array has one element, element zero, which is another SV. The field `FILL` above indicates the last element in the array, similar to `$#$a`.
If `$a` pointed to an array of two elements then we would see the following.
```
use Devel::Peek 'Dump';
$a = [42,24];
Dump $a;
```
The output:
```
SV = IV(0x158c998) at 0x158c9a8
REFCNT = 1
FLAGS = (ROK)
RV = 0x1577de8
SV = PVAV(0x1578e10) at 0x1577de8
REFCNT = 1
FLAGS = ()
ARRAY = 0x1585820
FILL = 1
MAX = 1
FLAGS = (REAL)
Elt No. 0
SV = IV(0x1577f88) at 0x1577f98
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 42
Elt No. 1
SV = IV(0x158be88) at 0x158be98
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 24
```
Note that `Dump` will not report *all* the elements in the array, only several first (depending on how deep it already went into the report tree).
###
A reference to a hash
The following shows the raw form of a reference to a hash.
```
use Devel::Peek;
$a = {hello=>42};
Dump $a;
```
The output:
```
SV = IV(0x55cb50b50fb0) at 0x55cb50b50fc0
REFCNT = 1
FLAGS = (ROK)
RV = 0x55cb50b2b758
SV = PVHV(0x55cb50b319c0) at 0x55cb50b2b758
REFCNT = 1
FLAGS = (SHAREKEYS)
ARRAY = 0x55cb50b941a0 (0:7, 1:1)
hash quality = 100.0%
KEYS = 1
FILL = 1
MAX = 7
Elt "hello" HASH = 0x3128ece4
SV = IV(0x55cb50b464f8) at 0x55cb50b46508
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 42
```
This shows `$a` is a reference pointing to an SV. That SV is a PVHV, a hash.
The "quality" of a hash is defined as the total number of comparisons needed to access every element once, relative to the expected number needed for a random hash. The value can go over 100%.
The total number of comparisons is equal to the sum of the squares of the number of entries in each bucket. For a random hash of `<n`> keys into `<k`> buckets, the expected value is:
```
n + n(n-1)/2k
```
###
Dumping a large array or hash
The `Dump()` function, by default, dumps up to 4 elements from a toplevel array or hash. This number can be increased by supplying a second argument to the function.
```
use Devel::Peek;
$a = [10,11,12,13,14];
Dump $a;
```
Notice that `Dump()` prints only elements 10 through 13 in the above code. The following code will print all of the elements.
```
use Devel::Peek 'Dump';
$a = [10,11,12,13,14];
Dump $a, 5;
```
###
A reference to an SV which holds a C pointer
This is what you really need to know as an XS programmer, of course. When an XSUB returns a pointer to a C structure that pointer is stored in an SV and a reference to that SV is placed on the XSUB stack. So the output from an XSUB which uses something like the T\_PTROBJ map might look something like this:
```
SV = IV(0xf381c) at 0xc859a8
REFCNT = 1
FLAGS = (ROK)
RV = 0xb8ad8
SV = PVMG(0xbb3c8) at 0xc859a0
REFCNT = 1
FLAGS = (OBJECT,IOK,pIOK)
IV = 729160
NV = 0
PV = 0
STASH = 0xc1d10 "CookBookB::Opaque"
```
This shows that we have an SV which is a reference, which points at another SV. In this case that second SV is a PVMG, a blessed scalar. Because it is blessed it has the `OBJECT` flag set. Note that an SV which holds a C pointer also has the `IOK` flag set. The `STASH` is set to the package name which this SV was blessed into.
The output from an XSUB which uses something like the T\_PTRREF map, which doesn't bless the object, might look something like this:
```
SV = IV(0xf381c) at 0xc859a8
REFCNT = 1
FLAGS = (ROK)
RV = 0xb8ad8
SV = PVMG(0xbb3c8) at 0xc859a0
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 729160
NV = 0
PV = 0
```
###
A reference to a subroutine
Looks like this:
```
SV = IV(0x24d2dd8) at 0x24d2de8
REFCNT = 1
FLAGS = (TEMP,ROK)
RV = 0x24e79d8
SV = PVCV(0x24e5798) at 0x24e79d8
REFCNT = 2
FLAGS = ()
COMP_STASH = 0x22c9c50 "main"
START = 0x22eed60 ===> 0
ROOT = 0x22ee490
GVGV::GV = 0x22de9d8 "MY" :: "top_targets"
FILE = "(eval 5)"
DEPTH = 0
FLAGS = 0x0
OUTSIDE_SEQ = 93
PADLIST = 0x22e9ed8
PADNAME = 0x22e9ec0(0x22eed00) PAD = 0x22e9ea8(0x22eecd0)
OUTSIDE = 0x22c9fb0 (MAIN)
```
This shows that
* the subroutine is not an XSUB (since `START` and `ROOT` are non-zero, and `XSUB` is not listed, and is thus null);
* that it was compiled in the package `main`;
* under the name `MY::top_targets`;
* inside a 5th eval in the program;
* it is not currently executed (because `DEPTH` is 0);
* it has no prototype (`PROTOTYPE` field is missing).
EXPORTS
-------
`Dump`, `mstat`, `DeadCode`, `DumpArray`, `DumpWithOP` and `DumpProg`, `fill_mstats`, `mstats_fillhash`, `mstats2hash` by default. Additionally available `SvREFCNT`, `SvREFCNT_inc` and `SvREFCNT_dec`.
BUGS
----
Readers have been known to skip important parts of <perlguts>, causing much frustration for all.
AUTHOR
------
Ilya Zakharevich [email protected]
Copyright (c) 1995-98 Ilya Zakharevich. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Author of this software makes no claim whatsoever about suitability, reliability, edability, editability or usability of this product, and should not be kept liable for any damage resulting from the use of it. If you can use it, you are in luck, if not, I should not be kept responsible. Keep a handy copy of your backup tape at hand.
SEE ALSO
---------
<perlguts>, and <perlguts>, again.
perl perlmacosx perlmacosx
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Installation Prefix](#Installation-Prefix)
+ [SDK support](#SDK-support)
+ [Universal Binary support](#Universal-Binary-support)
+ [64-bit PPC support](#64-bit-PPC-support)
+ [libperl and Prebinding](#libperl-and-Prebinding)
+ [Updating Apple's Perl](#Updating-Apple's-Perl)
+ [Known problems](#Known-problems)
+ [Cocoa](#Cocoa)
* [Starting From Scratch](#Starting-From-Scratch)
* [AUTHOR](#AUTHOR)
* [DATE](#DATE)
NAME
----
perlmacosx - Perl under Mac OS X
SYNOPSIS
--------
This document briefly describes Perl under Mac OS X.
```
curl -O https://www.cpan.org/src/perl-5.36.0.tar.gz
tar -xzf perl-5.36.0.tar.gz
cd perl-5.36.0
./Configure -des -Dprefix=/usr/local/
make
make test
sudo make install
```
DESCRIPTION
-----------
The latest Perl release (5.36.0 as of this writing) builds without changes under all versions of Mac OS X from 10.3 "Panther" onwards.
In order to build your own version of Perl you will need 'make', which is part of Apple's developer tools - also known as Xcode. From Mac OS X 10.7 "Lion" onwards, it can be downloaded separately as the 'Command Line Tools' bundle directly from <https://developer.apple.com/downloads/> (you will need a free account to log in), or as a part of the Xcode suite, freely available at the App Store. Xcode is a pretty big app, so unless you already have it or really want it, you are advised to get the 'Command Line Tools' bundle separately from the link above. If you want to do it from within Xcode, go to Xcode -> Preferences -> Downloads and select the 'Command Line Tools' option.
Between Mac OS X 10.3 "Panther" and 10.6 "Snow Leopard", the 'Command Line Tools' bundle was called 'unix tools', and was usually supplied with Mac OS install DVDs.
Earlier Mac OS X releases (10.2 "Jaguar" and older) did not include a completely thread-safe libc, so threading is not fully supported. Also, earlier releases included a buggy libdb, so some of the DB\_File tests are known to fail on those releases.
###
Installation Prefix
The default installation location for this release uses the traditional UNIX directory layout under /usr/local. This is the recommended location for most users, and will leave the Apple-supplied Perl and its modules undisturbed.
Using an installation prefix of '/usr' will result in a directory layout that mirrors that of Apple's default Perl, with core modules stored in '/System/Library/Perl/${version}', CPAN modules stored in '/Library/Perl/${version}', and the addition of '/Network/Library/Perl/${version}' to @INC for modules that are stored on a file server and used by many Macs.
###
SDK support
First, export the path to the SDK into the build environment:
```
export SDK=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk
```
Please make sure the SDK version (i.e. the numbers right before '.sdk') matches your system's (in this case, Mac OS X 10.8 "Mountain Lion"), as it is possible to have more than one SDK installed. Also make sure the path exists in your system, and if it doesn't please make sure the SDK is properly installed, as it should come with the 'Command Line Tools' bundle mentioned above. Finally, if you have an older Mac OS X (10.6 "Snow Leopard" and below) running Xcode 4.2 or lower, the SDK path might be something like `'/Developer/SDKs/MacOSX10.3.9.sdk'`.
You can use the SDK by exporting some additions to Perl's 'ccflags' and '..flags' config variables:
```
./Configure -Accflags="-nostdinc -B$SDK/usr/include/gcc \
-B$SDK/usr/lib/gcc -isystem$SDK/usr/include \
-F$SDK/System/Library/Frameworks" \
-Aldflags="-Wl,-syslibroot,$SDK" \
-de
```
###
Universal Binary support
Note: From Mac OS X 10.6 "Snow Leopard" onwards, Apple only supports Intel-based hardware. This means you can safely skip this section unless you have an older Apple computer running on ppc or wish to create a perl binary with backwards compatibility.
You can compile perl as a universal binary (built for both ppc and intel). In Mac OS X 10.4 "Tiger", you must export the 'u' variant of the SDK:
```
export SDK=/Developer/SDKs/MacOSX10.4u.sdk
```
Mac OS X 10.5 "Leopard" and above do not require the 'u' variant.
In addition to the compiler flags used to select the SDK, also add the flags for creating a universal binary:
```
./Configure -Accflags="-arch i686 -arch ppc -nostdinc \
-B$SDK/usr/include/gcc \
-B$SDK/usr/lib/gcc -isystem$SDK/usr/include \
-F$SDK/System/Library/Frameworks" \
-Aldflags="-arch i686 -arch ppc -Wl,-syslibroot,$SDK" \
-de
```
Keep in mind that these compiler and linker settings will also be used when building CPAN modules. For XS modules to be compiled as a universal binary, any libraries it links to must also be universal binaries. The system libraries that Apple includes with the 10.4u SDK are all universal, but user-installed libraries may need to be re-installed as universal binaries.
###
64-bit PPC support
Follow the instructions in *INSTALL* to build perl with support for 64-bit integers (`use64bitint`) or both 64-bit integers and 64-bit addressing (`use64bitall`). In the latter case, the resulting binary will run only on G5-based hosts.
Support for 64-bit addressing is experimental: some aspects of Perl may be omitted or buggy. Note the messages output by *Configure* for further information. Please use <https://github.com/Perl/perl5/issues> to submit a problem report in the event that you encounter difficulties.
When building 64-bit modules, it is your responsibility to ensure that linked external libraries and frameworks provide 64-bit support: if they do not, module building may appear to succeed, but attempts to use the module will result in run-time dynamic linking errors, and subsequent test failures. You can use `file` to discover the architectures supported by a library:
```
$ file libgdbm.3.0.0.dylib
libgdbm.3.0.0.dylib: Mach-O fat file with 2 architectures
libgdbm.3.0.0.dylib (for architecture ppc): Mach-O dynamically linked shared library ppc
libgdbm.3.0.0.dylib (for architecture ppc64): Mach-O 64-bit dynamically linked shared library ppc64
```
Note that this issue precludes the building of many Macintosh-specific CPAN modules (`Mac::*`), as the required Apple frameworks do not provide PPC64 support. Similarly, downloads from Fink or Darwinports are unlikely to provide 64-bit support; the libraries must be rebuilt from source with the appropriate compiler and linker flags. For further information, see Apple's *64-Bit Transition Guide* at <https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/64bitPorting/transition/transition.html>.
###
libperl and Prebinding
Mac OS X ships with a dynamically-loaded libperl, but the default for this release is to compile a static libperl. The reason for this is pre-binding. Dynamic libraries can be pre-bound to a specific address in memory in order to decrease load time. To do this, one needs to be aware of the location and size of all previously-loaded libraries. Apple collects this information as part of their overall OS build process, and thus has easy access to it when building Perl, but ordinary users would need to go to a great deal of effort to obtain the information needed for pre-binding.
You can override the default and build a shared libperl if you wish (Configure ... -Duseshrplib).
With Mac OS X 10.4 "Tiger" and newer, there is almost no performance penalty for non-prebound libraries. Earlier releases will suffer a greater load time than either the static library, or Apple's pre-bound dynamic library.
###
Updating Apple's Perl
In a word - don't, at least not without a \*very\* good reason. Your scripts can just as easily begin with "#!/usr/local/bin/perl" as with "#!/usr/bin/perl". Scripts supplied by Apple and other third parties as part of installation packages and such have generally only been tested with the /usr/bin/perl that's installed by Apple.
If you find that you do need to update the system Perl, one issue worth keeping in mind is the question of static vs. dynamic libraries. If you upgrade using the default static libperl, you will find that the dynamic libperl supplied by Apple will not be deleted. If both libraries are present when an application that links against libperl is built, ld will link against the dynamic library by default. So, if you need to replace Apple's dynamic libperl with a static libperl, you need to be sure to delete the older dynamic library after you've installed the update.
###
Known problems
If you have installed extra libraries such as GDBM through Fink (in other words, you have libraries under */sw/lib*), or libdlcompat to */usr/local/lib*, you may need to be extra careful when running Configure to not to confuse Configure and Perl about which libraries to use. Being confused will show up for example as "dyld" errors about symbol problems, for example during "make test". The safest bet is to run Configure as
```
Configure ... -Uloclibpth -Dlibpth=/usr/lib
```
to make Configure look only into the system libraries. If you have some extra library directories that you really want to use (such as newer Berkeley DB libraries in pre-Panther systems), add those to the libpth:
```
Configure ... -Uloclibpth -Dlibpth='/usr/lib /opt/lib'
```
The default of building Perl statically may cause problems with complex applications like Tk: in that case consider building shared Perl
```
Configure ... -Duseshrplib
```
but remember that there's a startup cost to pay in that case (see above "libperl and Prebinding").
Starting with Tiger (Mac OS X 10.4), Apple shipped broken locale files for the eu\_ES locale (Basque-Spain). In previous releases of Perl, this resulted in failures in the *lib/locale* test. These failures have been suppressed in the current release of Perl by making the test ignore the broken locale. If you need to use the eu\_ES locale, you should contact Apple support.
### Cocoa
There are two ways to use Cocoa from Perl. Apple's PerlObjCBridge module, included with Mac OS X, can be used by standalone scripts to access Foundation (i.e. non-GUI) classes and objects.
An alternative is CamelBones, a framework that allows access to both Foundation and AppKit classes and objects, so that full GUI applications can be built in Perl. CamelBones can be found on SourceForge, at <https://www.sourceforge.net/projects/camelbones/>.
Starting From Scratch
----------------------
Unfortunately it is not that difficult somehow manage to break one's Mac OS X Perl rather severely. If all else fails and you want to really, **REALLY**, start from scratch and remove even your Apple Perl installation (which has become corrupted somehow), the following instructions should do it. **Please think twice before following these instructions: they are much like conducting brain surgery to yourself. Without anesthesia.** We will **not** come to fix your system if you do this.
First, get rid of the libperl.dylib:
```
# cd /System/Library/Perl/darwin/CORE
# rm libperl.dylib
```
Then delete every .bundle file found anywhere in the folders:
```
/System/Library/Perl
/Library/Perl
```
You can find them for example by
```
# find /System/Library/Perl /Library/Perl -name '*.bundle' -print
```
After this you can either copy Perl from your operating system media (you will need at least the /System/Library/Perl and /usr/bin/perl), or rebuild Perl from the source code with `Configure -Dprefix=/usr -Duseshrplib` NOTE: the `-Dprefix=/usr` to replace the system Perl works much better with Perl 5.8.1 and later, in Perl 5.8.0 the settings were not quite right.
"Pacifist" from CharlesSoft (<https://www.charlessoft.com/>) is a nice way to extract the Perl binaries from the OS media, without having to reinstall the entire OS.
AUTHOR
------
This README was written by Sherm Pendley <[email protected]>, and subsequently updated by Dominic Dunlop <[email protected]> and Breno G. de Oliveira <[email protected]>. The "Starting From Scratch" recipe was contributed by John Montbriand <[email protected]>.
DATE
----
Last modified 2013-04-29.
| programming_docs |
perl List::Util List::Util
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LIST-REDUCTION FUNCTIONS](#LIST-REDUCTION-FUNCTIONS)
+ [reduce](#reduce)
+ [reductions](#reductions)
+ [any](#any)
+ [all](#all)
+ [none](#none)
+ [notall](#notall)
+ [first](#first)
+ [max](#max)
+ [maxstr](#maxstr)
+ [min](#min)
+ [minstr](#minstr)
+ [product](#product)
+ [sum](#sum)
+ [sum0](#sum0)
* [KEY/VALUE PAIR LIST FUNCTIONS](#KEY/VALUE-PAIR-LIST-FUNCTIONS)
+ [pairs](#pairs)
+ [unpairs](#unpairs)
+ [pairkeys](#pairkeys)
+ [pairvalues](#pairvalues)
+ [pairgrep](#pairgrep)
+ [pairfirst](#pairfirst)
+ [pairmap](#pairmap)
* [OTHER FUNCTIONS](#OTHER-FUNCTIONS)
+ [shuffle](#shuffle)
+ [sample](#sample)
+ [uniq](#uniq)
+ [uniqint](#uniqint)
+ [uniqnum](#uniqnum)
+ [uniqstr](#uniqstr)
+ [head](#head)
+ [tail](#tail)
+ [zip](#zip)
+ [mesh](#mesh)
* [CONFIGURATION VARIABLES](#CONFIGURATION-VARIABLES)
+ [$RAND](#%24RAND)
* [KNOWN BUGS](#KNOWN-BUGS)
+ [RT #95409](#RT-%2395409)
+ [uniqnum() on oversized bignums](#uniqnum()-on-oversized-bignums)
* [SUGGESTED ADDITIONS](#SUGGESTED-ADDITIONS)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
List::Util - A selection of general-utility list subroutines
SYNOPSIS
--------
```
use List::Util qw(
reduce any all none notall first reductions
max maxstr min minstr product sum sum0
pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap
shuffle uniq uniqint uniqnum uniqstr zip mesh
);
```
DESCRIPTION
-----------
`List::Util` contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size so small such that being individual extensions would be wasteful.
By default `List::Util` does not export any subroutines.
LIST-REDUCTION FUNCTIONS
-------------------------
The following set of functions all apply a given block of code to a list of values.
### reduce
```
$result = reduce { BLOCK } @list
```
Reduces `@list` by calling `BLOCK` in a scalar context multiple times, setting `$a` and `$b` each time. The first call will be with `$a` and `$b` set to the first two elements of the list, subsequent calls will be done by setting `$a` to the result of the previous call and `$b` to the next element in the list.
Returns the result of the last call to the `BLOCK`. If `@list` is empty then `undef` is returned. If `@list` only contains one element then that element is returned and `BLOCK` is not executed.
The following examples all demonstrate how `reduce` could be used to implement the other list-reduction functions in this module. (They are not in fact implemented like this, but instead in a more efficient manner in individual C functions).
```
$foo = reduce { defined($a) ? $a :
$code->(local $_ = $b) ? $b :
undef } undef, @list # first
$foo = reduce { $a > $b ? $a : $b } 1..10 # max
$foo = reduce { $a gt $b ? $a : $b } 'A'..'Z' # maxstr
$foo = reduce { $a < $b ? $a : $b } 1..10 # min
$foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr
$foo = reduce { $a + $b } 1 .. 10 # sum
$foo = reduce { $a . $b } @bar # concat
$foo = reduce { $a || $code->(local $_ = $b) } 0, @bar # any
$foo = reduce { $a && $code->(local $_ = $b) } 1, @bar # all
$foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar # none
$foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar # notall
# Note that these implementations do not fully short-circuit
```
If your algorithm requires that `reduce` produce an identity value, then make sure that you always pass that identity value as the first argument to prevent `undef` being returned
```
$foo = reduce { $a + $b } 0, @values; # sum with 0 identity value
```
The above example code blocks also suggest how to use `reduce` to build a more efficient combined version of one of these basic functions and a `map` block. For example, to find the total length of all the strings in a list, we could use
```
$total = sum map { length } @strings;
```
However, this produces a list of temporary integer values as long as the original list of strings, only to reduce it down to a single value again. We can compute the same result more efficiently by using `reduce` with a code block that accumulates lengths by writing this instead as:
```
$total = reduce { $a + length $b } 0, @strings
```
The other scalar-returning list reduction functions are all specialisations of this generic idea.
### reductions
```
@results = reductions { BLOCK } @list
```
*Since version 1.54.*
Similar to `reduce` except that it also returns the intermediate values along with the final result. As before, `$a` is set to the first element of the given list, and the `BLOCK` is then called once for remaining item in the list set into `$b`, with the result being captured for return as well as becoming the new value for `$a`.
The returned list will begin with the initial value for `$a`, followed by each return value from the block in order. The final value of the result will be identical to what the `reduce` function would have returned given the same block and list.
```
reduce { "$a-$b" } "a".."d" # "a-b-c-d"
reductions { "$a-$b" } "a".."d" # "a", "a-b", "a-b-c", "a-b-c-d"
```
### any
```
my $bool = any { BLOCK } @list;
```
*Since version 1.33.*
Similar to `grep` in that it evaluates `BLOCK` setting `$_` to each element of `@list` in turn. `any` returns true if any element makes the `BLOCK` return a true value. If `BLOCK` never returns true or `@list` was empty then it returns false.
Many cases of using `grep` in a conditional can be written using `any` instead, as it can short-circuit after the first true result.
```
if( any { length > 10 } @strings ) {
# at least one string has more than 10 characters
}
```
Note: Due to XS issues the block passed may be able to access the outer @\_ directly. This is not intentional and will break under debugger.
### all
```
my $bool = all { BLOCK } @list;
```
*Since version 1.33.*
Similar to ["any"](#any), except that it requires all elements of the `@list` to make the `BLOCK` return true. If any element returns false, then it returns false. If the `BLOCK` never returns false or the `@list` was empty then it returns true.
Note: Due to XS issues the block passed may be able to access the outer @\_ directly. This is not intentional and will break under debugger.
### none
### notall
```
my $bool = none { BLOCK } @list;
my $bool = notall { BLOCK } @list;
```
*Since version 1.33.*
Similar to ["any"](#any) and ["all"](#all), but with the return sense inverted. `none` returns true only if no value in the `@list` causes the `BLOCK` to return true, and `notall` returns true only if not all of the values do.
Note: Due to XS issues the block passed may be able to access the outer @\_ directly. This is not intentional and will break under debugger.
### first
```
my $val = first { BLOCK } @list;
```
Similar to `grep` in that it evaluates `BLOCK` setting `$_` to each element of `@list` in turn. `first` returns the first element where the result from `BLOCK` is a true value. If `BLOCK` never returns true or `@list` was empty then `undef` is returned.
```
$foo = first { defined($_) } @list # first defined value in @list
$foo = first { $_ > $value } @list # first value in @list which
# is greater than $value
```
### max
```
my $num = max @list;
```
Returns the entry in the list with the highest numerical value. If the list is empty then `undef` is returned.
```
$foo = max 1..10 # 10
$foo = max 3,9,12 # 12
$foo = max @bar, @baz # whatever
```
### maxstr
```
my $str = maxstr @list;
```
Similar to ["max"](#max), but treats all the entries in the list as strings and returns the highest string as defined by the `gt` operator. If the list is empty then `undef` is returned.
```
$foo = maxstr 'A'..'Z' # 'Z'
$foo = maxstr "hello","world" # "world"
$foo = maxstr @bar, @baz # whatever
```
### min
```
my $num = min @list;
```
Similar to ["max"](#max) but returns the entry in the list with the lowest numerical value. If the list is empty then `undef` is returned.
```
$foo = min 1..10 # 1
$foo = min 3,9,12 # 3
$foo = min @bar, @baz # whatever
```
### minstr
```
my $str = minstr @list;
```
Similar to ["min"](#min), but treats all the entries in the list as strings and returns the lowest string as defined by the `lt` operator. If the list is empty then `undef` is returned.
```
$foo = minstr 'A'..'Z' # 'A'
$foo = minstr "hello","world" # "hello"
$foo = minstr @bar, @baz # whatever
```
### product
```
my $num = product @list;
```
*Since version 1.35.*
Returns the numerical product of all the elements in `@list`. If `@list` is empty then `1` is returned.
```
$foo = product 1..10 # 3628800
$foo = product 3,9,12 # 324
```
### sum
```
my $num_or_undef = sum @list;
```
Returns the numerical sum of all the elements in `@list`. For backwards compatibility, if `@list` is empty then `undef` is returned.
```
$foo = sum 1..10 # 55
$foo = sum 3,9,12 # 24
$foo = sum @bar, @baz # whatever
```
### sum0
```
my $num = sum0 @list;
```
*Since version 1.26.*
Similar to ["sum"](#sum), except this returns 0 when given an empty list, rather than `undef`.
KEY/VALUE PAIR LIST FUNCTIONS
------------------------------
The following set of functions, all inspired by <List::Pairwise>, consume an even-sized list of pairs. The pairs may be key/value associations from a hash, or just a list of values. The functions will all preserve the original ordering of the pairs, and will not be confused by multiple pairs having the same "key" value - nor even do they require that the first of each pair be a plain string.
**NOTE**: At the time of writing, the following `pair*` functions that take a block do not modify the value of `$_` within the block, and instead operate using the `$a` and `$b` globals instead. This has turned out to be a poor design, as it precludes the ability to provide a `pairsort` function. Better would be to pass pair-like objects as 2-element array references in `$_`, in a style similar to the return value of the `pairs` function. At some future version this behaviour may be added.
Until then, users are alerted **NOT** to rely on the value of `$_` remaining unmodified between the outside and the inside of the control block. In particular, the following example is **UNSAFE**:
```
my @kvlist = ...
foreach (qw( some keys here )) {
my @items = pairgrep { $a eq $_ } @kvlist;
...
}
```
Instead, write this using a lexical variable:
```
foreach my $key (qw( some keys here )) {
my @items = pairgrep { $a eq $key } @kvlist;
...
}
```
### pairs
```
my @pairs = pairs @kvlist;
```
*Since version 1.29.*
A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of `ARRAY` references, each containing two items from the given list. It is a more efficient version of
```
@pairs = pairmap { [ $a, $b ] } @kvlist
```
It is most convenient to use in a `foreach` loop, for example:
```
foreach my $pair ( pairs @kvlist ) {
my ( $key, $value ) = @$pair;
...
}
```
Since version `1.39` these `ARRAY` references are blessed objects, recognising the two methods `key` and `value`. The following code is equivalent:
```
foreach my $pair ( pairs @kvlist ) {
my $key = $pair->key;
my $value = $pair->value;
...
}
```
Since version `1.51` they also have a `TO_JSON` method to ease serialisation.
### unpairs
```
my @kvlist = unpairs @pairs
```
*Since version 1.42.*
The inverse function to `pairs`; this function takes a list of `ARRAY` references containing two elements each, and returns a flattened list of the two values from each of the pairs, in order. This is notionally equivalent to
```
my @kvlist = map { @{$_}[0,1] } @pairs
```
except that it is implemented more efficiently internally. Specifically, for any input item it will extract exactly two values for the output list; using `undef` if the input array references are short.
Between `pairs` and `unpairs`, a higher-order list function can be used to operate on the pairs as single scalars; such as the following near-equivalents of the other `pair*` higher-order functions:
```
@kvlist = unpairs grep { FUNC } pairs @kvlist
# Like pairgrep, but takes $_ instead of $a and $b
@kvlist = unpairs map { FUNC } pairs @kvlist
# Like pairmap, but takes $_ instead of $a and $b
```
Note however that these versions will not behave as nicely in scalar context.
Finally, this technique can be used to implement a sort on a keyvalue pair list; e.g.:
```
@kvlist = unpairs sort { $a->key cmp $b->key } pairs @kvlist
```
### pairkeys
```
my @keys = pairkeys @kvlist;
```
*Since version 1.29.*
A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the first values of each of the pairs in the given list. It is a more efficient version of
```
@keys = pairmap { $a } @kvlist
```
### pairvalues
```
my @values = pairvalues @kvlist;
```
*Since version 1.29.*
A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the second values of each of the pairs in the given list. It is a more efficient version of
```
@values = pairmap { $b } @kvlist
```
### pairgrep
```
my @kvlist = pairgrep { BLOCK } @kvlist;
my $count = pairgrep { BLOCK } @kvlist;
```
*Since version 1.29.*
Similar to perl's `grep` keyword, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, in scalar context, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.
Returns an even-sized list of those pairs for which the `BLOCK` returned true in list context, or the count of the **number of pairs** in scalar context. (Note, therefore, in scalar context that it returns a number half the size of the count of items it would have returned in list context).
```
@subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist
```
As with `grep` aliasing `$_` to list elements, `pairgrep` aliases `$a` and `$b` to elements of the given list. Any modifications of it by the code block will be visible to the caller.
### pairfirst
```
my ( $key, $val ) = pairfirst { BLOCK } @kvlist;
my $found = pairfirst { BLOCK } @kvlist;
```
*Since version 1.30.*
Similar to the ["first"](#first) function, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, in scalar context, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.
Returns the first pair of values from the list for which the `BLOCK` returned true in list context, or an empty list of no such pair was found. In scalar context it returns a simple boolean value, rather than either the key or the value found.
```
( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist
```
As with `grep` aliasing `$_` to list elements, `pairfirst` aliases `$a` and `$b` to elements of the given list. Any modifications of it by the code block will be visible to the caller.
### pairmap
```
my @list = pairmap { BLOCK } @kvlist;
my $count = pairmap { BLOCK } @kvlist;
```
*Since version 1.29.*
Similar to perl's `map` keyword, but interprets the given list as an even-sized list of pairs. It invokes the `BLOCK` multiple times, in list context, with `$a` and `$b` set to successive pairs of values from the `@kvlist`.
Returns the concatenation of all the values returned by the `BLOCK` in list context, or the count of the number of items that would have been returned in scalar context.
```
@result = pairmap { "The key $a has value $b" } @kvlist
```
As with `map` aliasing `$_` to list elements, `pairmap` aliases `$a` and `$b` to elements of the given list. Any modifications of it by the code block will be visible to the caller.
See ["KNOWN BUGS"](#KNOWN-BUGS) for a known-bug with `pairmap`, and a workaround.
OTHER FUNCTIONS
----------------
### shuffle
```
my @values = shuffle @values;
```
Returns the values of the input in a random order
```
@cards = shuffle 0..51 # 0..51 in a random order
```
This function is affected by the `$RAND` variable.
### sample
```
my @items = sample $count, @values
```
*Since version 1.54.*
Randomly select the given number of elements from the input list. Any given position in the input list will be selected at most once.
If there are fewer than `$count` items in the list then the function will return once all of them have been randomly selected; effectively the function behaves similarly to ["shuffle"](#shuffle).
This function is affected by the `$RAND` variable.
### uniq
```
my @subset = uniq @values
```
*Since version 1.45.*
Filters a list of values to remove subsequent duplicates, as judged by a DWIM-ish string equality or `undef` test. Preserves the order of unique elements, and retains the first value of any duplicate set.
```
my $count = uniq @values
```
In scalar context, returns the number of elements that would have been returned as a list.
The `undef` value is treated by this function as distinct from the empty string, and no warning will be produced. It is left as-is in the returned list. Subsequent `undef` values are still considered identical to the first, and will be removed.
### uniqint
```
my @subset = uniqint @values
```
*Since version 1.55.*
Filters a list of values to remove subsequent duplicates, as judged by an integer numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. Values in the returned list will be coerced into integers.
```
my $count = uniqint @values
```
In scalar context, returns the number of elements that would have been returned as a list.
Note that `undef` is treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning if such warnings are enabled (`use warnings 'uninitialized';`). In addition, an `undef` in the returned list is coerced into a numerical zero, so that the entire list of values returned by `uniqint` are well-behaved as integers.
### uniqnum
```
my @subset = uniqnum @values
```
*Since version 1.44.*
Filters a list of values to remove subsequent duplicates, as judged by a numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set.
```
my $count = uniqnum @values
```
In scalar context, returns the number of elements that would have been returned as a list.
Note that `undef` is treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning if such warnings are enabled (`use warnings 'uninitialized';`). In addition, an `undef` in the returned list is coerced into a numerical zero, so that the entire list of values returned by `uniqnum` are well-behaved as numbers.
Note also that multiple IEEE `NaN` values are treated as duplicates of each other, regardless of any differences in their payloads, and despite the fact that `0+'NaN' == 0+'NaN'` yields false.
### uniqstr
```
my @subset = uniqstr @values
```
*Since version 1.45.*
Filters a list of values to remove subsequent duplicates, as judged by a string equality test. Preserves the order of unique elements, and retains the first value of any duplicate set.
```
my $count = uniqstr @values
```
In scalar context, returns the number of elements that would have been returned as a list.
Note that `undef` is treated much as other string operations treat it; it compares equal to the empty string but additionally produces a warning if such warnings are enabled (`use warnings 'uninitialized';`). In addition, an `undef` in the returned list is coerced into an empty string, so that the entire list of values returned by `uniqstr` are well-behaved as strings.
### head
```
my @values = head $size, @list;
```
*Since version 1.50.*
Returns the first `$size` elements from `@list`. If `$size` is negative, returns all but the last `$size` elements from `@list`.
```
@result = head 2, qw( foo bar baz );
# foo, bar
@result = head -2, qw( foo bar baz );
# foo
```
### tail
```
my @values = tail $size, @list;
```
*Since version 1.50.*
Returns the last `$size` elements from `@list`. If `$size` is negative, returns all but the first `$size` elements from `@list`.
```
@result = tail 2, qw( foo bar baz );
# bar, baz
@result = tail -2, qw( foo bar baz );
# baz
```
### zip
```
my @result = zip [1..3], ['a'..'c'];
# [1, 'a'], [2, 'b'], [3, 'c']
```
*Since version 1.56.*
Returns a list of array references, composed of elements from the given list of array references. Each array in the returned list is composed of elements at that corresponding position from each of the given input arrays. If any input arrays run out of elements before others, then `undef` will be inserted into the result to fill in the gaps.
The `zip` function is particularly handy for iterating over multiple arrays at the same time with a `foreach` loop, taking one element from each:
```
foreach ( zip \@xs, \@ys, \@zs ) {
my ($x, $y, $z) = @$_;
...
}
```
**NOTE** to users of <List::MoreUtils>: This function does not behave the same as `List::MoreUtils::zip`, but is actually a non-prototyped equivalent to `List::MoreUtils::zip_unflatten`. This function does not apply a prototype, so make sure to invoke it with references to arrays.
For a function similar to the `zip` function from `List::MoreUtils`, see <mesh>.
```
my @result = zip_shortest ...
```
A variation of the function that differs in how it behaves when given input arrays of differing lengths. `zip_shortest` will stop as soon as any one of the input arrays run out of elements, discarding any remaining unused values from the others.
```
my @result = zip_longest ...
```
`zip_longest` is an alias to the `zip` function, provided simply to be explicit about that behaviour as compared to `zip_shortest`.
### mesh
```
my @result = mesh [1..3], ['a'..'c'];
# (1, 'a', 2, 'b', 3, 'c')
```
*Since version 1.56.*
Returns a list of items collected from elements of the given list of array references. Each section of items in the returned list is composed of elements at the corresponding position from each of the given input arrays. If any input arrays run out of elements before others, then `undef` will be inserted into the result to fill in the gaps.
This is similar to <zip>, except that all of the ranges in the result are returned in one long flattened list, instead of being bundled into separate arrays.
Because it returns a flat list of items, the `mesh` function is particularly useful for building a hash out of two separate arrays of keys and values:
```
my %hash = mesh \@keys, \@values;
my $href = { mesh \@keys, \@values };
```
**NOTE** to users of <List::MoreUtils>: This function is a non-prototyped equivalent to `List::MoreUtils::mesh` or `List::MoreUtils::zip` (themselves aliases of each other). This function does not apply a prototype, so make sure to invoke it with references to arrays.
```
my @result = mesh_shortest ...
my @result = mesh_longest ...
```
These variations are similar to those of <zip>, in that they differ in behaviour when one of the input lists runs out of elements before the others.
CONFIGURATION VARIABLES
------------------------
###
$RAND
```
local $List::Util::RAND = sub { ... };
```
*Since version 1.54.*
This package variable is used by code which needs to generate random numbers (such as the ["shuffle"](#shuffle) and ["sample"](#sample) functions). If set to a CODE reference it provides an alternative to perl's builtin `rand()` function. When a new random number is needed this function will be invoked with no arguments and is expected to return a floating-point value, of which only the fractional part will be used.
KNOWN BUGS
-----------
###
RT #95409
<https://rt.cpan.org/Ticket/Display.html?id=95409>
If the block of code given to ["pairmap"](#pairmap) contains lexical variables that are captured by a returned closure, and the closure is executed after the block has been re-used for the next iteration, these lexicals will not see the correct values. For example:
```
my @subs = pairmap {
my $var = "$a is $b";
sub { print "$var\n" };
} one => 1, two => 2, three => 3;
$_->() for @subs;
```
Will incorrectly print
```
three is 3
three is 3
three is 3
```
This is due to the performance optimisation of using `MULTICALL` for the code block, which means that fresh SVs do not get allocated for each call to the block. Instead, the same SV is re-assigned for each iteration, and all the closures will share the value seen on the final iteration.
To work around this bug, surround the code with a second set of braces. This creates an inner block that defeats the `MULTICALL` logic, and does get fresh SVs allocated each time:
```
my @subs = pairmap {
{
my $var = "$a is $b";
sub { print "$var\n"; }
}
} one => 1, two => 2, three => 3;
```
This bug only affects closures that are generated by the block but used afterwards. Lexical variables that are only used during the lifetime of the block's execution will take their individual values for each invocation, as normal.
###
uniqnum() on oversized bignums
Due to the way that `uniqnum()` compares numbers, it cannot distinguish differences between bignums (especially bigints) that are too large to fit in the native platform types. For example,
```
my $x = Math::BigInt->new( "1" x 100 );
my $y = $x + 1;
say for uniqnum( $x, $y );
```
Will print just the value of `$x`, believing that `$y` is a numerically- equivalent value. This bug does not affect `uniqstr()`, which will correctly observe that the two values stringify to different strings.
SUGGESTED ADDITIONS
--------------------
The following are additions that have been requested, but I have been reluctant to add due to them being very simple to implement in perl
```
# How many elements are true
sub true { scalar grep { $_ } @_ }
# How many elements are false
sub false { scalar grep { !$_ } @_ }
```
SEE ALSO
---------
<Scalar::Util>, <List::MoreUtils>
COPYRIGHT
---------
Copyright (c) 1997-2007 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.
Recent additions and current maintenance by Paul Evans, <[email protected]>.
| programming_docs |
perl xsubpp xsubpp
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [SEE ALSO](#SEE-ALSO)
NAME
----
xsubpp - compiler to convert Perl XS code into C code
SYNOPSIS
--------
**xsubpp** [**-v**] [**-except**] [**-s pattern**] [**-prototypes**] [**-noversioncheck**] [**-nolinenumbers**] [**-nooptimize**] [**-typemap typemap**] [**-output filename**]... file.xs
DESCRIPTION
-----------
This compiler is typically run by the makefiles created by <ExtUtils::MakeMaker> or by <Module::Build> or other Perl module build tools.
*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. The compiler uses typemaps to determine how to map C function parameters and variables to Perl values.
The compiler will search for typemap files called *typemap*. It will use the following search path to find default typemaps, with the rightmost typemap taking precedence.
```
../../../typemap:../../typemap:../typemap:typemap
```
It will also use a default typemap installed as `ExtUtils::typemap`.
OPTIONS
-------
Note that the `XSOPT` MakeMaker option may be used to add these options to any makefiles generated by MakeMaker.
**-hiertype**
Retains '::' in type names so that C++ hierarchical types can be mapped.
**-except**
Adds exception handling stubs to the C code.
**-typemap typemap**
Indicates that a user-supplied typemap should take precedence over the default typemaps. This option may be used multiple times, with the last typemap having the highest precedence.
**-output filename**
Specifies the name of the output file to generate. If no file is specified, output will be written to standard output.
**-v**
Prints the *xsubpp* version number to standard output, then exits.
**-prototypes**
By default *xsubpp* will not automatically generate prototype code for all xsubs. This flag will enable prototypes.
**-noversioncheck**
Disables the run time test that determines if the object file (derived from the `.xs` file) and the `.pm` files have the same version number.
**-nolinenumbers**
Prevents the inclusion of '#line' directives in the output.
**-nooptimize**
Disables certain optimizations. The only optimization that is currently affected is the use of *target*s by the output C code (see <perlguts>). This may significantly slow down the generated code, but this is the way **xsubpp** of 5.005 and earlier operated.
**-noinout**
Disable recognition of `IN`, `OUT_LIST` and `INOUT_LIST` declarations.
**-noargtypes**
Disable recognition of ANSI-like descriptions of function signature.
**-C++**
Currently doesn't do anything at all. This flag has been a no-op for many versions of perl, at least as far back as perl5.003\_07. It's allowed here for backwards compatibility.
**-s=...** or **-strip=...**
*This option is obscure and discouraged.*
If specified, the given string will be stripped off from the beginning of the C function name in the generated XS functions (if it starts with that prefix). This only applies to XSUBs without `CODE` or `PPCODE` blocks. For example, the XS:
```
void foo_bar(int i);
```
when `xsubpp` is invoked with `-s foo_` will install a `foo_bar` function in Perl, but really call `bar(i)` in C. Most of the time, this is the opposite of what you want and failure modes are somewhat obscure, so please avoid this option where possible.
ENVIRONMENT
-----------
No environment variables are used.
AUTHOR
------
Originally by Larry Wall. Turned into the `ExtUtils::ParseXS` module by Ken Williams.
MODIFICATION HISTORY
---------------------
See the file *Changes*.
SEE ALSO
---------
perl(1), perlxs(1), perlxstut(1), ExtUtils::ParseXS
perl perlnumber perlnumber
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Storing numbers](#Storing-numbers)
* [Numeric operators and numeric conversions](#Numeric-operators-and-numeric-conversions)
* [Flavors of Perl numeric operations](#Flavors-of-Perl-numeric-operations)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlnumber - semantics of numbers and numeric operations in Perl
SYNOPSIS
--------
```
$n = 1234; # decimal integer
$n = 0b1110011; # binary integer
$n = 01234; # octal integer
$n = 0x1234; # hexadecimal integer
$n = 12.34e-56; # exponential notation
$n = "-12.34e56"; # number specified as a string
$n = "1234"; # number specified as a string
```
DESCRIPTION
-----------
This document describes how Perl internally handles numeric values.
Perl's operator overloading facility is completely ignored here. Operator overloading allows user-defined behaviors for numbers, such as operations over arbitrarily large integers, floating points numbers with arbitrary precision, operations over "exotic" numbers such as modular arithmetic or p-adic arithmetic, and so on. See <overload> for details.
Storing numbers
----------------
Perl can internally represent numbers in 3 different ways: as native integers, as native floating point numbers, and as decimal strings. Decimal strings may have an exponential notation part, as in `"12.34e-56"`. *Native* here means "a format supported by the C compiler which was used to build perl".
The term "native" does not mean quite as much when we talk about native integers, as it does when native floating point numbers are involved. The only implication of the term "native" on integers is that the limits for the maximal and the minimal supported true integral quantities are close to powers of 2. However, "native" floats have a most fundamental restriction: they may represent only those numbers which have a relatively "short" representation when converted to a binary fraction. For example, 0.9 cannot be represented by a native float, since the binary fraction for 0.9 is infinite:
```
binary0.1110011001100...
```
with the sequence `1100` repeating again and again. In addition to this limitation, the exponent of the binary number is also restricted when it is represented as a floating point number. On typical hardware, floating point values can store numbers with up to 53 binary digits, and with binary exponents between -1024 and 1024. In decimal representation this is close to 16 decimal digits and decimal exponents in the range of -304..304. The upshot of all this is that Perl cannot store a number like 12345678901234567 as a floating point number on such architectures without loss of information.
Similarly, decimal strings can represent only those numbers which have a finite decimal expansion. Being strings, and thus of arbitrary length, there is no practical limit for the exponent or number of decimal digits for these numbers. (But realize that what we are discussing the rules for just the *storage* of these numbers. The fact that you can store such "large" numbers does not mean that the *operations* over these numbers will use all of the significant digits. See ["Numeric operators and numeric conversions"](#Numeric-operators-and-numeric-conversions) for details.)
In fact numbers stored in the native integer format may be stored either in the signed native form, or in the unsigned native form. Thus the limits for Perl numbers stored as native integers would typically be -2\*\*31..2\*\*32-1, with appropriate modifications in the case of 64-bit integers. Again, this does not mean that Perl can do operations only over integers in this range: it is possible to store many more integers in floating point format.
Summing up, Perl numeric values can store only those numbers which have a finite decimal expansion or a "short" binary expansion.
Numeric operators and numeric conversions
------------------------------------------
As mentioned earlier, Perl can store a number in any one of three formats, but most operators typically understand only one of those formats. When a numeric value is passed as an argument to such an operator, it will be converted to the format understood by the operator.
Six such conversions are possible:
```
native integer --> native floating point (*)
native integer --> decimal string
native floating_point --> native integer (*)
native floating_point --> decimal string (*)
decimal string --> native integer
decimal string --> native floating point (*)
```
These conversions are governed by the following general rules:
* If the source number can be represented in the target form, that representation is used.
* If the source number is outside of the limits representable in the target form, a representation of the closest limit is used. (*Loss of information*)
* If the source number is between two numbers representable in the target form, a representation of one of these numbers is used. (*Loss of information*)
* In `native floating point --> native integer` conversions the magnitude of the result is less than or equal to the magnitude of the source. (*"Rounding to zero".*)
* If the `decimal string --> native integer` conversion cannot be done without loss of information, the result is compatible with the conversion sequence `decimal_string --> native_floating_point --> native_integer`. In particular, rounding is strongly biased to 0, though a number like `"0.99999999999999999999"` has a chance of being rounded to 1.
**RESTRICTION**: The conversions marked with `(*)` above involve steps performed by the C compiler. In particular, bugs/features of the compiler used may lead to breakage of some of the above rules.
Flavors of Perl numeric operations
-----------------------------------
Perl operations which take a numeric argument treat that argument in one of four different ways: they may force it to one of the integer, floating, or string formats; or they may behave differently depending on the format of the operand. Forcing a numeric value to a particular format does not change the number stored in the value.
All the operators which need an argument in the integer format treat the argument as in modular arithmetic, e.g., `mod 2**32` on a 32-bit architecture. `sprintf "%u", -1` therefore provides the same result as `sprintf "%u", ~0`.
Arithmetic operators The binary operators `+` `-` `*` `/` `%` `==` `!=` `>` `<` `>=` `<=` and the unary operators `-` `abs` and `--` will attempt to convert arguments to integers. If both conversions are possible without loss of precision, and the operation can be performed without loss of precision then the integer result is used. Otherwise arguments are converted to floating point format and the floating point result is used. The caching of conversions (as described above) means that the integer conversion does not throw away fractional parts on floating point numbers.
++ `++` behaves as the other operators above, except that if it is a string matching the format `/^[a-zA-Z]*[0-9]*\z/` the string increment described in <perlop> is used.
Arithmetic operators during `use integer`
In scopes where `use integer;` is in force, nearly all the operators listed above will force their argument(s) into integer format, and return an integer result. The exceptions, `abs`, `++` and `--`, do not change their behavior with `use integer;`
Other mathematical operators Operators such as `**`, `sin` and `exp` force arguments to floating point format.
Bitwise operators Arguments are forced into the integer format if not strings.
Bitwise operators during `use integer`
forces arguments to integer format. Also shift operations internally use signed integers rather than the default unsigned.
Operators which expect an integer force the argument into the integer format. This is applicable to the third and fourth arguments of `sysread`, for example.
Operators which expect a string force the argument into the string format. For example, this is applicable to `printf "%s", $value`.
Though forcing an argument into a particular form does not change the stored number, Perl remembers the result of such conversions. In particular, though the first such conversion may be time-consuming, repeated operations will not need to redo the conversion.
AUTHOR
------
Ilya Zakharevich `[email protected]`
Editorial adjustments by Gurusamy Sarathy <[email protected]>
Updates for 5.8.0 by Nicholas Clark <[email protected]>
SEE ALSO
---------
<overload>, <perlop>
perl CPAN::Distroprefs CPAN::Distroprefs
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [INTERFACE](#INTERFACE)
* [RESULTS](#RESULTS)
+ [Common](#Common)
- [type](#type)
- [file](#file)
- [ext](#ext)
- [dir](#dir)
- [abs](#abs)
+ [Errors](#Errors)
- [msg](#msg)
+ [Successes](#Successes)
- [prefs](#prefs)
* [PREFS](#PREFS)
+ [data](#data)
+ [match\_attributes](#match_attributes)
+ [has\_any\_match](#has_any_match)
+ [has\_valid\_subkeys](#has_valid_subkeys)
+ [matches](#matches)
* [LICENSE](#LICENSE)
NAME
----
CPAN::Distroprefs -- read and match distroprefs
SYNOPSIS
--------
```
use CPAN::Distroprefs;
my %info = (... distribution/environment info ...);
my $finder = CPAN::Distroprefs->find($prefs_dir, \%ext_map);
while (my $result = $finder->next) {
die $result->as_string if $result->is_fatal;
warn($result->as_string), next if $result->is_warning;
for my $pref (@{ $result->prefs }) {
if ($pref->matches(\%info)) {
return $pref;
}
}
}
```
DESCRIPTION
-----------
This module encapsulates reading [Distroprefs](cpan) and matching them against CPAN distributions.
INTERFACE
---------
```
my $finder = CPAN::Distroprefs->find($dir, \%ext_map);
while (my $result = $finder->next) { ... }
```
Build an iterator which finds distroprefs files in the tree below the given directory. Within the tree directories matching `m/^[._]/` are pruned.
`%ext_map` is a hashref whose keys are file extensions and whose values are modules used to load matching files:
```
{
'yml' => 'YAML::Syck',
'dd' => 'Data::Dumper',
...
}
```
Each time `$finder->next` is called, the iterator returns one of two possible values:
* a CPAN::Distroprefs::Result object
* `undef`, indicating that no prefs files remain to be found
RESULTS
-------
[`find()`](#INTERFACE) returns CPAN::Distroprefs::Result objects to indicate success or failure when reading a prefs file.
### Common
All results share some common attributes:
#### type
`success`, `warning`, or `fatal`
#### file
the file from which these prefs were read, or to which this error refers (relative filename)
#### ext
the file's extension, which determines how to load it
#### dir
the directory the file was read from
#### abs
the absolute path to the file
### Errors
Error results (warning and fatal) contain:
#### msg
the error message (usually either `$!` or a YAML error)
### Successes
Success results contain:
#### prefs
an arrayref of CPAN::Distroprefs::Pref objects
PREFS
-----
CPAN::Distroprefs::Pref objects represent individual distroprefs documents. They are constructed automatically as part of `success` results from `find()`.
#### data
the pref information as a hashref, suitable for e.g. passing to Kwalify
#### match\_attributes
returns a list of the valid match attributes (see the Distroprefs section in [CPAN](cpan))
currently: `env perl perlconfig distribution module`
#### has\_any\_match
true if this pref has a 'match' attribute at all
#### has\_valid\_subkeys
true if this pref has a 'match' attribute and at least one valid match attribute
#### matches
```
if ($pref->matches(\%arg)) { ... }
```
true if this pref matches the passed-in hashref, which must have a value for each of the `match_attributes` (above)
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Locale::Maketext::Guts Locale::Maketext::Guts
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Locale::Maketext::Guts - Deprecated module to load Locale::Maketext utf8 code
SYNOPSIS
--------
```
# Do this instead please
use Locale::Maketext
```
DESCRIPTION
-----------
Previously Local::Maketext::GutsLoader performed some magic to load Locale::Maketext when utf8 was unavailable. The subs this module provided were merged back into Locale::Maketext
perl Test::Tutorial Test::Tutorial
==============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Nuts and bolts of testing.](#Nuts-and-bolts-of-testing.)
+ [Where to start?](#Where-to-start?)
+ [Names](#Names)
+ [Test the manual](#Test-the-manual)
+ [Sometimes the tests are wrong](#Sometimes-the-tests-are-wrong)
+ [Testing lots of values](#Testing-lots-of-values)
+ [Informative names](#Informative-names)
+ [Skipping tests](#Skipping-tests)
+ [Todo tests](#Todo-tests)
+ [Testing with taint mode.](#Testing-with-taint-mode.)
* [FOOTNOTES](#FOOTNOTES)
* [AUTHORS](#AUTHORS)
* [MAINTAINERS](#MAINTAINERS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::Tutorial - A tutorial about writing really basic tests
DESCRIPTION
-----------
*AHHHHHHH!!!! NOT TESTING! Anything but testing! Beat me, whip me, send me to Detroit, but don't make me write tests!*
*\*sob\**
*Besides, I don't know how to write the damned things.*
Is this you? Is writing tests right up there with writing documentation and having your fingernails pulled out? Did you open up a test and read
```
######## We start with some black magic
```
and decide that's quite enough for you?
It's ok. That's all gone now. We've done all the black magic for you. And here are the tricks...
###
Nuts and bolts of testing.
Here's the most basic test program.
```
#!/usr/bin/perl -w
print "1..1\n";
print 1 + 1 == 2 ? "ok 1\n" : "not ok 1\n";
```
Because 1 + 1 is 2, it prints:
```
1..1
ok 1
```
What this says is: `1..1` "I'm going to run one test." [1] `ok 1` "The first test passed". And that's about all magic there is to testing. Your basic unit of testing is the *ok*. For each thing you test, an `ok` is printed. Simple. <Test::Harness> interprets your test results to determine if you succeeded or failed (more on that later).
Writing all these print statements rapidly gets tedious. Fortunately, there's <Test::Simple>. It has one function, `ok()`.
```
#!/usr/bin/perl -w
use Test::Simple tests => 1;
ok( 1 + 1 == 2 );
```
That does the same thing as the previous code. `ok()` is the backbone of Perl testing, and we'll be using it instead of roll-your-own from here on. If `ok()` gets a true value, the test passes. False, it fails.
```
#!/usr/bin/perl -w
use Test::Simple tests => 2;
ok( 1 + 1 == 2 );
ok( 2 + 2 == 5 );
```
From that comes:
```
1..2
ok 1
not ok 2
# Failed test (test.pl at line 5)
# Looks like you failed 1 tests of 2.
```
`1..2` "I'm going to run two tests." This number is a *plan*. It helps to ensure your test program ran all the way through and didn't die or skip some tests. `ok 1` "The first test passed." `not ok 2` "The second test failed". Test::Simple helpfully prints out some extra commentary about your tests.
It's not scary. Come, hold my hand. We're going to give an example of testing a module. For our example, we'll be testing a date library, <Date::ICal>. It's on CPAN, so download a copy and follow along. [2]
###
Where to start?
This is the hardest part of testing, where do you start? People often get overwhelmed at the apparent enormity of the task of testing a whole module. The best place to start is at the beginning. <Date::ICal> is an object-oriented module, and that means you start by making an object. Test `new()`.
```
#!/usr/bin/perl -w
# assume these two lines are in all subsequent examples
use strict;
use warnings;
use Test::Simple tests => 2;
use Date::ICal;
my $ical = Date::ICal->new; # create an object
ok( defined $ical ); # check that we got something
ok( $ical->isa('Date::ICal') ); # and it's the right class
```
Run that and you should get:
```
1..2
ok 1
ok 2
```
Congratulations! You've written your first useful test.
### Names
That output isn't terribly descriptive, is it? When you have two tests you can figure out which one is #2, but what if you have 102 tests?
Each test can be given a little descriptive name as the second argument to `ok()`.
```
use Test::Simple tests => 2;
ok( defined $ical, 'new() returned something' );
ok( $ical->isa('Date::ICal'), " and it's the right class" );
```
Now you'll see:
```
1..2
ok 1 - new() returned something
ok 2 - and it's the right class
```
###
Test the manual
The simplest way to build up a decent testing suite is to just test what the manual says it does. [3] Let's pull something out of the ["SYNOPSIS" in Date::ICal](Date::ICal#SYNOPSIS) and test that all its bits work.
```
#!/usr/bin/perl -w
use Test::Simple tests => 8;
use Date::ICal;
$ical = Date::ICal->new( year => 1964, month => 10, day => 16,
hour => 16, min => 12, sec => 47,
tz => '0530' );
ok( defined $ical, 'new() returned something' );
ok( $ical->isa('Date::ICal'), " and it's the right class" );
ok( $ical->sec == 47, ' sec()' );
ok( $ical->min == 12, ' min()' );
ok( $ical->hour == 16, ' hour()' );
ok( $ical->day == 17, ' day()' );
ok( $ical->month == 10, ' month()' );
ok( $ical->year == 1964, ' year()' );
```
Run that and you get:
```
1..8
ok 1 - new() returned something
ok 2 - and it's the right class
ok 3 - sec()
ok 4 - min()
ok 5 - hour()
not ok 6 - day()
# Failed test (- at line 16)
ok 7 - month()
ok 8 - year()
# Looks like you failed 1 tests of 8.
```
Whoops, a failure! [4] <Test::Simple> helpfully lets us know on what line the failure occurred, but not much else. We were supposed to get 17, but we didn't. What did we get?? Dunno. You could re-run the test in the debugger or throw in some print statements to find out.
Instead, switch from <Test::Simple> to <Test::More>. <Test::More> does everything <Test::Simple> does, and more! In fact, <Test::More> does things *exactly* the way <Test::Simple> does. You can literally swap <Test::Simple> out and put <Test::More> in its place. That's just what we're going to do.
<Test::More> does more than <Test::Simple>. The most important difference at this point is it provides more informative ways to say "ok". Although you can write almost any test with a generic `ok()`, it can't tell you what went wrong. The `is()` function lets us declare that something is supposed to be the same as something else:
```
use Test::More tests => 8;
use Date::ICal;
$ical = Date::ICal->new( year => 1964, month => 10, day => 16,
hour => 16, min => 12, sec => 47,
tz => '0530' );
ok( defined $ical, 'new() returned something' );
ok( $ical->isa('Date::ICal'), " and it's the right class" );
is( $ical->sec, 47, ' sec()' );
is( $ical->min, 12, ' min()' );
is( $ical->hour, 16, ' hour()' );
is( $ical->day, 17, ' day()' );
is( $ical->month, 10, ' month()' );
is( $ical->year, 1964, ' year()' );
```
"Is `$ical->sec` 47?" "Is `$ical->min` 12?" With `is()` in place, you get more information:
```
1..8
ok 1 - new() returned something
ok 2 - and it's the right class
ok 3 - sec()
ok 4 - min()
ok 5 - hour()
not ok 6 - day()
# Failed test (- at line 16)
# got: '16'
# expected: '17'
ok 7 - month()
ok 8 - year()
# Looks like you failed 1 tests of 8.
```
Aha. `$ical->day` returned 16, but we expected 17. A quick check shows that the code is working fine, we made a mistake when writing the tests. Change it to:
```
is( $ical->day, 16, ' day()' );
```
... and everything works.
Any time you're doing a "this equals that" sort of test, use `is()`. It even works on arrays. The test is always in scalar context, so you can test how many elements are in an array this way. [5]
```
is( @foo, 5, 'foo has 5 elements' );
```
###
Sometimes the tests are wrong
This brings up a very important lesson. Code has bugs. Tests are code. Ergo, tests have bugs. A failing test could mean a bug in the code, but don't discount the possibility that the test is wrong.
On the flip side, don't be tempted to prematurely declare a test incorrect just because you're having trouble finding the bug. Invalidating a test isn't something to be taken lightly, and don't use it as a cop out to avoid work.
###
Testing lots of values
We're going to be wanting to test a lot of dates here, trying to trick the code with lots of different edge cases. Does it work before 1970? After 2038? Before 1904? Do years after 10,000 give it trouble? Does it get leap years right? We could keep repeating the code above, or we could set up a little try/expect loop.
```
use Test::More tests => 32;
use Date::ICal;
my %ICal_Dates = (
# An ICal string And the year, month, day
# hour, minute and second we expect.
'19971024T120000' => # from the docs.
[ 1997, 10, 24, 12, 0, 0 ],
'20390123T232832' => # after the Unix epoch
[ 2039, 1, 23, 23, 28, 32 ],
'19671225T000000' => # before the Unix epoch
[ 1967, 12, 25, 0, 0, 0 ],
'18990505T232323' => # before the MacOS epoch
[ 1899, 5, 5, 23, 23, 23 ],
);
while( my($ical_str, $expect) = each %ICal_Dates ) {
my $ical = Date::ICal->new( ical => $ical_str );
ok( defined $ical, "new(ical => '$ical_str')" );
ok( $ical->isa('Date::ICal'), " and it's the right class" );
is( $ical->year, $expect->[0], ' year()' );
is( $ical->month, $expect->[1], ' month()' );
is( $ical->day, $expect->[2], ' day()' );
is( $ical->hour, $expect->[3], ' hour()' );
is( $ical->min, $expect->[4], ' min()' );
is( $ical->sec, $expect->[5], ' sec()' );
}
```
Now we can test bunches of dates by just adding them to `%ICal_Dates`. Now that it's less work to test with more dates, you'll be inclined to just throw more in as you think of them. Only problem is, every time we add to that we have to keep adjusting the `use Test::More tests => ##` line. That can rapidly get annoying. There are ways to make this work better.
First, we can calculate the plan dynamically using the `plan()` function.
```
use Test::More;
use Date::ICal;
my %ICal_Dates = (
...same as before...
);
# For each key in the hash we're running 8 tests.
plan tests => keys(%ICal_Dates) * 8;
...and then your tests...
```
To be even more flexible, use `done_testing`. This means we're just running some tests, don't know how many. [6]
```
use Test::More; # instead of tests => 32
... # tests here
done_testing(); # reached the end safely
```
If you don't specify a plan, <Test::More> expects to see `done_testing()` before your program exits. It will warn you if you forget it. You can give `done_testing()` an optional number of tests you expected to run, and if the number ran differs, <Test::More> will give you another kind of warning.
###
Informative names
Take a look at the line:
```
ok( defined $ical, "new(ical => '$ical_str')" );
```
We've added more detail about what we're testing and the ICal string itself we're trying out to the name. So you get results like:
```
ok 25 - new(ical => '19971024T120000')
ok 26 - and it's the right class
ok 27 - year()
ok 28 - month()
ok 29 - day()
ok 30 - hour()
ok 31 - min()
ok 32 - sec()
```
If something in there fails, you'll know which one it was and that will make tracking down the problem easier. Try to put a bit of debugging information into the test names.
Describe what the tests test, to make debugging a failed test easier for you or for the next person who runs your test.
###
Skipping tests
Poking around in the existing <Date::ICal> tests, I found this in *t/01sanity.t* [7]
```
#!/usr/bin/perl -w
use Test::More tests => 7;
use Date::ICal;
# Make sure epoch time is being handled sanely.
my $t1 = Date::ICal->new( epoch => 0 );
is( $t1->epoch, 0, "Epoch time of 0" );
# XXX This will only work on unix systems.
is( $t1->ical, '19700101Z', " epoch to ical" );
is( $t1->year, 1970, " year()" );
is( $t1->month, 1, " month()" );
is( $t1->day, 1, " day()" );
# like the tests above, but starting with ical instead of epoch
my $t2 = Date::ICal->new( ical => '19700101Z' );
is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" );
is( $t2->epoch, 0, " and back to ICal" );
```
The beginning of the epoch is different on most non-Unix operating systems [8]. Even though Perl smooths out the differences for the most part, certain ports do it differently. MacPerl is one off the top of my head. [9] Rather than putting a comment in the test and hoping someone will read the test while debugging the failure, we can explicitly say it's never going to work and skip the test.
```
use Test::More tests => 7;
use Date::ICal;
# Make sure epoch time is being handled sanely.
my $t1 = Date::ICal->new( epoch => 0 );
is( $t1->epoch, 0, "Epoch time of 0" );
SKIP: {
skip('epoch to ICal not working on Mac OS', 6)
if $^O eq 'MacOS';
is( $t1->ical, '19700101Z', " epoch to ical" );
is( $t1->year, 1970, " year()" );
is( $t1->month, 1, " month()" );
is( $t1->day, 1, " day()" );
# like the tests above, but starting with ical instead of epoch
my $t2 = Date::ICal->new( ical => '19700101Z' );
is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" );
is( $t2->epoch, 0, " and back to ICal" );
}
```
A little bit of magic happens here. When running on anything but MacOS, all the tests run normally. But when on MacOS, `skip()` causes the entire contents of the SKIP block to be jumped over. It never runs. Instead, `skip()` prints special output that tells <Test::Harness> that the tests have been skipped.
```
1..7
ok 1 - Epoch time of 0
ok 2 # skip epoch to ICal not working on MacOS
ok 3 # skip epoch to ICal not working on MacOS
ok 4 # skip epoch to ICal not working on MacOS
ok 5 # skip epoch to ICal not working on MacOS
ok 6 # skip epoch to ICal not working on MacOS
ok 7 # skip epoch to ICal not working on MacOS
```
This means your tests won't fail on MacOS. This means fewer emails from MacPerl users telling you about failing tests that you know will never work. You've got to be careful with skip tests. These are for tests which don't work and *never will*. It is not for skipping genuine bugs (we'll get to that in a moment).
The tests are wholly and completely skipped. [10] This will work.
```
SKIP: {
skip("I don't wanna die!");
die, die, die, die, die;
}
```
###
Todo tests
While thumbing through the <Date::ICal> man page, I came across this:
```
ical
$ical_string = $ical->ical;
Retrieves, or sets, the date on the object, using any
valid ICal date/time string.
```
"Retrieves or sets". Hmmm. I didn't see a test for using `ical()` to set the date in the Date::ICal test suite. So I wrote one:
```
use Test::More tests => 1;
use Date::ICal;
my $ical = Date::ICal->new;
$ical->ical('20201231Z');
is( $ical->ical, '20201231Z', 'Setting via ical()' );
```
Run that. I saw:
```
1..1
not ok 1 - Setting via ical()
# Failed test (- at line 6)
# got: '20010814T233649Z'
# expected: '20201231Z'
# Looks like you failed 1 tests of 1.
```
Whoops! Looks like it's unimplemented. Assume you don't have the time to fix this. [11] Normally, you'd just comment out the test and put a note in a todo list somewhere. Instead, explicitly state "this test will fail" by wrapping it in a `TODO` block:
```
use Test::More tests => 1;
TODO: {
local $TODO = 'ical($ical) not yet implemented';
my $ical = Date::ICal->new;
$ical->ical('20201231Z');
is( $ical->ical, '20201231Z', 'Setting via ical()' );
}
```
Now when you run, it's a little different:
```
1..1
not ok 1 - Setting via ical() # TODO ical($ical) not yet implemented
# got: '20010822T201551Z'
# expected: '20201231Z'
```
<Test::More> doesn't say "Looks like you failed 1 tests of 1". That '# TODO' tells <Test::Harness> "this is supposed to fail" and it treats a failure as a successful test. You can write tests even before you've fixed the underlying code.
If a TODO test passes, <Test::Harness> will report it "UNEXPECTEDLY SUCCEEDED". When that happens, remove the TODO block with `local $TODO` and turn it into a real test.
###
Testing with taint mode.
Taint mode is a funny thing. It's the globalest of all global features. Once you turn it on, it affects *all* code in your program and *all* modules used (and all the modules they use). If a single piece of code isn't taint clean, the whole thing explodes. With that in mind, it's very important to ensure your module works under taint mode.
It's very simple to have your tests run under taint mode. Just throw a `-T` into the `#!` line. <Test::Harness> will read the switches in `#!` and use them to run your tests.
```
#!/usr/bin/perl -Tw
...test normally here...
```
When you say `make test` it will run with taint mode on.
FOOTNOTES
---------
1. The first number doesn't really mean anything, but it has to be 1. It's the second number that's important.
2. For those following along at home, I'm using version 1.31. It has some bugs, which is good -- we'll uncover them with our tests.
3. You can actually take this one step further and test the manual itself. Have a look at <Test::Inline> (formerly <Pod::Tests>).
4. Yes, there's a mistake in the test suite. What! Me, contrived?
5. We'll get to testing the contents of lists later.
6. But what happens if your test program dies halfway through?! Since we didn't say how many tests we're going to run, how can we know it failed? No problem, <Test::More> employs some magic to catch that death and turn the test into a failure, even if every test passed up to that point.
7. I cleaned it up a little.
8. Most Operating Systems record time as the number of seconds since a certain date. This date is the beginning of the epoch. Unix's starts at midnight January 1st, 1970 GMT.
9. MacOS's epoch is midnight January 1st, 1904. VMS's is midnight, November 17th, 1858, but vmsperl emulates the Unix epoch so it's not a problem.
10. As long as the code inside the SKIP block at least compiles. Please don't ask how. No, it's not a filter.
11. Do NOT be tempted to use TODO tests as a way to avoid fixing simple bugs!
AUTHORS
-------
Michael G Schwern <[email protected]> and the perl-qa dancers!
MAINTAINERS
-----------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2001 by Michael G Schwern <[email protected]>.
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 these files 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 perlqnx perlqnx
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Required Software for Compiling Perl on QNX4](#Required-Software-for-Compiling-Perl-on-QNX4)
+ [Outstanding Issues with Perl on QNX4](#Outstanding-Issues-with-Perl-on-QNX4)
+ [QNX auxiliary files](#QNX-auxiliary-files)
+ [Outstanding issues with perl under QNX6](#Outstanding-issues-with-perl-under-QNX6)
+ [Cross-compilation](#Cross-compilation)
- [Setting up a cross-compilation environment](#Setting-up-a-cross-compilation-environment)
- [Preparing the target system](#Preparing-the-target-system)
- [Calling Configure](#Calling-Configure)
* [AUTHOR](#AUTHOR)
NAME
----
perlqnx - Perl version 5 on QNX
DESCRIPTION
-----------
As of perl5.7.2 all tests pass under:
```
QNX 4.24G
Watcom 10.6 with Beta/970211.wcc.update.tar.F
socket3r.lib Nov21 1996.
```
As of perl5.8.1 there is at least one test still failing.
Some tests may complain under known circumstances.
See below and hints/qnx.sh for more information.
Under QNX 6.2.0 there are still a few tests which fail. See below and hints/qnx.sh for more information.
###
Required Software for Compiling Perl on QNX4
As with many unix ports, this one depends on a few "standard" unix utilities which are not necessarily standard for QNX4.
/bin/sh This is used heavily by Configure and then by perl itself. QNX4's version is fine, but Configure will choke on the 16-bit version, so if you are running QNX 4.22, link /bin/sh to /bin32/ksh
ar This is the standard unix library builder. We use wlib. With Watcom 10.6, when wlib is linked as "ar", it behaves like ar and all is fine. Under 9.5, a cover is required. One is included in ../qnx
nm This is used (optionally) by configure to list the contents of libraries. I will generate a cover function on the fly in the UU directory.
cpp Configure and perl need a way to invoke a C preprocessor. I have created a simple cover for cc which does the right thing. Without this, Configure will create its own wrapper which works, but it doesn't handle some of the command line arguments that perl will throw at it.
make You really need GNU make to compile this. GNU make ships by default with QNX 4.23, but you can get it from quics for earlier versions.
###
Outstanding Issues with Perl on QNX4
There is no support for dynamically linked libraries in QNX4.
If you wish to compile with the Socket extension, you need to have the TCP/IP toolkit, and you need to make sure that -lsocket locates the correct copy of socket3r.lib. Beware that the Watcom compiler ships with a stub version of socket3r.lib which has very little functionality. Also beware the order in which wlink searches directories for libraries. You may have /usr/lib/socket3r.lib pointing to the correct library, but wlink may pick up /usr/watcom/10.6/usr/lib/socket3r.lib instead. Make sure they both point to the correct library, that is, /usr/tcptk/current/usr/lib/socket3r.lib.
The following tests may report errors under QNX4:
dist/Cwd/Cwd.t will complain if `pwd` and cwd don't give the same results. cwd calls `fullpath -t`, so if you cd `fullpath -t` before running the test, it will pass.
lib/File/Find/taint.t will complain if '.' is in your PATH. The PATH test is triggered because cwd calls `fullpath -t`.
ext/IO/lib/IO/t/io\_sock.t: Subtests 14 and 22 are skipped due to the fact that the functionality to read back the non-blocking status of a socket is not implemented in QNX's TCP/IP. This has been reported to QNX and it may work with later versions of TCP/IP.
t/io/tell.t: Subtest 27 is failing. We are still investigating.
###
QNX auxiliary files
The files in the "qnx" directory are:
qnx/ar A script that emulates the standard unix archive (aka library) utility. Under Watcom 10.6, ar is linked to wlib and provides the expected interface. With Watcom 9.5, a cover function is required. This one is fairly crude but has proved adequate for compiling perl.
qnx/cpp A script that provides C preprocessing functionality. Configure can generate a similar cover, but it doesn't handle all the command-line options that perl throws at it. This might be reasonably placed in /usr/local/bin.
###
Outstanding issues with perl under QNX6
The following tests are still failing for Perl 5.8.1 under QNX 6.2.0:
```
op/sprintf.........................FAILED at test 91
lib/Benchmark......................FAILED at test 26
```
This is due to a bug in the C library's printf routine. printf("'%e'", 0. ) produces '0.000000e+0', but ANSI requires '0.000000e+00'. QNX has acknowledged the bug.
###
Cross-compilation
Perl supports cross-compiling to QNX NTO through the Native Development Kit (NDK) for the Blackberry 10. This means that you can cross-compile for both ARM and x86 versions of the platform.
####
Setting up a cross-compilation environment
You can download the NDK from <http://developer.blackberry.com/native/downloads/>.
See <http://developer.blackberry.com/native/documentation/cascades/getting_started/setting_up.html> for instructions to set up your device prior to attempting anything else.
Once you've installed the NDK and set up your device, all that's left to do is setting up the device and the cross-compilation environment. Blackberry provides a script, `bbndk-env.sh` (occasionally named something like `bbndk-env_10_1_0_4828.sh`) which can be used to do this. However, there's a bit of a snag that we have to work through: The script modifies PATH so that 'gcc' or 'ar' point to their cross-compilation equivalents, which screws over the build process.
So instead you'll want to do something like this:
```
$ orig_path=$PATH
$ source $location_of_bbndk/bbndk-env*.sh
$ export PATH="$orig_path:$PATH"
```
Besides putting the cross-compiler and the rest of the toolchain in your PATH, this will also provide the QNX\_TARGET variable, which we will pass to Configure through -Dsysroot.
####
Preparing the target system
It's quite possible that the target system doesn't have a readily available /tmp, so it's generally safer to do something like this:
```
$ ssh $TARGETUSER@$TARGETHOST 'rm -rf perl; mkdir perl; mkdir perl/tmp'
$ export TARGETDIR=`ssh $TARGETUSER@$TARGETHOST pwd`/perl
$ export TARGETENV="export TMPDIR=$TARGETDIR/tmp; "
```
Later on, we'll pass this to Configure through -Dtargetenv
####
Calling Configure
If you are targetting an ARM device -- which currently includes the vast majority of phones and tablets -- you'll want to pass -Dcc=arm-unknown-nto-qnx8.0.0eabi-gcc to Configure. Alternatively, if you are targetting an x86 device, or using the simulator provided with the NDK, you should specify -Dcc=ntox86-gcc instead.
A sample Configure invocation looks something like this:
```
./Configure -des -Dusecrosscompile \
-Dsysroot=$QNX_TARGET \
-Dtargetdir=$TARGETDIR \
-Dtargetenv="$TARGETENV" \
-Dcc=ntox86-gcc \
-Dtarghost=... # Usual cross-compilation options
```
AUTHOR
------
Norton T. Allen ([email protected])
perl CPAN::Meta::Prereqs CPAN::Meta::Prereqs
===================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [requirements\_for](#requirements_for)
+ [phases](#phases)
+ [types\_in](#types_in)
+ [with\_merged\_prereqs](#with_merged_prereqs)
+ [merged\_requirements](#merged_requirements)
+ [as\_string\_hash](#as_string_hash)
+ [is\_finalized](#is_finalized)
+ [finalize](#finalize)
+ [clone](#clone)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Prereqs - a set of distribution prerequisites by phase and type
VERSION
-------
version 2.150010
DESCRIPTION
-----------
A CPAN::Meta::Prereqs object represents the prerequisites for a CPAN distribution or one of its optional features. Each set of prereqs is organized by phase and type, as described in <CPAN::Meta::Prereqs>.
METHODS
-------
### new
```
my $prereq = CPAN::Meta::Prereqs->new( \%prereq_spec );
```
This method returns a new set of Prereqs. The input should look like the contents of the `prereqs` field described in <CPAN::Meta::Spec>, meaning something more or less like this:
```
my $prereq = CPAN::Meta::Prereqs->new({
runtime => {
requires => {
'Some::Module' => '1.234',
...,
},
...,
},
...,
});
```
You can also construct an empty set of prereqs with:
```
my $prereqs = CPAN::Meta::Prereqs->new;
```
This empty set of prereqs is useful for accumulating new prereqs before finally dumping the whole set into a structure or string.
### requirements\_for
```
my $requirements = $prereqs->requirements_for( $phase, $type );
```
This method returns a <CPAN::Meta::Requirements> object for the given phase/type combination. If no prerequisites are registered for that combination, a new CPAN::Meta::Requirements object will be returned, and it may be added to as needed.
If `$phase` or `$type` are undefined or otherwise invalid, an exception will be raised.
### phases
```
my @phases = $prereqs->phases;
```
This method returns the list of all phases currently populated in the prereqs object, suitable for iterating.
### types\_in
```
my @runtime_types = $prereqs->types_in('runtime');
```
This method returns the list of all types currently populated in the prereqs object for the provided phase, suitable for iterating.
### with\_merged\_prereqs
```
my $new_prereqs = $prereqs->with_merged_prereqs( $other_prereqs );
my $new_prereqs = $prereqs->with_merged_prereqs( \@other_prereqs );
```
This method returns a new CPAN::Meta::Prereqs objects in which all the other prerequisites given are merged into the current set. This is primarily provided for combining a distribution's core prereqs with the prereqs of one of its optional features.
The new prereqs object has no ties to the originals, and altering it further will not alter them.
### merged\_requirements
```
my $new_reqs = $prereqs->merged_requirements( \@phases, \@types );
my $new_reqs = $prereqs->merged_requirements( \@phases );
my $new_reqs = $prereqs->merged_requirements();
```
This method joins together all requirements across a number of phases and types into a new <CPAN::Meta::Requirements> object. If arguments are omitted, it defaults to "runtime", "build" and "test" for phases and "requires" and "recommends" for types.
### as\_string\_hash
This method returns a hashref containing structures suitable for dumping into a distmeta data structure. It is made up of hashes and strings, only; there will be no Prereqs, CPAN::Meta::Requirements, or `version` objects inside it.
### is\_finalized
This method returns true if the set of prereqs has been marked "finalized," and cannot be altered.
### finalize
Calling `finalize` on a Prereqs object will close it for further modification. Attempting to make any changes that would actually alter the prereqs will result in an exception being thrown.
### clone
```
my $cloned_prereqs = $prereqs->clone;
```
This method returns a Prereqs object that is identical to the original object, but can be altered without affecting the original object. Finalization does not survive cloning, meaning that you may clone a finalized set of prereqs and then modify the clone.
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 CPAN::Meta::Feature CPAN::Meta::Feature
===================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [identifier](#identifier)
+ [description](#description)
+ [prereqs](#prereqs)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Feature - an optional feature provided by a CPAN distribution
VERSION
-------
version 2.150010
DESCRIPTION
-----------
A CPAN::Meta::Feature object describes an optional feature offered by a CPAN distribution and specified in the distribution's *META.json* (or *META.yml*) file.
For the most part, this class will only be used when operating on the result of the `feature` or `features` methods on a <CPAN::Meta> object.
METHODS
-------
### new
```
my $feature = CPAN::Meta::Feature->new( $identifier => \%spec );
```
This returns a new Feature object. The `%spec` argument to the constructor should be the same as the value of the `optional_feature` entry in the distmeta. It must contain entries for `description` and `prereqs`.
### identifier
This method returns the feature's identifier.
### description
This method returns the feature's long description.
### prereqs
This method returns the feature's prerequisites as a <CPAN::Meta::Prereqs> object.
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 Data::Dumper Data::Dumper
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods](#Methods)
+ [Functions](#Functions)
+ [Configuration Variables or Methods](#Configuration-Variables-or-Methods)
+ [Exports](#Exports)
* [EXAMPLES](#EXAMPLES)
* [BUGS](#BUGS)
+ [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
* [VERSION](#VERSION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Data::Dumper - stringified perl data structures, suitable for both printing and `eval`
SYNOPSIS
--------
```
use Data::Dumper;
# simple procedural interface
print Dumper($foo, $bar);
# extended usage with names
print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
# configuration variables
{
local $Data::Dumper::Purity = 1;
eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
}
# OO usage
$d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
...
print $d->Dump;
...
$d->Purity(1)->Terse(1)->Deepcopy(1);
eval $d->Dump;
```
DESCRIPTION
-----------
Given a list of scalars or reference variables, writes out their contents in perl syntax. The references can also be objects. The content of each variable is output in a single Perl statement. Handles self-referential structures correctly.
The return value can be `eval`ed to get back an identical copy of the original reference structure. (Please do consider the security implications of eval'ing code from untrusted sources!)
Any references that are the same as one of those passed in will be named `$VAR`*n* (where *n* is a numeric suffix), and other duplicate references to substructures within `$VAR`*n* will be appropriately labeled using arrow notation. You can specify names for individual values to be dumped if you use the `Dump()` method, or you can change the default `$VAR` prefix to something else. See `$Data::Dumper::Varname` and `$Data::Dumper::Terse` below.
The default output of self-referential structures can be `eval`ed, but the nested references to `$VAR`*n* will be undefined, since a recursive structure cannot be constructed using one Perl statement. You should set the `Purity` flag to 1 to get additional statements that will correctly fill in these references. Moreover, if `eval`ed when strictures are in effect, you need to ensure that any variables it accesses are previously declared.
In the extended usage form, the references to be dumped can be given user-specified names. If a name begins with a `*`, the output will describe the dereferenced type of the supplied reference for hashes and arrays, and coderefs. Output of names will be avoided where possible if the `Terse` flag is set.
In many cases, methods that are used to set the internal state of the object will return the object itself, so method calls can be conveniently chained together.
Several styles of output are possible, all controlled by setting the `Indent` flag. See ["Configuration Variables or Methods"](#Configuration-Variables-or-Methods) below for details.
### Methods
*PACKAGE*->new(*ARRAYREF [*, *ARRAYREF]*) Returns a newly created `Data::Dumper` object. The first argument is an anonymous array of values to be dumped. The optional second argument is an anonymous array of names for the values. The names need not have a leading `$` sign, and must be comprised of alphanumeric characters. You can begin a name with a `*` to specify that the dereferenced type must be dumped instead of the reference itself, for ARRAY and HASH references.
The prefix specified by `$Data::Dumper::Varname` will be used with a numeric suffix if the name for a value is undefined.
Data::Dumper will catalog all references encountered while dumping the values. Cross-references (in the form of names of substructures in perl syntax) will be inserted at all possible points, preserving any structural interdependencies in the original set of values. Structure traversal is depth-first, and proceeds in order from the first supplied value to the last.
*$OBJ*->Dump *or* *PACKAGE*->Dump(*ARRAYREF [*, *ARRAYREF]*) Returns the stringified form of the values stored in the object (preserving the order in which they were supplied to `new`), subject to the configuration options below. In a list context, it returns a list of strings corresponding to the supplied values.
The second form, for convenience, simply calls the `new` method on its arguments before dumping the object immediately.
*$OBJ*->Seen(*[HASHREF]*) Queries or adds to the internal table of already encountered references. You must use `Reset` to explicitly clear the table if needed. Such references are not dumped; instead, their names are inserted wherever they are encountered subsequently. This is useful especially for properly dumping subroutine references.
Expects an anonymous hash of name => value pairs. Same rules apply for names as in `new`. If no argument is supplied, will return the "seen" list of name => value pairs, in a list context. Otherwise, returns the object itself.
*$OBJ*->Values(*[ARRAYREF]*) Queries or replaces the internal array of values that will be dumped. When called without arguments, returns the values as a list. When called with a reference to an array of replacement values, returns the object itself. When called with any other type of argument, dies.
*$OBJ*->Names(*[ARRAYREF]*) Queries or replaces the internal array of user supplied names for the values that will be dumped. When called without arguments, returns the names. When called with an array of replacement names, returns the object itself. If the number of replacement names exceeds the number of values to be named, the excess names will not be used. If the number of replacement names falls short of the number of values to be named, the list of replacement names will be exhausted and remaining values will not be renamed. When called with any other type of argument, dies.
*$OBJ*->Reset Clears the internal table of "seen" references and returns the object itself.
### Functions
Dumper(*LIST*) Returns the stringified form of the values in the list, subject to the configuration options below. The values will be named `$VAR`*n* in the output, where *n* is a numeric suffix. Will return a list of strings in a list context.
###
Configuration Variables or Methods
Several configuration variables can be used to control the kind of output generated when using the procedural interface. These variables are usually `local`ized in a block so that other parts of the code are not affected by the change.
These variables determine the default state of the object created by calling the `new` method, but cannot be used to alter the state of the object thereafter. The equivalent method names should be used instead to query or set the internal state of the object.
The method forms return the object itself when called with arguments, so that they can be chained together nicely.
* $Data::Dumper::Indent *or* *$OBJ*->Indent(*[NEWVAL]*)
Controls the style of indentation. It can be set to 0, 1, 2 or 3. Style 0 spews output without any newlines, indentation, or spaces between list items. It is the most compact format possible that can still be called valid perl. Style 1 outputs a readable form with newlines but no fancy indentation (each level in the structure is simply indented by a fixed amount of whitespace). Style 2 (the default) outputs a very readable form which lines up the hash keys. Style 3 is like style 2, but also annotates the elements of arrays with their index (but the comment is on its own line, so array output consumes twice the number of lines). Style 2 is the default.
* $Data::Dumper::Trailingcomma *or* *$OBJ*->Trailingcomma(*[NEWVAL]*)
Controls whether a comma is added after the last element of an array or hash. Even when true, no comma is added between the last element of an array or hash and a closing bracket when they appear on the same line. The default is false.
* $Data::Dumper::Purity *or* *$OBJ*->Purity(*[NEWVAL]*)
Controls the degree to which the output can be `eval`ed to recreate the supplied reference structures. Setting it to 1 will output additional perl statements that will correctly recreate nested references. The default is 0.
* $Data::Dumper::Pad *or* *$OBJ*->Pad(*[NEWVAL]*)
Specifies the string that will be prefixed to every line of the output. Empty string by default.
* $Data::Dumper::Varname *or* *$OBJ*->Varname(*[NEWVAL]*)
Contains the prefix to use for tagging variable names in the output. The default is "VAR".
* $Data::Dumper::Useqq *or* *$OBJ*->Useqq(*[NEWVAL]*)
When set, enables the use of double quotes for representing string values. Whitespace other than space will be represented as `[\n\t\r]`, "unsafe" characters will be backslashed, and unprintable characters will be output as quoted octal integers. The default is 0.
* $Data::Dumper::Terse *or* *$OBJ*->Terse(*[NEWVAL]*)
When set, Data::Dumper will emit single, non-self-referential values as atoms/terms rather than statements. This means that the `$VAR`*n* names will be avoided where possible, but be advised that such output may not always be parseable by `eval`.
* $Data::Dumper::Freezer *or* $*OBJ*->Freezer(*[NEWVAL]*)
Can be set to a method name, or to an empty string to disable the feature. Data::Dumper will invoke that method via the object before attempting to stringify it. This method can alter the contents of the object (if, for instance, it contains data allocated from C), and even rebless it in a different package. The client is responsible for making sure the specified method can be called via the object, and that the object ends up containing only perl data types after the method has been called. Defaults to an empty string.
If an object does not support the method specified (determined using UNIVERSAL::can()) then the call will be skipped. If the method dies a warning will be generated.
* $Data::Dumper::Toaster *or* $*OBJ*->Toaster(*[NEWVAL]*)
Can be set to a method name, or to an empty string to disable the feature. Data::Dumper will emit a method call for any objects that are to be dumped using the syntax `bless(DATA, CLASS)->METHOD()`. Note that this means that the method specified will have to perform any modifications required on the object (like creating new state within it, and/or reblessing it in a different package) and then return it. The client is responsible for making sure the method can be called via the object, and that it returns a valid object. Defaults to an empty string.
* $Data::Dumper::Deepcopy *or* $*OBJ*->Deepcopy(*[NEWVAL]*)
Can be set to a boolean value to enable deep copies of structures. Cross-referencing will then only be done when absolutely essential (i.e., to break reference cycles). Default is 0.
* $Data::Dumper::Quotekeys *or* $*OBJ*->Quotekeys(*[NEWVAL]*)
Can be set to a boolean value to control whether hash keys are quoted. A defined false value will avoid quoting hash keys when it looks like a simple string. Default is 1, which will always enclose hash keys in quotes.
* $Data::Dumper::Bless *or* $*OBJ*->Bless(*[NEWVAL]*)
Can be set to a string that specifies an alternative to the `bless` builtin operator used to create objects. A function with the specified name should exist, and should accept the same arguments as the builtin. Default is `bless`.
* $Data::Dumper::Pair *or* $*OBJ*->Pair(*[NEWVAL]*)
Can be set to a string that specifies the separator between hash keys and values. To dump nested hash, array and scalar values to JavaScript, use: `$Data::Dumper::Pair = ' : ';`. Implementing `bless` in JavaScript is left as an exercise for the reader. A function with the specified name exists, and accepts the same arguments as the builtin.
Default is: `=>` .
* $Data::Dumper::Maxdepth *or* $*OBJ*->Maxdepth(*[NEWVAL]*)
Can be set to a positive integer that specifies the depth beyond which we don't venture into a structure. Has no effect when `Data::Dumper::Purity` is set. (Useful in debugger when we often don't want to see more than enough). Default is 0, which means there is no maximum depth.
* $Data::Dumper::Maxrecurse *or* $*OBJ*->Maxrecurse(*[NEWVAL]*)
Can be set to a positive integer that specifies the depth beyond which recursion into a structure will throw an exception. This is intended as a security measure to prevent perl running out of stack space when dumping an excessively deep structure. Can be set to 0 to remove the limit. Default is 1000.
* $Data::Dumper::Useperl *or* $*OBJ*->Useperl(*[NEWVAL]*)
Can be set to a boolean value which controls whether the pure Perl implementation of `Data::Dumper` is used. The `Data::Dumper` module is a dual implementation, with almost all functionality written in both pure Perl and also in XS ('C'). Since the XS version is much faster, it will always be used if possible. This option lets you override the default behavior, usually for testing purposes only. Default is 0, which means the XS implementation will be used if possible.
* $Data::Dumper::Sortkeys *or* $*OBJ*->Sortkeys(*[NEWVAL]*)
Can be set to a boolean value to control whether hash keys are dumped in sorted order. A true value will cause the keys of all hashes to be dumped in Perl's default sort order. Can also be set to a subroutine reference which will be called for each hash that is dumped. In this case `Data::Dumper` will call the subroutine once for each hash, passing it the reference of the hash. The purpose of the subroutine is to return a reference to an array of the keys that will be dumped, in the order that they should be dumped. Using this feature, you can control both the order of the keys, and which keys are actually used. In other words, this subroutine acts as a filter by which you can exclude certain keys from being dumped. Default is 0, which means that hash keys are not sorted.
* $Data::Dumper::Deparse *or* $*OBJ*->Deparse(*[NEWVAL]*)
Can be set to a boolean value to control whether code references are turned into perl source code. If set to a true value, `B::Deparse` will be used to get the source of the code reference. In older versions, using this option imposed a significant performance penalty when dumping parts of a data structure other than code references, but that is no longer the case.
Caution : use this option only if you know that your coderefs will be properly reconstructed by `B::Deparse`.
* $Data::Dumper::Sparseseen *or* $*OBJ*->Sparseseen(*[NEWVAL]*)
By default, Data::Dumper builds up the "seen" hash of scalars that it has encountered during serialization. This is very expensive. This seen hash is necessary to support and even just detect circular references. It is exposed to the user via the `Seen()` call both for writing and reading.
If you, as a user, do not need explicit access to the "seen" hash, then you can set the `Sparseseen` option to allow Data::Dumper to eschew building the "seen" hash for scalars that are known not to possess more than one reference. This speeds up serialization considerably if you use the XS implementation.
Note: If you turn on `Sparseseen`, then you must not rely on the content of the seen hash since its contents will be an implementation detail!
### Exports
Dumper EXAMPLES
--------
Run these code snippets to get a quick feel for the behavior of this module. When you are through with these examples, you may want to add or change the various configuration variables described above, to see their behavior. (See the testsuite in the Data::Dumper distribution for more examples.)
```
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
$Data::Dumper::Pair = " : "; # specify hash key/value separator
print Dumper($boo);
########
# recursive structures
########
@c = ('c');
$c = \@c;
$b = {};
$a = [1, $b, $c];
$b->{a} = $a;
$b->{b} = $a->[1];
$b->{c} = $a->[2];
print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
$Data::Dumper::Purity = 1; # fill in the holes for eval
print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
$Data::Dumper::Deepcopy = 1; # avoid cross-refs
print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
$Data::Dumper::Purity = 0; # avoid cross-refs
print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
########
# deep structures
########
$a = "pearl";
$b = [ $a ];
$c = { 'b' => $b };
$d = [ $c ];
$e = { 'd' => $d };
$f = { 'e' => $e };
print Data::Dumper->Dump([$f], [qw(f)]);
$Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
print Data::Dumper->Dump([$f], [qw(f)]);
########
# object-oriented usage
########
$d = Data::Dumper->new([$a,$b], [qw(a b)]);
$d->Seen({'*c' => $c}); # stash a ref without printing it
$d->Indent(3);
print $d->Dump;
$d->Reset->Purity(0); # empty the seen cache
print join "----\n", $d->Dump;
########
# persistence
########
package Foo;
sub new { bless { state => 'awake' }, shift }
sub Freeze {
my $s = shift;
print STDERR "preparing to sleep\n";
$s->{state} = 'asleep';
return bless $s, 'Foo::ZZZ';
}
package Foo::ZZZ;
sub Thaw {
my $s = shift;
print STDERR "waking up\n";
$s->{state} = 'awake';
return bless $s, 'Foo';
}
package main;
use Data::Dumper;
$a = Foo->new;
$b = Data::Dumper->new([$a], ['c']);
$b->Freezer('Freeze');
$b->Toaster('Thaw');
$c = $b->Dump;
print $c;
$d = eval $c;
print Data::Dumper->Dump([$d], ['d']);
########
# symbol substitution (useful for recreating CODE refs)
########
sub foo { print "foo speaking\n" }
*other = \&foo;
$bar = [ \&other ];
$d = Data::Dumper->new([\&other,$bar],['*other','bar']);
$d->Seen({ '*foo' => \&foo });
print $d->Dump;
########
# sorting and filtering hash keys
########
$Data::Dumper::Sortkeys = \&my_filter;
my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
my $bar = { %$foo };
my $baz = { reverse %$foo };
print Dumper [ $foo, $bar, $baz ];
sub my_filter {
my ($hash) = @_;
# return an array ref containing the hash keys to dump
# in the order that you want them to be dumped
return [
# Sort the keys of %$foo in reverse numeric order
$hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
# Only dump the odd number keys of %$bar
$hash eq $bar ? (grep {$_ % 2} keys %$hash) :
# Sort keys in default order for all other hashes
(sort keys %$hash)
];
}
```
BUGS
----
Due to limitations of Perl subroutine call semantics, you cannot pass an array or hash. Prepend it with a `\` to pass its reference instead. This will be remedied in time, now that Perl has subroutine prototypes. For now, you need to use the extended usage form, and prepend the name with a `*` to output it as a hash or array.
`Data::Dumper` cheats with CODE references. If a code reference is encountered in the structure being processed (and if you haven't set the `Deparse` flag), an anonymous subroutine that contains the string '"DUMMY"' will be inserted in its place, and a warning will be printed if `Purity` is set. You can `eval` the result, but bear in mind that the anonymous sub that gets created is just a placeholder. Even using the `Deparse` flag will in some cases produce results that behave differently after being passed to `eval`; see the documentation for <B::Deparse>.
SCALAR objects have the weirdest looking `bless` workaround.
### NOTE
Different runs of Perl will have different ordering of hash keys. The change was done for greater security, see ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks). This means that different runs of Perl will have different Data::Dumper outputs if the data contains hashes. If you need to have identical Data::Dumper outputs from different runs of Perl, use the environment variable PERL\_HASH\_SEED, see ["PERL\_HASH\_SEED" in perlrun](perlrun#PERL_HASH_SEED). Using this restores the old (platform-specific) ordering: an even prettier solution might be to use the `Sortkeys` filter of Data::Dumper.
AUTHOR
------
Gurusamy Sarathy [email protected]
Copyright (c) 1996-2019 Gurusamy Sarathy. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
VERSION
-------
Version 2.184
SEE ALSO
---------
perl(1)
| programming_docs |
perl Encode Encode
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
+ [Table of Contents](#Table-of-Contents)
* [DESCRIPTION](#DESCRIPTION)
+ [TERMINOLOGY](#TERMINOLOGY)
- [character](#character)
- [byte](#byte)
- [octet](#octet)
* [THE PERL ENCODING API](#THE-PERL-ENCODING-API)
+ [Basic methods](#Basic-methods)
- [encode](#encode)
- [decode](#decode)
- [find\_encoding](#find_encoding)
- [find\_mime\_encoding](#find_mime_encoding)
- [from\_to](#from_to)
- [encode\_utf8](#encode_utf8)
- [decode\_utf8](#decode_utf8)
+ [Listing available encodings](#Listing-available-encodings)
+ [Defining Aliases](#Defining-Aliases)
+ [Finding IANA Character Set Registry names](#Finding-IANA-Character-Set-Registry-names)
* [Encoding via PerlIO](#Encoding-via-PerlIO)
* [Handling Malformed Data](#Handling-Malformed-Data)
+ [List of CHECK values](#List-of-CHECK-values)
- [FB\_DEFAULT](#FB_DEFAULT)
- [FB\_CROAK](#FB_CROAK)
- [FB\_QUIET](#FB_QUIET)
- [FB\_WARN](#FB_WARN)
- [FB\_PERLQQ FB\_HTMLCREF FB\_XMLCREF](#FB_PERLQQ-FB_HTMLCREF-FB_XMLCREF)
- [The bitmask](#The-bitmask)
- [LEAVE\_SRC](#LEAVE_SRC)
+ [coderef for CHECK](#coderef-for-CHECK)
* [Defining Encodings](#Defining-Encodings)
* [The UTF8 flag](#The-UTF8-flag)
+ [Messing with Perl's Internals](#Messing-with-Perl's-Internals)
- [is\_utf8](#is_utf8)
- [\_utf8\_on](#_utf8_on)
- [\_utf8\_off](#_utf8_off)
* [UTF-8 vs. utf8 vs. UTF8](#UTF-8-vs.-utf8-vs.-UTF8)
* [SEE ALSO](#SEE-ALSO)
* [MAINTAINER](#MAINTAINER)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Encode - character encodings in Perl
SYNOPSIS
--------
```
use Encode qw(decode encode);
$characters = decode('UTF-8', $octets, Encode::FB_CROAK);
$octets = encode('UTF-8', $characters, Encode::FB_CROAK);
```
###
Table of Contents
Encode consists of a collection of modules whose details are too extensive to fit in one document. This one itself explains the top-level APIs and general topics at a glance. For other topics and more details, see the documentation for these modules:
<Encode::Alias> - Alias definitions to encodings
<Encode::Encoding> - Encode Implementation Base Class
<Encode::Supported> - List of Supported Encodings
<Encode::CN> - Simplified Chinese Encodings
<Encode::JP> - Japanese Encodings
<Encode::KR> - Korean Encodings
<Encode::TW> - Traditional Chinese Encodings DESCRIPTION
-----------
The `Encode` module provides the interface between Perl strings and the rest of the system. Perl strings are sequences of *characters*.
The repertoire of characters that Perl can represent is a superset of those defined by the Unicode Consortium. On most platforms the ordinal values of a character as returned by `ord(*S*)` is the *Unicode codepoint* for that character. The exceptions are platforms where the legacy encoding is some variant of EBCDIC rather than a superset of ASCII; see <perlebcdic>.
During recent history, data is moved around a computer in 8-bit chunks, often called "bytes" but also known as "octets" in standards documents. Perl is widely used to manipulate data of many types: not only strings of characters representing human or computer languages, but also "binary" data, being the machine's representation of numbers, pixels in an image, or just about anything.
When Perl is processing "binary data", the programmer wants Perl to process "sequences of bytes". This is not a problem for Perl: because a byte has 256 possible values, it easily fits in Perl's much larger "logical character".
This document mostly explains the *how*. <perlunitut> and <perlunifaq> explain the *why*.
### TERMINOLOGY
#### character
A character in the range 0 .. 2\*\*32-1 (or more); what Perl's strings are made of.
#### byte
A character in the range 0..255; a special case of a Perl character.
#### octet
8 bits of data, with ordinal values 0..255; term for bytes passed to or from a non-Perl context, such as a disk file, standard I/O stream, database, command-line argument, environment variable, socket etc.
THE PERL ENCODING API
----------------------
###
Basic methods
#### encode
```
$octets = encode(ENCODING, STRING[, CHECK])
```
Encodes the scalar value *STRING* from Perl's internal form into *ENCODING* and returns a sequence of octets. *ENCODING* can be either a canonical name or an alias. For encoding names and aliases, see ["Defining Aliases"](#Defining-Aliases). For CHECK, see ["Handling Malformed Data"](#Handling-Malformed-Data).
**CAVEAT**: the input scalar *STRING* might be modified in-place depending on what is set in CHECK. See ["LEAVE\_SRC"](#LEAVE_SRC) if you want your inputs to be left unchanged.
For example, to convert a string from Perl's internal format into ISO-8859-1, also known as Latin1:
```
$octets = encode("iso-8859-1", $string);
```
**CAVEAT**: When you run `$octets = encode("UTF-8", $string)`, then $octets *might not be equal to* $string. Though both contain the same data, the UTF8 flag for $octets is *always* off. When you encode anything, the UTF8 flag on the result is always off, even when it contains a completely valid UTF-8 string. See ["The UTF8 flag"](#The-UTF8-flag) below.
If the $string is `undef`, then `undef` is returned.
`str2bytes` may be used as an alias for `encode`.
#### decode
```
$string = decode(ENCODING, OCTETS[, CHECK])
```
This function returns the string that results from decoding the scalar value *OCTETS*, assumed to be a sequence of octets in *ENCODING*, into Perl's internal form. As with encode(), *ENCODING* can be either a canonical name or an alias. For encoding names and aliases, see ["Defining Aliases"](#Defining-Aliases); for *CHECK*, see ["Handling Malformed Data"](#Handling-Malformed-Data).
**CAVEAT**: the input scalar *OCTETS* might be modified in-place depending on what is set in CHECK. See ["LEAVE\_SRC"](#LEAVE_SRC) if you want your inputs to be left unchanged.
For example, to convert ISO-8859-1 data into a string in Perl's internal format:
```
$string = decode("iso-8859-1", $octets);
```
**CAVEAT**: When you run `$string = decode("UTF-8", $octets)`, then $string *might not be equal to* $octets. Though both contain the same data, the UTF8 flag for $string is on. See ["The UTF8 flag"](#The-UTF8-flag) below.
If the $string is `undef`, then `undef` is returned.
`bytes2str` may be used as an alias for `decode`.
#### find\_encoding
```
[$obj =] find_encoding(ENCODING)
```
Returns the *encoding object* corresponding to *ENCODING*. Returns `undef` if no matching *ENCODING* is find. The returned object is what does the actual encoding or decoding.
```
$string = decode($name, $bytes);
```
is in fact
```
$string = do {
$obj = find_encoding($name);
croak qq(encoding "$name" not found) unless ref $obj;
$obj->decode($bytes);
};
```
with more error checking.
You can therefore save time by reusing this object as follows;
```
my $enc = find_encoding("iso-8859-1");
while(<>) {
my $string = $enc->decode($_);
... # now do something with $string;
}
```
Besides ["decode"](#decode) and ["encode"](#encode), other methods are available as well. For instance, `name()` returns the canonical name of the encoding object.
```
find_encoding("latin1")->name; # iso-8859-1
```
See <Encode::Encoding> for details.
#### find\_mime\_encoding
```
[$obj =] find_mime_encoding(MIME_ENCODING)
```
Returns the *encoding object* corresponding to *MIME\_ENCODING*. Acts same as `find_encoding()` but `mime_name()` of returned object must match to *MIME\_ENCODING*. So as opposite of `find_encoding()` canonical names and aliases are not used when searching for object.
```
find_mime_encoding("utf8"); # returns undef because "utf8" is not valid I<MIME_ENCODING>
find_mime_encoding("utf-8"); # returns encode object "utf-8-strict"
find_mime_encoding("UTF-8"); # same as "utf-8" because I<MIME_ENCODING> is case insensitive
find_mime_encoding("utf-8-strict"); returns undef because "utf-8-strict" is not valid I<MIME_ENCODING>
```
#### from\_to
```
[$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK])
```
Converts *in-place* data between two encodings. The data in $octets must be encoded as octets and *not* as characters in Perl's internal format. For example, to convert ISO-8859-1 data into Microsoft's CP1250 encoding:
```
from_to($octets, "iso-8859-1", "cp1250");
```
and to convert it back:
```
from_to($octets, "cp1250", "iso-8859-1");
```
Because the conversion happens in place, the data to be converted cannot be a string constant: it must be a scalar variable.
`from_to()` returns the length of the converted string in octets on success, and `undef` on error.
**CAVEAT**: The following operations may look the same, but are not:
```
from_to($data, "iso-8859-1", "UTF-8"); #1
$data = decode("iso-8859-1", $data); #2
```
Both #1 and #2 make $data consist of a completely valid UTF-8 string, but only #2 turns the UTF8 flag on. #1 is equivalent to:
```
$data = encode("UTF-8", decode("iso-8859-1", $data));
```
See ["The UTF8 flag"](#The-UTF8-flag) below.
Also note that:
```
from_to($octets, $from, $to, $check);
```
is equivalent to:
```
$octets = encode($to, decode($from, $octets), $check);
```
Yes, it does *not* respect the $check during decoding. It is deliberately done that way. If you need minute control, use `decode` followed by `encode` as follows:
```
$octets = encode($to, decode($from, $octets, $check_from), $check_to);
```
#### encode\_utf8
```
$octets = encode_utf8($string);
```
**WARNING**: [This function can produce invalid UTF-8!](#UTF-8-vs.-utf8-vs.-UTF8) Do not use it for data exchange. Unless you want Perl's older "lax" mode, prefer `$octets = encode("UTF-8", $string)`.
Equivalent to `$octets = encode("utf8", $string)`. The characters in $string are encoded in Perl's internal format, and the result is returned as a sequence of octets. Because all possible characters in Perl have a (loose, not strict) utf8 representation, this function cannot fail.
#### decode\_utf8
```
$string = decode_utf8($octets [, CHECK]);
```
**WARNING**: [This function accepts invalid UTF-8!](#UTF-8-vs.-utf8-vs.-UTF8) Do not use it for data exchange. Unless you want Perl's older "lax" mode, prefer `$string = decode("UTF-8", $octets [, CHECK])`.
Equivalent to `$string = decode("utf8", $octets [, CHECK])`. The sequence of octets represented by $octets is decoded from (loose, not strict) utf8 into a sequence of logical characters. Because not all sequences of octets are valid not strict utf8, it is quite possible for this function to fail. For CHECK, see ["Handling Malformed Data"](#Handling-Malformed-Data).
**CAVEAT**: the input *$octets* might be modified in-place depending on what is set in CHECK. See ["LEAVE\_SRC"](#LEAVE_SRC) if you want your inputs to be left unchanged.
###
Listing available encodings
```
use Encode;
@list = Encode->encodings();
```
Returns a list of canonical names of available encodings that have already been loaded. To get a list of all available encodings including those that have not yet been loaded, say:
```
@all_encodings = Encode->encodings(":all");
```
Or you can give the name of a specific module:
```
@with_jp = Encode->encodings("Encode::JP");
```
When "`::`" is not in the name, "`Encode::`" is assumed.
```
@ebcdic = Encode->encodings("EBCDIC");
```
To find out in detail which encodings are supported by this package, see <Encode::Supported>.
###
Defining Aliases
To add a new alias to a given encoding, use:
```
use Encode;
use Encode::Alias;
define_alias(NEWNAME => ENCODING);
```
After that, *NEWNAME* can be used as an alias for *ENCODING*. *ENCODING* may be either the name of an encoding or an *encoding object*.
Before you do that, first make sure the alias is nonexistent using `resolve_alias()`, which returns the canonical name thereof. For example:
```
Encode::resolve_alias("latin1") eq "iso-8859-1" # true
Encode::resolve_alias("iso-8859-12") # false; nonexistent
Encode::resolve_alias($name) eq $name # true if $name is canonical
```
`resolve_alias()` does not need `use Encode::Alias`; it can be imported via `use Encode qw(resolve_alias)`.
See <Encode::Alias> for details.
###
Finding IANA Character Set Registry names
The canonical name of a given encoding does not necessarily agree with IANA Character Set Registry, commonly seen as `Content-Type: text/plain; charset=*WHATEVER*`. For most cases, the canonical name works, but sometimes it does not, most notably with "utf-8-strict".
As of `Encode` version 2.21, a new method `mime_name()` is therefore added.
```
use Encode;
my $enc = find_encoding("UTF-8");
warn $enc->name; # utf-8-strict
warn $enc->mime_name; # UTF-8
```
See also: <Encode::Encoding>
Encoding via PerlIO
--------------------
If your perl supports `PerlIO` (which is the default), you can use a `PerlIO` layer to decode and encode directly via a filehandle. The following two examples are fully identical in functionality:
```
### Version 1 via PerlIO
open(INPUT, "< :encoding(shiftjis)", $infile)
|| die "Can't open < $infile for reading: $!";
open(OUTPUT, "> :encoding(euc-jp)", $outfile)
|| die "Can't open > $output for writing: $!";
while (<INPUT>) { # auto decodes $_
print OUTPUT; # auto encodes $_
}
close(INPUT) || die "can't close $infile: $!";
close(OUTPUT) || die "can't close $outfile: $!";
### Version 2 via from_to()
open(INPUT, "< :raw", $infile)
|| die "Can't open < $infile for reading: $!";
open(OUTPUT, "> :raw", $outfile)
|| die "Can't open > $output for writing: $!";
while (<INPUT>) {
from_to($_, "shiftjis", "euc-jp", 1); # switch encoding
print OUTPUT; # emit raw (but properly encoded) data
}
close(INPUT) || die "can't close $infile: $!";
close(OUTPUT) || die "can't close $outfile: $!";
```
In the first version above, you let the appropriate encoding layer handle the conversion. In the second, you explicitly translate from one encoding to the other.
Unfortunately, it may be that encodings are not `PerlIO`-savvy. You can check to see whether your encoding is supported by `PerlIO` by invoking the `perlio_ok` method on it:
```
Encode::perlio_ok("hz"); # false
find_encoding("euc-cn")->perlio_ok; # true wherever PerlIO is available
use Encode qw(perlio_ok); # imported upon request
perlio_ok("euc-jp")
```
Fortunately, all encodings that come with `Encode` core are `PerlIO`-savvy except for `hz` and `ISO-2022-kr`. For the gory details, see <Encode::Encoding> and <Encode::PerlIO>.
Handling Malformed Data
------------------------
The optional *CHECK* argument tells `Encode` what to do when encountering malformed data. Without *CHECK*, `Encode::FB_DEFAULT` (== 0) is assumed.
As of version 2.12, `Encode` supports coderef values for `CHECK`; see below.
**NOTE:** Not all encodings support this feature. Some encodings ignore the *CHECK* argument. For example, <Encode::Unicode> ignores *CHECK* and it always croaks on error.
###
List of *CHECK* values
#### FB\_DEFAULT
```
I<CHECK> = Encode::FB_DEFAULT ( == 0)
```
If *CHECK* is 0, encoding and decoding replace any malformed character with a *substitution character*. When you encode, *SUBCHAR* is used. When you decode, the Unicode REPLACEMENT CHARACTER, code point U+FFFD, is used. If the data is supposed to be UTF-8, an optional lexical warning of warning category `"utf8"` is given.
#### FB\_CROAK
```
I<CHECK> = Encode::FB_CROAK ( == 1)
```
If *CHECK* is 1, methods immediately die with an error message. Therefore, when *CHECK* is 1, you should trap exceptions with `eval{}`, unless you really want to let it `die`.
#### FB\_QUIET
```
I<CHECK> = Encode::FB_QUIET
```
If *CHECK* is set to `Encode::FB_QUIET`, encoding and decoding immediately return the portion of the data that has been processed so far when an error occurs. The data argument is overwritten with everything after that point; that is, the unprocessed portion of the data. This is handy when you have to call `decode` repeatedly in the case where your source data may contain partial multi-byte character sequences, (that is, you are reading with a fixed-width buffer). Here's some sample code to do exactly that:
```
my($buffer, $string) = ("", "");
while (read($fh, $buffer, 256, length($buffer))) {
$string .= decode($encoding, $buffer, Encode::FB_QUIET);
# $buffer now contains the unprocessed partial character
}
```
#### FB\_WARN
```
I<CHECK> = Encode::FB_WARN
```
This is the same as `FB_QUIET` above, except that instead of being silent on errors, it issues a warning. This is handy for when you are debugging.
**CAVEAT**: All warnings from Encode module are reported, independently of [pragma warnings](warnings) settings. If you want to follow settings of lexical warnings configured by [pragma warnings](warnings) then append also check value `ENCODE::ONLY_PRAGMA_WARNINGS`. This value is available since Encode version 2.99.
####
FB\_PERLQQ FB\_HTMLCREF FB\_XMLCREF
perlqq mode (*CHECK* = Encode::FB\_PERLQQ)
HTML charref mode (*CHECK* = Encode::FB\_HTMLCREF)
XML charref mode (*CHECK* = Encode::FB\_XMLCREF) For encodings that are implemented by the `Encode::XS` module, `CHECK` `==` `Encode::FB_PERLQQ` puts `encode` and `decode` into `perlqq` fallback mode.
When you decode, `\x*HH*` is inserted for a malformed character, where *HH* is the hex representation of the octet that could not be decoded to utf8. When you encode, `\x{*HHHH*}` will be inserted, where *HHHH* is the Unicode code point (in any number of hex digits) of the character that cannot be found in the character repertoire of the encoding.
The HTML/XML character reference modes are about the same. In place of `\x{*HHHH*}`, HTML uses `&#*NNN*;` where *NNN* is a decimal number, and XML uses `&#x*HHHH*;` where *HHHH* is the hexadecimal number.
In `Encode` 2.10 or later, `LEAVE_SRC` is also implied.
####
The bitmask
These modes are all actually set via a bitmask. Here is how the `FB_*XXX*` constants are laid out. You can import the `FB_*XXX*` constants via `use Encode qw(:fallbacks)`, and you can import the generic bitmask constants via `use Encode qw(:fallback_all)`.
```
FB_DEFAULT FB_CROAK FB_QUIET FB_WARN FB_PERLQQ
DIE_ON_ERR 0x0001 X
WARN_ON_ERR 0x0002 X
RETURN_ON_ERR 0x0004 X X
LEAVE_SRC 0x0008 X
PERLQQ 0x0100 X
HTMLCREF 0x0200
XMLCREF 0x0400
```
#### LEAVE\_SRC
```
Encode::LEAVE_SRC
```
If the `Encode::LEAVE_SRC` bit is *not* set but *CHECK* is set, then the source string to encode() or decode() will be overwritten in place. If you're not interested in this, then bitwise-OR it with the bitmask.
###
coderef for CHECK
As of `Encode` 2.12, `CHECK` can also be a code reference which takes the ordinal value of the unmapped character as an argument and returns octets that represent the fallback character. For instance:
```
$ascii = encode("ascii", $utf8, sub{ sprintf "<U+%04X>", shift });
```
Acts like `FB_PERLQQ` but U+*XXXX* is used instead of `\x{*XXXX*}`.
Fallback for `decode` must return decoded string (sequence of characters) and takes a list of ordinal values as its arguments. So for example if you wish to decode octets as UTF-8, and use ISO-8859-15 as a fallback for bytes that are not valid UTF-8, you could write
```
$str = decode 'UTF-8', $octets, sub {
my $tmp = join '', map chr, @_;
return decode 'ISO-8859-15', $tmp;
};
```
Defining Encodings
-------------------
To define a new encoding, use:
```
use Encode qw(define_encoding);
define_encoding($object, CANONICAL_NAME [, alias...]);
```
*CANONICAL\_NAME* will be associated with *$object*. The object should provide the interface described in <Encode::Encoding>. If more than two arguments are provided, additional arguments are considered aliases for *$object*.
See <Encode::Encoding> for details.
The UTF8 flag
--------------
Before the introduction of Unicode support in Perl, The `eq` operator just compared the strings represented by two scalars. Beginning with Perl 5.8, `eq` compares two strings with simultaneous consideration of *the UTF8 flag*. To explain why we made it so, I quote from page 402 of *Programming Perl, 3rd ed.*
Goal #1: Old byte-oriented programs should not spontaneously break on the old byte-oriented data they used to work on.
Goal #2: Old byte-oriented programs should magically start working on the new character-oriented data when appropriate.
Goal #3: Programs should run just as fast in the new character-oriented mode as in the old byte-oriented mode.
Goal #4: Perl should remain one language, rather than forking into a byte-oriented Perl and a character-oriented Perl.
When *Programming Perl, 3rd ed.* was written, not even Perl 5.6.0 had been born yet, many features documented in the book remained unimplemented for a long time. Perl 5.8 corrected much of this, and the introduction of the UTF8 flag is one of them. You can think of there being two fundamentally different kinds of strings and string-operations in Perl: one a byte-oriented mode for when the internal UTF8 flag is off, and the other a character-oriented mode for when the internal UTF8 flag is on.
This UTF8 flag is not visible in Perl scripts, exactly for the same reason you cannot (or rather, you *don't have to*) see whether a scalar contains a string, an integer, or a floating-point number. But you can still peek and poke these if you will. See the next section.
###
Messing with Perl's Internals
The following API uses parts of Perl's internals in the current implementation. As such, they are efficient but may change in a future release.
#### is\_utf8
```
is_utf8(STRING [, CHECK])
```
[INTERNAL] Tests whether the UTF8 flag is turned on in the *STRING*. If *CHECK* is true, also checks whether *STRING* contains well-formed UTF-8. Returns true if successful, false otherwise.
Typically only necessary for debugging and testing. 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.
**CAVEAT**: If *STRING* has UTF8 flag set, it does **NOT** mean that *STRING* is UTF-8 encoded and vice-versa.
As of Perl 5.8.1, <utf8> also has the `utf8::is_utf8` function.
####
\_utf8\_on
```
_utf8_on(STRING)
```
[INTERNAL] Turns the *STRING*'s internal UTF8 flag **on**. The *STRING* is *not* checked for containing only well-formed UTF-8. Do not use this unless you *know with absolute certainty* that the STRING holds only well-formed UTF-8. Returns the previous state of the UTF8 flag (so please don't treat the return value as indicating success or failure), or `undef` if *STRING* is not a string.
**NOTE**: For security reasons, this function does not work on tainted values.
####
\_utf8\_off
```
_utf8_off(STRING)
```
[INTERNAL] Turns the *STRING*'s internal UTF8 flag **off**. Do not use frivolously. Returns the previous state of the UTF8 flag, or `undef` if *STRING* is not a string. Do not treat the return value as indicative of success or failure, because that isn't what it means: it is only the previous setting.
**NOTE**: For security reasons, this function does not work on tainted values.
UTF-8 vs. utf8 vs. UTF8
------------------------
```
....We now view strings not as sequences of bytes, but as sequences
of numbers in the range 0 .. 2**32-1 (or in the case of 64-bit
computers, 0 .. 2**64-1) -- Programming Perl, 3rd ed.
```
That has historically been Perl's notion of UTF-8, as that is how UTF-8 was first conceived by Ken Thompson when he invented it. However, thanks to later revisions to the applicable standards, official UTF-8 is now rather stricter than that. For example, its range is much narrower (0 .. 0x10\_FFFF to cover only 21 bits instead of 32 or 64 bits) and some sequences are not allowed, like those used in surrogate pairs, the 31 non-character code points 0xFDD0 .. 0xFDEF, the last two code points in *any* plane (0x*XX*\_FFFE and 0x*XX*\_FFFF), all non-shortest encodings, etc.
The former default in which Perl would always use a loose interpretation of UTF-8 has now been overruled:
```
From: Larry Wall <[email protected]>
Date: December 04, 2004 11:51:58 JST
To: [email protected]
Subject: Re: Make Encode.pm support the real UTF-8
Message-Id: <[email protected]>
On Fri, Dec 03, 2004 at 10:12:12PM +0000, Tim Bunce wrote:
: I've no problem with 'utf8' being perl's unrestricted uft8 encoding,
: but "UTF-8" is the name of the standard and should give the
: corresponding behaviour.
For what it's worth, that's how I've always kept them straight in my
head.
Also for what it's worth, Perl 6 will mostly default to strict but
make it easy to switch back to lax.
Larry
```
Got that? As of Perl 5.8.7, **"UTF-8"** means UTF-8 in its current sense, which is conservative and strict and security-conscious, whereas **"utf8"** means UTF-8 in its former sense, which was liberal and loose and lax. `Encode` version 2.10 or later thus groks this subtle but critically important distinction between `"UTF-8"` and `"utf8"`.
```
encode("utf8", "\x{FFFF_FFFF}", 1); # okay
encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks
```
This distinction is also important for decoding. In the following, `$s` stores character U+200000, which exceeds UTF-8's allowed range. `$s` thus stores an invalid Unicode code point:
```
$s = decode("utf8", "\xf8\x88\x80\x80\x80");
```
`"UTF-8"`, by contrast, will either coerce the input to something valid:
```
$s = decode("UTF-8", "\xf8\x88\x80\x80\x80"); # U+FFFD
```
.. or croak:
```
decode("UTF-8", "\xf8\x88\x80\x80\x80", FB_CROAK|LEAVE_SRC);
```
In the `Encode` module, `"UTF-8"` is actually a canonical name for `"utf-8-strict"`. That hyphen between the `"UTF"` and the `"8"` is critical; without it, `Encode` goes "liberal" and (perhaps overly-)permissive:
```
find_encoding("UTF-8")->name # is 'utf-8-strict'
find_encoding("utf-8")->name # ditto. names are case insensitive
find_encoding("utf_8")->name # ditto. "_" are treated as "-"
find_encoding("UTF8")->name # is 'utf8'.
```
Perl's internal UTF8 flag is called "UTF8", without a hyphen. It indicates whether a string is internally encoded as "utf8", also without a hyphen.
SEE ALSO
---------
<Encode::Encoding>, <Encode::Supported>, <Encode::PerlIO>, <encoding>, <perlebcdic>, ["open" in perlfunc](perlfunc#open), <perlunicode>, <perluniintro>, <perlunifaq>, <perlunitut> <utf8>, the Perl Unicode Mailing List <http://lists.perl.org/list/perl-unicode.html>
MAINTAINER
----------
This project was originated by the late Nick Ing-Simmons and later maintained by Dan Kogai *<[email protected]>*. See AUTHORS for a full list of people involved. For any questions, send mail to *<[email protected]>* so that we can all share.
While Dan Kogai retains the copyright as a maintainer, credit should go to all those involved. See AUTHORS for a list of those who submitted code to the project.
COPYRIGHT
---------
Copyright 2002-2014 Dan Kogai *<[email protected]>*.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl perldiag perldiag
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perldiag - various Perl diagnostics
DESCRIPTION
-----------
These messages are classified as follows (listed in increasing order of desperation):
```
(W) A warning (optional).
(D) A deprecation (enabled by default).
(S) A severe warning (enabled by default).
(F) A fatal error (trappable).
(P) An internal error you should never see (trappable).
(X) A very fatal error (nontrappable).
(A) An alien error message (not generated by Perl).
```
The majority of messages from the first three classifications above (W, D & S) can be controlled using the `warnings` pragma.
If a message can be controlled by the `warnings` pragma, its warning category is included with the classification letter in the description below. E.g. `(W closed)` means a warning in the `closed` category.
Optional warnings are enabled by using the `warnings` pragma or the **-w** and **-W** switches. Warnings may be captured by setting `$SIG{__WARN__}` to a reference to a routine that will be called on each warning instead of printing it. See <perlvar>.
Severe warnings are always enabled, unless they are explicitly disabled with the `warnings` pragma or the **-X** switch.
Trappable errors may be trapped using the eval operator. See ["eval" in perlfunc](perlfunc#eval). In almost all cases, warnings may be selectively disabled or promoted to fatal errors using the `warnings` pragma. See <warnings>.
The messages are in alphabetical order, without regard to upper or lower-case. Some of these messages are generic. Spots that vary are denoted with a %s or other printf-style escape. These escapes are ignored by the alphabetical order, as are all characters other than letters. To look up your message, just ignore anything that is not a letter.
accept() on closed socket %s (W closed) You tried to do an accept on a closed socket. Did you forget to check the return value of your socket() call? See ["accept" in perlfunc](perlfunc#accept).
Aliasing via reference is experimental (S experimental::refaliasing) This warning is emitted if you use a reference constructor on the left-hand side of an assignment to alias one variable to another. Simply suppress the warning if you want to use the feature, but know that in doing so you are taking the risk of using an experimental feature which may change or be removed in a future Perl version:
```
no warnings "experimental::refaliasing";
use feature "refaliasing";
\$x = \$y;
```
'%c' allowed only after types %s in %s (F) The modifiers '!', '<' and '>' are allowed in pack() or unpack() only after certain types. See ["pack" in perlfunc](perlfunc#pack).
alpha->numify() is lossy (W numeric) An alpha version can not be numified without losing information.
Ambiguous call resolved as CORE::%s(), qualify as such or use & (W ambiguous) A subroutine you have declared has the same name as a Perl keyword, and you have used the name without qualification for calling one or the other. Perl decided to call the builtin because the subroutine is not imported.
To force interpretation as a subroutine call, either put an ampersand before the subroutine name, or qualify the name with its package. Alternatively, you can import the subroutine (or pretend that it's imported with the `use subs` pragma).
To silently interpret it as the Perl operator, use the `CORE::` prefix on the operator (e.g. `CORE::log($x)`) or declare the subroutine to be an object method (see ["Subroutine Attributes" in perlsub](perlsub#Subroutine-Attributes) or <attributes>).
Ambiguous range in transliteration operator (F) You wrote something like `tr/a-z-0//` which doesn't mean anything at all. To include a `-` character in a transliteration, put it either first or last. (In the past, `tr/a-z-0//` was synonymous with `tr/a-y//`, which was probably not what you would have expected.)
Ambiguous use of %s resolved as %s (S ambiguous) You said something that may not be interpreted the way you thought. Normally it's pretty easy to disambiguate it by supplying a missing quote, operator, parenthesis pair or declaration.
Ambiguous use of -%s resolved as -&%s() (S ambiguous) You wrote something like `-foo`, which might be the string `"-foo"`, or a call to the function `foo`, negated. If you meant the string, just write `"-foo"`. If you meant the function call, write `-foo()`.
Ambiguous use of %c resolved as operator %c (S ambiguous) `%`, `&`, and `*` are both infix operators (modulus, bitwise and, and multiplication) *and* initial special characters (denoting hashes, subroutines and typeglobs), and you said something like `*foo * foo` that might be interpreted as either of them. We assumed you meant the infix operator, but please try to make it more clear -- in the example given, you might write `*foo * foo()` if you really meant to multiply a glob by the result of calling a function.
Ambiguous use of %c{%s} resolved to %c%s (W ambiguous) You wrote something like `@{foo}`, which might be asking for the variable `@foo`, or it might be calling a function named foo, and dereferencing it as an array reference. If you wanted the variable, you can just write `@foo`. If you wanted to call the function, write `@{foo()}` ... or you could just not have a variable and a function with the same name, and save yourself a lot of trouble.
Ambiguous use of %c{%s[...]} resolved to %c%s[...]
Ambiguous use of %c{%s{...}} resolved to %c%s{...} (W ambiguous) You wrote something like `${foo[2]}` (where foo represents the name of a Perl keyword), which might be looking for element number 2 of the array named `@foo`, in which case please write `$foo[2]`, or you might have meant to pass an anonymous arrayref to the function named foo, and then do a scalar deref on the value it returns. If you meant that, write `${foo([2])}`.
In regular expressions, the `${foo[2]}` syntax is sometimes necessary to disambiguate between array subscripts and character classes. `/$length[2345]/`, for instance, will be interpreted as `$length` followed by the character class `[2345]`. If an array subscript is what you want, you can avoid the warning by changing `/${length[2345]}/` to the unsightly `/${\$length[2345]}/`, by renaming your array to something that does not coincide with a built-in keyword, or by simply turning off warnings with `no warnings 'ambiguous';`.
'|' and '<' may not both be specified on command line (F) An error peculiar to VMS. Perl does its own command line redirection, and found that STDIN was a pipe, and that you also tried to redirect STDIN using '<'. Only one STDIN stream to a customer, please.
'|' and '>' may not both be specified on command line (F) An error peculiar to VMS. Perl does its own command line redirection, and thinks you tried to redirect stdout both to a file and into a pipe to another command. You need to choose one or the other, though nothing's stopping you from piping into a program or Perl script which 'splits' output into two streams, such as
```
open(OUT,">$ARGV[0]") or die "Can't write to $ARGV[0]: $!";
while (<STDIN>) {
print;
print OUT;
}
close OUT;
```
Applying %s to %s will act on scalar(%s) (W misc) The pattern match (`//`), substitution (`s///`), and transliteration (`tr///`) operators work on scalar values. If you apply one of them to an array or a hash, it will convert the array or hash to a scalar value (the length of an array, or the population info of a hash) and then work on that scalar value. This is probably not what you meant to do. See ["grep" in perlfunc](perlfunc#grep) and ["map" in perlfunc](perlfunc#map) for alternatives.
Arg too short for msgsnd (F) msgsnd() requires a string at least as long as sizeof(long).
Argument "%s" isn't numeric%s (W numeric) The indicated string was fed as an argument to an operator that expected a numeric value instead. If you're fortunate the message will identify which operator was so unfortunate.
Note that for the `Inf` and `NaN` (infinity and not-a-number) the definition of "numeric" is somewhat unusual: the strings themselves (like "Inf") are considered numeric, and anything following them is considered non-numeric.
Argument list not closed for PerlIO layer "%s" (W layer) When pushing a layer with arguments onto the Perl I/O system you forgot the ) that closes the argument list. (Layers take care of transforming data between external and internal representations.) Perl stopped parsing the layer list at this point and did not attempt to push this layer. If your program didn't explicitly request the failing operation, it may be the result of the value of the environment variable PERLIO.
Argument "%s" treated as 0 in increment (++) (W numeric) The indicated string was fed as an argument to the `++` operator which expects either a number or a string matching `/^[a-zA-Z]*[0-9]*\z/`. See ["Auto-increment and Auto-decrement" in perlop](perlop#Auto-increment-and-Auto-decrement) for details.
Array passed to stat will be coerced to a scalar%s (W syntax) You called stat() on an array, but the array will be coerced to a scalar - the number of elements in the array.
A signature parameter must start with '$', '@' or '%' (F) Each subroutine signature parameter declaration must start with a valid sigil; for example:
```
sub foo ($a, $, $b = 1, @c) {}
```
A slurpy parameter may not have a default value (F) Only scalar subroutine signature parameters may have a default value; for example:
```
sub foo ($a = 1) {} # legal
sub foo (@a = (1)) {} # invalid
sub foo (%a = (a => b)) {} # invalid
```
assertion botched: %s (X) The malloc package that comes with Perl had an internal failure.
Assertion %s failed: file "%s", line %d (X) A general assertion failed. The file in question must be examined.
Assigned value is not a reference (F) You tried to assign something that was not a reference to an lvalue reference (e.g., `\$x = $y`). If you meant to make $x an alias to $y, use `\$x = \$y`.
Assigned value is not %s reference (F) You tried to assign a reference to a reference constructor, but the two references were not of the same type. You cannot alias a scalar to an array, or an array to a hash; the two types must match.
```
\$x = \@y; # error
\@x = \%y; # error
$y = [];
\$x = $y; # error; did you mean \$y?
```
Assigning non-zero to $[ is no longer possible (F) When the "array\_base" feature is disabled (e.g., and under `use v5.16;`, and as of Perl 5.30) the special variable `$[`, which is deprecated, is now a fixed zero value.
Assignment to both a list and a scalar (F) If you assign to a conditional operator, the 2nd and 3rd arguments must either both be scalars or both be lists. Otherwise Perl won't know which context to supply to the right side.
Assuming NOT a POSIX class since %s in regex; marked by <-- HERE in m/%s/ (W regexp) You had something like these:
```
[[:alnum]]
[[:digit:xyz]
```
They look like they might have been meant to be the POSIX classes `[:alnum:]` or `[:digit:]`. If so, they should be written:
```
[[:alnum:]]
[[:digit:]xyz]
```
Since these aren't legal POSIX class specifications, but are legal bracketed character classes, Perl treats them as the latter. In the first example, it matches the characters `":"`, `"["`, `"a"`, `"l"`, `"m"`, `"n"`, and `"u"`.
If these weren't meant to be POSIX classes, this warning message is spurious, and can be suppressed by reordering things, such as
```
[[al:num]]
```
or
```
[[:munla]]
```
<> at require-statement should be quotes (F) You wrote `require <file>` when you should have written `require 'file'`.
Attempt to access disallowed key '%s' in a restricted hash (F) The failing code has attempted to get or set a key which is not in the current set of allowed keys of a restricted hash.
Attempt to bless into a freed package (F) You wrote `bless $foo` with one argument after somehow causing the current package to be freed. Perl cannot figure out what to do, so it throws up its hands in despair.
Attempt to bless into a reference (F) The CLASSNAME argument to the bless() operator is expected to be the name of the package to bless the resulting object into. You've supplied instead a reference to something: perhaps you wrote
```
bless $self, $proto;
```
when you intended
```
bless $self, ref($proto) || $proto;
```
If you actually want to bless into the stringified version of the reference supplied, you need to stringify it yourself, for example by:
```
bless $self, "$proto";
```
Attempt to clear deleted array (S debugging) An array was assigned to when it was being freed. Freed values are not supposed to be visible to Perl code. This can also happen if XS code calls `av_clear` from a custom magic callback on the array.
Attempt to delete disallowed key '%s' from a restricted hash (F) The failing code attempted to delete from a restricted hash a key which is not in its key set.
Attempt to delete readonly key '%s' from a restricted hash (F) The failing code attempted to delete a key whose value has been declared readonly from a restricted hash.
Attempt to free non-arena SV: 0x%x (S internal) All SV objects are supposed to be allocated from arenas that will be garbage collected on exit. An SV was discovered to be outside any of those arenas.
Attempt to free nonexistent shared string '%s'%s (S internal) Perl maintains a reference-counted internal table of strings to optimize the storage and access of hash keys and other strings. This indicates someone tried to decrement the reference count of a string that can no longer be found in the table.
Attempt to free temp prematurely: SV 0x%x (S debugging) Mortalized values are supposed to be freed by the free\_tmps() routine. This indicates that something else is freeing the SV before the free\_tmps() routine gets a chance, which means that the free\_tmps() routine will be freeing an unreferenced scalar when it does try to free it.
Attempt to free unreferenced glob pointers (S internal) The reference counts got screwed up on symbol aliases.
Attempt to free unreferenced scalar: SV 0x%x (S internal) Perl went to decrement the reference count of a scalar to see if it would go to 0, and discovered that it had already gone to 0 earlier, and should have been freed, and in fact, probably was freed. This could indicate that SvREFCNT\_dec() was called too many times, or that SvREFCNT\_inc() was called too few times, or that the SV was mortalized when it shouldn't have been, or that memory has been corrupted.
Attempt to pack pointer to temporary value (W pack) You tried to pass a temporary value (like the result of a function, or a computed expression) to the "p" pack() template. This means the result contains a pointer to a location that could become invalid anytime, even before the end of the current statement. Use literals or global values as arguments to the "p" pack() template to avoid this warning.
Attempt to reload %s aborted. (F) You tried to load a file with `use` or `require` that failed to compile once already. Perl will not try to compile this file again unless you delete its entry from %INC. See ["require" in perlfunc](perlfunc#require) and ["%INC" in perlvar](perlvar#%25INC).
Attempt to set length of freed array (W misc) You tried to set the length of an array which has been freed. You can do this by storing a reference to the scalar representing the last index of an array and later assigning through that reference. For example
```
$r = do {my @a; \$#a};
$$r = 503
```
Attempt to use reference as lvalue in substr (W substr) You supplied a reference as the first argument to substr() used as an lvalue, which is pretty strange. Perhaps you forgot to dereference it first. See ["substr" in perlfunc](perlfunc#substr).
Attribute prototype(%s) discards earlier prototype attribute in same sub (W misc) A sub was declared as sub foo : prototype(A) : prototype(B) {}, for example. Since each sub can only have one prototype, the earlier declaration(s) are discarded while the last one is applied.
av\_reify called on tied array (S debugging) This indicates that something went wrong and Perl got *very* confused about `@_` or `@DB::args` being tied.
Bad arg length for %s, is %u, should be %d (F) You passed a buffer of the wrong size to one of msgctl(), semctl() or shmctl(). In C parlance, the correct sizes are, respectively, sizeof(struct msqid\_ds \*), sizeof(struct semid\_ds \*), and sizeof(struct shmid\_ds \*).
Bad evalled substitution pattern (F) You've used the `/e` switch to evaluate the replacement for a substitution, but perl found a syntax error in the code to evaluate, most likely an unexpected right brace '}'.
Bad filehandle: %s (F) A symbol was passed to something wanting a filehandle, but the symbol has no filehandle associated with it. Perhaps you didn't do an open(), or did it in another package.
Bad free() ignored (S malloc) An internal routine called free() on something that had never been malloc()ed in the first place. Mandatory, but can be disabled by setting environment variable `PERL_BADFREE` to 0.
This message can be seen quite often with DB\_File on systems with "hard" dynamic linking, like `AIX` and `OS/2`. It is a bug of `Berkeley DB` which is left unnoticed if `DB` uses *forgiving* system malloc().
Badly placed ()'s (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
Bad name after %s (F) You started to name a symbol by using a package prefix, and then didn't finish the symbol. In particular, you can't interpolate outside of quotes, so
```
$var = 'myvar';
$sym = mypack::$var;
```
is not the same as
```
$var = 'myvar';
$sym = "mypack::$var";
```
Bad plugin affecting keyword '%s' (F) An extension using the keyword plugin mechanism violated the plugin API.
Bad realloc() ignored (S malloc) An internal routine called realloc() on something that had never been malloc()ed in the first place. Mandatory, but can be disabled by setting the environment variable `PERL_BADFREE` to 1.
Bad symbol for array (P) An internal request asked to add an array entry to something that wasn't a symbol table entry.
Bad symbol for dirhandle (P) An internal request asked to add a dirhandle entry to something that wasn't a symbol table entry.
Bad symbol for filehandle (P) An internal request asked to add a filehandle entry to something that wasn't a symbol table entry.
Bad symbol for hash (P) An internal request asked to add a hash entry to something that wasn't a symbol table entry.
Bad symbol for scalar (P) An internal request asked to add a scalar entry to something that wasn't a symbol table entry.
Bareword found in conditional (W bareword) The compiler found a bareword where it expected a conditional, which often indicates that an || or && was parsed as part of the last argument of the previous construct, for example:
```
open FOO || die;
```
It may also indicate a misspelled constant that has been interpreted as a bareword:
```
use constant TYPO => 1;
if (TYOP) { print "foo" }
```
The `strict` pragma is useful in avoiding such errors.
Bareword in require contains "%s"
Bareword in require maps to disallowed filename "%s"
Bareword in require maps to empty filename (F) The bareword form of require has been invoked with a filename which could not have been generated by a valid bareword permitted by the parser. You shouldn't be able to get this error from Perl code, but XS code may throw it if it passes an invalid module name to `Perl_load_module`.
Bareword in require must not start with a double-colon: "%s" (F) In `require Bare::Word`, the bareword is not allowed to start with a double-colon. Write `require ::Foo::Bar` as `require Foo::Bar` instead.
Bareword "%s" not allowed while "strict subs" in use (F) With "strict subs" in use, a bareword is only allowed as a subroutine identifier, in curly brackets or to the left of the "=>" symbol. Perhaps you need to predeclare a subroutine?
Bareword "%s" refers to nonexistent package (W bareword) You used a qualified bareword of the form `Foo::`, but the compiler saw no other uses of that namespace before that point. Perhaps you need to predeclare a package?
Bareword filehandle "%s" not allowed under 'no feature "bareword\_filehandles"' (F) You attempted to use a bareword filehandle with the `bareword_filehandles` feature disabled.
Only the built-in handles `STDIN`, `STDOUT`, `STDERR`, `ARGV`, `ARGVOUT` and `DATA` can be used with the `bareword_filehandles` feature disabled.
BEGIN failed--compilation aborted (F) An untrapped exception was raised while executing a BEGIN subroutine. Compilation stops immediately and the interpreter is exited.
BEGIN not safe after errors--compilation aborted (F) Perl found a `BEGIN {}` subroutine (or a `use` directive, which implies a `BEGIN {}`) after one or more compilation errors had already occurred. Since the intended environment for the `BEGIN {}` could not be guaranteed (due to the errors), and since subsequent code likely depends on its correct operation, Perl just gave up.
\%d better written as $%d (W syntax) Outside of patterns, backreferences live on as variables. The use of backslashes is grandfathered on the right-hand side of a substitution, but stylistically it's better to use the variable form because other Perl programmers will expect it, and it works better if there are more than 9 backreferences.
Binary number > 0b11111111111111111111111111111111 non-portable (W portable) The binary number you specified is larger than 2\*\*32-1 (4294967295) and therefore non-portable between systems. See <perlport> for more on portability concerns.
bind() on closed socket %s (W closed) You tried to do a bind on a closed socket. Did you forget to check the return value of your socket() call? See ["bind" in perlfunc](perlfunc#bind).
binmode() on closed filehandle %s (W unopened) You tried binmode() on a filehandle that was never opened. Check your control flow and number of arguments.
Bit vector size > 32 non-portable (W portable) Using bit vector sizes larger than 32 is non-portable.
Bizarre copy of %s (P) Perl detected an attempt to copy an internal value that is not copiable.
Bizarre SvTYPE [%d] (P) When starting a new thread or returning values from a thread, Perl encountered an invalid data type.
Both or neither range ends should be Unicode in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'` or within `(?[...])`)
In a bracketed character class in a regular expression pattern, you had a range which has exactly one end of it specified using `\N{}`, and the other end is specified using a non-portable mechanism. Perl treats the range as a Unicode range, that is, all the characters in it are considered to be the Unicode characters, and which may be different code points on some platforms Perl runs on. For example, `[\N{U+06}-\x08]` is treated as if you had instead said `[\N{U+06}-\N{U+08}]`, that is it matches the characters whose code points in Unicode are 6, 7, and 8. But that `\x08` might indicate that you meant something different, so the warning gets raised.
Buffer overflow in prime\_env\_iter: %s (W internal) A warning peculiar to VMS. While Perl was preparing to iterate over %ENV, it encountered a logical name or symbol definition which was too long, so it was truncated to the string shown.
Built-in function '%s' is experimental (S experimental::builtin) A call is being made to a function in the `builtin::` namespace, which is currently experimental. The existence or nature of the function may be subject to change in a future version of Perl.
builtin::import can only be called at compile time (F) The `import` method of the `builtin` package was invoked when no code is currently being compiled. Since this method is used to introduce new lexical subroutines into the scope currently being compiled, this is not going to have any effect.
Callback called exit (F) A subroutine invoked from an external package via call\_sv() exited by calling exit.
%s() called too early to check prototype (W prototype) You've called a function that has a prototype before the parser saw a definition or declaration for it, and Perl could not check that the call conforms to the prototype. You need to either add an early prototype declaration for the subroutine in question, or move the subroutine definition ahead of the call to get proper prototype checking. Alternatively, if you are certain that you're calling the function correctly, you may put an ampersand before the name to avoid the warning. See <perlsub>.
Cannot chr %f (F) You passed an invalid number (like an infinity or not-a-number) to `chr`.
Cannot complete in-place edit of %s: %s (F) Your perl script appears to have changed directory while performing an in-place edit of a file specified by a relative path, and your system doesn't include the directory relative POSIX functions needed to handle that.
Cannot compress %f in pack (F) You tried compressing an infinity or not-a-number as an unsigned integer with BER, which makes no sense.
Cannot compress integer in pack (F) An argument to pack("w",...) was too large to compress. The BER compressed integer format can only be used with positive integers, and you attempted to compress a very large number (> 1e308). See ["pack" in perlfunc](perlfunc#pack).
Cannot compress negative numbers in pack (F) An argument to pack("w",...) was negative. The BER compressed integer format can only be used with positive integers. See ["pack" in perlfunc](perlfunc#pack).
Cannot convert a reference to %s to typeglob (F) You manipulated Perl's symbol table directly, stored a reference in it, then tried to access that symbol via conventional Perl syntax. The access triggers Perl to autovivify that typeglob, but it there is no legal conversion from that type of reference to a typeglob.
Cannot copy to %s (P) Perl detected an attempt to copy a value to an internal type that cannot be directly assigned to.
Cannot find encoding "%s" (S io) You tried to apply an encoding that did not exist to a filehandle, either with open() or binmode().
Cannot open %s as a dirhandle: it is already open as a filehandle (F) You tried to use opendir() to associate a dirhandle to a symbol (glob or scalar) that already holds a filehandle. Since this idiom might render your code confusing, it was deprecated in Perl 5.10. As of Perl 5.28, it is a fatal error.
Cannot open %s as a filehandle: it is already open as a dirhandle (F) You tried to use open() to associate a filehandle to a symbol (glob or scalar) that already holds a dirhandle. Since this idiom might render your code confusing, it was deprecated in Perl 5.10. As of Perl 5.28, it is a fatal error.
Cannot pack %f with '%c' (F) You tried converting an infinity or not-a-number to an integer, which makes no sense.
Cannot printf %f with '%c' (F) You tried printing an infinity or not-a-number as a character (%c), which makes no sense. Maybe you meant '%s', or just stringifying it?
Cannot set tied @DB::args (F) `caller` tried to set `@DB::args`, but found it tied. Tying `@DB::args` is not supported. (Before this error was added, it used to crash.)
Cannot tie unreifiable array (P) You somehow managed to call `tie` on an array that does not keep a reference count on its arguments and cannot be made to do so. Such arrays are not even supposed to be accessible to Perl code, but are only used internally.
Cannot yet reorder sv\_vcatpvfn() arguments from va\_list (F) Some XS code tried to use `sv_vcatpvfn()` or a related function with a format string that specifies explicit indexes for some of the elements, and using a C-style variable-argument list (a `va_list`). This is not currently supported. XS authors wanting to do this must instead construct a C array of `SV*` scalars containing the arguments.
Can only compress unsigned integers in pack (F) An argument to pack("w",...) was not an integer. The BER compressed integer format can only be used with positive integers, and you attempted to compress something else. See ["pack" in perlfunc](perlfunc#pack).
Can't "%s" out of a "defer" block (F) An attempt was made to jump out of the scope of a `defer` block by using a control-flow statement such as `return`, `goto` or a loop control. This is not permitted.
Can't "%s" out of a "finally" block (F) Similar to above, but involving a `finally` block at the end of a `try`/`catch` construction rather than a `defer` block.
Can't bless non-reference value (F) Only hard references may be blessed. This is how Perl "enforces" encapsulation of objects. See <perlobj>.
Can't "break" in a loop topicalizer (F) You called `break`, but you're in a `foreach` block rather than a `given` block. You probably meant to use `next` or `last`.
Can't "break" outside a given block (F) You called `break`, but you're not inside a `given` block.
Can't call method "%s" on an undefined value (F) You used the syntax of a method call, but the slot filled by the object reference or package name contains an undefined value. Something like this will reproduce the error:
```
$BADREF = undef;
process $BADREF 1,2,3;
$BADREF->process(1,2,3);
```
Can't call method "%s" on unblessed reference (F) A method call must know in what package it's supposed to run. It ordinarily finds this out from the object reference you supply, but you didn't supply an object reference in this case. A reference isn't an object reference until it has been blessed. See <perlobj>.
Can't call method "%s" without a package or object reference (F) You used the syntax of a method call, but the slot filled by the object reference or package name contains an expression that returns a defined value which is neither an object reference nor a package name. Something like this will reproduce the error:
```
$BADREF = 42;
process $BADREF 1,2,3;
$BADREF->process(1,2,3);
```
Can't call mro\_isa\_changed\_in() on anonymous symbol table (P) Perl got confused as to whether a hash was a plain hash or a symbol table hash when trying to update @ISA caches.
Can't call mro\_method\_changed\_in() on anonymous symbol table (F) An XS module tried to call `mro_method_changed_in` on a hash that was not attached to the symbol table.
Can't chdir to %s (F) You called `perl -x/foo/bar`, but */foo/bar* is not a directory that you can chdir to, possibly because it doesn't exist.
Can't coerce %s to %s in %s (F) Certain types of SVs, in particular real symbol table entries (typeglobs), can't be forced to stop being what they are. So you can't say things like:
```
*foo += 1;
```
You CAN say
```
$foo = *foo;
$foo += 1;
```
but then $foo no longer contains a glob.
Can't "continue" outside a when block (F) You called `continue`, but you're not inside a `when` or `default` block.
Can't create pipe mailbox (P) An error peculiar to VMS. The process is suffering from exhausted quotas or other plumbing problems.
Can't declare %s in "%s" (F) Only scalar, array, and hash variables may be declared as "my", "our" or "state" variables. They must have ordinary identifiers as names.
Can't "default" outside a topicalizer (F) You have used a `default` block that is neither inside a `foreach` loop nor a `given` block. (Note that this error is issued on exit from the `default` block, so you won't get the error if you use an explicit `continue`.)
Can't determine class of operator %s, assuming BASEOP (S) This warning indicates something wrong in the internals of perl. Perl was trying to find the class (e.g. LISTOP) of a particular OP, and was unable to do so. This is likely to be due to a bug in the perl internals, or due to a bug in XS code which manipulates perl optrees.
Can't do inplace edit: %s is not a regular file (S inplace) You tried to use the **-i** switch on a special file, such as a file in /dev, a FIFO or an uneditable directory. The file was ignored.
Can't do inplace edit on %s: %s (S inplace) The creation of the new file failed for the indicated reason.
Can't do inplace edit: %s would not be unique (S inplace) Your filesystem does not support filenames longer than 14 characters and Perl was unable to create a unique filename during inplace editing with the **-i** switch. The file was ignored.
Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". (W locale) You are 1) running under "`use locale`"; 2) the current locale is not a UTF-8 one; 3) you tried to do the designated case-change operation on the specified Unicode character; and 4) the result of this operation would mix Unicode and locale rules, which likely conflict. Mixing of different rule types is forbidden, so the operation was not done; instead the result is the indicated value, which is the best available that uses entirely Unicode rules. That turns out to almost always be the original character, unchanged.
It is generally a bad idea to mix non-UTF-8 locales and Unicode, and this issue is one of the reasons why. This warning is raised when Unicode rules would normally cause the result of this operation to contain a character that is in the range specified by the locale, 0..255, and hence is subject to the locale's rules, not Unicode's.
If you are using locale purely for its characteristics related to things like its numeric and time formatting (and not `LC_CTYPE`), consider using a restricted form of the locale pragma (see ["The "use locale" pragma" in perllocale](perllocale#The-%22use-locale%22-pragma)) like "`use locale ':not_characters'`".
Note that failed case-changing operations done as a result of case-insensitive `/i` regular expression matching will show up in this warning as having the `fc` operation (as that is what the regular expression engine calls behind the scenes.)
Can't do waitpid with flags (F) This machine doesn't have either waitpid() or wait4(), so only waitpid() without flags is emulated.
Can't emulate -%s on #! line (F) The #! line specifies a switch that doesn't make sense at this point. For example, it'd be kind of silly to put a **-x** on the #! line.
Can't %s %s-endian %ss on this platform (F) Your platform's byte-order is neither big-endian nor little-endian, or it has a very strange pointer size. Packing and unpacking big- or little-endian floating point values and pointers may not be possible. See ["pack" in perlfunc](perlfunc#pack).
Can't exec "%s": %s (W exec) A system(), exec(), or piped open call could not execute the named program for the indicated reason. Typical reasons include: the permissions were wrong on the file, the file wasn't found in `$ENV{PATH}`, the executable in question was compiled for another architecture, or the #! line in a script points to an interpreter that can't be run for similar reasons. (Or maybe your system doesn't support #! at all.)
Can't exec %s (F) Perl was trying to execute the indicated program for you because that's what the #! line said. If that's not what you wanted, you may need to mention "perl" on the #! line somewhere.
Can't execute %s (F) You used the **-S** switch, but the copies of the script to execute found in the PATH did not have correct permissions.
Can't find an opnumber for "%s" (F) A string of a form `CORE::word` was given to prototype(), but there is no builtin with the name `word`.
Can't find label %s (F) You said to goto a label that isn't mentioned anywhere that it's possible for us to go to. See ["goto" in perlfunc](perlfunc#goto).
Can't find %s on PATH (F) You used the **-S** switch, but the script to execute could not be found in the PATH.
Can't find %s on PATH, '.' not in PATH (F) You used the **-S** switch, but the script to execute could not be found in the PATH, or at least not with the correct permissions. The script exists in the current directory, but PATH prohibits running it.
Can't find string terminator %s anywhere before EOF (F) Perl strings can stretch over multiple lines. This message means that the closing delimiter was omitted. Because bracketed quotes count nesting levels, the following is missing its final parenthesis:
```
print q(The character '(' starts a side comment.);
```
If you're getting this error from a here-document, you may have included unseen whitespace before or after your closing tag or there may not be a linebreak after it. A good programmer's editor will have a way to help you find these characters (or lack of characters). See <perlop> for the full details on here-documents.
Can't find Unicode property definition "%s"
Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ (F) The named property which you specified via `\p` or `\P` is not one known to Perl. Perhaps you misspelled the name? See ["Properties accessible through \p{} and \P{}" in perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D) for a complete list of available official properties. If it is a [user-defined property](perlunicode#User-Defined-Character-Properties) it must have been defined by the time the regular expression is matched.
If you didn't mean to use a Unicode property, escape the `\p`, either by `\\p` (just the `\p`) or by `\Q\p` (the rest of the string, or until `\E`).
Can't fork: %s (F) A fatal error occurred while trying to fork while opening a pipeline.
Can't fork, trying again in 5 seconds (W pipe) A fork in a piped open failed with EAGAIN and will be retried after five seconds.
Can't get filespec - stale stat buffer? (S) A warning peculiar to VMS. This arises because of the difference between access checks under VMS and under the Unix model Perl assumes. Under VMS, access checks are done by filename, rather than by bits in the stat buffer, so that ACLs and other protections can be taken into account. Unfortunately, Perl assumes that the stat buffer contains all the necessary information, and passes it, instead of the filespec, to the access-checking routine. It will try to retrieve the filespec using the device name and FID present in the stat buffer, but this works only if you haven't made a subsequent call to the CRTL stat() routine, because the device name is overwritten with each call. If this warning appears, the name lookup failed, and the access-checking routine gave up and returned FALSE, just to be conservative. (Note: The access-checking routine knows about the Perl `stat` operator and file tests, so you shouldn't ever see this warning in response to a Perl command; it arises only if some internal code takes stat buffers lightly.)
Can't get pipe mailbox device name (P) An error peculiar to VMS. After creating a mailbox to act as a pipe, Perl can't retrieve its name for later use.
Can't get SYSGEN parameter value for MAXBUF (P) An error peculiar to VMS. Perl asked $GETSYI how big you want your mailbox buffers to be, and didn't get an answer.
Can't "goto" into a binary or list expression (F) A "goto" statement was executed to jump into the middle of a binary or list expression. You can't get there from here. The reason for this restriction is that the interpreter would get confused as to how many arguments there are, resulting in stack corruption or crashes. This error occurs in cases such as these:
```
goto F;
print do { F: }; # Can't jump into the arguments to print
goto G;
$x + do { G: $y }; # How is + supposed to get its first operand?
```
Can't "goto" into a "defer" block (F) A `goto` statement was executed to jump into the scope of a `defer` block. This is not permitted.
Can't "goto" into a "given" block (F) A "goto" statement was executed to jump into the middle of a `given` block. You can't get there from here. See ["goto" in perlfunc](perlfunc#goto).
Can't "goto" into the middle of a foreach loop (F) A "goto" statement was executed to jump into the middle of a foreach loop. You can't get there from here. See ["goto" in perlfunc](perlfunc#goto).
Can't "goto" out of a pseudo block (F) A "goto" statement was executed to jump out of what might look like a block, except that it isn't a proper block. This usually occurs if you tried to jump out of a sort() block or subroutine, which is a no-no. See ["goto" in perlfunc](perlfunc#goto).
Can't goto subroutine from an eval-%s (F) The "goto subroutine" call can't be used to jump out of an eval "string" or block.
Can't goto subroutine from a sort sub (or similar callback) (F) The "goto subroutine" call can't be used to jump out of the comparison sub for a sort(), or from a similar callback (such as the reduce() function in List::Util).
Can't goto subroutine outside a subroutine (F) The deeply magical "goto subroutine" call can only replace one subroutine call for another. It can't manufacture one out of whole cloth. In general you should be calling it out of only an AUTOLOAD routine anyway. See ["goto" in perlfunc](perlfunc#goto).
Can't ignore signal CHLD, forcing to default (W signal) Perl has detected that it is being run with the SIGCHLD signal (sometimes known as SIGCLD) disabled. Since disabling this signal will interfere with proper determination of exit status of child processes, Perl has reset the signal to its default value. This situation typically indicates that the parent program under which Perl may be running (e.g. cron) is being very careless.
Can't kill a non-numeric process ID (F) Process identifiers must be (signed) integers. It is a fatal error to attempt to kill() an undefined, empty-string or otherwise non-numeric process identifier.
Can't "last" outside a loop block (F) A "last" statement was executed to break out of the current block, except that there's this itty bitty problem called there isn't a current block. Note that an "if" or "else" block doesn't count as a "loopish" block, as doesn't a block given to sort(), map() or grep(). You can usually double the curlies to get the same effect though, because the inner curlies will be considered a block that loops once. See ["last" in perlfunc](perlfunc#last).
Can't linearize anonymous symbol table (F) Perl tried to calculate the method resolution order (MRO) of a package, but failed because the package stash has no name.
Can't load '%s' for module %s (F) The module you tried to load failed to load a dynamic extension. This may either mean that you upgraded your version of perl to one that is incompatible with your old dynamic extensions (which is known to happen between major versions of perl), or (more likely) that your dynamic extension was built against an older version of the library that is installed on your system. You may need to rebuild your old dynamic extensions.
Can't localize lexical variable %s (F) You used local on a variable name that was previously declared as a lexical variable using "my" or "state". This is not allowed. If you want to localize a package variable of the same name, qualify it with the package name.
Can't localize through a reference (F) You said something like `local $$ref`, which Perl can't currently handle, because when it goes to restore the old value of whatever $ref pointed to after the scope of the local() is finished, it can't be sure that $ref will still be a reference.
Can't locate %s (F) You said to `do` (or `require`, or `use`) a file that couldn't be found. Perl looks for the file in all the locations mentioned in @INC, unless the file name included the full path to the file. Perhaps you need to set the PERL5LIB or PERL5OPT environment variable to say where the extra library is, or maybe the script needs to add the library name to @INC. Or maybe you just misspelled the name of the file. See ["require" in perlfunc](perlfunc#require) and <lib>.
Can't locate auto/%s.al in @INC (F) A function (or method) was called in a package which allows autoload, but there is no function to autoload. Most probable causes are a misprint in a function/method name or a failure to `AutoSplit` the file, say, by doing `make install`.
Can't locate loadable object for module %s in @INC (F) The module you loaded is trying to load an external library, like for example, *foo.so* or *bar.dll*, but the [DynaLoader](dynaloader) module was unable to locate this library. See [DynaLoader](dynaloader).
Can't locate object method "%s" via package "%s" (F) You called a method correctly, and it correctly indicated a package functioning as a class, but that package doesn't define that particular method, nor does any of its base classes. See <perlobj>.
Can't locate object method "%s" via package "%s" (perhaps you forgot to load "%s"?) (F) You called a method on a class that did not exist, and the method could not be found in UNIVERSAL. This often means that a method requires a package that has not been loaded.
Can't locate package %s for @%s::ISA (W syntax) The @ISA array contained the name of another package that doesn't seem to exist.
Can't locate PerlIO%s (F) You tried to use in open() a PerlIO layer that does not exist, e.g. open(FH, ">:nosuchlayer", "somefile").
Can't make list assignment to %ENV on this system (F) List assignment to %ENV is not supported on some systems, notably VMS.
Can't make loaded symbols global on this platform while loading %s (S) A module passed the flag 0x01 to DynaLoader::dl\_load\_file() to request that symbols from the stated file are made available globally within the process, but that functionality is not available on this platform. Whilst the module likely will still work, this may prevent the perl interpreter from loading other XS-based extensions which need to link directly to functions defined in the C or XS code in the stated file.
Can't modify %s in %s (F) You aren't allowed to assign to the item indicated, or otherwise try to change it, such as with an auto-increment.
Can't modify non-lvalue subroutine call of &%s
Can't modify non-lvalue subroutine call of &%s in %s (F) Subroutines meant to be used in lvalue context should be declared as such. See ["Lvalue subroutines" in perlsub](perlsub#Lvalue-subroutines).
Can't modify reference to %s in %s assignment (F) Only a limited number of constructs can be used as the argument to a reference constructor on the left-hand side of an assignment, and what you used was not one of them. See ["Assigning to References" in perlref](perlref#Assigning-to-References).
Can't modify reference to localized parenthesized array in list assignment (F) Assigning to `\local(@array)` or `\(local @array)` is not supported, as it is not clear exactly what it should do. If you meant to make @array refer to some other array, use `\@array = \@other_array`. If you want to make the elements of @array aliases of the scalars referenced on the right-hand side, use `\(@array) = @scalar_refs`.
Can't modify reference to parenthesized hash in list assignment (F) Assigning to `\(%hash)` is not supported. If you meant to make %hash refer to some other hash, use `\%hash = \%other_hash`. If you want to make the elements of %hash into aliases of the scalars referenced on the right-hand side, use a hash slice: `\@hash{@keys} = @those_scalar_refs`.
Can't msgrcv to read-only var (F) The target of a msgrcv must be modifiable to be used as a receive buffer.
Can't "next" outside a loop block (F) A "next" statement was executed to reiterate the current block, but there isn't a current block. Note that an "if" or "else" block doesn't count as a "loopish" block, as doesn't a block given to sort(), map() or grep(). You can usually double the curlies to get the same effect though, because the inner curlies will be considered a block that loops once. See ["next" in perlfunc](perlfunc#next).
Can't open %s: %s (S inplace) The implicit opening of a file through use of the `<>` filehandle, either implicitly under the `-n` or `-p` command-line switches, or explicitly, failed for the indicated reason. Usually this is because you don't have read permission for a file which you named on the command line.
(F) You tried to call perl with the **-e** switch, but */dev/null* (or your operating system's equivalent) could not be opened.
Can't open a reference (W io) You tried to open a scalar reference for reading or writing, using the 3-arg open() syntax:
```
open FH, '>', $ref;
```
but your version of perl is compiled without perlio, and this form of open is not supported.
Can't open bidirectional pipe (W pipe) You tried to say `open(CMD, "|cmd|")`, which is not supported. You can try any of several modules in the Perl library to do this, such as IPC::Open2. Alternately, direct the pipe's output to a file using ">", and then read it in under a different file handle.
Can't open error file %s as stderr (F) An error peculiar to VMS. Perl does its own command line redirection, and couldn't open the file specified after '2>' or '2>>' on the command line for writing.
Can't open input file %s as stdin (F) An error peculiar to VMS. Perl does its own command line redirection, and couldn't open the file specified after '<' on the command line for reading.
Can't open output file %s as stdout (F) An error peculiar to VMS. Perl does its own command line redirection, and couldn't open the file specified after '>' or '>>' on the command line for writing.
Can't open output pipe (name: %s) (P) An error peculiar to VMS. Perl does its own command line redirection, and couldn't open the pipe into which to send data destined for stdout.
Can't open perl script "%s": %s (F) The script you specified can't be opened for the indicated reason.
If you're debugging a script that uses #!, and normally relies on the shell's $PATH search, the -S option causes perl to do that search, so you don't have to type the path or ``which $scriptname``.
Can't read CRTL environ (S) A warning peculiar to VMS. Perl tried to read an element of %ENV from the CRTL's internal environment array and discovered the array was missing. You need to figure out where your CRTL misplaced its environ or define *PERL\_ENV\_TABLES* (see <perlvms>) so that environ is not searched.
Can't redeclare "%s" in "%s" (F) A "my", "our" or "state" declaration was found within another declaration, such as `my ($x, my($y), $z)` or `our (my $x)`.
Can't "redo" outside a loop block (F) A "redo" statement was executed to restart the current block, but there isn't a current block. Note that an "if" or "else" block doesn't count as a "loopish" block, as doesn't a block given to sort(), map() or grep(). You can usually double the curlies to get the same effect though, because the inner curlies will be considered a block that loops once. See ["redo" in perlfunc](perlfunc#redo).
Can't remove %s: %s, skipping file (S inplace) You requested an inplace edit without creating a backup file. Perl was unable to remove the original file to replace it with the modified file. The file was left unmodified.
Can't rename in-place work file '%s' to '%s': %s (F) When closed implicitly, the temporary file for in-place editing couldn't be renamed to the original filename.
Can't rename %s to %s: %s, skipping file (F) The rename done by the **-i** switch failed for some reason, probably because you don't have write permission to the directory.
Can't reopen input pipe (name: %s) in binary mode (P) An error peculiar to VMS. Perl thought stdin was a pipe, and tried to reopen it to accept binary data. Alas, it failed.
Can't represent character for Ox%X on this platform (F) There is a hard limit to how big a character code point can be due to the fundamental properties of UTF-8, especially on EBCDIC platforms. The given code point exceeds that. The only work-around is to not use such a large code point.
Can't reset %ENV on this system (F) You called `reset('E')` or similar, which tried to reset all variables in the current package beginning with "E". In the main package, that includes %ENV. Resetting %ENV is not supported on some systems, notably VMS.
Can't resolve method "%s" overloading "%s" in package "%s" (F)(P) Error resolving overloading specified by a method name (as opposed to a subroutine reference): no such method callable via the package. If the method name is `???`, this is an internal error.
Can't return %s from lvalue subroutine (F) Perl detected an attempt to return illegal lvalues (such as temporary or readonly values) from a subroutine used as an lvalue. This is not allowed.
Can't return outside a subroutine (F) The return statement was executed in mainline code, that is, where there was no subroutine call to return out of. See <perlsub>.
Can't return %s to lvalue scalar context (F) You tried to return a complete array or hash from an lvalue subroutine, but you called the subroutine in a way that made Perl think you meant to return only one value. You probably meant to write parentheses around the call to the subroutine, which tell Perl that the call should be in list context.
Can't take log of %g (F) For ordinary real numbers, you can't take the logarithm of a negative number or zero. There's a Math::Complex package that comes standard with Perl, though, if you really want to do that for the negative numbers.
Can't take sqrt of %g (F) For ordinary real numbers, you can't take the square root of a negative number. There's a Math::Complex package that comes standard with Perl, though, if you really want to do that.
Can't undef active subroutine (F) You can't undefine a routine that's currently running. You can, however, redefine it while it's running, and you can even undef the redefined subroutine while the old routine is running. Go figure.
Can't unweaken a nonreference (F) You attempted to unweaken something that was not a reference. Only references can be unweakened.
Can't upgrade %s (%d) to %d (P) The internal sv\_upgrade routine adds "members" to an SV, making it into a more specialized kind of SV. The top several SV types are so specialized, however, that they cannot be interconverted. This message indicates that such a conversion was attempted.
Can't use '%c' after -mname (F) You tried to call perl with the **-m** switch, but you put something other than "=" after the module name.
Can't use a hash as a reference (F) You tried to use a hash as a reference, as in `%foo->{"bar"}` or `%$ref->{"hello"}`. Versions of perl <= 5.22.0 used to allow this syntax, but shouldn't have. This was deprecated in perl 5.6.1.
Can't use an array as a reference (F) You tried to use an array as a reference, as in `@foo->[23]` or `@$ref->[99]`. Versions of perl <= 5.22.0 used to allow this syntax, but shouldn't have. This was deprecated in perl 5.6.1.
Can't use anonymous symbol table for method lookup (F) The internal routine that does method lookup was handed a symbol table that doesn't have a name. Symbol tables can become anonymous for example by undefining stashes: `undef %Some::Package::`.
Can't use an undefined value as %s reference (F) A value used as either a hard reference or a symbolic reference must be a defined value. This helps to delurk some insidious errors.
Can't use bareword ("%s") as %s ref while "strict refs" in use (F) Only hard references are allowed by "strict refs". Symbolic references are disallowed. See <perlref>.
Can't use %! because Errno.pm is not available (F) The first time the `%!` hash is used, perl automatically loads the Errno.pm module. The Errno module is expected to tie the %! hash to provide symbolic names for `$!` errno values.
Can't use both '<' and '>' after type '%c' in %s (F) A type cannot be forced to have both big-endian and little-endian byte-order at the same time, so this combination of modifiers is not allowed. See ["pack" in perlfunc](perlfunc#pack).
Can't use 'defined(@array)' (Maybe you should just omit the defined()?) (F) defined() is not useful on arrays because it checks for an undefined *scalar* value. If you want to see if the array is empty, just use `if (@array) { # not empty }` for example.
Can't use 'defined(%hash)' (Maybe you should just omit the defined()?) (F) `defined()` is not usually right on hashes.
Although `defined %hash` is false on a plain not-yet-used hash, it becomes true in several non-obvious circumstances, including iterators, weak references, stash names, even remaining true after `undef %hash`. These things make `defined %hash` fairly useless in practice, so it now generates a fatal error.
If a check for non-empty is what you wanted then just put it in boolean context (see ["Scalar values" in perldata](perldata#Scalar-values)):
```
if (%hash) {
# not empty
}
```
If you had `defined %Foo::Bar::QUUX` to check whether such a package variable exists then that's never really been reliable, and isn't a good way to enquire about the features of a package, or whether it's loaded, etc.
Can't use %s for loop variable (P) The parser got confused when trying to parse a `foreach` loop.
Can't use global %s in %s (F) You tried to declare a magical variable as a lexical variable. This is not allowed, because the magic can be tied to only one location (namely the global variable) and it would be incredibly confusing to have variables in your program that looked like magical variables but weren't.
Can't use '%c' in a group with different byte-order in %s (F) You attempted to force a different byte-order on a type that is already inside a group with a byte-order modifier. For example you cannot force little-endianness on a type that is inside a big-endian group.
Can't use "my %s" in sort comparison (F) The global variables $a and $b are reserved for sort comparisons. You mentioned $a or $b in the same line as the <=> or cmp operator, and the variable had earlier been declared as a lexical variable. Either qualify the sort variable with the package name, or rename the lexical variable.
Can't use %s ref as %s ref (F) You've mixed up your reference types. You have to dereference a reference of the type needed. You can use the ref() function to test the type of the reference, if need be.
Can't use string ("%s") as %s ref while "strict refs" in use
Can't use string ("%s"...) as %s ref while "strict refs" in use (F) You've told Perl to dereference a string, something which `use strict` blocks to prevent it happening accidentally. See ["Symbolic references" in perlref](perlref#Symbolic-references). This can be triggered by an `@` or `$` in a double-quoted string immediately before interpolating a variable, for example in `"user @$twitter_id"`, which says to treat the contents of `$twitter_id` as an array reference; use a `\` to have a literal `@` symbol followed by the contents of `$twitter_id`: `"user \@$twitter_id"`.
Can't use subscript on %s (F) The compiler tried to interpret a bracketed expression as a subscript. But to the left of the brackets was an expression that didn't look like a hash or array reference, or anything else subscriptable.
Can't use \%c to mean $%c in expression (W syntax) In an ordinary expression, backslash is a unary operator that creates a reference to its argument. The use of backslash to indicate a backreference to a matched substring is valid only as part of a regular expression pattern. Trying to do this in ordinary Perl code produces a value that prints out looking like SCALAR(0xdecaf). Use the $1 form instead.
Can't weaken a nonreference (F) You attempted to weaken something that was not a reference. Only references can be weakened.
Can't "when" outside a topicalizer (F) You have used a when() block that is neither inside a `foreach` loop nor a `given` block. (Note that this error is issued on exit from the `when` block, so you won't get the error if the match fails, or if you use an explicit `continue`.)
Can't x= to read-only value (F) You tried to repeat a constant value (often the undefined value) with an assignment operator, which implies modifying the value itself. Perhaps you need to copy the value to a temporary, and repeat that.
Character following "\c" must be printable ASCII (F) In `\c*X*`, *X* must be a printable (non-control) ASCII character.
Note that ASCII characters that don't map to control characters are discouraged, and will generate the warning (when enabled) [""\c%c" is more clearly written simply as "%s""](#%22%5Cc%25c%22-is-more-clearly-written-simply-as-%22%25s%22).
Character following \%c must be '{' or a single-character Unicode property name in regex; marked by <-- HERE in m/%s/ (F) (In the above the `%c` is replaced by either `p` or `P`.) You specified something that isn't a legal Unicode property name. Most Unicode properties are specified by `\p{...}`. But if the name is a single character one, the braces may be omitted.
Character in 'C' format wrapped in pack (W pack) You said
```
pack("C", $x)
```
where $x is either less than 0 or more than 255; the `"C"` format is only for encoding native operating system characters (ASCII, EBCDIC, and so on) and not for Unicode characters, so Perl behaved as if you meant
```
pack("C", $x & 255)
```
If you actually want to pack Unicode codepoints, use the `"U"` format instead.
Character in 'c' format wrapped in pack (W pack) You said
```
pack("c", $x)
```
where $x is either less than -128 or more than 127; the `"c"` format is only for encoding native operating system characters (ASCII, EBCDIC, and so on) and not for Unicode characters, so Perl behaved as if you meant
```
pack("c", $x & 255);
```
If you actually want to pack Unicode codepoints, use the `"U"` format instead.
Character in '%c' format wrapped in unpack (W unpack) You tried something like
```
unpack("H", "\x{2a1}")
```
where the format expects to process a byte (a character with a value below 256), but a higher value was provided instead. Perl uses the value modulus 256 instead, as if you had provided:
```
unpack("H", "\x{a1}")
```
Character in 'W' format wrapped in pack (W pack) You said
```
pack("U0W", $x)
```
where $x is either less than 0 or more than 255. However, `U0`-mode expects all values to fall in the interval [0, 255], so Perl behaved as if you meant:
```
pack("U0W", $x & 255)
```
Character(s) in '%c' format wrapped in pack (W pack) You tried something like
```
pack("u", "\x{1f3}b")
```
where the format expects to process a sequence of bytes (character with a value below 256), but some of the characters had a higher value. Perl uses the character values modulus 256 instead, as if you had provided:
```
pack("u", "\x{f3}b")
```
Character(s) in '%c' format wrapped in unpack (W unpack) You tried something like
```
unpack("s", "\x{1f3}b")
```
where the format expects to process a sequence of bytes (character with a value below 256), but some of the characters had a higher value. Perl uses the character values modulus 256 instead, as if you had provided:
```
unpack("s", "\x{f3}b")
```
charnames alias definitions may not contain a sequence of multiple spaces; marked by <-- HERE in %s (F) You defined a character name which had multiple space characters in a row. Change them to single spaces. Usually these names are defined in the `:alias` import argument to `use charnames`, but they could be defined by a translator installed into `$^H{charnames}`. See ["CUSTOM ALIASES" in charnames](charnames#CUSTOM-ALIASES).
chdir() on unopened filehandle %s (W unopened) You tried chdir() on a filehandle that was never opened.
"\c%c" is more clearly written simply as "%s" (W syntax) The `\c*X*` construct is intended to be a way to specify non-printable characters. You used it for a printable one, which is better written as simply itself, perhaps preceded by a backslash for non-word characters. Doing it the way you did is not portable between ASCII and EBCDIC platforms.
Cloning substitution context is unimplemented (F) Creating a new thread inside the `s///` operator is not supported.
closedir() attempted on invalid dirhandle %s (W io) The dirhandle you tried to close is either closed or not really a dirhandle. Check your control flow.
close() on unopened filehandle %s (W unopened) You tried to close a filehandle that was never opened.
Closure prototype called (F) If a closure has attributes, the subroutine passed to an attribute handler is the prototype that is cloned when a new closure is created. This subroutine cannot be called.
\C no longer supported in regex; marked by <-- HERE in m/%s/ (F) The \C character class used to allow a match of single byte within a multi-byte utf-8 character, but was removed in v5.24 as it broke encapsulation and its implementation was extremely buggy. If you really need to process the individual bytes, you probably want to convert your string to one where each underlying byte is stored as a character, with utf8::encode().
Code missing after '/' (F) You had a (sub-)template that ends with a '/'. There must be another template code following the slash. See ["pack" in perlfunc](perlfunc#pack).
Code point 0x%X is not Unicode, and not portable (S non\_unicode portable) You had a code point that has never been in any standard, so it is likely that languages other than Perl will NOT understand it. This code point also will not fit in a 32-bit word on ASCII platforms and therefore is non-portable between systems.
At one time, it was legal in some standards to have code points up to 0x7FFF\_FFFF, but not higher, and this code point is higher.
Acceptance of these code points is a Perl extension, and you should expect that nothing other than Perl can handle them; Perl itself on EBCDIC platforms before v5.24 does not handle them.
Perl also makes no guarantees that the representation of these code points won't change at some point in the future, say when machines become available that have larger than a 64-bit word. At that time, files containing any of these, written by an older Perl might require conversion before being readable by a newer Perl.
Code point 0x%X is not Unicode, may not be portable (S non\_unicode) You had a code point above the Unicode maximum of U+10FFFF.
Perl allows strings to contain a superset of Unicode code points, but these may not be accepted by other languages/systems. Further, even if these languages/systems accept these large code points, they may have chosen a different representation for them than the UTF-8-like one that Perl has, which would mean files are not exchangeable between them and Perl.
On EBCDIC platforms, code points above 0x3FFF\_FFFF have a different representation in Perl v5.24 than before, so any file containing these that was written before that version will require conversion before being readable by a later Perl.
%s: Command not found (A) You've accidentally run your script through **csh** or another shell instead of Perl. Check the #! line, or manually feed your script into Perl yourself. The #! line at the top of your file could look like
```
#!/usr/bin/perl
```
%s: command not found (A) You've accidentally run your script through **bash** or another shell instead of Perl. Check the #! line, or manually feed your script into Perl yourself. The #! line at the top of your file could look like
```
#!/usr/bin/perl
```
%s: command not found: %s (A) You've accidentally run your script through **zsh** or another shell instead of Perl. Check the #! line, or manually feed your script into Perl yourself. The #! line at the top of your file could look like
```
#!/usr/bin/perl
```
Compilation failed in require (F) Perl could not compile a file specified in a `require` statement. Perl uses this generic message when none of the errors that it encountered were severe enough to halt compilation immediately.
Complex regular subexpression recursion limit (%d) exceeded (W regexp) The regular expression engine uses recursion in complex situations where back-tracking is required. Recursion depth is limited to 32766, or perhaps less in architectures where the stack cannot grow arbitrarily. ("Simple" and "medium" situations are handled without recursion and are not subject to a limit.) Try shortening the string under examination; looping in Perl code (e.g. with `while`) rather than in the regular expression engine; or rewriting the regular expression so that it is simpler or backtracks less. (See <perlfaq2> for information on *Mastering Regular Expressions*.)
connect() on closed socket %s (W closed) You tried to do a connect on a closed socket. Did you forget to check the return value of your socket() call? See ["connect" in perlfunc](perlfunc#connect).
Constant(%s): Call to &{$^H{%s}} did not return a defined value (F) The subroutine registered to handle constant overloading (see <overload>) or a custom charnames handler (see ["CUSTOM TRANSLATORS" in charnames](charnames#CUSTOM-TRANSLATORS)) returned an undefined value.
Constant(%s): $^H{%s} is not defined (F) The parser found inconsistencies while attempting to define an overloaded constant. Perhaps you forgot to load the corresponding <overload> pragma?
Constant is not %s reference (F) A constant value (perhaps declared using the `use constant` pragma) is being dereferenced, but it amounts to the wrong type of reference. The message indicates the type of reference that was expected. This usually indicates a syntax error in dereferencing the constant value. See ["Constant Functions" in perlsub](perlsub#Constant-Functions) and <constant>.
Constants from lexical variables potentially modified elsewhere are no longer permitted (F) 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.
This usage was deprecated, and as of Perl 5.32 is no longer allowed, making it possible to change the behavior in the future.
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 };
```
Constant subroutine %s redefined (W redefine)(S) You redefined a subroutine which had previously been eligible for inlining. See ["Constant Functions" in perlsub](perlsub#Constant-Functions) for commentary and workarounds.
Constant subroutine %s undefined (W misc) You undefined a subroutine which had previously been eligible for inlining. See ["Constant Functions" in perlsub](perlsub#Constant-Functions) for commentary and workarounds.
Constant(%s) unknown (F) The parser found inconsistencies either while attempting to define an overloaded constant, or when trying to find the character name specified in the `\N{...}` escape. Perhaps you forgot to load the corresponding <overload> pragma?
:const is experimental (S experimental::const\_attr) The "const" attribute is experimental. If you want to use the feature, disable the warning with `no warnings 'experimental::const_attr'`, but know that in doing so you are taking the risk that your code may break in a future Perl version.
:const is not permitted on named subroutines (F) The "const" attribute causes an anonymous subroutine to be run and its value captured at the time that it is cloned. Named subroutines are not cloned like this, so the attribute does not make sense on them.
Copy method did not return a reference (F) The method which overloads "=" is buggy. See ["Copy Constructor" in overload](overload#Copy-Constructor).
&CORE::%s cannot be called directly (F) You tried to call a subroutine in the `CORE::` namespace with `&foo` syntax or through a reference. Some subroutines in this package cannot yet be called that way, but must be called as barewords. Something like this will work:
```
BEGIN { *shove = \&CORE::push; }
shove @array, 1,2,3; # pushes on to @array
```
CORE::%s is not a keyword (F) The CORE:: namespace is reserved for Perl keywords.
Corrupted regexp opcode %d > %d (P) This is either an error in Perl, or, if you're using one, your [custom regular expression engine](perlreapi). If not the latter, report the problem to <https://github.com/Perl/perl5/issues>.
corrupted regexp pointers (P) The regular expression engine got confused by what the regular expression compiler gave it.
corrupted regexp program (P) The regular expression engine got passed a regexp program without a valid magic number.
Corrupt malloc ptr 0x%x at 0x%x (P) The malloc package that comes with Perl had an internal failure.
Count after length/code in unpack (F) You had an unpack template indicating a counted-length string, but you have also specified an explicit size for the string. See ["pack" in perlfunc](perlfunc#pack).
Declaring references is experimental (S experimental::declared\_refs) This warning is emitted if you use a reference constructor on the right-hand side of `my`, `state`, `our`, or `local`. Simply suppress the warning if you want to use the feature, but know that in doing so you are taking the risk of using an experimental feature which may change or be removed in a future Perl version:
```
no warnings "experimental::declared_refs";
use feature "declared_refs";
$fooref = my \$foo;
```
Deep recursion on anonymous subroutine
Deep recursion on subroutine "%s" (W recursion) This subroutine has called itself (directly or indirectly) 100 times more than it has returned. This probably indicates an infinite recursion, unless you're writing strange benchmark programs, in which case it indicates something else.
This threshold can be changed from 100, by recompiling the *perl* binary, setting the C pre-processor macro `PERL_SUB_DEPTH_WARN` to the desired value.
(?(DEFINE)....) does not allow branches in regex; marked by <-- HERE in m/%s/ (F) You used something like `(?(DEFINE)...|..)` which is illegal. The most likely cause of this error is that you left out a parenthesis inside of the `....` part.
The <-- HERE shows whereabouts in the regular expression the problem was discovered.
%s defines neither package nor VERSION--version check failed (F) You said something like "use Module 42" but in the Module file there are neither package declarations nor a `$VERSION`.
delete argument is not a HASH or ARRAY element or slice (F) The argument to `delete` must be either a hash or array element, such as:
```
$foo{$bar}
$ref->{"susie"}[12]
```
or a hash or array slice, such as:
```
@foo[$bar, $baz, $xyzzy]
$ref->[12]->@{"susie", "queue"}
```
or a hash key/value or array index/value slice, such as:
```
%foo[$bar, $baz, $xyzzy]
$ref->[12]->%{"susie", "queue"}
```
Delimiter for here document is too long (F) In a here document construct like `<<FOO`, the label `FOO` is too long for Perl to handle. You have to be seriously twisted to write code that triggers this error.
DESTROY created new reference to dead object '%s' (F) A DESTROY() method created a new reference to the object which is just being DESTROYed. Perl is confused, and prefers to abort rather than to create a dangling reference.
Did not produce a valid header See ["500 Server error"](#500-Server-error).
%s did not return a true value (F) A required (or used) file must return a true value to indicate that it compiled correctly and ran its initialization code correctly. It's traditional to end such a file with a "1;", though any true value would do. See ["require" in perlfunc](perlfunc#require).
(Did you mean &%s instead?) (W misc) You probably referred to an imported subroutine &FOO as $FOO or some such.
(Did you mean "local" instead of "our"?) (W shadow) Remember that "our" does not localize the declared global variable. You have declared it again in the same lexical scope, which seems superfluous.
(Did you mean $ or @ instead of %?) (W) You probably said %hash{$key} when you meant $hash{$key} or @hash{@keys}. On the other hand, maybe you just meant %hash and got carried away.
Died (F) You passed die() an empty string (the equivalent of `die ""`) or you called it with no args and `$@` was empty.
Document contains no data See ["500 Server error"](#500-Server-error).
%s does not define %s::VERSION--version check failed (F) You said something like "use Module 42" but the Module did not define a `$VERSION`.
'/' does not take a repeat count in %s (F) You cannot put a repeat count of any kind right after the '/' code. See ["pack" in perlfunc](perlfunc#pack).
do "%s" failed, '.' is no longer in @INC; did you mean do "./%s"? (D deprecated) Previously `do "somefile";` would search the current directory for the specified file. Since perl v5.26.0, *.* has been removed from `@INC` by default, so this is no longer true. To search the current directory (and only the current directory) you can write `do "./somefile";` .
Don't know how to get file name (P) `PerlIO_getname`, a perl internal I/O function specific to VMS, was somehow called on another platform. This should not happen.
Don't know how to handle magic of type \%o (P) The internal handling of magical variables has been cursed.
Downgrading a use VERSION declaration to below v5.11 is deprecated (S deprecated) This warning is emitted on a `use VERSION` statement that requests a version below v5.11 (when the effects of `use strict` would be disabled), after a previous declaration of one having a larger number (which would have enabled these effects). Because of a change to the way that `use VERSION` interacts with the strictness flags, this is no longer supported.
(Do you need to predeclare %s?) (S syntax) This is an educated guess made in conjunction with the message "%s found where operator expected". It often means a subroutine or module name is being referenced that hasn't been declared yet. This may be because of ordering problems in your file, or because of a missing "sub", "package", "require", or "use" statement. If you're referencing something that isn't defined yet, you don't actually have to define the subroutine or package before the current location. You can use an empty "sub foo;" or "package FOO;" to enter a "forward" declaration.
dump() must be written as CORE::dump() as of Perl 5.30 (F) You used the obsolete `dump()` built-in function. That was deprecated in Perl 5.8.0. As of Perl 5.30 it must be written in fully qualified format: `CORE::dump()`.
See ["dump" in perlfunc](perlfunc#dump).
dump is not supported (F) Your machine doesn't support dump/undump.
Duplicate free() ignored (S malloc) An internal routine called free() on something that had already been freed.
Duplicate modifier '%c' after '%c' in %s (W unpack) You have applied the same modifier more than once after a type in a pack template. See ["pack" in perlfunc](perlfunc#pack).
each on anonymous %s will always start from the beginning (W syntax) You called [each](perlfunc#each) on an anonymous hash or array. Since a new hash or array is created each time, each() will restart iterating over your hash or array every time.
elseif should be elsif (S syntax) There is no keyword "elseif" in Perl because Larry thinks it's ugly. Your code will be interpreted as an attempt to call a method named "elseif" for the class returned by the following block. This is unlikely to be what you want.
Empty \%c in regex; marked by <-- HERE in m/%s/
Empty \%c{}
Empty \%c{} in regex; marked by <-- HERE in m/%s/ (F) You used something like `\b{}`, `\B{}`, `\o{}`, `\p`, `\P`, or `\x` without specifying anything for it to operate on.
Unfortunately, for backwards compatibility reasons, an empty `\x` is legal outside `use re 'strict'` and expands to a NUL character.
Empty (?) without any modifiers in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'`) `(?)` does nothing, so perhaps this is a typo.
${^ENCODING} is no longer supported (F) The special variable `${^ENCODING}`, formerly used to implement the `encoding` pragma, is no longer supported as of Perl 5.26.0.
Setting it to anything other than `undef` is a fatal error as of Perl 5.28.
entering effective %s failed (F) While under the `use filetest` pragma, switching the real and effective uids or gids failed.
%ENV is aliased to %s (F) You're running under taint mode, and the `%ENV` variable has been aliased to another hash, so it doesn't reflect anymore the state of the program's environment. This is potentially insecure.
Error converting file specification %s (F) An error peculiar to VMS. Because Perl may have to deal with file specifications in either VMS or Unix syntax, it converts them to a single form when it must operate on them directly. Either you've passed an invalid file specification to Perl, or you've found a case the conversion routines don't handle. Drat.
Error %s in expansion of %s (F) An error was encountered in handling a user-defined property (["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties)). These are programmer written subroutines, hence subject to errors that may prevent them from compiling or running. The calls to these subs are `eval`'d, and if there is a failure, this message is raised, using the contents of `$@` from the failed `eval`.
Another possibility is that tainted data was encountered somewhere in the chain of expanding the property. If so, the message wording will indicate that this is the problem. See ["Insecure user-defined property %s"](#Insecure-user-defined-property-%25s).
Eval-group in insecure regular expression (F) Perl detected tainted data when trying to compile a regular expression that contains the `(?{ ... })` zero-width assertion, which is unsafe. See ["(?{ code })" in perlre](perlre#%28%3F%7B-code-%7D%29), and <perlsec>.
Eval-group not allowed at runtime, use re 'eval' in regex m/%s/ (F) Perl tried to compile a regular expression containing the `(?{ ... })` zero-width assertion at run time, as it would when the pattern contains interpolated values. Since that is a security risk, it is not allowed. If you insist, you may still do this by using the `re 'eval'` pragma or by explicitly building the pattern from an interpolated string at run time and using that in an eval(). See ["(?{ code })" in perlre](perlre#%28%3F%7B-code-%7D%29).
Eval-group not allowed, use re 'eval' in regex m/%s/ (F) A regular expression contained the `(?{ ... })` zero-width assertion, but that construct is only allowed when the `use re 'eval'` pragma is in effect. See ["(?{ code })" in perlre](perlre#%28%3F%7B-code-%7D%29).
EVAL without pos change exceeded limit in regex; marked by <-- HERE in m/%s/ (F) You used a pattern that nested too many EVAL calls without consuming any text. Restructure the pattern so that text is consumed.
The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Excessively long <> operator (F) The contents of a <> operator may not exceed the maximum size of a Perl identifier. If you're just trying to glob a long list of filenames, try using the glob() operator, or put the filenames into a variable and glob that.
exec? I'm not \*that\* kind of operating system (F) The `exec` function is not implemented on some systems, e.g. Catamount. See <perlport>.
%sExecution of %s aborted due to compilation errors. (F) The final summary message when a Perl compilation fails.
exists argument is not a HASH or ARRAY element or a subroutine (F) The argument to `exists` must be a hash or array element or a subroutine with an ampersand, such as:
```
$foo{$bar}
$ref->{"susie"}[12]
&do_something
```
exists argument is not a subroutine name (F) The argument to `exists` for `exists &sub` must be a subroutine name, and not a subroutine call. `exists &sub()` will generate this error.
Exiting eval via %s (W exiting) You are exiting an eval by unconventional means, such as a goto, or a loop control statement.
Exiting format via %s (W exiting) You are exiting a format by unconventional means, such as a goto, or a loop control statement.
Exiting pseudo-block via %s (W exiting) You are exiting a rather special block construct (like a sort block or subroutine) by unconventional means, such as a goto, or a loop control statement. See ["sort" in perlfunc](perlfunc#sort).
Exiting subroutine via %s (W exiting) You are exiting a subroutine by unconventional means, such as a goto, or a loop control statement.
Exiting substitution via %s (W exiting) You are exiting a substitution by unconventional means, such as a return, a goto, or a loop control statement.
Expecting close bracket in regex; marked by <-- HERE in m/%s/ (F) You wrote something like
```
(?13
```
to denote a capturing group of the form [`(?*PARNO*)`](perlre#%28%3FPARNO%29-%28%3F-PARNO%29-%28%3F%2BPARNO%29-%28%3FR%29-%28%3F0%29), but omitted the `")"`.
Expecting interpolated extended charclass in regex; marked by <-- HERE in m/%s/ (F) It looked like you were attempting to interpolate an already-compiled extended character class, like so:
```
my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
...
qr/(?[ \p{Digit} & $thai_or_lao ])/;
```
But the marked code isn't syntactically correct to be such an interpolated class.
Experimental aliasing via reference not enabled (F) To do aliasing via references, you must first enable the feature:
```
no warnings "experimental::refaliasing";
use feature "refaliasing";
\$x = \$y;
```
Experimental %s on scalar is now forbidden (F) An experimental feature added in Perl 5.14 allowed `each`, `keys`, `push`, `pop`, `shift`, `splice`, `unshift`, and `values` to be called with a scalar argument. This experiment is considered unsuccessful, and has been removed. The `postderef` feature may meet your needs better.
Experimental subroutine signatures not enabled (F) To use subroutine signatures, you must first enable them:
```
use feature "signatures";
sub foo ($left, $right) { ... }
```
Explicit blessing to '' (assuming package main) (W misc) You are blessing a reference to a zero length string. This has the effect of blessing the reference into the package main. This is usually not what you want. Consider providing a default target package, e.g. bless($ref, $p || 'MyPackage');
%s: Expression syntax (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
%s failed--call queue aborted (F) An untrapped exception was raised while executing a UNITCHECK, CHECK, INIT, or END subroutine. Processing of the remainder of the queue of such routines has been prematurely ended.
Failed to close in-place work file %s: %s (F) Closing an output file from in-place editing, as with the `-i` command-line switch, failed.
False [] range "%s" in regex; marked by <-- HERE in m/%s/ (W regexp)(F) A character class range must start and end at a literal character, not another character class like `\d` or `[:alpha:]`. The "-" in your false range is interpreted as a literal "-". In a `(?[...])` construct, this is an error, rather than a warning. Consider quoting the "-", "\-". The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Fatal VMS error (status=%d) at %s, line %d (P) An error peculiar to VMS. Something untoward happened in a VMS system service or RTL routine; Perl's exit status should provide more details. The filename in "at %s" and the line number in "line %d" tell you which section of the Perl source code is distressed.
fcntl is not implemented (F) Your machine apparently doesn't implement fcntl(). What is this, a PDP-11 or something?
FETCHSIZE returned a negative value (F) A tied array claimed to have a negative number of elements, which is not possible.
Field too wide in 'u' format in pack (W pack) Each line in an uuencoded string starts with a length indicator which can't encode values above 63. So there is no point in asking for a line length bigger than that. Perl will behave as if you specified `u63` as the format.
Filehandle %s opened only for input (W io) You tried to write on a read-only filehandle. If you intended it to be a read-write filehandle, you needed to open it with "+<" or "+>" or "+>>" instead of with "<" or nothing. If you intended only to write the file, use ">" or ">>". See ["open" in perlfunc](perlfunc#open).
Filehandle %s opened only for output (W io) You tried to read from a filehandle opened only for writing, If you intended it to be a read/write filehandle, you needed to open it with "+<" or "+>" or "+>>" instead of with ">". If you intended only to read from the file, use "<". See ["open" in perlfunc](perlfunc#open). Another possibility is that you attempted to open filedescriptor 0 (also known as STDIN) for output (maybe you closed STDIN earlier?).
Filehandle %s reopened as %s only for input (W io) You opened for reading a filehandle that got the same filehandle id as STDOUT or STDERR. This occurred because you closed STDOUT or STDERR previously.
Filehandle STDIN reopened as %s only for output (W io) You opened for writing a filehandle that got the same filehandle id as STDIN. This occurred because you closed STDIN previously.
Final $ should be \$ or $name (F) You must now decide whether the final $ in a string was meant to be a literal dollar sign, or was meant to introduce a variable name that happens to be missing. So you have to put either the backslash or the name.
defer is experimental (S experimental::defer) The `defer` block modifier is experimental. If you want to use the feature, disable the warning with `no warnings 'experimental::defer'`, but know that in doing so you are taking the risk that your code may break in a future Perl version.
flock() on closed filehandle %s (W closed) The filehandle you're attempting to flock() got itself closed some time before now. Check your control flow. flock() operates on filehandles. Are you attempting to call flock() on a dirhandle by the same name?
for my (...) is experimental (S experimental::for\_list) This warning is emitted if you use `for` to iterate multiple values at a time. This syntax is currently experimental and its behaviour may change in future releases of Perl.
Format not terminated (F) A format must be terminated by a line with a solitary dot. Perl got to the end of your file without finding such a line.
Format %s redefined (W redefine) You redefined a format. To suppress this warning, say
```
{
no warnings 'redefine';
eval "format NAME =...";
}
```
Found = in conditional, should be == (W syntax) You said
```
if ($foo = 123)
```
when you meant
```
if ($foo == 123)
```
(or something like that).
%s found where operator expected (S syntax) The Perl lexer knows whether to expect a term or an operator. If it sees what it knows to be a term when it was expecting to see an operator, it gives you this warning. Usually it indicates that an operator or delimiter was omitted, such as a semicolon.
gdbm store returned %d, errno %d, key "%s" (S) A warning from the GDBM\_File extension that a store failed.
gethostent not implemented (F) Your C library apparently doesn't implement gethostent(), probably because if it did, it'd feel morally obligated to return every hostname on the Internet.
get%sname() on closed socket %s (W closed) You tried to get a socket or peer socket name on a closed socket. Did you forget to check the return value of your socket() call?
getpwnam returned invalid UIC %#o for user "%s" (S) A warning peculiar to VMS. The call to `sys$getuai` underlying the `getpwnam` operator returned an invalid UIC.
getsockopt() on closed socket %s (W closed) You tried to get a socket option on a closed socket. Did you forget to check the return value of your socket() call? See ["getsockopt" in perlfunc](perlfunc#getsockopt).
given is experimental (S experimental::smartmatch) `given` depends on smartmatch, which is experimental, so its behavior may change or even be removed in any future release of perl. See the explanation under ["Experimental Details on given and when" in perlsyn](perlsyn#Experimental-Details-on-given-and-when).
Global symbol "%s" requires explicit package name (did you forget to declare "my %s"?) (F) You've said "use strict" or "use strict vars", which indicates that all variables must either be lexically scoped (using "my" or "state"), declared beforehand using "our", or explicitly qualified to say which package the global variable is in (using "::").
glob failed (%s) (S glob) Something went wrong with the external program(s) used for `glob` and `<*.c>`. Usually, this means that you supplied a `glob` pattern that caused the external program to fail and exit with a nonzero status. If the message indicates that the abnormal exit resulted in a coredump, this may also mean that your csh (C shell) is broken. If so, you should change all of the csh-related variables in config.sh: If you have tcsh, make the variables refer to it as if it were csh (e.g. `full_csh='/usr/bin/tcsh'`); otherwise, make them all empty (except that `d_csh` should be `'undef'`) so that Perl will think csh is missing. In either case, after editing config.sh, run `./Configure -S` and rebuild Perl.
Glob not terminated (F) The lexer saw a left angle bracket in a place where it was expecting a term, so it's looking for the corresponding right angle bracket, and not finding it. Chances are you left some needed parentheses out earlier in the line, and you really meant a "less than".
gmtime(%f) failed (W overflow) You called `gmtime` with a number that it could not handle: too large, too small, or NaN. The returned value is `undef`.
gmtime(%f) too large (W overflow) You called `gmtime` with a number that was larger than it can reliably handle and `gmtime` probably returned the wrong date. This warning is also triggered with NaN (the special not-a-number value).
gmtime(%f) too small (W overflow) You called `gmtime` with a number that was smaller than it can reliably handle and `gmtime` probably returned the wrong date.
Got an error from DosAllocMem (P) An error peculiar to OS/2. Most probably you're using an obsolete version of Perl, and this should not happen anyway.
goto must have label (F) Unlike with "next" or "last", you're not allowed to goto an unspecified destination. See ["goto" in perlfunc](perlfunc#goto).
Goto undefined subroutine%s (F) You tried to call a subroutine with `goto &sub` syntax, but the indicated subroutine hasn't been defined, or if it was, it has since been undefined.
Group name must start with a non-digit word character in regex; marked by <-- HERE in m/%s/ (F) Group names must follow the rules for perl identifiers, meaning they must start with a non-digit word character. A common cause of this error is using (?&0) instead of (?0). See <perlre>.
()-group starts with a count (F) A ()-group started with a count. A count is supposed to follow something: a template character or a ()-group. See ["pack" in perlfunc](perlfunc#pack).
%s had compilation errors. (F) The final summary message when a `perl -c` fails.
Had to create %s unexpectedly (S internal) A routine asked for a symbol from a symbol table that ought to have existed already, but for some reason it didn't, and had to be created on an emergency basis to prevent a core dump.
%s has too many errors (F) The parser has given up trying to parse the program after 10 errors. Further error messages would likely be uninformative.
Hexadecimal float: exponent overflow (W overflow) The hexadecimal floating point has a larger exponent than the floating point supports.
Hexadecimal float: exponent underflow (W overflow) The hexadecimal floating point has a smaller exponent than the floating point supports. With the IEEE 754 floating point, this may also mean that the subnormals (formerly known as denormals) are being used, which may or may not be an error.
Hexadecimal float: internal error (%s) (F) Something went horribly bad in hexadecimal float handling.
Hexadecimal float: mantissa overflow (W overflow) The hexadecimal floating point literal had more bits in the mantissa (the part between the 0x and the exponent, also known as the fraction or the significand) than the floating point supports.
Hexadecimal float: precision loss (W overflow) The hexadecimal floating point had internally more digits than could be output. This can be caused by unsupported long double formats, or by 64-bit integers not being available (needed to retrieve the digits under some configurations).
Hexadecimal float: unsupported long double format (F) You have configured Perl to use long doubles but the internals of the long double format are unknown; therefore the hexadecimal float output is impossible.
Hexadecimal number > 0xffffffff non-portable (W portable) The hexadecimal number you specified is larger than 2\*\*32-1 (4294967295) and therefore non-portable between systems. See <perlport> for more on portability concerns.
Identifier too long (F) Perl limits identifiers (names for variables, functions, etc.) to about 250 characters for simple names, and somewhat more for compound names (like `$A::B`). You've exceeded Perl's limits. Future versions of Perl are likely to eliminate these arbitrary limitations.
Ignoring zero length \N{} in character class in regex; marked by <-- HERE in m/%s/ (W regexp) Named Unicode character escapes (`\N{...}`) may return a zero-length sequence. When such an escape is used in a character class its behavior is not well defined. Check that the correct escape has been used, and the correct charname handler is in scope.
Illegal %s digit '%c' ignored (W digit) Here `%s` is one of "binary", "octal", or "hex". You may have tried to use a digit other than one that is legal for the given type, such as only 0 and 1 for binary. For octals, this is raised only if the illegal character is an '8' or '9'. For hex, 'A' - 'F' and 'a' - 'f' are legal. Interpretation of the number stopped just before the offending digit or character.
Illegal binary digit '%c' (F) You used a digit other than 0 or 1 in a binary number.
Illegal character after '\_' in prototype for %s : %s (W illegalproto) An illegal character was found in a prototype declaration. The '\_' in a prototype must be followed by a ';', indicating the rest of the parameters are optional, or one of '@' or '%', since those two will accept 0 or more final parameters.
Illegal character \%o (carriage return) (F) Perl normally treats carriage returns in the program text as it would any other whitespace, which means you should never see this error when Perl was built using standard options. For some reason, your version of Perl appears to have been built without this support. Talk to your Perl administrator.
Illegal character following sigil in a subroutine signature (F) A parameter in a subroutine signature contained an unexpected character following the `$`, `@` or `%` sigil character. Normally the sigil should be followed by the variable name or `=` etc. Perhaps you are trying use a prototype while in the scope of `use feature 'signatures'`? For example:
```
sub foo ($$) {} # legal - a prototype
use feature 'signatures;
sub foo ($$) {} # illegal - was expecting a signature
sub foo ($a, $b)
:prototype($$) {} # legal
```
Illegal character in prototype for %s : %s (W illegalproto) An illegal character was found in a prototype declaration. Legal characters in prototypes are $, @, %, \*, ;, [, ], &, \, and +. Perhaps you were trying to write a subroutine signature but didn't enable that feature first (`use feature 'signatures'`), so your signature was instead interpreted as a bad prototype.
Illegal declaration of anonymous subroutine (F) When using the `sub` keyword to construct an anonymous subroutine, you must always specify a block of code. See <perlsub>.
Illegal declaration of subroutine %s (F) A subroutine was not declared correctly. See <perlsub>.
Illegal division by zero (F) You tried to divide a number by 0. Either something was wrong in your logic, or you need to put a conditional in to guard against meaningless input.
Illegal modulus zero (F) You tried to divide a number by 0 to get the remainder. Most numbers don't take to this kindly.
Illegal number of bits in vec (F) The number of bits in vec() (the third argument) must be a power of two from 1 to 32 (or 64, if your platform supports that).
Illegal octal digit '%c' (F) You used an 8 or 9 in an octal number.
Illegal operator following parameter in a subroutine signature (F) A parameter in a subroutine signature, was followed by something other than `=` introducing a default, `,` or `)`.
```
use feature 'signatures';
sub foo ($=1) {} # legal
sub foo ($a = 1) {} # legal
sub foo ($a += 1) {} # illegal
sub foo ($a == 1) {} # illegal
```
Illegal pattern in regex; marked by <-- HERE in m/%s/ (F) You wrote something like
```
(?+foo)
```
The `"+"` is valid only when followed by digits, indicating a capturing group. See [`(?*PARNO*)`](perlre#%28%3FPARNO%29-%28%3F-PARNO%29-%28%3F%2BPARNO%29-%28%3FR%29-%28%3F0%29).
Illegal suidscript (F) The script run under suidperl was somehow illegal.
Illegal switch in PERL5OPT: -%c (X) The PERL5OPT environment variable may only be used to set the following switches: **-[CDIMUdmtw]**.
Illegal user-defined property name (F) You specified a Unicode-like property name in a regular expression pattern (using `\p{}` or `\P{}`) that Perl knows isn't an official Unicode property, and was likely meant to be a user-defined property name, but it can't be one of those, as they must begin with either `In` or `Is`. Check the spelling. See also ["Can't find Unicode property definition "%s""](#Can%27t-find-Unicode-property-definition-%22%25s%22).
Ill-formed CRTL environ value "%s" (W internal) A warning peculiar to VMS. Perl tried to read the CRTL's internal environ array, and encountered an element without the `=` delimiter used to separate keys from values. The element is ignored.
Ill-formed message in prime\_env\_iter: |%s| (W internal) A warning peculiar to VMS. Perl tried to read a logical name or CLI symbol definition when preparing to iterate over %ENV, and didn't see the expected delimiter between key and value, so the line was ignored.
(in cleanup) %s (W misc) This prefix usually indicates that a DESTROY() method raised the indicated exception. Since destructors are usually called by the system at arbitrary points during execution, and often a vast number of times, the warning is issued only once for any number of failures that would otherwise result in the same message being repeated.
Failure of user callbacks dispatched using the `G_KEEPERR` flag could also result in this warning. See ["G\_KEEPERR" in perlcall](perlcall#G_KEEPERR).
Implicit use of @\_ in %s with signatured subroutine is experimental (S experimental::args\_array\_with\_signatures) An expression that implicitly involves the `@_` arguments array was found in a subroutine that uses a signature. This is experimental because the interaction between the arguments array and parameter handling via signatures is not guaranteed to remain stable in any future version of Perl, and such code should be avoided.
Incomplete expression within '(?[ ])' in regex; marked by <-- HERE in m/%s/ (F) There was a syntax error within the `(?[ ])`. This can happen if the expression inside the construct was completely empty, or if there are too many or few operands for the number of operators. Perl is not smart enough to give you a more precise indication as to what is wrong.
Inconsistent hierarchy during C3 merge of class '%s': merging failed on parent '%s' (F) The method resolution order (MRO) of the given class is not C3-consistent, and you have enabled the C3 MRO for this class. See the C3 documentation in <mro> for more information.
Indentation on line %d of here-doc doesn't match delimiter (F) You have an indented here-document where one or more of its lines have whitespace at the beginning that does not match the closing delimiter.
For example, line 2 below is wrong because it does not have at least 2 spaces, but lines 1 and 3 are fine because they have at least 2:
```
if ($something) {
print <<~EOF;
Line 1
Line 2 not
Line 3
EOF
}
```
Note that tabs and spaces are compared strictly, meaning 1 tab will not match 8 spaces.
Infinite recursion in regex (F) You used a pattern that references itself without consuming any input text. You should check the pattern to ensure that recursive patterns either consume text or fail.
Infinite recursion in user-defined property (F) A user-defined property (["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties)) can depend on the definitions of other user-defined properties. If the chain of dependencies leads back to this property, infinite recursion would occur, were it not for the check that raised this error.
Restructure your property definitions to avoid this.
Infinite recursion via empty pattern (F) You tried to use the empty pattern inside of a regex code block, for instance `/(?{ s!!! })/`, which resulted in re-executing the same pattern, which is an infinite loop which is broken by throwing an exception.
Initialization of state variables in list currently forbidden (F) `state` only permits initializing a single variable, specified without parentheses. So `state $a = 42` and `state @a = qw(a b c)` are allowed, but not `state ($a) = 42` or `(state $a) = 42`. To initialize more than one `state` variable, initialize them one at a time.
%%s[%s] in scalar context better written as $%s[%s] (W syntax) In scalar context, you've used an array index/value slice (indicated by %) to select a single element of an array. Generally it's better to ask for a scalar value (indicated by $). The difference is that `$foo[&bar]` always behaves like a scalar, both in the value it returns and when evaluating its argument, while `%foo[&bar]` provides a list context to its subscript, which can do weird things if you're expecting only one subscript. When called in list context, it also returns the index (what `&bar` returns) in addition to the value.
%%s{%s} in scalar context better written as $%s{%s} (W syntax) In scalar context, you've used a hash key/value slice (indicated by %) to select a single element of a hash. Generally it's better to ask for a scalar value (indicated by $). The difference is that `$foo{&bar}` always behaves like a scalar, both in the value it returns and when evaluating its argument, while `@foo{&bar}` and provides a list context to its subscript, which can do weird things if you're expecting only one subscript. When called in list context, it also returns the key in addition to the value.
Insecure dependency in %s (F) You tried to do something that the tainting mechanism didn't like. The tainting mechanism is turned on when you're running setuid or setgid, or when you specify **-T** to turn it on explicitly. The tainting mechanism labels all data that's derived directly or indirectly from the user, who is considered to be unworthy of your trust. If any such data is used in a "dangerous" operation, you get this error. See <perlsec> for more information.
Insecure directory in %s (F) You can't use system(), exec(), or a piped open in a setuid or setgid script if `$ENV{PATH}` contains a directory that is writable by the world. Also, the PATH must not contain any relative directory. See <perlsec>.
Insecure $ENV{%s} while running %s (F) You can't use system(), exec(), or a piped open in a setuid or setgid script if any of `$ENV{PATH}`, `$ENV{IFS}`, `$ENV{CDPATH}`, `$ENV{ENV}`, `$ENV{BASH_ENV}` or `$ENV{TERM}` are derived from data supplied (or potentially supplied) by the user. The script must set the path to a known value, using trustworthy data. See <perlsec>.
Insecure user-defined property %s (F) Perl detected tainted data when trying to compile a regular expression that contains a call to a user-defined character property function, i.e. `\p{IsFoo}` or `\p{InFoo}`. See ["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties) and <perlsec>.
Integer overflow in format string for %s (F) The indexes and widths specified in the format string of `printf()` or `sprintf()` are too large. The numbers must not overflow the size of integers for your architecture.
Integer overflow in %s number (S overflow) The hexadecimal, octal or binary number you have specified either as a literal or as an argument to hex() or oct() is too big for your architecture, and has been converted to a floating point number. On a 32-bit architecture the largest hexadecimal, octal or binary number representable without overflow is 0xFFFFFFFF, 037777777777, or 0b11111111111111111111111111111111 respectively. Note that Perl transparently promotes all numbers to a floating point representation internally--subject to loss of precision errors in subsequent operations.
Integer overflow in srand (S overflow) The number you have passed to srand is too big to fit in your architecture's integer representation. The number has been replaced with the largest integer supported (0xFFFFFFFF on 32-bit architectures). This means you may be getting less randomness than you expect, because different random seeds above the maximum will return the same sequence of random numbers.
Integer overflow in version
Integer overflow in version %d (W overflow) Some portion of a version initialization is too large for the size of integers for your architecture. This is not a warning because there is no rational reason for a version to try and use an element larger than typically 2\*\*32. This is usually caused by trying to use some odd mathematical operation as a version, like 100/9.
Internal disaster in regex; marked by <-- HERE in m/%s/ (P) Something went badly wrong in the regular expression parser. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Internal inconsistency in tracking vforks (S) A warning peculiar to VMS. Perl keeps track of the number of times you've called `fork` and `exec`, to determine whether the current call to `exec` should affect the current script or a subprocess (see ["exec LIST" in perlvms](perlvms#exec-LIST)). Somehow, this count has become scrambled, so Perl is making a guess and treating this `exec` as a request to terminate the Perl script and execute the specified command.
internal %<num>p might conflict with future printf extensions (S internal) Perl's internal routine that handles `printf` and `sprintf` formatting follows a slightly different set of rules when called from C or XS code. Specifically, formats consisting of digits followed by "p" (e.g., "%7p") are reserved for future use. If you see this message, then an XS module tried to call that routine with one such reserved format.
Internal urp in regex; marked by <-- HERE in m/%s/ (P) Something went badly awry in the regular expression parser. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
%s (...) interpreted as function (W syntax) You've run afoul of the rule that says that any list operator followed by parentheses turns into a function, with all the list operators arguments found inside the parentheses. See ["Terms and List Operators (Leftward)" in perlop](perlop#Terms-and-List-Operators-%28Leftward%29).
In '(?...)', the '(' and '?' must be adjacent in regex; marked by <-- HERE in m/%s/ (F) The two-character sequence `"(?"` in this context in a regular expression pattern should be an indivisible token, with nothing intervening between the `"("` and the `"?"`, but you separated them with whitespace.
In '(\*...)', the '(' and '\*' must be adjacent in regex; marked by <-- HERE in m/%s/ (F) The two-character sequence `"(*"` in this context in a regular expression pattern should be an indivisible token, with nothing intervening between the `"("` and the `"*"`, but you separated them. Fix the pattern and retry.
Invalid %s attribute: %s (F) The indicated attribute for a subroutine or variable was not recognized by Perl or by a user-supplied handler. See <attributes>.
Invalid %s attributes: %s (F) The indicated attributes for a subroutine or variable were not recognized by Perl or by a user-supplied handler. See <attributes>.
Invalid character in charnames alias definition; marked by <-- HERE in '%s (F) You tried to create a custom alias for a character name, with the `:alias` option to `use charnames` and the specified character in the indicated name isn't valid. See ["CUSTOM ALIASES" in charnames](charnames#CUSTOM-ALIASES).
Invalid \0 character in %s for %s: %s\0%s (W syscalls) Embedded \0 characters in pathnames or other system call arguments produce a warning as of 5.20. The parts after the \0 were formerly ignored by system calls.
Invalid character in \N{...}; marked by <-- HERE in \N{%s} (F) Only certain characters are valid for character names. The indicated one isn't. See ["CUSTOM ALIASES" in charnames](charnames#CUSTOM-ALIASES).
Invalid conversion in %s: "%s" (W printf) Perl does not understand the given format conversion. See ["sprintf" in perlfunc](perlfunc#sprintf).
Invalid escape in the specified encoding in regex; marked by <-- HERE in m/%s/ (W regexp)(F) The numeric escape (for example `\xHH`) of value < 256 didn't correspond to a single character through the conversion from the encoding specified by the encoding pragma. The escape was replaced with REPLACEMENT CHARACTER (U+FFFD) instead, except within `(?[ ])`, where it is a fatal error. The <-- HERE shows whereabouts in the regular expression the escape was discovered.
Invalid hexadecimal number in \N{U+...}
Invalid hexadecimal number in \N{U+...} in regex; marked by <-- HERE in m/%s/ (F) The character constant represented by `...` is not a valid hexadecimal number. Either it is empty, or you tried to use a character other than 0 - 9 or A - F, a - f in a hexadecimal number.
Invalid module name %s with -%c option: contains single ':' (F) The module argument to perl's **-m** and **-M** command-line options cannot contain single colons in the module name, but only in the arguments after "=". In other words, **-MFoo::Bar=:baz** is ok, but **-MFoo:Bar=baz** is not.
Invalid mro name: '%s' (F) You tried to `mro::set_mro("classname", "foo")` or `use mro 'foo'`, where `foo` is not a valid method resolution order (MRO). Currently, the only valid ones supported are `dfs` and `c3`, unless you have loaded a module that is a MRO plugin. See <mro> and <perlmroapi>.
Invalid negative number (%s) in chr (W utf8) You passed a negative number to `chr`. Negative numbers are not valid character numbers, so it returns the Unicode replacement character (U+FFFD).
Invalid number '%s' for -C option. (F) You supplied a number to the -C option that either has extra leading zeroes or overflows perl's unsigned integer representation.
invalid option -D%c, use -D'' to see choices (S debugging) Perl was called with invalid debugger flags. Call perl with the **-D** option with no flags to see the list of acceptable values. See also ["-Dletters" in perlrun](perlrun#-Dletters).
Invalid quantifier in {,} in regex; marked by <-- HERE in m/%s/ (F) The pattern looks like a {min,max} quantifier, but the min or max could not be parsed as a valid number - either it has leading zeroes, or it represents too big a number to cope with. The <-- HERE shows where in the regular expression the problem was discovered. See <perlre>.
Invalid [] range "%s" in regex; marked by <-- HERE in m/%s/ (F) The range specified in a character class had a minimum character greater than the maximum character. One possibility is that you forgot the `{}` from your ending `\x{}` - `\x` without the curly braces can go only up to `ff`. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Invalid range "%s" in transliteration operator (F) The range specified in the tr/// or y/// operator had a minimum character greater than the maximum character. See <perlop>.
Invalid reference to group in regex; marked by <-- HERE in m/%s/ (F) The capture group you specified can't possibly exist because the number you used is not within the legal range of possible values for this machine.
Invalid separator character %s in attribute list (F) Something other than a colon or whitespace was seen between the elements of an attribute list. If the previous attribute had a parenthesised parameter list, perhaps that list was terminated too soon. See <attributes>.
Invalid separator character %s in PerlIO layer specification %s (W layer) When pushing layers onto the Perl I/O system, something other than a colon or whitespace was seen between the elements of a layer list. If the previous attribute had a parenthesised parameter list, perhaps that list was terminated too soon.
Invalid strict version format (%s) (F) A version number did not meet the "strict" criteria for versions. A "strict" version number is a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. The parenthesized text indicates which criteria were not met. See the <version> module for more details on allowed version formats.
Invalid type '%s' in %s (F) The given character is not a valid pack or unpack type. See ["pack" in perlfunc](perlfunc#pack).
(W) The given character is not a valid pack or unpack type but used to be silently ignored.
Invalid version format (%s) (F) A version number did not meet the "lax" criteria for versions. A "lax" version number is a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string. If the v-string has fewer than three components, it must have a leading 'v' character. Otherwise, the leading 'v' is optional. Both decimal and dotted-decimal versions may have a trailing "alpha" component separated by an underscore character after a fractional or dotted-decimal component. The parenthesized text indicates which criteria were not met. See the <version> module for more details on allowed version formats.
Invalid version object (F) The internal structure of the version object was invalid. Perhaps the internals were modified directly in some way or an arbitrary reference was blessed into the "version" class.
In '(\*VERB...)', the '(' and '\*' must be adjacent in regex; marked by <-- HERE in m/%s/
Inverting a character class which contains a multi-character sequence is illegal in regex; marked by <-- HERE in m/%s/ (F) You wrote something like
```
qr/\P{name=KATAKANA LETTER AINU P}/
qr/[^\p{name=KATAKANA LETTER AINU P}]/
```
This name actually evaluates to a sequence of two Katakana characters, not just a single one, and it is illegal to try to take the complement of a sequence. (Mathematically it would mean any sequence of characters from 0 to infinity in length that weren't these two in a row, and that is likely not of any real use.)
(F) The two-character sequence `"(*"` in this context in a regular expression pattern should be an indivisible token, with nothing intervening between the `"("` and the `"*"`, but you separated them.
ioctl is not implemented (F) Your machine apparently doesn't implement ioctl(), which is pretty strange for a machine that supports C.
ioctl() on unopened %s (W unopened) You tried ioctl() on a filehandle that was never opened. Check your control flow and number of arguments.
IO layers (like '%s') unavailable (F) Your Perl has not been configured to have PerlIO, and therefore you cannot use IO layers. To have PerlIO, Perl must be configured with 'useperlio'.
IO::Socket::atmark not implemented on this architecture (F) Your machine doesn't implement the sockatmark() functionality, neither as a system call nor an ioctl call (SIOCATMARK).
'%s' is an unknown bound type in regex; marked by <-- HERE in m/%s/ (F) You used `\b{...}` or `\B{...}` and the `...` is not known to Perl. The current valid ones are given in ["\b{}, \b, \B{}, \B" in perlrebackslash](perlrebackslash#%5Cb%7B%7D%2C-%5Cb%2C-%5CB%7B%7D%2C-%5CB).
%s is forbidden - matches null string many times in regex; marked by <-- HERE in m/%s/ (F) The pattern you've specified might cause the regular expression to infinite loop so it is forbidden. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
%s() isn't allowed on :utf8 handles (F) The sysread(), recv(), syswrite() and send() operators are not allowed on handles that have the `:utf8` layer, either explicitly, or implicitly, eg., with the `:encoding(UTF-16LE)` layer.
Previously sysread() and recv() currently use only the `:utf8` flag for the stream, ignoring the actual layers. Since sysread() and recv() did no UTF-8 validation they can end up creating invalidly encoded scalars.
Similarly, syswrite() and send() used only the `:utf8` flag, otherwise ignoring any layers. If the flag is set, both wrote 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.
"%s" is more clearly written simply as "%s" in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'` or within `(?[...])`)
You specified a character that has the given plainer way of writing it, and which is also portable to platforms running with different character sets.
$\* is no longer supported as of Perl 5.30 (F) The special variable `$*`, deprecated in older perls, was removed in 5.10.0, is no longer supported and is a fatal error as of Perl 5.30. In previous versions of perl the use of `$*` enabled or disabled multi-line matching within a string.
Instead of using `$*` you should use the `/m` (and maybe `/s`) regexp modifiers. You can enable `/m` for a lexical scope (even a whole file) with `use re '/m'`. (In older versions: when `$*` was set to a true value then all regular expressions behaved as if they were written using `/m`.)
Use of this variable will be a fatal error in Perl 5.30.
$# is no longer supported as of Perl 5.30 (F) The special variable `$#`, deprecated in older perls, was removed as of 5.10.0, is no longer supported and is a fatal error as of Perl 5.30. You should use the printf/sprintf functions instead.
'%s' is not a code reference (W overload) The second (fourth, sixth, ...) argument of overload::constant needs to be a code reference. Either an anonymous subroutine, or a reference to a subroutine.
'%s' is not an overloadable type (W overload) You tried to overload a constant type the overload package is unaware of.
'%s' is not recognised as a builtin function (F) An attempt was made to `use` the <builtin> pragma module to create a lexical alias for an unknown function name.
-i used with no filenames on the command line, reading from STDIN (S inplace) The `-i` option was passed on the command line, indicating that the script is intended to edit files in place, but no files were given. This is usually a mistake, since editing STDIN in place doesn't make sense, and can be confusing because it can make perl look like it is hanging when it is really just trying to read from STDIN. You should either pass a filename to edit, or remove `-i` from the command line. See [perlrun](perlrun#-i%5Bextension%5D) for more details.
Junk on end of regexp in regex m/%s/ (P) The regular expression parser is confused.
\K not permitted in lookahead/lookbehind in regex; marked by <-- HERE in m/%s/ (F) Your regular expression used `\K` in a lookahead or lookbehind assertion, which currently isn't permitted.
This may change in the future, see [Support \K in lookarounds](https://github.com/Perl/perl5/issues/18134).
Label not found for "last %s" (F) You named a loop to break out of, but you're not currently in a loop of that name, not even if you count where you were called from. See ["last" in perlfunc](perlfunc#last).
Label not found for "next %s" (F) You named a loop to continue, but you're not currently in a loop of that name, not even if you count where you were called from. See ["last" in perlfunc](perlfunc#last).
Label not found for "redo %s" (F) You named a loop to restart, but you're not currently in a loop of that name, not even if you count where you were called from. See ["last" in perlfunc](perlfunc#last).
leaving effective %s failed (F) While under the `use filetest` pragma, switching the real and effective uids or gids failed.
length/code after end of string in unpack (F) While unpacking, the string buffer was already used up when an unpack length/code combination tried to obtain more data. This results in an undefined value for the length. See ["pack" in perlfunc](perlfunc#pack).
length() used on %s (did you mean "scalar(%s)"?) (W syntax) You used length() on either an array or a hash when you probably wanted a count of the items.
Array size can be obtained by doing:
```
scalar(@array);
```
The number of items in a hash can be obtained by doing:
```
scalar(keys %hash);
```
Lexing code attempted to stuff non-Latin-1 character into Latin-1 input (F) An extension is attempting to insert text into the current parse (using [lex\_stuff\_pvn](perlapi#lex_stuff_pvn) or similar), but tried to insert a character that couldn't be part of the current input. This is an inherent pitfall of the stuffing mechanism, and one of the reasons to avoid it. Where it is necessary to stuff, stuffing only plain ASCII is recommended.
Lexing code internal error (%s) (F) Lexing code supplied by an extension violated the lexer's API in a detectable way.
listen() on closed socket %s (W closed) You tried to do a listen on a closed socket. Did you forget to check the return value of your socket() call? See ["listen" in perlfunc](perlfunc#listen).
List form of piped open not implemented (F) On some platforms, notably Windows, the three-or-more-arguments form of `open` does not support pipes, such as `open($pipe, '|-', @args)`. Use the two-argument `open($pipe, '|prog arg1 arg2...')` form instead.
Literal vertical space in [] is illegal except under /x in regex; marked by <-- HERE in m/%s/ (F) (only under `use re 'strict'` or within `(?[...])`)
Likely you forgot the `/x` modifier or there was a typo in the pattern. For example, did you really mean to match a form-feed? If so, all the ASCII vertical space control characters are representable by escape sequences which won't present such a jarring appearance as your pattern does when displayed.
```
\r carriage return
\f form feed
\n line feed
\cK vertical tab
```
%s: loadable library and perl binaries are mismatched (got %s handshake key %p, needed %p) (P) A dynamic loading library `.so` or `.dll` was being loaded into the process that was built against a different build of perl than the said library was compiled against. Reinstalling the XS module will likely fix this error.
Locale '%s' contains (at least) the following characters which have unexpected meanings: %s The Perl program will use the expected meanings (W locale) You are using the named UTF-8 locale. UTF-8 locales are expected to have very particular behavior, which most do. This message arises when perl found some departures from the expectations, and is notifying you that the expected behavior overrides these differences. In some cases the differences are caused by the locale definition being defective, but the most common causes of this warning are when there are ambiguities and conflicts in following the Standard, and the locale has chosen an approach that differs from Perl's.
One of these is because that, contrary to the claims, Unicode is not completely locale insensitive. Turkish and some related languages have two types of `"I"` characters. One is dotted in both upper- and lowercase, and the other is dotless in both cases. Unicode allows a locale to use either the Turkish rules, or the rules used in all other instances, where there is only one type of `"I"`, which is dotless in the uppercase, and dotted in the lower. The perl core does not (yet) handle the Turkish case, and this message warns you of that. Instead, the <Unicode::Casing> module allows you to mostly implement the Turkish casing rules.
The other common cause is for the characters
```
$ + < = > ^ ` | ~
```
These are problematic. The C standard says that these should be considered punctuation in the C locale (and the POSIX standard defers to the C standard), and Unicode is generally considered a superset of the C locale. But Unicode has added an extra category, "Symbol", and classifies these particular characters as being symbols. Most UTF-8 locales have them treated as punctuation, so that [ispunct(2)](http://man.he.net/man2/ispunct) returns non-zero for them. But a few locales have it return 0. Perl takes the first approach, not using `ispunct()` at all (see [Note [5] in perlrecharclass](perlrecharclass#%5B5%5D)), and this message is raised to notify you that you are getting Perl's approach, not the locale's.
Locale '%s' may not work well.%s (W locale) You are using the named locale, which is a non-UTF-8 one, and which perl has determined is not fully compatible with what it can handle. The second `%s` gives a reason.
By far the most common reason is that the locale has characters in it that are represented by more than one byte. The only such locales that Perl can handle are the UTF-8 locales. Most likely the specified locale is a non-UTF-8 one for an East Asian language such as Chinese or Japanese. If the locale is a superset of ASCII, the ASCII portion of it may work in Perl.
Some essentially obsolete locales that aren't supersets of ASCII, mainly those in ISO 646 or other 7-bit locales, such as ASMO 449, can also have problems, depending on what portions of the ASCII character set get changed by the locale and are also used by the program. The warning message lists the determinable conflicting characters.
Note that not all incompatibilities are found.
If this happens to you, there's not much you can do except switch to use a different locale or use [Encode](encode) to translate from the locale into UTF-8; if that's impracticable, you have been warned that some things may break.
This message is output once each time a bad locale is switched into within the scope of `use locale`, or on the first possibly-affected operation if the `use locale` inherits a bad one. It is not raised for any operations from the [POSIX](posix) module.
localtime(%f) failed (W overflow) You called `localtime` with a number that it could not handle: too large, too small, or NaN. The returned value is `undef`.
localtime(%f) too large (W overflow) You called `localtime` with a number that was larger than it can reliably handle and `localtime` probably returned the wrong date. This warning is also triggered with NaN (the special not-a-number value).
localtime(%f) too small (W overflow) You called `localtime` with a number that was smaller than it can reliably handle and `localtime` probably returned the wrong date.
Lookbehind longer than %d not implemented in regex m/%s/ (F) There is currently a limit on the length of string which lookbehind can handle. This restriction may be eased in a future release.
Lost precision when %s %f by 1 (W imprecision) You attempted to increment or decrement a value by one, but the result is too large for the underlying floating point representation to store accurately. Hence, the target of `++` or `--` is increased or decreased by quite different value than one, such as zero (*i.e.* the target is unchanged) or two, due to rounding. Perl issues this warning because it has already switched from integers to floating point when values are too large for integers, and now even floating point is insufficient. You may wish to switch to using <Math::BigInt> explicitly.
lstat() on filehandle%s (W io) You tried to do an lstat on a filehandle. What did you mean by that? lstat() makes sense only on filenames. (Perl did a fstat() instead on the filehandle.)
lvalue attribute %s already-defined subroutine (W misc) Although [attributes.pm](attributes) allows this, turning the lvalue attribute on or off on a Perl subroutine that is already defined does not always work properly. It may or may not do what you want, depending on what code is inside the subroutine, with exact details subject to change between Perl versions. Only do this if you really know what you are doing.
lvalue attribute ignored after the subroutine has been defined (W misc) Using the `:lvalue` declarative syntax to make a Perl subroutine an lvalue subroutine after it has been defined is not permitted. To make the subroutine an lvalue subroutine, add the lvalue attribute to the definition, or put the `sub foo :lvalue;` declaration before the definition.
See also [attributes.pm](attributes).
Magical list constants are not supported (F) You assigned a magical array to a stash element, and then tried to use the subroutine from the same slot. You are asking Perl to do something it cannot do, details subject to change between Perl versions.
Malformed integer in [] in pack (F) Between the brackets enclosing a numeric repeat count only digits are permitted. See ["pack" in perlfunc](perlfunc#pack).
Malformed integer in [] in unpack (F) Between the brackets enclosing a numeric repeat count only digits are permitted. See ["pack" in perlfunc](perlfunc#pack).
Malformed PERLLIB\_PREFIX (F) An error peculiar to OS/2. PERLLIB\_PREFIX should be of the form
```
prefix1;prefix2
```
or prefix1 prefix2
with nonempty prefix1 and prefix2. If `prefix1` is indeed a prefix of a builtin library search path, prefix2 is substituted. The error may appear if components are not found, or are too long. See "PERLLIB\_PREFIX" in <perlos2>.
Malformed prototype for %s: %s (F) You tried to use a function with a malformed prototype. The syntax of function prototypes is given a brief compile-time check for obvious errors like invalid characters. A more rigorous check is run when the function is called. Perhaps the function's author was trying to write a subroutine signature but didn't enable that feature first (`use feature 'signatures'`), so the signature was instead interpreted as a bad prototype.
Malformed UTF-8 character%s (S utf8)(F) Perl detected a string that should be UTF-8, but didn't comply with UTF-8 encoding rules, or represents a code point whose ordinal integer value doesn't fit into the word size of the current platform (overflows). Details as to the exact malformation are given in the variable, `%s`, part of the message.
One possible cause is that you set the UTF8 flag yourself for data that you thought to be in UTF-8 but it wasn't (it was for example legacy 8-bit data). To guard against this, you can use `Encode::decode('UTF-8', ...)`.
If you use the `:encoding(UTF-8)` PerlIO layer for input, invalid byte sequences are handled gracefully, but if you use `:utf8`, the flag is set without validating the data, possibly resulting in this error message.
See also ["Handling Malformed Data" in Encode](encode#Handling-Malformed-Data).
Malformed UTF-8 returned by \N{%s} immediately after '%s' (F) The charnames handler returned malformed UTF-8.
Malformed UTF-8 string in "%s" (F) 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.
Malformed UTF-8 string in '%c' format in unpack (F) You tried to unpack something that didn't comply with UTF-8 encoding rules and perl was unable to guess how to make more progress.
Malformed UTF-8 string in pack (F) You tried to pack something that didn't comply with UTF-8 encoding rules and perl was unable to guess how to make more progress.
Malformed UTF-8 string in unpack (F) You tried to unpack something that didn't comply with UTF-8 encoding rules and perl was unable to guess how to make more progress.
Malformed UTF-16 surrogate (F) Perl thought it was reading UTF-16 encoded character data but while doing it Perl met a malformed Unicode surrogate.
Mandatory parameter follows optional parameter (F) In a subroutine signature, you wrote something like "$a = undef, $b", making an earlier parameter optional and a later one mandatory. Parameters are filled from left to right, so it's impossible for the caller to omit an earlier one and pass a later one. If you want to act as if the parameters are filled from right to left, declare the rightmost optional and then shuffle the parameters around in the subroutine's body.
Matched non-Unicode code point 0x%X against Unicode property; may not be portable (S non\_unicode) Perl allows strings to contain a superset of Unicode code points; each code point may be as large as what is storable in a signed integer on your system, but these may not be accepted by other languages/systems. This message occurs when you matched a string containing such a code point against a regular expression pattern, and the code point was matched against a Unicode property, `\p{...}` or `\P{...}`. Unicode properties are only defined on Unicode code points, so the result of this match is undefined by Unicode, but Perl (starting in v5.20) treats non-Unicode code points as if they were typical unassigned Unicode ones, and matched this one accordingly. Whether a given property matches these code points or not is specified in ["Properties accessible through \p{} and \P{}" in perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D).
This message is suppressed (unless it has been made fatal) if it is immaterial to the results of the match if the code point is Unicode or not. For example, the property `\p{ASCII_Hex_Digit}` only can match the 22 characters `[0-9A-Fa-f]`, so obviously all other code points, Unicode or not, won't match it. (And `\P{ASCII_Hex_Digit}` will match every code point except these 22.)
Getting this message indicates that the outcome of the match arguably should have been the opposite of what actually happened. If you think that is the case, you may wish to make the `non_unicode` warnings category fatal; if you agree with Perl's decision, you may wish to turn off this category.
See ["Beyond Unicode code points" in perlunicode](perlunicode#Beyond-Unicode-code-points) for more information.
%s matches null string many times in regex; marked by <-- HERE in m/%s/ (W regexp) The pattern you've specified would be an infinite loop if the regular expression engine didn't specifically check for that. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Maximal count of pending signals (%u) exceeded (F) Perl aborted due to too high a number of signals pending. This usually indicates that your operating system tried to deliver signals too fast (with a very high priority), starving the perl process from resources it would need to reach a point where it can process signals safely. (See ["Deferred Signals (Safe Signals)" in perlipc](perlipc#Deferred-Signals-%28Safe-Signals%29).)
"%s" may clash with future reserved word (W) This warning may be due to running a perl5 script through a perl4 interpreter, especially if the word that is being warned about is "use" or "my".
'%' may not be used in pack (F) You can't pack a string by supplying a checksum, because the checksumming process loses information, and you can't go the other way. See ["unpack" in perlfunc](perlfunc#unpack).
Method for operation %s not found in package %s during blessing (F) An attempt was made to specify an entry in an overloading table that doesn't resolve to a valid subroutine. See <overload>.
Method %s not permitted See ["500 Server error"](#500-Server-error).
Might be a runaway multi-line %s string starting on line %d (S) An advisory indicating that the previous error may have been caused by a missing delimiter on a string or pattern, because it eventually ended earlier on the current line.
Misplaced \_ in number (W syntax) An underscore (underbar) in a numeric constant did not separate two digits.
Missing argument for %n in %s (F) A `%n` was used in a format string with no corresponding argument for perl to write the current string length to.
Missing argument in %s (W missing) You called a function with fewer arguments than other arguments you supplied indicated would be needed.
Currently only emitted when a printf-type format required more arguments than were supplied, but might be used in the future for other cases where we can statically determine that arguments to functions are missing, e.g. for the ["pack" in perlfunc](perlfunc#pack) function.
Missing argument to -%c (F) The argument to the indicated command line switch must follow immediately after the switch, without intervening spaces.
Missing braces on \N{}
Missing braces on \N{} in regex; marked by <-- HERE in m/%s/ (F) Wrong syntax of character name literal `\N{charname}` within double-quotish context. This can also happen when there is a space (or comment) between the `\N` and the `{` in a regex with the `/x` modifier. This modifier does not change the requirement that the brace immediately follow the `\N`.
Missing braces on \o{} (F) A `\o` must be followed immediately by a `{` in double-quotish context.
Missing comma after first argument to %s function (F) While certain functions allow you to specify a filehandle or an "indirect object" before the argument list, this ain't one of them.
Missing command in piped open (W pipe) You used the `open(FH, "| command")` or `open(FH, "command |")` construction, but the command was missing or blank.
Missing control char name in \c (F) A double-quoted string ended with "\c", without the required control character name.
Missing ']' in prototype for %s : %s (W illegalproto) A grouping was started with `[` but never closed with `]`.
Missing name in "%s sub" (F) The syntax for lexically scoped subroutines requires that they have a name with which they can be found.
Missing $ on loop variable (F) Apparently you've been programming in **csh** too much. Variables are always mentioned with the $ in Perl, unlike in the shells, where it can vary from one line to the next.
(Missing operator before %s?) (S syntax) This is an educated guess made in conjunction with the message "%s found where operator expected". Often the missing operator is a comma.
Missing or undefined argument to %s (F) You tried to call require or do with no argument or with an undefined value as an argument. Require expects either a package name or a file-specification as an argument; do expects a filename. See ["require EXPR" in perlfunc](perlfunc#require-EXPR) and ["do EXPR" in perlfunc](perlfunc#do-EXPR).
Missing right brace on \%c{} in regex; marked by <-- HERE in m/%s/ (F) Missing right brace in `\x{...}`, `\p{...}`, `\P{...}`, or `\N{...}`.
Missing right brace on \N{}
Missing right brace on \N{} or unescaped left brace after \N (F) `\N` has two meanings.
The traditional one has it followed by a name enclosed in braces, meaning the character (or sequence of characters) given by that name. Thus `\N{ASTERISK}` is another way of writing `*`, valid in both double-quoted strings and regular expression patterns. In patterns, it doesn't have the meaning an unescaped `*` does.
Starting in Perl 5.12.0, `\N` also can have an additional meaning (only) in patterns, namely to match a non-newline character. (This is short for `[^\n]`, and like `.` but is not affected by the `/s` regex modifier.)
This can lead to some ambiguities. When `\N` is not followed immediately by a left brace, Perl assumes the `[^\n]` meaning. Also, if the braces form a valid quantifier such as `\N{3}` or `\N{5,}`, Perl assumes that this means to match the given quantity of non-newlines (in these examples, 3; and 5 or more, respectively). In all other case, where there is a `\N{` and a matching `}`, Perl assumes that a character name is desired.
However, if there is no matching `}`, Perl doesn't know if it was mistakenly omitted, or if `[^\n]{` was desired, and raises this error. If you meant the former, add the right brace; if you meant the latter, escape the brace with a backslash, like so: `\N\{`
Missing right curly or square bracket (F) The lexer counted more opening curly or square brackets than closing ones. As a general rule, you'll find it's missing near the place you were last editing.
(Missing semicolon on previous line?) (S syntax) This is an educated guess made in conjunction with the message "%s found where operator expected". Don't automatically put a semicolon on the previous line just because you saw this message.
Modification of a read-only value attempted (F) You tried, directly or indirectly, to change the value of a constant. You didn't, of course, try "2 = 1", because the compiler catches that. But an easy way to do the same thing is:
```
sub mod { $_[0] = 1 }
mod(2);
```
Another way is to assign to a substr() that's off the end of the string.
Yet another way is to assign to a `foreach` loop *VAR* when *VAR* is aliased to a constant in the look *LIST*:
```
$x = 1;
foreach my $n ($x, 2) {
$n *= 2; # modifies the $x, but fails on attempt to
} # modify the 2
```
<PerlIO::scalar> will also produce this message as a warning if you attempt to open a read-only scalar for writing.
Modification of non-creatable array value attempted, %s (F) You tried to make an array value spring into existence, and the subscript was probably negative, even counting from end of the array backwards.
Modification of non-creatable hash value attempted, %s (P) You tried to make a hash value spring into existence, and it couldn't be created for some peculiar reason.
Module name must be constant (F) Only a bare module name is allowed as the first argument to a "use".
Module name required with -%c option (F) The `-M` or `-m` options say that Perl should load some module, but you omitted the name of the module. Consult [perlrun](perlrun#-m%5B-%5Dmodule) for full details about `-M` and `-m`.
More than one argument to '%s' open (F) The `open` function has been asked to open multiple files. This can happen if you are trying to open a pipe to a command that takes a list of arguments, but have forgotten to specify a piped open mode. See ["open" in perlfunc](perlfunc#open) for details.
mprotect for COW string %p %u failed with %d (S) You compiled perl with **-D**PERL\_DEBUG\_READONLY\_COW (see ["Copy on Write" in perlguts](perlguts#Copy-on-Write)), but a shared string buffer could not be made read-only.
mprotect for %p %u failed with %d (S) You compiled perl with **-D**PERL\_DEBUG\_READONLY\_OPS (see <perlhacktips>), but an op tree could not be made read-only.
mprotect RW for COW string %p %u failed with %d (S) You compiled perl with **-D**PERL\_DEBUG\_READONLY\_COW (see ["Copy on Write" in perlguts](perlguts#Copy-on-Write)), but a read-only shared string buffer could not be made mutable.
mprotect RW for %p %u failed with %d (S) You compiled perl with **-D**PERL\_DEBUG\_READONLY\_OPS (see <perlhacktips>), but a read-only op tree could not be made mutable before freeing the ops.
msg%s not implemented (F) You don't have System V message IPC on your system.
Multidimensional hash lookup is disabled (F) You supplied a list of subscripts to a hash lookup under `no feature "multidimensional";`, eg:
```
$z = $foo{$x, $y};
```
which by default acts like:
```
$z = $foo{join($;, $x, $y)};
```
Multidimensional syntax %s not supported (W syntax) Multidimensional arrays aren't written like `$foo[1,2,3]`. They're written like `$foo[1][2][3]`, as in C.
Multiple slurpy parameters not allowed (F) In subroutine signatures, a slurpy parameter (`@` or `%`) must be the last parameter, and there must not be more than one of them; for example:
```
sub foo ($a, @b) {} # legal
sub foo ($a, @b, %) {} # invalid
```
'/' must follow a numeric type in unpack (F) You had an unpack template that contained a '/', but this did not follow some unpack specification producing a numeric value. See ["pack" in perlfunc](perlfunc#pack).
%s must not be a named sequence in transliteration operator (F) Transliteration (`tr///` and `y///`) transliterates individual characters. But a named sequence by definition is more than an individual character, and hence doing this operation on it doesn't make sense.
"my sub" not yet implemented (F) Lexically scoped subroutines are not yet implemented. Don't try that yet.
"my" subroutine %s can't be in a package (F) Lexically scoped subroutines aren't in a package, so it doesn't make sense to try to declare one with a package qualifier on the front.
"my %s" used in sort comparison (W syntax) The package variables $a and $b are used for sort comparisons. You used $a or $b in as an operand to the `<=>` or `cmp` operator inside a sort comparison block, and the variable had earlier been declared as a lexical variable. Either qualify the sort variable with the package name, or rename the lexical variable.
"my" variable %s can't be in a package (F) Lexically scoped variables aren't in a package, so it doesn't make sense to try to declare one with a package qualifier on the front. Use local() if you want to localize a package variable.
Name "%s::%s" used only once: possible typo (W once) Typographical errors often show up as unique variable names. If you had a good reason for having a unique name, then just mention it again somehow to suppress the message. The `our` declaration is also provided for this purpose.
NOTE: This warning detects package symbols that have been used only once. This means lexical variables will never trigger this warning. It also means that all of the package variables $c, @c, %c, as well as \*c, &c, sub c{}, c(), and c (the filehandle or format) are considered the same; if a program uses $c only once but also uses any of the others it will not trigger this warning. Symbols beginning with an underscore and symbols using special identifiers (q.v. <perldata>) are exempt from this warning.
Need exactly 3 octal digits in regex; marked by <-- HERE in m/%s/ (F) Within `(?[ ])`, all constants interpreted as octal need to be exactly 3 digits long. This helps catch some ambiguities. If your constant is too short, add leading zeros, like
```
(?[ [ \078 ] ]) # Syntax error!
(?[ [ \0078 ] ]) # Works
(?[ [ \007 8 ] ]) # Clearer
```
The maximum number this construct can express is `\777`. If you need a larger one, you need to use [\o{}](perlrebackslash#Octal-escapes) instead. If you meant two separate things, you need to separate them:
```
(?[ [ \7776 ] ]) # Syntax error!
(?[ [ \o{7776} ] ]) # One meaning
(?[ [ \777 6 ] ]) # Another meaning
(?[ [ \777 \006 ] ]) # Still another
```
Negative '/' count in unpack (F) The length count obtained from a length/code unpack operation was negative. See ["pack" in perlfunc](perlfunc#pack).
Negative length (F) You tried to do a read/write/send/recv operation with a buffer length that is less than 0. This is difficult to imagine.
Negative offset to vec in lvalue context (F) When `vec` is called in an lvalue context, the second argument must be greater than or equal to zero.
Negative repeat count does nothing (W numeric) You tried to execute the [`x`](perlop#Multiplicative-Operators) repetition operator fewer than 0 times, which doesn't make sense.
Nested quantifiers in regex; marked by <-- HERE in m/%s/ (F) You can't quantify a quantifier without intervening parentheses. So things like \*\* or +\* or ?\* are illegal. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Note that the minimal matching quantifiers, `*?`, `+?`, and `??` appear to be nested quantifiers, but aren't. See <perlre>.
%s never introduced (S internal) The symbol in question was declared but somehow went out of scope before it could possibly have been used.
next::method/next::can/maybe::next::method cannot find enclosing method (F) `next::method` needs to be called within the context of a real method in a real package, and it could not find such a context. See <mro>.
\N in a character class must be a named character: \N{...} in regex; marked by <-- HERE in m/%s/ (F) The new (as of Perl 5.12) meaning of `\N` as `[^\n]` is not valid in a bracketed character class, for the same reason that `.` in a character class loses its specialness: it matches almost everything, which is probably not what you want.
\N{} here is restricted to one character in regex; marked by <-- HERE in m/%s/ (F) Named Unicode character escapes (`\N{...}`) may return a multi-character sequence. Even though a character class is supposed to match just one character of input, perl will match the whole thing correctly, except under certain conditions. These currently are
When the class is inverted (`[^...]`) The mathematically logical behavior for what matches when inverting is very different from what people expect, so we have decided to forbid it.
The escape is the beginning or final end point of a range Similarly unclear is what should be generated when the `\N{...}` is used as one of the end points of the range, such as in
```
[\x{41}-\N{ARABIC SEQUENCE YEH WITH HAMZA ABOVE WITH AE}]
```
What is meant here is unclear, as the `\N{...}` escape is a sequence of code points, so this is made an error.
In a regex set The syntax `(?[ ])` in a regular expression yields a list of single code points, none can be a sequence.
No %s allowed while running setuid (F) Certain operations are deemed to be too insecure for a setuid or setgid script to even be allowed to attempt. Generally speaking there will be another way to do what you want that is, if not secure, at least securable. See <perlsec>.
No code specified for -%c (F) Perl's **-e** and **-E** command-line options require an argument. If you want to run an empty program, pass the empty string as a separate argument or run a program consisting of a single 0 or 1:
```
perl -e ""
perl -e0
perl -e1
```
No comma allowed after %s (F) A list operator that has a filehandle or "indirect object" is not allowed to have a comma between that and the following arguments. Otherwise it'd be just another one of the arguments.
One possible cause for this is that you expected to have imported a constant to your name space with **use** or **import** while no such importing took place, it may for example be that your operating system does not support that particular constant. Hopefully you did use an explicit import list for the constants you expect to see; please see ["use" in perlfunc](perlfunc#use) and ["import" in perlfunc](perlfunc#import). While an explicit import list would probably have caught this error earlier it naturally does not remedy the fact that your operating system still does not support that constant. Maybe you have a typo in the constants of the symbol import list of **use** or **import** or in the constant name at the line where this error was triggered?
No command into which to pipe on command line (F) An error peculiar to VMS. Perl handles its own command line redirection, and found a '|' at the end of the command line, so it doesn't know where you want to pipe the output from this command.
No DB::DB routine defined (F) The currently executing code was compiled with the **-d** switch, but for some reason the current debugger (e.g. *perl5db.pl* or a `Devel::` module) didn't define a routine to be called at the beginning of each statement.
No dbm on this machine (P) This is counted as an internal error, because every machine should supply dbm nowadays, because Perl comes with SDBM. See [SDBM\_File](sdbm_file).
No DB::sub routine defined (F) The currently executing code was compiled with the **-d** switch, but for some reason the current debugger (e.g. *perl5db.pl* or a `Devel::` module) didn't define a `DB::sub` routine to be called at the beginning of each ordinary subroutine call.
No digits found for %s literal (F) No hexadecimal digits were found following `0x` or no binary digits were found following `0b`.
No directory specified for -I (F) The **-I** command-line switch requires a directory name as part of the *same* argument. Use **-Ilib**, for instance. **-I lib** won't work.
No error file after 2> or 2>> on command line (F) An error peculiar to VMS. Perl handles its own command line redirection, and found a '2>' or a '2>>' on the command line, but can't find the name of the file to which to write data destined for stderr.
No group ending character '%c' found in template (F) A pack or unpack template has an opening '(' or '[' without its matching counterpart. See ["pack" in perlfunc](perlfunc#pack).
No input file after < on command line (F) An error peculiar to VMS. Perl handles its own command line redirection, and found a '<' on the command line, but can't find the name of the file from which to read data for stdin.
No next::method '%s' found for %s (F) `next::method` found no further instances of this method name in the remaining packages of the MRO of this class. If you don't want it throwing an exception, use `maybe::next::method` or `next::can`. See <mro>.
Non-finite repeat count does nothing (W numeric) You tried to execute the [`x`](perlop#Multiplicative-Operators) repetition operator `Inf` (or `-Inf`) or `NaN` times, which doesn't make sense.
Non-hex character in regex; marked by <-- HERE in m/%s/ (F) In a regular expression, there was a non-hexadecimal character where a hex one was expected, like
```
(?[ [ \xDG ] ])
(?[ [ \x{DEKA} ] ])
```
Non-hex character '%c' terminates \x early. Resolved as "%s" (W digit) In parsing a hexadecimal numeric constant, a character was unexpectedly encountered that isn't hexadecimal. The resulting value is as indicated.
Note that, within braces, every character starting with the first non-hexadecimal up to the ending brace is ignored.
Non-octal character in regex; marked by <-- HERE in m/%s/ (F) In a regular expression, there was a non-octal character where an octal one was expected, like
```
(?[ [ \o{1278} ] ])
```
Non-octal character '%c' terminates \o early. Resolved as "%s" (W digit) In parsing an octal numeric constant, a character was unexpectedly encountered that isn't octal. The resulting value is as indicated.
When not using `\o{...}`, you wrote something like `\08`, or `\179` in a double-quotish string. The resolution is as indicated, with all but the last digit treated as a single character, specified in octal. The last digit is the next character in the string. To tell Perl that this is indeed what you want, you can use the `\o{ }` syntax, or use exactly three digits to specify the octal for the character.
Note that, within braces, every character starting with the first non-octal up to the ending brace is ignored.
"no" not allowed in expression (F) The "no" keyword is recognized and executed at compile time, and returns no useful value. See <perlmod>.
Non-string passed as bitmask (W misc) A number has been passed as a bitmask argument to select(). Use the vec() function to construct the file descriptor bitmasks for select. See ["select" in perlfunc](perlfunc#select).
No output file after > on command line (F) An error peculiar to VMS. Perl handles its own command line redirection, and found a lone '>' at the end of the command line, so it doesn't know where you wanted to redirect stdout.
No output file after > or >> on command line (F) An error peculiar to VMS. Perl handles its own command line redirection, and found a '>' or a '>>' on the command line, but can't find the name of the file to which to write data destined for stdout.
No package name allowed for subroutine %s in "our"
No package name allowed for variable %s in "our" (F) Fully qualified subroutine and variable names are not allowed in "our" declarations, because that doesn't make much sense under existing rules. Such syntax is reserved for future extensions.
No Perl script found in input (F) You called `perl -x`, but no line was found in the file beginning with #! and containing the word "perl".
No setregid available (F) Configure didn't find anything resembling the setregid() call for your system.
No setreuid available (F) Configure didn't find anything resembling the setreuid() call for your system.
No such class %s (F) You provided a class qualifier in a "my", "our" or "state" declaration, but this class doesn't exist at this point in your program.
No such class field "%s" in variable %s of type %s (F) You tried to access a key from a hash through the indicated typed variable but that key is not allowed by the package of the same type. The indicated package has restricted the set of allowed keys using the <fields> pragma.
No such hook: %s (F) You specified a signal hook that was not recognized by Perl. Currently, Perl accepts `__DIE__` and `__WARN__` as valid signal hooks.
No such pipe open (P) An error peculiar to VMS. The internal routine my\_pclose() tried to close a pipe which hadn't been opened. This should have been caught earlier as an attempt to close an unopened filehandle.
No such signal: SIG%s (W signal) You specified a signal name as a subscript to %SIG that was not recognized. Say `kill -l` in your shell to see the valid signal names on your system.
No Unicode property value wildcard matches: (W regexp) You specified a wildcard for a Unicode property value, but there is no property value in the current Unicode release that matches it. Check your spelling.
Not a CODE reference (F) Perl was trying to evaluate a reference to a code value (that is, a subroutine), but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See also <perlref>.
Not a GLOB reference (F) Perl was trying to evaluate a reference to a "typeglob" (that is, a symbol table entry that looks like `*foo`), but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See <perlref>.
Not a HASH reference (F) Perl was trying to evaluate a reference to a hash value, but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See <perlref>.
'#' not allowed immediately following a sigil in a subroutine signature (F) In a subroutine signature definition, a comment following a sigil (`$`, `@` or `%`), needs to be separated by whitespace or a comma etc., in particular to avoid confusion with the `$#` variable. For example:
```
# bad
sub f ($# ignore first arg
, $b) {}
# good
sub f ($, # ignore first arg
$b) {}
```
Not an ARRAY reference (F) Perl was trying to evaluate a reference to an array value, but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See <perlref>.
Not a SCALAR reference (F) Perl was trying to evaluate a reference to a scalar value, but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See <perlref>.
Not a subroutine reference (F) Perl was trying to evaluate a reference to a code value (that is, a subroutine), but found a reference to something else instead. You can use the ref() function to find out what kind of ref it really was. See also <perlref>.
Not a subroutine reference in overload table (F) An attempt was made to specify an entry in an overloading table that doesn't somehow point to a valid subroutine. See <overload>.
Not enough arguments for %s (F) The function requires more arguments than you specified.
Not enough format arguments (W syntax) A format specified more picture fields than the next line supplied. See <perlform>.
%s: not found (A) You've accidentally run your script through the Bourne shell instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
no UTC offset information; assuming local time is UTC (S) A warning peculiar to VMS. Perl was unable to find the local timezone offset, so it's assuming that local system time is equivalent to UTC. If it's not, define the logical name *SYS$TIMEZONE\_DIFFERENTIAL* to translate to the number of seconds which need to be added to UTC to get local time.
NULL OP IN RUN (S debugging) Some internal routine called run() with a null opcode pointer.
Null picture in formline (F) The first argument to formline must be a valid format picture specification. It was found to be empty, which probably means you supplied it an uninitialized value. See <perlform>.
NULL regexp parameter (P) The internal pattern matching routines are out of their gourd.
Number too long (F) Perl limits the representation of decimal numbers in programs to about 250 characters. You've exceeded that length. Future versions of Perl are likely to eliminate this arbitrary limitation. In the meantime, try using scientific notation (e.g. "1e6" instead of "1\_000\_000").
Number with no digits (F) Perl was looking for a number but found nothing that looked like a number. This happens, for example with `\o{}`, with no number between the braces.
Numeric format result too large (F) The length of the result of a numeric format supplied to sprintf() or printf() would have been too large for the underlying C function to report. This limit is typically 2GB.
Numeric variables with more than one digit may not start with '0' (F) The only numeric variable which is allowed to start with a 0 is `$0`, and you mentioned a variable that starts with 0 that has more than one digit. You probably want to remove the leading 0, or if the intent was to express a variable name in octal you should convert to decimal.
Octal number > 037777777777 non-portable (W portable) The octal number you specified is larger than 2\*\*32-1 (4294967295) and therefore non-portable between systems. See <perlport> for more on portability concerns.
Odd name/value argument for subroutine '%s' (F) A subroutine using a slurpy hash parameter in its signature received an odd number of arguments to populate the hash. It requires the arguments to be paired, with the same number of keys as values. The caller of the subroutine is presumably at fault.
The message attempts to include the name of the called subroutine. If the subroutine has been aliased, the subroutine's original name will be shown, regardless of what name the caller used.
Odd number of arguments for overload::constant (W overload) The call to overload::constant contained an odd number of arguments. The arguments should come in pairs.
Odd number of elements in anonymous hash (W misc) You specified an odd number of elements to initialize a hash, which is odd, because hashes come in key/value pairs.
Odd number of elements in hash assignment (W misc) You specified an odd number of elements to initialize a hash, which is odd, because hashes come in key/value pairs.
Offset outside string (F)(W layer) You tried to do a read/write/send/recv/seek operation with an offset pointing outside the buffer. This is difficult to imagine. The sole exceptions to this are that zero padding will take place when going past the end of the string when either `sysread()`ing a file, or when seeking past the end of a scalar opened for I/O (in anticipation of future reads and to imitate the behavior with real files).
Old package separator used in string (W syntax) You used the old package separator, "'", in a variable named inside a double-quoted string; e.g., `"In $name's house"`. This is equivalent to `"In $name::s house"`. If you meant the former, put a backslash before the apostrophe (`"In $name\'s house"`).
%s() on unopened %s (W unopened) An I/O operation was attempted on a filehandle that was never initialized. You need to do an open(), a sysopen(), or a socket() call, or call a constructor from the FileHandle package.
-%s on unopened filehandle %s (W unopened) You tried to invoke a file test operator on a filehandle that isn't open. Check your control flow. See also ["-X" in perlfunc](perlfunc#-X).
oops: oopsAV (S internal) An internal warning that the grammar is screwed up.
oops: oopsHV (S internal) An internal warning that the grammar is screwed up.
Operand with no preceding operator in regex; marked by <-- HERE in m/%s/ (F) You wrote something like
```
(?[ \p{Digit} \p{Thai} ])
```
There are two operands, but no operator giving how you want to combine them.
Operation "%s": no method found, %s (F) An attempt was made to perform an overloaded operation for which no handler was defined. While some handlers can be autogenerated in terms of other handlers, there is no default handler for any operation, unless the `fallback` overloading key is specified to be true. See <overload>.
Operation "%s" returns its argument for non-Unicode code point 0x%X (S non\_unicode) You performed an operation requiring Unicode rules on a code point that is not in Unicode, so what it should do is not defined. Perl has chosen to have it do nothing, and warn you.
If the operation shown is "ToFold", it means that case-insensitive matching in a regular expression was done on the code point.
If you know what you are doing you can turn off this warning by `no warnings 'non_unicode';`.
Operation "%s" returns its argument for UTF-16 surrogate U+%X (S surrogate) You performed an operation requiring Unicode rules on a Unicode surrogate. Unicode frowns upon the use of surrogates for anything but storing strings in UTF-16, but rules are (reluctantly) defined for the surrogates, and they are to do nothing for this operation. Because the use of surrogates can be dangerous, Perl warns.
If the operation shown is "ToFold", it means that case-insensitive matching in a regular expression was done on the code point.
If you know what you are doing you can turn off this warning by `no warnings 'surrogate';`.
Operator or semicolon missing before %s (S ambiguous) You used a variable or subroutine call where the parser was expecting an operator. The parser has assumed you really meant to use an operator, but this is highly likely to be incorrect. For example, if you say "\*foo \*foo" it will be interpreted as if you said "\*foo \* 'foo'".
Optional parameter lacks default expression (F) In a subroutine signature, you wrote something like "$a =", making a named optional parameter without a default value. A nameless optional parameter is permitted to have no default value, but a named one must have a specific default. You probably want "$a = undef".
"our" variable %s redeclared (W shadow) You seem to have already declared the same global once before in the current lexical scope.
Out of memory! (X) The malloc() function returned 0, indicating there was insufficient remaining memory (or virtual memory) to satisfy the request. Perl has no option but to exit immediately.
At least in Unix you may be able to get past this by increasing your process datasize limits: in csh/tcsh use `limit` and `limit datasize n` (where `n` is the number of kilobytes) to check the current limits and change them, and in ksh/bash/zsh use `ulimit -a` and `ulimit -d n`, respectively.
Out of memory during %s extend (X) An attempt was made to extend an array, a list, or a string beyond the largest possible memory allocation.
Out of memory during "large" request for %s (F) The malloc() function returned 0, indicating there was insufficient remaining memory (or virtual memory) to satisfy the request. However, the request was judged large enough (compile-time default is 64K), so a possibility to shut down by trapping this error is granted.
Out of memory during request for %s (X)(F) The malloc() function returned 0, indicating there was insufficient remaining memory (or virtual memory) to satisfy the request.
The request was judged to be small, so the possibility to trap it depends on the way perl was compiled. By default it is not trappable. However, if compiled for this, Perl may use the contents of `$^M` as an emergency pool after die()ing with this message. In this case the error is trappable *once*, and the error message will include the line and file where the failed request happened.
Out of memory during ridiculously large request (F) You can't allocate more than 2^31+"small amount" bytes. This error is most likely to be caused by a typo in the Perl program. e.g., `$arr[time]` instead of `$arr[$time]`.
Out of memory for yacc stack (F) The yacc parser wanted to grow its stack so it could continue parsing, but realloc() wouldn't give it more memory, virtual or otherwise.
'.' outside of string in pack (F) The argument to a '.' in your template tried to move the working position to before the start of the packed string being built.
'@' outside of string in unpack (F) You had a template that specified an absolute position outside the string being unpacked. See ["pack" in perlfunc](perlfunc#pack).
'@' outside of string with malformed UTF-8 in unpack (F) You had a template that specified an absolute position outside the string being unpacked. The string being unpacked was also invalid UTF-8. See ["pack" in perlfunc](perlfunc#pack).
overload arg '%s' is invalid (W overload) The <overload> pragma was passed an argument it did not recognize. Did you mistype an operator?
Overloaded dereference did not return a reference (F) An object with an overloaded dereference operator was dereferenced, but the overloaded operation did not return a reference. See <overload>.
Overloaded qr did not return a REGEXP (F) An object with a `qr` overload was used as part of a match, but the overloaded operation didn't return a compiled regexp. See <overload>.
%s package attribute may clash with future reserved word: %s (W reserved) A lowercase attribute name was used that had a package-specific handler. That name might have a meaning to Perl itself some day, even though it doesn't yet. Perhaps you should use a mixed-case attribute name, instead. See <attributes>.
pack/unpack repeat count overflow (F) You can't specify a repeat count so large that it overflows your signed integers. See ["pack" in perlfunc](perlfunc#pack).
page overflow (W io) A single call to write() produced more lines than can fit on a page. See <perlform>.
panic: %s (P) An internal error.
panic: attempt to call %s in %s (P) One of the file test operators entered a code branch that calls an ACL related-function, but that function is not available on this platform. Earlier checks mean that it should not be possible to enter this branch on this platform.
panic: child pseudo-process was never scheduled (P) A child pseudo-process in the ithreads implementation on Windows was not scheduled within the time period allowed and therefore was not able to initialize properly.
panic: ck\_grep, type=%u (P) Failed an internal consistency check trying to compile a grep.
panic: corrupt saved stack index %ld (P) The savestack was requested to restore more localized values than there are in the savestack.
panic: del\_backref (P) Failed an internal consistency check while trying to reset a weak reference.
panic: fold\_constants JMPENV\_PUSH returned %d (P) While attempting folding constants an exception other than an `eval` failure was caught.
panic: frexp: %f (P) The library function frexp() failed, making printf("%f") impossible.
panic: goto, type=%u, ix=%ld (P) We popped the context stack to a context with the specified label, and then discovered it wasn't a context we know how to do a goto in.
panic: gp\_free failed to free glob pointer (P) The internal routine used to clear a typeglob's entries tried repeatedly, but each time something re-created entries in the glob. Most likely the glob contains an object with a reference back to the glob and a destructor that adds a new object to the glob.
panic: INTERPCASEMOD, %s (P) The lexer got into a bad state at a case modifier.
panic: INTERPCONCAT, %s (P) The lexer got into a bad state parsing a string with brackets.
panic: kid popen errno read (F) A forked child returned an incomprehensible message about its errno.
panic: leave\_scope inconsistency %u (P) The savestack probably got out of sync. At least, there was an invalid enum on the top of it.
panic: magic\_killbackrefs (P) Failed an internal consistency check while trying to reset all weak references to an object.
panic: malloc, %s (P) Something requested a negative number of bytes of malloc.
panic: memory wrap (P) Something tried to allocate either more memory than possible or a negative amount.
panic: newFORLOOP, %s (P) The parser failed an internal consistency check while trying to parse a `foreach` loop.
panic: pad\_alloc, %p!=%p (P) The compiler got confused about which scratch pad it was allocating and freeing temporaries and lexicals from.
panic: pad\_free curpad, %p!=%p (P) The compiler got confused about which scratch pad it was allocating and freeing temporaries and lexicals from.
panic: pad\_free po (P) A zero scratch pad offset was detected internally. An attempt was made to free a target that had not been allocated to begin with.
panic: pad\_reset curpad, %p!=%p (P) The compiler got confused about which scratch pad it was allocating and freeing temporaries and lexicals from.
panic: pad\_sv po (P) A zero scratch pad offset was detected internally. Most likely an operator needed a target but that target had not been allocated for whatever reason.
panic: pad\_swipe curpad, %p!=%p (P) The compiler got confused about which scratch pad it was allocating and freeing temporaries and lexicals from.
panic: pad\_swipe po (P) An invalid scratch pad offset was detected internally.
panic: pp\_iter, type=%u (P) The foreach iterator got called in a non-loop context frame.
panic: pp\_match%s (P) The internal pp\_match() routine was called with invalid operational data.
panic: realloc, %s (P) Something requested a negative number of bytes of realloc.
panic: reference miscount on nsv in sv\_replace() (%d != 1) (P) The internal sv\_replace() function was handed a new SV with a reference count other than 1.
panic: restartop in %s (P) Some internal routine requested a goto (or something like it), and didn't supply the destination.
panic: return, type=%u (P) We popped the context stack to a subroutine or eval context, and then discovered it wasn't a subroutine or eval context.
panic: scan\_num, %s (P) scan\_num() got called on something that wasn't a number.
panic: Sequence (?{...}): no code block found in regex m/%s/ (P) While compiling a pattern that has embedded (?{}) or (??{}) code blocks, perl couldn't locate the code block that should have already been seen and compiled by perl before control passed to the regex compiler.
panic: sv\_chop %s (P) The sv\_chop() routine was passed a position that is not within the scalar's string buffer.
panic: sv\_insert, midend=%p, bigend=%p (P) The sv\_insert() routine was told to remove more string than there was string.
panic: top\_env (P) The compiler attempted to do a goto, or something weird like that.
panic: unexpected constant lvalue entersub entry via type/targ %d:%d (P) When compiling a subroutine call in lvalue context, Perl failed an internal consistency check. It encountered a malformed op tree.
panic: unimplemented op %s (#%d) called (P) The compiler is screwed up and attempted to use an op that isn't permitted at run time.
panic: unknown OA\_\*: %x (P) The internal routine that handles arguments to `&CORE::foo()` subroutine calls was unable to determine what type of arguments were expected.
panic: utf16\_to\_utf8: odd bytelen (P) Something tried to call utf16\_to\_utf8 with an odd (as opposed to even) byte length.
panic: utf16\_to\_utf8\_reversed: odd bytelen (P) Something tried to call utf16\_to\_utf8\_reversed with an odd (as opposed to even) byte length.
panic: yylex, %s (P) The lexer got into a bad state while processing a case modifier.
Parentheses missing around "%s" list (W parenthesis) You said something like
```
my $foo, $bar = @_;
```
when you meant
```
my ($foo, $bar) = @_;
```
Remember that "my", "our", "local" and "state" bind tighter than comma.
Parsing code internal error (%s) (F) Parsing code supplied by an extension violated the parser's API in a detectable way.
Pattern subroutine nesting without pos change exceeded limit in regex (F) You used a pattern that uses too many nested subpattern calls without consuming any text. Restructure the pattern so text is consumed before the nesting limit is exceeded.
`-p` destination: %s (F) An error occurred during the implicit output invoked by the `-p` command-line switch. (This output goes to STDOUT unless you've redirected it with select().)
Perl API version %s of %s does not match %s (F) The XS module in question was compiled against a different incompatible version of Perl than the one that has loaded the XS module.
Perl folding rules are not up-to-date for 0x%X; please use the perlbug utility to report; in regex; marked by <-- HERE in m/%s/ (S regexp) You used a regular expression with case-insensitive matching, and there is a bug in Perl in which the built-in regular expression folding rules are not accurate. This may lead to incorrect results. Please report this as a bug to <https://github.com/Perl/perl5/issues>.
Perl\_my\_%s() not available (F) Your platform has very uncommon byte-order and integer size, so it was not possible to set up some or all fixed-width byte-order conversion functions. This is only a problem when you're using the '<' or '>' modifiers in (un)pack templates. See ["pack" in perlfunc](perlfunc#pack).
Perl %s required (did you mean %s?)--this is only %s, stopped (F) The code you are trying to run has asked for a newer version of Perl than you are running. Perhaps `use 5.10` was written instead of `use 5.010` or `use v5.10`. Without the leading `v`, the number is interpreted as a decimal, with every three digits after the decimal point representing a part of the version number. So 5.10 is equivalent to v5.100.
Perl %s required--this is only %s, stopped (F) The module in question uses features of a version of Perl more recent than the currently running version. How long has it been since you upgraded, anyway? See ["require" in perlfunc](perlfunc#require).
PERL\_SH\_DIR too long (F) An error peculiar to OS/2. PERL\_SH\_DIR is the directory to find the `sh`-shell in. See "PERL\_SH\_DIR" in <perlos2>.
PERL\_SIGNALS illegal: "%s" (X) See ["PERL\_SIGNALS" in perlrun](perlrun#PERL_SIGNALS) for legal values.
Perls since %s too modern--this is %s, stopped (F) The code you are trying to run claims it will not run on the version of Perl you are using because it is too new. Maybe the code needs to be updated, or maybe it is simply wrong and the version check should just be removed.
perl: warning: Non hex character in '$ENV{PERL\_HASH\_SEED}', seed only partially set (S) PERL\_HASH\_SEED should match /^\s\*(?:0x)?[0-9a-fA-F]+\s\*\z/ but it contained a non hex character. This could mean you are not using the hash seed you think you are.
perl: warning: Setting locale failed. (S) The whole warning message will look something like:
```
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LC_ALL = "En_US",
LANG = (unset)
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
```
Exactly what were the failed locale settings varies. In the above the settings were that the LC\_ALL was "En\_US" and the LANG had no value. This error means that Perl detected that you and/or your operating system supplier and/or system administrator have set up the so-called locale system but Perl could not use those settings. This was not dead serious, fortunately: there is a "default locale" called "C" that Perl can and will use, and the script will be run. Before you really fix the problem, however, you will get the same error message each time you run Perl. How to really fix the problem can be found in <perllocale> section **LOCALE PROBLEMS**.
perl: warning: strange setting in '$ENV{PERL\_PERTURB\_KEYS}': '%s' (S) Perl was run with the environment variable PERL\_PERTURB\_KEYS defined but containing an unexpected value. The legal values of this setting are as follows.
```
Numeric | String | Result
--------+---------------+-----------------------------------------
0 | NO | Disables key traversal randomization
1 | RANDOM | Enables full key traversal randomization
2 | DETERMINISTIC | Enables repeatable key traversal
| | randomization
```
Both numeric and string values are accepted, but note that string values are case sensitive. The default for this setting is "RANDOM" or 1.
pid %x not a child (W exec) A warning peculiar to VMS. Waitpid() was asked to wait for a process which isn't a subprocess of the current process. While this is fine from VMS' perspective, it's probably not what you intended.
'P' must have an explicit size in unpack (F) The unpack format P must have an explicit size, not "\*".
POSIX class [:%s:] unknown in regex; marked by <-- HERE in m/%s/ (F) The class in the character class [: :] syntax is unknown. The <-- HERE shows whereabouts in the regular expression the problem was discovered. Note that the POSIX character classes do **not** have the `is` prefix the corresponding C interfaces have: in other words, it's `[[:print:]]`, not `isprint`. See <perlre>.
POSIX getpgrp can't take an argument (F) Your system has POSIX getpgrp(), which takes no argument, unlike the BSD version, which takes a pid.
POSIX syntax [%c %c] belongs inside character classes%s in regex; marked by <-- HERE in m/%s/ (W regexp) Perl thinks that you intended to write a POSIX character class, but didn't use enough brackets. These POSIX class constructs [: :], [= =], and [. .] go *inside* character classes, the [] are part of the construct, for example: `qr/[012[:alpha:]345]/`. What the regular expression pattern compiled to is probably not what you were intending. For example, `qr/[:alpha:]/` compiles to a regular bracketed character class consisting of the four characters `":"`, `"a"`, `"l"`, `"h"`, and `"p"`. To specify the POSIX class, it should have been written `qr/[[:alpha:]]/`.
Note that [= =] and [. .] are not currently implemented; they are simply placeholders for future extensions and will cause fatal errors. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
If the specification of the class was not completely valid, the message indicates that.
POSIX syntax [. .] is reserved for future extensions in regex; marked by <-- HERE in m/%s/ (F) Within regular expression character classes ([]) the syntax beginning with "[." and ending with ".]" is reserved for future extensions. If you need to represent those character sequences inside a regular expression character class, just quote the square brackets with the backslash: "\[." and ".\]". The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
POSIX syntax [= =] is reserved for future extensions in regex; marked by <-- HERE in m/%s/ (F) Within regular expression character classes ([]) the syntax beginning with "[=" and ending with "=]" is reserved for future extensions. If you need to represent those character sequences inside a regular expression character class, just quote the square brackets with the backslash: "\[=" and "=\]". The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Possible attempt to put comments in qw() list (W qw) qw() lists contain items separated by whitespace; as with literal strings, comment characters are not ignored, but are instead treated as literal data. (You may have used different delimiters than the parentheses shown here; braces are also frequently used.)
You probably wrote something like this:
```
@list = qw(
a # a comment
b # another comment
);
```
when you should have written this:
```
@list = qw(
a
b
);
```
If you really want comments, build your list the old-fashioned way, with quotes and commas:
```
@list = (
'a', # a comment
'b', # another comment
);
```
Possible attempt to separate words with commas (W qw) qw() lists contain items separated by whitespace; therefore commas aren't needed to separate the items. (You may have used different delimiters than the parentheses shown here; braces are also frequently used.)
You probably wrote something like this:
```
qw! a, b, c !;
```
which puts literal commas into some of the list items. Write it without commas if you don't want them to appear in your data:
```
qw! a b c !;
```
Possible memory corruption: %s overflowed 3rd argument (F) An ioctl() or fcntl() returned more than Perl was bargaining for. Perl guesses a reasonable buffer size, but puts a sentinel byte at the end of the buffer just in case. This sentinel byte got clobbered, and Perl assumes that memory is now corrupted. See ["ioctl" in perlfunc](perlfunc#ioctl).
Possible precedence issue with control flow operator (W syntax) There is a possible problem with the mixing of a control flow operator (e.g. `return`) and a low-precedence operator like `or`. Consider:
```
sub { return $a or $b; }
```
This is parsed as:
```
sub { (return $a) or $b; }
```
Which is effectively just:
```
sub { return $a; }
```
Either use parentheses or the high-precedence variant of the operator.
Note this may be also triggered for constructs like:
```
sub { 1 if die; }
```
Possible precedence problem on bitwise %s operator (W precedence) Your program uses a bitwise logical operator in conjunction with a numeric comparison operator, like this :
```
if ($x & $y == 0) { ... }
```
This expression is actually equivalent to `$x & ($y == 0)`, due to the higher precedence of `==`. This is probably not what you want. (If you really meant to write this, disable the warning, or, better, put the parentheses explicitly and write `$x & ($y == 0)`).
Possible unintended interpolation of $\ in regex (W ambiguous) You said something like `m/$\/` in a regex. The regex `m/foo$\s+bar/m` translates to: match the word 'foo', the output record separator (see ["$\" in perlvar](perlvar#%24%5C)) and the letter 's' (one time or more) followed by the word 'bar'.
If this is what you intended then you can silence the warning by using `m/${\}/` (for example: `m/foo${\}s+bar/`).
If instead you intended to match the word 'foo' at the end of the line followed by whitespace and the word 'bar' on the next line then you can use `m/$(?)\/` (for example: `m/foo$(?)\s+bar/`).
Possible unintended interpolation of %s in string (W ambiguous) You said something like '@foo' in a double-quoted string but there was no array `@foo` in scope at the time. If you wanted a literal @foo, then write it as \@foo; otherwise find out what happened to the array you apparently lost track of.
Precedence problem: open %s should be open(%s) (S precedence) The old irregular construct
```
open FOO || die;
```
is now misinterpreted as
```
open(FOO || die);
```
because of the strict regularization of Perl 5's grammar into unary and list operators. (The old open was a little of both.) You must put parentheses around the filehandle, or use the new "or" operator instead of "||".
Premature end of script headers See ["500 Server error"](#500-Server-error).
printf() on closed filehandle %s (W closed) The filehandle you're writing to got itself closed sometime before now. Check your control flow.
print() on closed filehandle %s (W closed) The filehandle you're printing on got itself closed sometime before now. Check your control flow.
Process terminated by SIG%s (W) This is a standard message issued by OS/2 applications, while \*nix applications die in silence. It is considered a feature of the OS/2 port. One can easily disable this by appropriate sighandlers, see ["Signals" in perlipc](perlipc#Signals). See also "Process terminated by SIGTERM/SIGINT" in <perlos2>.
Prototype after '%c' for %s : %s (W illegalproto) A character follows % or @ in a prototype. This is useless, since % and @ gobble the rest of the subroutine arguments.
Prototype mismatch: %s vs %s (S prototype) The subroutine being declared or defined had previously been declared or defined with a different function prototype.
Prototype not terminated (F) You've omitted the closing parenthesis in a function prototype definition.
Prototype '%s' overridden by attribute 'prototype(%s)' in %s (W prototype) A prototype was declared in both the parentheses after the sub name and via the prototype attribute. The prototype in parentheses is useless, since it will be replaced by the prototype from the attribute before it's ever used.
Quantifier follows nothing in regex; marked by <-- HERE in m/%s/ (F) You started a regular expression with a quantifier. Backslash it if you meant it literally. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Quantifier in {,} bigger than %d in regex; marked by <-- HERE in m/%s/ (F) There is currently a limit to the size of the min and max values of the {min,max} construct. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Quantifier {n,m} with n > m can't match in regex
Quantifier {n,m} with n > m can't match in regex; marked by <-- HERE in m/%s/ (W regexp) Minima should be less than or equal to maxima. If you really want your regexp to match something 0 times, just put {0}.
Quantifier unexpected on zero-length expression in regex m/%s/ (W regexp) You applied a regular expression quantifier in a place where it makes no sense, such as on a zero-width assertion. Try putting the quantifier inside the assertion instead. For example, the way to match "abc" provided that it is followed by three repetitions of "xyz" is `/abc(?=(?:xyz){3})/`, not `/abc(?=xyz){3}/`.
Range iterator outside integer range (F) One (or both) of the numeric arguments to the range operator ".." are outside the range which can be represented by integers internally. One possible workaround is to force Perl to use magical string increment by prepending "0" to your numbers.
Ranges of ASCII printables should be some subset of "0-9", "A-Z", or "a-z" in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'` or within `(?[...])`)
Stricter rules help to find typos and other errors. Perhaps you didn't even intend a range here, if the `"-"` was meant to be some other character, or should have been escaped (like `"\-"`). If you did intend a range, the one that was used is not portable between ASCII and EBCDIC platforms, and doesn't have an obvious meaning to a casual reader.
```
[3-7] # OK; Obvious and portable
[d-g] # OK; Obvious and portable
[A-Y] # OK; Obvious and portable
[A-z] # WRONG; Not portable; not clear what is meant
[a-Z] # WRONG; Not portable; not clear what is meant
[%-.] # WRONG; Not portable; not clear what is meant
[\x41-Z] # WRONG; Not portable; not obvious to non-geek
```
(You can force portability by specifying a Unicode range, which means that the endpoints are specified by [`\N{...}`](perlrecharclass#Character-Ranges), but the meaning may still not be obvious.) The stricter rules require that ranges that start or stop with an ASCII character that is not a control have all their endpoints be the literal character, and not some escape sequence (like `"\x41"`), and the ranges must be all digits, or all uppercase letters, or all lowercase letters.
Ranges of digits should be from the same group in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'` or within `(?[...])`)
Stricter rules help to find typos and other errors. You included a range, and at least one of the end points is a decimal digit. Under the stricter rules, when this happens, both end points should be digits in the same group of 10 consecutive digits.
readdir() attempted on invalid dirhandle %s (W io) The dirhandle you're reading from is either closed or not really a dirhandle. Check your control flow.
readline() on closed filehandle %s (W closed) The filehandle you're reading from got itself closed sometime before now. Check your control flow.
readline() on unopened filehandle %s (W unopened) The filehandle you're reading from was never opened. Check your control flow.
read() on closed filehandle %s (W closed) You tried to read from a closed filehandle.
read() on unopened filehandle %s (W unopened) You tried to read from a filehandle that was never opened.
realloc() of freed memory ignored (S malloc) An internal routine called realloc() on something that had already been freed.
Recompile perl with **-D**DEBUGGING to use **-D** switch (S debugging) You can't use the **-D** option unless the code to produce the desired output is compiled into Perl, which entails some overhead, which is why it's currently left out of your copy.
Recursive call to Perl\_load\_module in PerlIO\_find\_layer (P) It is currently not permitted to load modules when creating a filehandle inside an %INC hook. This can happen with `open my $fh, '<', \$scalar`, which implicitly loads PerlIO::scalar. Try loading PerlIO::scalar explicitly first.
Recursive inheritance detected in package '%s' (F) While calculating the method resolution order (MRO) of a package, Perl believes it found an infinite loop in the `@ISA` hierarchy. This is a crude check that bails out after 100 levels of `@ISA` depth.
Redundant argument in %s (W redundant) You called a function with more arguments than other arguments you supplied indicated would be needed. Currently only emitted when a printf-type format required fewer arguments than were supplied, but might be used in the future for e.g. ["pack" in perlfunc](perlfunc#pack).
refcnt\_dec: fd %d%s
refcnt: fd %d%s
refcnt\_inc: fd %d%s (P) Perl's I/O implementation failed an internal consistency check. If you see this message, something is very wrong.
Reference found where even-sized list expected (W misc) You gave a single reference where Perl was expecting a list with an even number of elements (for assignment to a hash). This usually means that you used the anon hash constructor when you meant to use parens. In any case, a hash requires key/value **pairs**.
```
%hash = { one => 1, two => 2, }; # WRONG
%hash = [ qw/ an anon array / ]; # WRONG
%hash = ( one => 1, two => 2, ); # right
%hash = qw( one 1 two 2 ); # also fine
```
Reference is already weak (W misc) You have attempted to weaken a reference that is already weak. Doing so has no effect.
Reference is not weak (W misc) You have attempted to unweaken a reference that is not weak. Doing so has no effect.
Reference to invalid group 0 in regex; marked by <-- HERE in m/%s/ (F) You used `\g0` or similar in a regular expression. You may refer to capturing parentheses only with strictly positive integers (normal backreferences) or with strictly negative integers (relative backreferences). Using 0 does not make sense.
Reference to nonexistent group in regex; marked by <-- HERE in m/%s/ (F) You used something like `\7` in your regular expression, but there are not at least seven sets of capturing parentheses in the expression. If you wanted to have the character with ordinal 7 inserted into the regular expression, prepend zeroes to make it three digits long: `\007`
The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Reference to nonexistent named group in regex; marked by <-- HERE in m/%s/ (F) You used something like `\k'NAME'` or `\k<NAME>` in your regular expression, but there is no corresponding named capturing parentheses such as `(?'NAME'...)` or `(?<NAME>...)`. Check if the name has been spelled correctly both in the backreference and the declaration.
The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Reference to nonexistent or unclosed group in regex; marked by <-- HERE in m/%s/ (F) You used something like `\g{-7}` in your regular expression, but there are not at least seven sets of closed capturing parentheses in the expression before where the `\g{-7}` was located.
The <-- HERE shows whereabouts in the regular expression the problem was discovered.
regexp memory corruption (P) The regular expression engine got confused by what the regular expression compiler gave it.
Regexp modifier "/%c" may appear a maximum of twice
Regexp modifier "%c" may appear a maximum of twice in regex; marked by <-- HERE in m/%s/ (F) The regular expression pattern had too many occurrences of the specified modifier. Remove the extraneous ones.
Regexp modifier "%c" may not appear after the "-" in regex; marked by <-- HERE in m/%s/ (F) Turning off the given modifier has the side effect of turning on another one. Perl currently doesn't allow this. Reword the regular expression to use the modifier you want to turn on (and place it before the minus), instead of the one you want to turn off.
Regexp modifier "/%c" may not appear twice
Regexp modifier "%c" may not appear twice in regex; marked by <-- HERE in m/%s/ (F) The regular expression pattern had too many occurrences of the specified modifier. Remove the extraneous ones.
Regexp modifiers "/%c" and "/%c" are mutually exclusive
Regexp modifiers "%c" and "%c" are mutually exclusive in regex; marked by <-- HERE in m/%s/ (F) The regular expression pattern had more than one of these mutually exclusive modifiers. Retain only the modifier that is supposed to be there.
Regexp out of space in regex m/%s/ (P) A "can't happen" error, because safemalloc() should have caught it earlier.
Repeated format line will never terminate (~~ and @#) (F) Your format contains the ~~ repeat-until-blank sequence and a numeric field that will never go blank so that the repetition never terminates. You might use ^# instead. See <perlform>.
Replacement list is longer than search list (W misc) You have used a replacement list that is longer than the search list. So the additional elements in the replacement list are meaningless.
'(\*%s' requires a terminating ':' in regex; marked by <-- HERE in m/%s/ (F) You used a construct that needs a colon and pattern argument. Supply these or check that you are using the right construct.
'%s' resolved to '\o{%s}%d' As of Perl 5.32, this message is no longer generated. Instead, see ["Non-octal character '%c' terminates \o early. Resolved as "%s""](#Non-octal-character-%27%25c%27-terminates-%5Co-early.-Resolved-as-%22%25s%22). (W misc, regexp) You wrote something like `\08`, or `\179` in a double-quotish string. All but the last digit is treated as a single character, specified in octal. The last digit is the next character in the string. To tell Perl that this is indeed what you want, you can use the `\o{ }` syntax, or use exactly three digits to specify the octal for the character.
Reversed %s= operator (W syntax) You wrote your assignment operator backwards. The = must always come last, to avoid ambiguity with subsequent unary operators.
rewinddir() attempted on invalid dirhandle %s (W io) The dirhandle you tried to do a rewinddir() on is either closed or not really a dirhandle. Check your control flow.
Scalars leaked: %d (S internal) Something went wrong in Perl's internal bookkeeping of scalars: not all scalar variables were deallocated by the time Perl exited. What this usually indicates is a memory leak, which is of course bad, especially if the Perl program is intended to be long-running.
Scalar value @%s[%s] better written as $%s[%s] (W syntax) You've used an array slice (indicated by @) to select a single element of an array. Generally it's better to ask for a scalar value (indicated by $). The difference is that `$foo[&bar]` always behaves like a scalar, both when assigning to it and when evaluating its argument, while `@foo[&bar]` behaves like a list when you assign to it, and provides a list context to its subscript, which can do weird things if you're expecting only one subscript.
On the other hand, if you were actually hoping to treat the array element as a list, you need to look into how references work, because Perl will not magically convert between scalars and lists for you. See <perlref>.
Scalar value @%s{%s} better written as $%s{%s} (W syntax) You've used a hash slice (indicated by @) to select a single element of a hash. Generally it's better to ask for a scalar value (indicated by $). The difference is that `$foo{&bar}` always behaves like a scalar, both when assigning to it and when evaluating its argument, while `@foo{&bar}` behaves like a list when you assign to it, and provides a list context to its subscript, which can do weird things if you're expecting only one subscript.
On the other hand, if you were actually hoping to treat the hash element as a list, you need to look into how references work, because Perl will not magically convert between scalars and lists for you. See <perlref>.
Search pattern not terminated (F) The lexer couldn't find the final delimiter of a // or m{} construct. Remember that bracketing delimiters count nesting level. Missing the leading `$` from a variable `$m` may cause this error.
Note that since Perl 5.10.0 a // can also be the *defined-or* construct, not just the empty search pattern. Therefore code written in Perl 5.10.0 or later that uses the // as the *defined-or* can be misparsed by pre-5.10.0 Perls as a non-terminated search pattern.
seekdir() attempted on invalid dirhandle %s (W io) The dirhandle you are doing a seekdir() on is either closed or not really a dirhandle. Check your control flow.
%sseek() on unopened filehandle (W unopened) You tried to use the seek() or sysseek() function on a filehandle that was either never opened or has since been closed.
select not implemented (F) This machine doesn't implement the select() system call.
Self-ties of arrays and hashes are not supported (F) Self-ties are of arrays and hashes are not supported in the current implementation.
Semicolon seems to be missing (W semicolon) A nearby syntax error was probably caused by a missing semicolon, or possibly some other missing operator, such as a comma.
semi-panic: attempt to dup freed string (S internal) The internal newSVsv() routine was called to duplicate a scalar that had previously been marked as free.
sem%s not implemented (F) You don't have System V semaphore IPC on your system.
send() on closed socket %s (W closed) The socket you're sending to got itself closed sometime before now. Check your control flow.
Sequence "\c{" invalid (F) These three characters may not appear in sequence in a double-quotish context. This message is raised only on non-ASCII platforms (a different error message is output on ASCII ones). If you were intending to specify a control character with this sequence, you'll have to use a different way to specify it.
Sequence (? incomplete in regex; marked by <-- HERE in m/%s/ (F) A regular expression ended with an incomplete extension (?. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Sequence (?%c...) not implemented in regex; marked by <-- HERE in m/%s/ (F) A proposed regular expression extension has the character reserved but has not yet been written. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ (F) You used a regular expression extension that doesn't make sense. The <-- HERE shows whereabouts in the regular expression the problem was discovered. This may happen when using the `(?^...)` construct to tell Perl to use the default regular expression modifiers, and you redundantly specify a default modifier. For other causes, see <perlre>.
Sequence (?#... not terminated in regex m/%s/ (F) A regular expression comment must be terminated by a closing parenthesis. Embedded parentheses aren't allowed. See <perlre>.
Sequence (?&... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named reference of the form `(?&...)` was missing the final closing parenthesis after the name. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (?%c... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named group of the form `(?'...')` or `(?<...>)` was missing the final closing quote or angle bracket. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (%s... not terminated in regex; marked by <-- HERE in m/%s/ (F) A lookahead assertion `(?=...)` or `(?!...)` or lookbehind assertion `(?<=...)` or `(?<!...)` was missing the final closing parenthesis. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (?(%c... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named reference of the form `(?('...')...)` or `(?(<...>)...)` was missing the final closing quote or angle bracket after the name. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (?... not terminated in regex; marked by <-- HERE in m/%s/ (F) There was no matching closing parenthesis for the '('. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ (F) The regular expression expects a mandatory argument following the escape sequence and this has been omitted or incorrectly written.
Sequence (?{...}) not terminated with ')' (F) The end of the perl code contained within the {...} must be followed immediately by a ')'.
Sequence (?P>... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named reference of the form `(?P>...)` was missing the final closing parenthesis after the name. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (?P<... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named group of the form `(?P<...>')` was missing the final closing angle bracket. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence ?P=... not terminated in regex; marked by <-- HERE in m/%s/ (F) A named reference of the form `(?P=...)` was missing the final closing parenthesis after the name. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
Sequence (?R) not terminated in regex m/%s/ (F) An `(?R)` or `(?0)` sequence in a regular expression was missing the final parenthesis.
500 Server error (A) This is the error message generally seen in a browser window when trying to run a CGI program (including SSI) over the web. The actual error text varies widely from server to server. The most frequently-seen variants are "500 Server error", "Method (something) not permitted", "Document contains no data", "Premature end of script headers", and "Did not produce a valid header".
**This is a CGI error, not a Perl error**.
You need to make sure your script is executable, is accessible by the user CGI is running the script under (which is probably not the user account you tested it under), does not rely on any environment variables (like PATH) from the user it isn't running under, and isn't in a location where the CGI server can't find it, basically, more or less. Please see the following for more information:
```
https://www.perl.org/CGI_MetaFAQ.html
http://www.htmlhelp.org/faq/cgifaq.html
http://www.w3.org/Security/Faq/
```
You should also look at <perlfaq9>.
setegid() not implemented (F) You tried to assign to `$)`, and your operating system doesn't support the setegid() system call (or equivalent), or at least Configure didn't think so.
seteuid() not implemented (F) You tried to assign to `$>`, and your operating system doesn't support the seteuid() system call (or equivalent), or at least Configure didn't think so.
setpgrp can't take arguments (F) Your system has the setpgrp() from BSD 4.2, which takes no arguments, unlike POSIX setpgid(), which takes a process ID and process group ID.
setrgid() not implemented (F) You tried to assign to `$(`, and your operating system doesn't support the setrgid() system call (or equivalent), or at least Configure didn't think so.
setruid() not implemented (F) You tried to assign to `$<`, and your operating system doesn't support the setruid() system call (or equivalent), or at least Configure didn't think so.
setsockopt() on closed socket %s (W closed) You tried to set a socket option on a closed socket. Did you forget to check the return value of your socket() call? See ["setsockopt" in perlfunc](perlfunc#setsockopt).
Setting $/ to a reference to %s is forbidden (F) 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.
You are recommended to change your code to set `$/` to `undef` explicitly if you wish to slurp the file. As of Perl 5.28 assigning `$/` to a reference to an integer which isn't positive is a fatal error.
Setting $/ to %s reference is forbidden (F) You tried to assign a reference to a non integer to `$/`. In older Perls this would have behaved similarly to setting it to a reference to a positive integer, where the integer was the address of the reference. As of Perl 5.20.0 this is a fatal error, to allow future versions of Perl to use non-integer refs for more interesting purposes.
shm%s not implemented (F) You don't have System V shared memory IPC on your system.
!=~ should be !~ (W syntax) The non-matching operator is !~, not !=~. !=~ will be interpreted as the != (numeric not equal) and ~ (1's complement) operators: probably not what you intended.
/%s/ should probably be written as "%s" (W syntax) You have used a pattern where Perl expected to find a string, as in the first argument to `join`. Perl will treat the true or false result of matching the pattern against $\_ as the string, which is probably not what you had in mind.
shutdown() on closed socket %s (W closed) You tried to do a shutdown on a closed socket. Seems a bit superfluous.
SIG%s handler "%s" not defined (W signal) The signal handler named in %SIG doesn't, in fact, exist. Perhaps you put it into the wrong package?
Slab leaked from cv %p (S) If you see this message, then something is seriously wrong with the internal bookkeeping of op trees. An op tree needed to be freed after a compilation error, but could not be found, so it was leaked instead.
sleep(%u) too large (W overflow) You called `sleep` with a number that was larger than it can reliably handle and `sleep` probably slept for less time than requested.
Slurpy parameter not last (F) In a subroutine signature, you put something after a slurpy (array or hash) parameter. The slurpy parameter takes all the available arguments, so there can't be any left to fill later parameters.
Smart matching a non-overloaded object breaks encapsulation (F) You should not use the `~~` operator on an object that does not overload it: Perl refuses to use the object's underlying structure for the smart match.
Smartmatch is experimental (S experimental::smartmatch) This warning is emitted if you use the smartmatch (`~~`) operator. This is currently an experimental feature, and its details are subject to change in future releases of Perl. Particularly, its current behavior is noticed for being unnecessarily complex and unintuitive, and is very likely to be overhauled.
Sorry, hash keys must be smaller than 2\*\*31 bytes (F) You tried to create a hash containing a very large key, where "very large" means that it needs at least 2 gigabytes to store. Unfortunately, Perl doesn't yet handle such large hash keys. You should reconsider your design to avoid hashing such a long string directly.
sort is now a reserved word (F) An ancient error message that almost nobody ever runs into anymore. But before sort was a keyword, people sometimes used it as a filehandle.
Source filters apply only to byte streams (F) You tried to activate a source filter (usually by loading a source filter module) within a string passed to `eval`. This is not permitted under the `unicode_eval` feature. Consider using `evalbytes` instead. See <feature>.
splice() offset past end of array (W misc) You attempted to specify an offset that was past the end of the array passed to splice(). Splicing will instead commence at the end of the array, rather than past it. If this isn't what you want, try explicitly pre-extending the array by assigning $#array = $offset. See ["splice" in perlfunc](perlfunc#splice).
Split loop (P) The split was looping infinitely. (Obviously, a split shouldn't iterate more times than there are characters of input, which is what happened.) See ["split" in perlfunc](perlfunc#split).
Statement unlikely to be reached (W exec) You did an exec() with some statement after it other than a die(). This is almost always an error, because exec() never returns unless there was a failure. You probably wanted to use system() instead, which does return. To suppress this warning, put the exec() in a block by itself.
"state" subroutine %s can't be in a package (F) Lexically scoped subroutines aren't in a package, so it doesn't make sense to try to declare one with a package qualifier on the front.
"state %s" used in sort comparison (W syntax) The package variables $a and $b are used for sort comparisons. You used $a or $b in as an operand to the `<=>` or `cmp` operator inside a sort comparison block, and the variable had earlier been declared as a lexical variable. Either qualify the sort variable with the package name, or rename the lexical variable.
"state" variable %s can't be in a package (F) Lexically scoped variables aren't in a package, so it doesn't make sense to try to declare one with a package qualifier on the front. Use local() if you want to localize a package variable.
stat() on unopened filehandle %s (W unopened) You tried to use the stat() function on a filehandle that was either never opened or has since been closed.
Strings with code points over 0xFF may not be mapped into in-memory file handles (W utf8) You tried to open a reference to a scalar for read or append where the scalar contained code points over 0xFF. In-memory files model on-disk files and can only contain bytes.
Stub found while resolving method "%s" overloading "%s" in package "%s" (P) Overloading resolution over @ISA tree may be broken by importation stubs. Stubs should never be implicitly created, but explicit calls to `can` may break this.
Subroutine attributes must come before the signature (F) When subroutine signatures are enabled, any subroutine attributes must come before the signature. Note that this order was the opposite in versions 5.22..5.26. So:
```
sub foo :lvalue ($a, $b) { ... } # 5.20 and 5.28 +
sub foo ($a, $b) :lvalue { ... } # 5.22 .. 5.26
```
Subroutine "&%s" is not available (W closure) During compilation, an inner named subroutine or eval is attempting to capture an outer lexical subroutine that is not currently available. This can happen for one of two reasons. First, the lexical subroutine may be declared in an outer anonymous subroutine that has not yet been created. (Remember that named subs are created at compile time, while anonymous subs are created at run-time.) For example,
```
sub { my sub a {...} sub f { \&a } }
```
At the time that f is created, it can't capture the current "a" sub, since the anonymous subroutine hasn't been created yet. Conversely, the following won't give a warning since the anonymous subroutine has by now been created and is live:
```
sub { my sub a {...} eval 'sub f { \&a }' }->();
```
The second situation is caused by an eval accessing a lexical subroutine that has gone out of scope, for example,
```
sub f {
my sub a {...}
sub { eval '\&a' }
}
f()->();
```
Here, when the '\&a' in the eval is being compiled, f() is not currently being executed, so its &a is not available for capture.
"%s" subroutine &%s masks earlier declaration in same %s (W shadow) A "my" or "state" subroutine has been redeclared in the current scope or statement, effectively eliminating all access to the previous instance. This is almost always a typographical error. Note that the earlier subroutine will still exist until the end of the scope or until all closure references to it are destroyed.
Subroutine %s redefined (W redefine) You redefined a subroutine. To suppress this warning, say
```
{
no warnings 'redefine';
eval "sub name { ... }";
}
```
Subroutine "%s" will not stay shared (W closure) An inner (nested) *named* subroutine is referencing a "my" subroutine defined in an outer named subroutine.
When the inner subroutine is called, it will see the value of the outer subroutine's lexical subroutine as it was before and during the \*first\* call to the outer subroutine; in this case, after the first call to the outer subroutine is complete, the inner and outer subroutines will no longer share a common value for the lexical subroutine. In other words, it will no longer be shared. This will especially make a difference if the lexical subroutines accesses lexical variables declared in its surrounding scope.
This problem can usually be solved by making the inner subroutine anonymous, using the `sub {}` syntax. When inner anonymous subs that reference lexical subroutines in outer subroutines are created, they are automatically rebound to the current values of such lexical subs.
Substitution loop (P) The substitution was looping infinitely. (Obviously, a substitution shouldn't iterate more times than there are characters of input, which is what happened.) See the discussion of substitution in ["Regexp Quote-Like Operators" in perlop](perlop#Regexp-Quote-Like-Operators).
Substitution pattern not terminated (F) The lexer couldn't find the interior delimiter of an s/// or s{}{} construct. Remember that bracketing delimiters count nesting level. Missing the leading `$` from variable `$s` may cause this error.
Substitution replacement not terminated (F) The lexer couldn't find the final delimiter of an s/// or s{}{} construct. Remember that bracketing delimiters count nesting level. Missing the leading `$` from variable `$s` may cause this error.
substr outside of string (W substr)(F) You tried to reference a substr() that pointed outside of a string. That is, the absolute value of the offset was larger than the length of the string. See ["substr" in perlfunc](perlfunc#substr). This warning is fatal if substr is used in an lvalue context (as the left hand side of an assignment or as a subroutine argument for example).
sv\_upgrade from type %d down to type %d (P) Perl tried to force the upgrade of an SV to a type which was actually inferior to its current type.
Switch (?(condition)... contains too many branches in regex; marked by <-- HERE in m/%s/ (F) A (?(condition)if-clause|else-clause) construct can have at most two branches (the if-clause and the else-clause). If you want one or both to contain alternation, such as using `this|that|other`, enclose it in clustering parentheses:
```
(?(condition)(?:this|that|other)|else-clause)
```
The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Switch condition not recognized in regex; marked by <-- HERE in m/%s/ (F) The condition part of a (?(condition)if-clause|else-clause) construct is not known. The condition must be one of the following:
```
(1) (2) ... true if 1st, 2nd, etc., capture matched
(<NAME>) ('NAME') true if named capture matched
(?=...) (?<=...) true if subpattern matches
(?!...) (?<!...) true if subpattern fails to match
(?{ CODE }) true if code returns a true value
(R) true if evaluating inside recursion
(R1) (R2) ... true if directly inside capture group 1, 2, etc.
(R&NAME) true if directly inside named capture
(DEFINE) always false; for defining named subpatterns
```
The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Switch (?(condition)... not terminated in regex; marked by <-- HERE in m/%s/ (F) You omitted to close a (?(condition)...) block somewhere in the pattern. Add a closing parenthesis in the appropriate position. See <perlre>.
switching effective %s is not implemented (F) While under the `use filetest` pragma, we cannot switch the real and effective uids or gids.
syntax error (F) Probably means you had a syntax error. Common reasons include:
```
A keyword is misspelled.
A semicolon is missing.
A comma is missing.
An opening or closing parenthesis is missing.
An opening or closing brace is missing.
A closing quote is missing.
```
Often there will be another error message associated with the syntax error giving more information. (Sometimes it helps to turn on **-w**.) The error message itself often tells you where it was in the line when it decided to give up. Sometimes the actual error is several tokens before this, because Perl is good at understanding random input. Occasionally the line number may be misleading, and once in a blue moon the only way to figure out what's triggering the error is to call `perl -c` repeatedly, chopping away half the program each time to see if the error went away. Sort of the cybernetic version of 20 questions.
syntax error at line %d: '%s' unexpected (A) You've accidentally run your script through the Bourne shell instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
syntax error in file %s at line %d, next 2 tokens "%s" (F) This error is likely to occur if you run a perl5 script through a perl4 interpreter, especially if the next 2 tokens are "use strict" or "my $var" or "our $var".
Syntax error in (?[...]) in regex; marked by <-- HERE in m/%s/ (F) Perl could not figure out what you meant inside this construct; this notifies you that it is giving up trying.
%s syntax OK (F) The final summary message when a `perl -c` succeeds.
sysread() on closed filehandle %s (W closed) You tried to read from a closed filehandle.
sysread() on unopened filehandle %s (W unopened) You tried to read from a filehandle that was never opened.
System V %s is not implemented on this machine (F) You tried to do something with a function beginning with "sem", "shm", or "msg" but that System V IPC is not implemented in your machine. In some machines the functionality can exist but be unconfigured. Consult your system support.
syswrite() on closed filehandle %s (W closed) The filehandle you're writing to got itself closed sometime before now. Check your control flow.
`-T` and `-B` not implemented on filehandles (F) Perl can't peek at the stdio buffer of filehandles when it doesn't know about your kind of stdio. You'll have to use a filename instead.
Target of goto is too deeply nested (F) You tried to use `goto` to reach a label that was too deeply nested for Perl to reach. Perl is doing you a favor by refusing.
telldir() attempted on invalid dirhandle %s (W io) The dirhandle you tried to telldir() is either closed or not really a dirhandle. Check your control flow.
tell() on unopened filehandle (W unopened) You tried to use the tell() function on a filehandle that was either never opened or has since been closed.
The crypt() function is unimplemented due to excessive paranoia. (F) Configure couldn't find the crypt() function on your machine, probably because your vendor didn't supply it, probably because they think the U.S. Government thinks it's a secret, or at least that they will continue to pretend that it is. And if you quote me on that, I will deny it.
The experimental declared\_refs feature is not enabled (F) To declare references to variables, as in `my \%x`, you must first enable the feature:
```
no warnings "experimental::declared_refs";
use feature "declared_refs";
```
The %s function is unimplemented (F) The function indicated isn't implemented on this architecture, according to the probings of Configure.
The private\_use feature is experimental (S experimental::private\_use) This feature is actually a hook for future use.
The stat preceding %s wasn't an lstat (F) It makes no sense to test the current stat buffer for symbolic linkhood if the last stat that wrote to the stat buffer already went past the symlink to get to the real file. Use an actual filename instead.
The Unicode property wildcards feature is experimental (S experimental::uniprop\_wildcards) This feature is experimental and its behavior may in any future release of perl. See ["Wildcards in Property Values" in perlunicode](perlunicode#Wildcards-in-Property-Values).
The 'unique' attribute may only be applied to 'our' variables (F) This attribute was never supported on `my` or `sub` declarations.
This Perl can't reset CRTL environ elements (%s)
This Perl can't set CRTL environ elements (%s=%s) (W internal) Warnings peculiar to VMS. You tried to change or delete an element of the CRTL's internal environ array, but your copy of Perl wasn't built with a CRTL that contained the setenv() function. You'll need to rebuild Perl with a CRTL that does, or redefine *PERL\_ENV\_TABLES* (see <perlvms>) so that the environ array isn't the target of the change to %ENV which produced the warning.
This Perl has not been built with support for randomized hash key traversal but something called Perl\_hv\_rand\_set(). (F) Something has attempted to use an internal API call which depends on Perl being compiled with the default support for randomized hash key traversal, but this Perl has been compiled without it. You should report this warning to the relevant upstream party, or recompile perl with default options.
This use of my() in false conditional is no longer allowed (F) You used a declaration similar to `my $x if 0`. 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. Since we intend to fix this bug, we don't want people relying on this behavior. You can achieve a similar static effect by declaring the variable in a separate block outside the function, eg
```
sub f { my $x if 0; return $x++ }
```
becomes
```
{ my $x; sub f { return $x++ } }
```
Beginning with perl 5.10.0, you can also use `state` variables to have lexicals that are initialized only once (see <feature>):
```
sub f { state $x; return $x++ }
```
This use of `my()` in a false conditional was deprecated beginning in Perl 5.10 and became a fatal error in Perl 5.30.
Timeout waiting for another thread to define \p{%s} (F) The first time a user-defined property (["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties)) is used, its definition is looked up and converted into an internal form for more efficient handling in subsequent uses. There could be a race if two or more threads tried to do this processing nearly simultaneously. Instead, a critical section is created around this task, locking out all but one thread from doing it. This message indicates that the thread that is doing the conversion is taking an unexpectedly long time. The timeout exists solely to prevent deadlock; it's long enough that the system was likely thrashing and about to crash. There is no real remedy but rebooting.
times not implemented (F) Your version of the C library apparently doesn't do times(). I suspect you're not running on Unix.
"-T" is on the #! line, it must also be used on the command line (X) The #! line (or local equivalent) in a Perl script contains the **-T** option (or the **-t** option), but Perl was not invoked with **-T** in its command line. This is an error because, by the time Perl discovers a **-T** in a script, it's too late to properly taint everything from the environment. So Perl gives up.
If the Perl script is being executed as a command using the #! mechanism (or its local equivalent), this error can usually be fixed by editing the #! line so that the **-%c** option is a part of Perl's first argument: e.g. change `perl -n -%c` to `perl -%c -n`.
If the Perl script is being executed as `perl scriptname`, then the **-%c** option must appear on the command line: `perl -%c scriptname`.
To%s: illegal mapping '%s' (F) You tried to define a customized To-mapping for lc(), lcfirst, uc(), or ucfirst() (or their string-inlined versions), but you specified an illegal mapping. See ["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties).
Too deeply nested ()-groups (F) Your template contains ()-groups with a ridiculously deep nesting level.
Too few args to syscall (F) There has to be at least one argument to syscall() to specify the system call to call, silly dilly.
Too few arguments for subroutine '%s' (got %d; expected %d) (F) A subroutine using a signature fewer arguments than required by the signature. The caller of the subroutine is presumably at fault.
The message attempts to include the name of the called subroutine. If the subroutine has been aliased, the subroutine's original name will be shown, regardless of what name the caller used. It will also indicate the number of arguments given and the number expected.
Too few arguments for subroutine '%s' (got %d; expected at least %d) Similar to the previous message but for subroutines that accept a variable number of arguments.
Too late for "-%s" option (X) The #! line (or local equivalent) in a Perl script contains the **-M**, **-m** or **-C** option.
In the case of **-M** and **-m**, this is an error because those options are not intended for use inside scripts. Use the `use` pragma instead.
The **-C** option only works if it is specified on the command line as well (with the same sequence of letters or numbers following). Either specify this option on the command line, or, if your system supports it, make your script executable and run it directly instead of passing it to perl.
Too late to run %s block (W void) A CHECK or INIT block is being defined during run time proper, when the opportunity to run them has already passed. Perhaps you are loading a file with `require` or `do` when you should be using `use` instead. Or perhaps you should put the `require` or `do` inside a BEGIN block.
Too many args to syscall (F) Perl supports a maximum of only 14 args to syscall().
Too many arguments for %s (F) The function requires fewer arguments than you specified.
Too many arguments for subroutine '%s' (got %d; expected %d) (F) A subroutine using a signature received more arguments than permitted by the signature. The caller of the subroutine is presumably at fault.
The message attempts to include the name of the called subroutine. If the subroutine has been aliased, the subroutine's original name will be shown, regardless of what name the caller used. It will also indicate the number of arguments given and the number expected.
Too many arguments for subroutine '%s' (got %d; expected at most %d) Similar to the previous message but for subroutines that accept a variable number of arguments.
Too many nested open parens in regex; marked by <-- HERE in m/%s/ (F) You have exceeded the number of open `"("` parentheses that haven't been matched by corresponding closing ones. This limit prevents eating up too much memory. It is initially set to 1000, but may be changed by setting `${^RE_COMPILE_RECURSION_LIMIT}` to some other value. This may need to be done in a BEGIN block before the regular expression pattern is compiled.
Too many )'s (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
Too many ('s (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
Trailing \ in regex m/%s/ (F) The regular expression ends with an unbackslashed backslash. Backslash it. See <perlre>.
Transliteration pattern not terminated (F) The lexer couldn't find the interior delimiter of a tr/// or tr[][] or y/// or y[][] construct. Missing the leading `$` from variables `$tr` or `$y` may cause this error.
Transliteration replacement not terminated (F) The lexer couldn't find the final delimiter of a tr///, tr[][], y/// or y[][] construct.
'%s' trapped by operation mask (F) You tried to use an operator from a Safe compartment in which it's disallowed. See [Safe](safe).
truncate not implemented (F) Your machine doesn't implement a file truncation mechanism that Configure knows about.
try/catch is experimental (S experimental::try) This warning is emitted if you use the `try` and `catch` syntax. This syntax is currently experimental and its behaviour may change in future releases of Perl.
try/catch/finally is experimental (S experimental::try) This warning is emitted if you use the `try` and `catch` syntax with a `finally` block. This syntax is currently experimental and its behaviour may change in future releases of Perl.
Type of arg %d to &CORE::%s must be %s (F) The subroutine in question in the CORE package requires its argument to be a hard reference to data of the specified type. Overloading is ignored, so a reference to an object that is not the specified type, but nonetheless has overloading to handle it, will still not be accepted.
Type of arg %d to %s must be %s (not %s) (F) This function requires the argument in that position to be of a certain type. Arrays must be @NAME or `@{EXPR}`. Hashes must be %NAME or `%{EXPR}`. No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference. See <perlref>.
umask not implemented (F) Your machine doesn't implement the umask function and you tried to use it to restrict permissions for yourself (EXPR & 0700).
Unbalanced context: %d more PUSHes than POPs (S internal) The exit code detected an internal inconsistency in how many execution contexts were entered and left.
Unbalanced saves: %d more saves than restores (S internal) The exit code detected an internal inconsistency in how many values were temporarily localized.
Unbalanced scopes: %d more ENTERs than LEAVEs (S internal) The exit code detected an internal inconsistency in how many blocks were entered and left.
Unbalanced string table refcount: (%d) for "%s" (S internal) On exit, Perl found some strings remaining in the shared string table used for copy on write and for hash keys. The entries should have been freed, so this indicates a bug somewhere.
Unbalanced tmps: %d more allocs than frees (S internal) The exit code detected an internal inconsistency in how many mortal scalars were allocated and freed.
Undefined format "%s" called (F) The format indicated doesn't seem to exist. Perhaps it's really in another package? See <perlform>.
Undefined sort subroutine "%s" called (F) The sort comparison routine specified doesn't seem to exist. Perhaps it's in a different package? See ["sort" in perlfunc](perlfunc#sort).
Undefined subroutine &%s called (F) The subroutine indicated hasn't been defined, or if it was, it has since been undefined.
Undefined subroutine called (F) The anonymous subroutine you're trying to call hasn't been defined, or if it was, it has since been undefined.
Undefined subroutine in sort (F) The sort comparison routine specified is declared but doesn't seem to have been defined yet. See ["sort" in perlfunc](perlfunc#sort).
Undefined top format "%s" called (F) The format indicated doesn't seem to exist. Perhaps it's really in another package? See <perlform>.
Undefined value assigned to typeglob (W misc) An undefined value was assigned to a typeglob, a la `*foo = undef`. This does nothing. It's possible that you really mean `undef *foo`.
%s: Undefined variable (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
Unescaped left brace in regex is illegal here in regex; marked by <-- HERE in m/%s/ (F) 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 enables 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. Those that are not potentially ambiguous do not warn; those that are do raise a non-deprecation warning.
The contexts where no warnings or errors are raised are:
* as the first character in a pattern, or following `"^"` indicating to anchor the match to the beginning of a line.
* as the first character following a `"|"` indicating alternation.
* as the first character in a parenthesized grouping like
```
/foo({bar)/
/foo(?:{bar)/
```
* as the first character following a quantifier
```
/\s*{/
```
Unescaped left brace in regex is passed through in regex; marked by <-- HERE in m/%s/ (W regexp) 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 enables 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. Those that are not potentially ambiguous do not warn; those that are raise this warning. This makes sure that an inadvertent typo doesn't silently cause the pattern to compile to something unintended.
The contexts where no warnings or errors are raised are:
* as the first character in a pattern, or following `"^"` indicating to anchor the match to the beginning of a line.
* as the first character following a `"|"` indicating alternation.
* as the first character in a parenthesized grouping like
```
/foo({bar)/
/foo(?:{bar)/
```
* as the first character following a quantifier
```
/\s*{/
```
Unescaped literal '%c' in regex; marked by <-- HERE in m/%s/ (W regexp) (only under `use re 'strict'`)
Within the scope of `use re 'strict'` in a regular expression pattern, you included an unescaped `}` or `]` which was interpreted literally. These two characters are sometimes metacharacters, and sometimes literals, depending on what precedes them in the pattern. This is unlike the similar `)` which is always a metacharacter unless escaped.
This action at a distance, perhaps a large distance, can lead to Perl silently misinterpreting what you meant, so when you specify that you want extra checking by `use re 'strict'`, this warning is generated. If you meant the character as a literal, simply confirm that to Perl by preceding the character with a backslash, or make it into a bracketed character class (like `[}]`). If you meant it as closing a corresponding `[` or `{`, you'll need to look back through the pattern to find out why that isn't happening.
unexec of %s into %s failed! (F) The unexec() routine failed for some reason. See your local FSF representative, who probably put it there in the first place.
Unexpected binary operator '%c' with no preceding operand in regex; marked by <-- HERE in m/%s/ (F) You had something like this:
```
(?[ | \p{Digit} ])
```
where the `"|"` is a binary operator with an operand on the right, but no operand on the left.
Unexpected character in regex; marked by <-- HERE in m/%s/ (F) You had something like this:
```
(?[ z ])
```
Within `(?[ ])`, no literal characters are allowed unless they are within an inner pair of square brackets, like
```
(?[ [ z ] ])
```
Another possibility is that you forgot a backslash. Perl isn't smart enough to figure out what you really meant.
Unexpected exit %u (S) exit() was called or the script otherwise finished gracefully when `PERL_EXIT_WARN` was set in `PL_exit_flags`.
Unexpected exit failure %d (S) An uncaught die() was called when `PERL_EXIT_WARN` was set in `PL_exit_flags`.
Unexpected ')' in regex; marked by <-- HERE in m/%s/ (F) You had something like this:
```
(?[ ( \p{Digit} + ) ])
```
The `")"` is out-of-place. Something apparently was supposed to be combined with the digits, or the `"+"` shouldn't be there, or something like that. Perl can't figure out what was intended.
Unexpected ']' with no following ')' in (?[... in regex; marked by <-- HERE in m/%s/ (F) While parsing an extended character class a ']' character was encountered at a point in the definition where the only legal use of ']' is to close the character class definition as part of a '])', you may have forgotten the close paren, or otherwise confused the parser.
Unexpected '(' with no preceding operator in regex; marked by <-- HERE in m/%s/ (F) You had something like this:
```
(?[ \p{Digit} ( \p{Lao} + \p{Thai} ) ])
```
There should be an operator before the `"("`, as there's no indication as to how the digits are to be combined with the characters in the Lao and Thai scripts.
Unicode non-character U+%X is not recommended for open interchange (S nonchar) Certain codepoints, such as U+FFFE and U+FFFF, are defined by the Unicode standard to be non-characters. Those are legal codepoints, but are reserved for internal use; so, applications shouldn't attempt to exchange them. An application may not be expecting any of these characters at all, and receiving them may lead to bugs. If you know what you are doing you can turn off this warning by `no warnings 'nonchar';`.
This is not really a "severe" error, but it is supposed to be raised by default even if warnings are not enabled, and currently the only way to do that in Perl is to mark it as serious.
Unicode property wildcard not terminated (F) A Unicode property wildcard looks like a delimited regular expression pattern (all within the braces of the enclosing `\p{...}`. The closing delimtter to match the opening one was not found. If the opening one is escaped by preceding it with a backslash, the closing one must also be so escaped.
Unicode string properties are not implemented in (?[...]) in regex; marked by <-- HERE in m/%s/ (F) A Unicode string property is one which expands to a sequence of multiple characters. An example is `\p{name=KATAKANA LETTER AINU P}`, which is comprised of the sequence `\N{KATAKANA LETTER SMALL H}` followed by `\N{COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK}`. Extended character classes, `(?[...])` currently cannot handle these.
Unicode surrogate U+%X is illegal in UTF-8 (S surrogate) You had a UTF-16 surrogate in a context where they are not considered acceptable. These code points, between U+D800 and U+DFFF (inclusive), are used by Unicode only for UTF-16. However, Perl internally allows all unsigned integer code points (up to the size limit available on your platform), including surrogates. But these can cause problems when being input or output, which is likely where this message came from. If you really really know what you are doing you can turn off this warning by `no warnings 'surrogate';`.
Unknown charname '%s' (F) The name you used inside `\N{}` is unknown to Perl. Check the spelling. You can say `use charnames ":loose"` to not have to be so precise about spaces, hyphens, and capitalization on standard Unicode names. (Any custom aliases that have been created must be specified exactly, regardless of whether `:loose` is used or not.) This error may also happen if the `\N{}` is not in the scope of the corresponding `use charnames`.
Unknown '(\*...)' construct '%s' in regex; marked by <-- HERE in m/%s/ (F) The `(*` was followed by something that the regular expression compiler does not recognize. Check your spelling.
Unknown error (P) Perl was about to print an error message in `$@`, but the `$@` variable did not exist, even after an attempt to create it.
Unknown locale category %d; can't set it to %s (W locale) You used a locale category that perl doesn't recognize, so it cannot carry out your request. Check that you are using a valid category. If so, see ["Multi-threaded" in perllocale](perllocale#Multi-threaded) for advice on reporting this as a bug, and for modifying perl locally to accommodate your needs.
Unknown open() mode '%s' (F) The second argument of 3-argument open() is not among the list of valid modes: `<`, `>`, `>>`, `+<`, `+>`, `+>>`, `-|`, `|-`, `<&`, `>&`.
Unknown PerlIO layer "%s" (W layer) An attempt was made to push an unknown layer onto the Perl I/O system. (Layers take care of transforming data between external and internal representations.) Note that some layers, such as `mmap`, are not supported in all environments. If your program didn't explicitly request the failing operation, it may be the result of the value of the environment variable PERLIO.
Unknown process %x sent message to prime\_env\_iter: %s (P) An error peculiar to VMS. Perl was reading values for %ENV before iterating over it, and someone else stuck a message in the stream of data Perl expected. Someone's very confused, or perhaps trying to subvert Perl's population of %ENV for nefarious purposes.
Unknown regexp modifier "/%s" (F) Alphanumerics immediately following the closing delimiter of a regular expression pattern are interpreted by Perl as modifier flags for the regex. One of the ones you specified is invalid. One way this can happen is if you didn't put in white space between the end of the regex and a following alphanumeric operator:
```
if ($a =~ /foo/and $bar == 3) { ... }
```
The `"a"` is a valid modifier flag, but the `"n"` is not, and raises this error. Likely what was meant instead was:
```
if ($a =~ /foo/ and $bar == 3) { ... }
```
Unknown "re" subpragma '%s' (known ones are: %s) (W) You tried to use an unknown subpragma of the "re" pragma.
Unknown switch condition (?(...)) in regex; marked by <-- HERE in m/%s/ (F) The condition part of a (?(condition)if-clause|else-clause) construct is not known. The condition must be one of the following:
```
(1) (2) ... true if 1st, 2nd, etc., capture matched
(<NAME>) ('NAME') true if named capture matched
(?=...) (?<=...) true if subpattern matches
(*pla:...) (*plb:...) true if subpattern matches; also
(*positive_lookahead:...)
(*positive_lookbehind:...)
(*nla:...) (*nlb:...) true if subpattern fails to match; also
(*negative_lookahead:...)
(*negative_lookbehind:...)
(?{ CODE }) true if code returns a true value
(R) true if evaluating inside recursion
(R1) (R2) ... true if directly inside capture group 1, 2,
etc.
(R&NAME) true if directly inside named capture
(DEFINE) always false; for defining named subpatterns
```
The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Unknown Unicode option letter '%c' (F) You specified an unknown Unicode option. See [perlrun](perlrun#-C-%5Bnumber%2Flist%5D) documentation of the `-C` switch for the list of known options.
Unknown Unicode option value %d (F) You specified an unknown Unicode option. See [perlrun](perlrun#-C-%5Bnumber%2Flist%5D) documentation of the `-C` switch for the list of known options.
Unknown user-defined property name \p{%s} (F) You specified to use a property within the `\p{...}` which was a syntactically valid user-defined property, but no definition was found for it by the time one was required to proceed. Check your spelling. See ["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties).
Unknown verb pattern '%s' in regex; marked by <-- HERE in m/%s/ (F) You either made a typo or have incorrectly put a `*` quantifier after an open brace in your pattern. Check the pattern and review <perlre> for details on legal verb patterns.
Unknown warnings category '%s' (F) An error issued by the `warnings` pragma. You specified a warnings category that is unknown to perl at this point.
Note that if you want to enable a warnings category registered by a module (e.g. `use warnings 'File::Find'`), you must have loaded this module first.
Unmatched [ in regex; marked by <-- HERE in m/%s/ (F) The brackets around a character class must match. If you wish to include a closing bracket in a character class, backslash it or put it first. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Unmatched ( in regex; marked by <-- HERE in m/%s/
Unmatched ) in regex; marked by <-- HERE in m/%s/ (F) Unbackslashed parentheses must always be balanced in regular expressions. If you're a vi user, the % key is valuable for finding the matching parenthesis. The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Unmatched right %s bracket (F) The lexer counted more closing curly or square brackets than opening ones, so you're probably missing a matching opening bracket. As a general rule, you'll find the missing one (so to speak) near the place you were last editing.
Unquoted string "%s" may clash with future reserved word (W reserved) You used a bareword that might someday be claimed as a reserved word. It's best to put such a word in quotes, or capitalize it somehow, or insert an underbar into it. You might also declare it as a subroutine.
Unrecognized character %s; marked by <-- HERE after %s near column %d (F) The Perl parser has no idea what to do with the specified character in your Perl script (or eval) near the specified column. Perhaps you tried to run a compressed script, a binary program, or a directory as a Perl program.
Unrecognized escape \%c in character class in regex; marked by <-- HERE in m/%s/ (F) You used a backslash-character combination which is not recognized by Perl inside character classes. This is a fatal error when the character class is used within `(?[ ])`.
Unrecognized escape \%c in character class passed through in regex; marked by <-- HERE in m/%s/ (W regexp) You used a backslash-character combination which is not recognized by Perl inside character classes. The character was understood literally, but this may change in a future version of Perl. The <-- HERE shows whereabouts in the regular expression the escape was discovered.
Unrecognized escape \%c passed through (W misc) You used a backslash-character combination which is not recognized by Perl. The character was understood literally, but this may change in a future version of Perl.
Unrecognized escape \%s passed through in regex; marked by <-- HERE in m/%s/ (W regexp) You used a backslash-character combination which is not recognized by Perl. The character(s) were understood literally, but this may change in a future version of Perl. The <-- HERE shows whereabouts in the regular expression the escape was discovered.
Unrecognized signal name "%s" (F) You specified a signal name to the kill() function that was not recognized. Say `kill -l` in your shell to see the valid signal names on your system.
Unrecognized switch: -%s (-h will show valid options) (F) You specified an illegal option to Perl. Don't do that. (If you think you didn't do that, check the #! line to see if it's supplying the bad switch on your behalf.)
Unsuccessful %s on filename containing newline (W newline) A file operation was attempted on a filename, and that operation failed, PROBABLY because the filename contained a newline, PROBABLY because you forgot to chomp() it off. See ["chomp" in perlfunc](perlfunc#chomp).
Unsupported directory function "%s" called (F) Your machine doesn't support opendir() and readdir().
Unsupported function %s (F) This machine doesn't implement the indicated function, apparently. At least, Configure doesn't think so.
Unsupported function fork (F) Your version of executable does not support forking.
Note that under some systems, like OS/2, there may be different flavors of Perl executables, some of which may support fork, some not. Try changing the name you call Perl by to `perl_`, `perl__`, and so on.
Unsupported script encoding %s (F) Your program file begins with a Unicode Byte Order Mark (BOM) which declares it to be in a Unicode encoding that Perl cannot read.
Unsupported socket function "%s" called (F) Your machine doesn't support the Berkeley socket mechanism, or at least that's what Configure thought.
Unterminated '(\*...' argument in regex; marked by <-- HERE in m/%s/ (F) You used a pattern of the form `(*...:...)` but did not terminate the pattern with a `)`. Fix the pattern and retry.
Unterminated attribute list (F) The lexer found something other than a simple identifier at the start of an attribute, and it wasn't a semicolon or the start of a block. Perhaps you terminated the parameter list of the previous attribute too soon. See <attributes>.
Unterminated attribute parameter in attribute list (F) The lexer saw an opening (left) parenthesis character while parsing an attribute list, but the matching closing (right) parenthesis character was not found. You may need to add (or remove) a backslash character to get your parentheses to balance. See <attributes>.
Unterminated compressed integer (F) An argument to unpack("w",...) was incompatible with the BER compressed integer format and could not be converted to an integer. See ["pack" in perlfunc](perlfunc#pack).
Unterminated '(\*...' construct in regex; marked by <-- HERE in m/%s/ (F) You used a pattern of the form `(*...)` but did not terminate the pattern with a `)`. Fix the pattern and retry.
Unterminated delimiter for here document (F) This message occurs when a here document label has an initial quotation mark but the final quotation mark is missing. Perhaps you wrote:
```
<<"foo
```
instead of:
```
<<"foo"
```
Unterminated \g... pattern in regex; marked by <-- HERE in m/%s/
Unterminated \g{...} pattern in regex; marked by <-- HERE in m/%s/ (F) In a regular expression, you had a `\g` that wasn't followed by a proper group reference. In the case of `\g{`, the closing brace is missing; otherwise the `\g` must be followed by an integer. Fix the pattern and retry.
Unterminated <> operator (F) The lexer saw a left angle bracket in a place where it was expecting a term, so it's looking for the corresponding right angle bracket, and not finding it. Chances are you left some needed parentheses out earlier in the line, and you really meant a "less than".
Unterminated verb pattern argument in regex; marked by <-- HERE in m/%s/ (F) You used a pattern of the form `(*VERB:ARG)` but did not terminate the pattern with a `)`. Fix the pattern and retry.
Unterminated verb pattern in regex; marked by <-- HERE in m/%s/ (F) You used a pattern of the form `(*VERB)` but did not terminate the pattern with a `)`. Fix the pattern and retry.
untie attempted while %d inner references still exist (W untie) A copy of the object returned from `tie` (or `tied`) was still valid when `untie` was called.
Usage: POSIX::%s(%s) (F) You called a POSIX function with incorrect arguments. See ["FUNCTIONS" in POSIX](posix#FUNCTIONS) for more information.
Usage: Win32::%s(%s) (F) You called a Win32 function with incorrect arguments. See [Win32](win32) for more information.
$[ used in %s (did you mean $] ?) (W syntax) You used `$[` in a comparison, such as:
```
if ($[ > 5.006) {
...
}
```
You probably meant to use `$]` instead. `$[` is the base for indexing arrays. `$]` is the Perl version number in decimal.
Use "%s" instead of "%s" (F) The second listed construct is no longer legal. Use the first one instead.
Useless assignment to a temporary (W misc) You assigned to an lvalue subroutine, but what the subroutine returned was a temporary scalar about to be discarded, so the assignment had no effect.
Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ (W regexp) You have used an internal modifier such as (?-o) that has no meaning unless removed from the entire regexp:
```
if ($string =~ /(?-o)$pattern/o) { ... }
```
must be written as
```
if ($string =~ /$pattern/) { ... }
```
The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Useless localization of %s (W syntax) The localization of lvalues such as `local($x=10)` is legal, but in fact the local() currently has no effect. This may change at some point in the future, but in the meantime such code is discouraged.
Useless (?%s) - use /%s modifier in regex; marked by <-- HERE in m/%s/ (W regexp) You have used an internal modifier such as (?o) that has no meaning unless applied to the entire regexp:
```
if ($string =~ /(?o)$pattern/) { ... }
```
must be written as
```
if ($string =~ /$pattern/o) { ... }
```
The <-- HERE shows whereabouts in the regular expression the problem was discovered. See <perlre>.
Useless use of attribute "const" (W misc) The `const` attribute has no effect except on anonymous closure prototypes. You applied it to a subroutine via [attributes.pm](attributes). This is only useful inside an attribute handler for an anonymous subroutine.
Useless use of /d modifier in transliteration operator (W misc) You have used the /d modifier where the searchlist has the same length as the replacelist. See <perlop> for more information about the /d modifier.
Useless use of \E (W misc) You have a \E in a double-quotish string without a `\U`, `\L` or `\Q` preceding it.
Useless use of greediness modifier '%c' in regex; marked by <-- HERE in m/%s/ (W regexp) You specified something like these:
```
qr/a{3}?/
qr/b{1,1}+/
```
The `"?"` and `"+"` don't have any effect, as they modify whether to match more or fewer when there is a choice, and by specifying to match exactly a given number, there is no room left for a choice.
Useless use of %s in scalar context (W scalar) You did something whose only interesting return value is a list without a side effect in scalar context, which does not accept a list.
For example
```
my $x = sort @y;
```
This is not very useful, and perl currently optimizes this away.
Useless use of %s in void context (W void) You did something without a side effect in a context that does nothing with the return value, such as a statement that doesn't return a value from a block, or the left side of a scalar comma operator. Very often this points not to stupidity on your part, but a failure of Perl to parse your program the way you thought it would. For example, you'd get this if you mixed up your C precedence with Python precedence and said
```
$one, $two = 1, 2;
```
when you meant to say
```
($one, $two) = (1, 2);
```
Another common error is to use ordinary parentheses to construct a list reference when you should be using square or curly brackets, for example, if you say
```
$array = (1,2);
```
when you should have said
```
$array = [1,2];
```
The square brackets explicitly turn a list value into a scalar value, while parentheses do not. So when a parenthesized list is evaluated in a scalar context, the comma is treated like C's comma operator, which throws away the left argument, which is not what you want. See <perlref> for more on this.
This warning will not be issued for numerical constants equal to 0 or 1 since they are often used in statements like
```
1 while sub_with_side_effects();
```
String constants that would normally evaluate to 0 or 1 are warned about.
Useless use of (?-p) in regex; marked by <-- HERE in m/%s/ (W regexp) The `p` modifier cannot be turned off once set. Trying to do so is futile.
Useless use of "re" pragma (W) You did `use re;` without any arguments. That isn't very useful.
Useless use of %s with no values (W syntax) You used the push() or unshift() function with no arguments apart from the array, like `push(@x)` or `unshift(@foo)`. That won't usually have any effect on the array, so is completely useless. It's possible in principle that push(@tied\_array) could have some effect if the array is tied to a class which implements a PUSH method. If so, you can write it as `push(@tied_array,())` to avoid this warning.
"use" not allowed in expression (F) The "use" keyword is recognized and executed at compile time, and returns no useful value. See <perlmod>.
Use of @\_ in %s with signatured subroutine is experimental (S experimental::args\_array\_with\_signatures) An expression involving the `@_` arguments array was found in a subroutine that uses a signature. This is experimental because the interaction between the arguments array and parameter handling via signatures is not guaranteed to remain stable in any future version of Perl, and such code should be avoided.
Use of bare << to mean <<"" is forbidden (F) You are now required to use the explicitly quoted form if you wish to use an empty line as the terminator of the here-document.
Use of a bare terminator was deprecated in Perl 5.000, and is a fatal error as of Perl 5.28.
Use of /c modifier is meaningless in s/// (W regexp) You used the /c modifier in a substitution. The /c modifier is not presently meaningful in substitutions.
Use of /c modifier is meaningless without /g (W regexp) You used the /c modifier with a regex operand, but didn't use the /g modifier. Currently, /c is meaningful only when /g is used. (This may change in the future.)
Use of code point 0x%s is not allowed; the permissible max is 0x%X
Use of code point 0x%s is not allowed; the permissible max is 0x%X in regex; marked by <-- HERE in m/%s/ (F) You used a code point that is not allowed, because it is too large. Unicode only allows code points up to 0x10FFFF, but Perl allows much larger ones. Earlier versions of Perl allowed code points above IV\_MAX (0x7FFFFFF on 32-bit platforms, 0x7FFFFFFFFFFFFFFF on 64-bit platforms), however, this could possibly break the perl interpreter in some constructs, including causing it to hang in a few cases.
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.
The use of out of range code points was deprecated in Perl 5.24, and became a fatal error in Perl 5.28.
Use of each() on hash after insertion without resetting hash iterator results in undefined behavior (S internal) The behavior of `each()` after insertion is undefined; it may skip items, or visit items more than once. Consider using `keys()` instead of `each()`.
Use of := for an empty attribute list is not allowed (F) The construction `my $x := 42` used to parse as equivalent to `my $x : = 42` (applying an empty attribute list to `$x`). This construct was deprecated in 5.12.0, and has now been made a syntax error, so `:=` can be reclaimed as a new operator in the future.
If you need an empty attribute list, for example in a code generator, add a space before the `=`.
Use of %s for non-UTF-8 locale is wrong. Assuming a UTF-8 locale (W locale) You are matching a regular expression using locale rules, and the specified construct was encountered. This construct is only valid for UTF-8 locales, which the current locale isn't. This doesn't make sense. Perl will continue, assuming a Unicode (UTF-8) locale, but the results are likely to be wrong.
Use of freed value in iteration (F) Perhaps you modified the iterated array within the loop? This error is typically caused by code like the following:
```
@a = (3,4);
@a = () for (1,2,@a);
```
You are not supposed to modify arrays while they are being iterated over. For speed and efficiency reasons, Perl internally does not do full reference-counting of iterated items, hence deleting such an item in the middle of an iteration causes Perl to see a freed value.
Use of /g modifier is meaningless in split (W regexp) You used the /g modifier on the pattern for a `split` operator. Since `split` always tries to match the pattern repeatedly, the `/g` has no effect.
Use of "goto" to jump into a construct is deprecated (D deprecated) Using `goto` to jump from an outer scope into an inner scope is deprecated and should be avoided.
This was deprecated in Perl 5.12.
Use of '%s' in \p{} or \P{} is deprecated because: %s (D deprecated) Certain properties are deprecated by Unicode, and may eventually be removed from the Standard, at which time Perl will follow along. In the meantime, this message is raised to notify you.
Use of inherited AUTOLOAD for non-method %s::%s() is no longer allowed (F) As an 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 was deprecated in Perl 5.004, and was made fatal in Perl 5.28.
Use of %s in printf format not supported (F) You attempted to use a feature of printf that is accessible from only C. This usually means there's a better way to do it in Perl.
Use of '%s' is deprecated as a string delimiter (D deprecated) You used the given character as a starting delimiter of a string outside the scope of `use feature 'extra_paired_delimiters'`. This character is the mirror image of another Unicode character; within the scope of that feature, the two are considered a pair for delimitting strings. It is planned to make that feature the default, at which point this usage would become illegal; hence this warning.
For now, you may live with this warning, or turn it off, but this code will no longer compile in a future version of Perl. Or you can turn on `use feature 'extra_paired_delimiters'` and use the character that is the mirror image of this one for the closing string delimiter.
Use of '%s' is experimental as a string delimiter (S experimental::extra\_paired\_delimiters) This warning is emitted if you use as a string delimiter one of the non-ASCII mirror image ones enabled by `use feature 'extra_paired_delimiters'`. Simply suppress the warning if you want to use the feature, but know that in doing so you are taking the risk of using an experimental feature which may change or be removed in a future Perl version:
Use of %s is not allowed in Unicode property wildcard subpatterns in regex; marked by <-- HERE in m/%s/ (F) You were using a wildcard subpattern a Unicode property value, and the subpattern contained something that is illegal. Not all regular expression capabilities are legal in such subpatterns, and this is one. Rewrite your subppattern to not use the offending construct. See ["Wildcards in Property Values" in perlunicode](perlunicode#Wildcards-in-Property-Values).
Use of -l on filehandle%s (W io) A filehandle represents an opened file, and when you opened the file it already went past any symlink you are presumably trying to look for. The operation returned `undef`. Use a filename instead.
Use of reference "%s" as array index (W misc) You tried to use a reference as an array index; this probably isn't what you mean, because references in numerical context tend to be huge numbers, and so usually indicates programmer error.
If you really do mean it, explicitly numify your reference, like so: `$array[0+$ref]`. This warning is not given for overloaded objects, however, because you can overload the numification and stringification operators and then you presumably know what you are doing.
Use of strings with code points over 0xFF as arguments to %s operator is not allowed (F) You tried to use one of the string bitwise operators (`&` or `|` or `^` or `~`) on a string containing a code point over 0xFF. The string bitwise operators treat their operands as strings of bytes, and values beyond 0xFF are nonsensical in this context.
Certain instances became fatal in Perl 5.28; others in perl 5.32.
Use of strings with code points over 0xFF as arguments to vec is forbidden (F) You tried to use [`vec`](perlfunc#vec-EXPR%2COFFSET%2CBITS) on a string containing a code point over 0xFF, which is nonsensical here.
This became fatal in Perl 5.32.
Use of tainted arguments in %s is deprecated (W taint, deprecated) You have supplied `system()` or `exec()` with multiple arguments and at least one of them is tainted. This used to be allowed but will become a fatal error in a future version of perl. Untaint your arguments. See <perlsec>.
Use of unassigned code point or non-standalone grapheme for a delimiter is not allowed (F) 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 when displayed to be a single character with the circumflex hovering over the "R". Perl currently allows things like that circumflex to be delimiters of strings, patterns, *etc*. When displayed, the circumflex would look like it belongs to the character just to the left of it. In order to move the language to be able to accept graphemes as delimiters, we cannot allow the use of delimiters which aren't graphemes by themselves. Also, a delimiter must already be assigned (or known to be never going to be assigned) to try to future-proof code, for 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](%20perlunicode#Beyond-Unicode-code-points), those can be delimiters, and their use is legal.
Use of uninitialized value%s (W uninitialized) An undefined value was used as if it were already defined. It was interpreted as a "" or a 0, but maybe it was a mistake. To suppress this warning assign a defined value to your variables.
To help you figure out what was undefined, perl will try to tell you the name of the variable (if any) that was undefined. In some cases it cannot do this, so it also tells you what operation you used the undefined value in. Note, however, that perl optimizes your program and the operation displayed in the warning may not necessarily appear literally in your program. For example, `"that $foo"` is usually optimized into `"that " . $foo`, and the warning will refer to the `concatenation (.)` operator, even though there is no `.` in your program.
"use re 'strict'" is experimental (S experimental::re\_strict) The things that are different when a regular expression pattern is compiled under `'strict'` are subject to change in future Perl releases in incompatible ways. This means that a pattern that compiles today may not in a future Perl release. This warning is to alert you to that risk.
Use \x{...} for more than two hex characters in regex; marked by <-- HERE in m/%s/ (F) In a regular expression, you said something like
```
(?[ [ \xBEEF ] ])
```
Perl isn't sure if you meant this
```
(?[ [ \x{BEEF} ] ])
```
or if you meant this
```
(?[ [ \x{BE} E F ] ])
```
You need to add either braces or blanks to disambiguate.
Using just the first character returned by \N{} in character class in regex; marked by <-- HERE in m/%s/ (W regexp) Named Unicode character escapes `(\N{...})` may return a multi-character sequence. Even though a character class is supposed to match just one character of input, perl will match the whole thing correctly, except when the class is inverted (`[^...]`), or the escape is the beginning or final end point of a range. For these, what should happen isn't clear at all. In these circumstances, Perl discards all but the first character of the returned sequence, which is not likely what you want.
Using just the single character results returned by \p{} in (?[...]) in regex; marked by <-- HERE in m/%s/ (W regexp) Extended character classes currently cannot handle operands that evaluate to more than one character. These are removed from the results of the expansion of the `\p{}`.
This situation can happen, for example, in
```
(?[ \p{name=/KATAKANA/} ])
```
"KATAKANA LETTER AINU P" is a legal Unicode name (technically a "named sequence"), but it is actually two characters. The above expression with match only the Unicode names containing KATAKANA that represent single characters.
Using /u for '%s' instead of /%s in regex; marked by <-- HERE in m/%s/ (W regexp) You used a Unicode boundary (`\b{...}` or `\B{...}`) in a portion of a regular expression where the character set modifiers `/a` or `/aa` are in effect. These two modifiers indicate an ASCII interpretation, and this doesn't make sense for a Unicode definition. The generated regular expression will compile so that the boundary uses all of Unicode. No other portion of the regular expression is affected.
Using !~ with %s doesn't make sense (F) Using the `!~` operator with `s///r`, `tr///r` or `y///r` is currently reserved for future use, as the exact behavior has not been decided. (Simply returning the boolean opposite of the modified string is usually not particularly useful.)
UTF-16 surrogate U+%X (S surrogate) You had a UTF-16 surrogate in a context where they are not considered acceptable. These code points, between U+D800 and U+DFFF (inclusive), are used by Unicode only for UTF-16. However, Perl internally allows all unsigned integer code points (up to the size limit available on your platform), including surrogates. But these can cause problems when being input or output, which is likely where this message came from. If you really really know what you are doing you can turn off this warning by `no warnings 'surrogate';`.
Value of %s can be "0"; test with defined() (W misc) In a conditional expression, you used <HANDLE>, <\*> (glob), `each()`, or `readdir()` as a boolean value. Each of these constructs can return a value of "0"; that would make the conditional expression false, which is probably not what you intended. When using these constructs in conditional expressions, test their values with the `defined` operator.
Value of CLI symbol "%s" too long (W misc) A warning peculiar to VMS. Perl tried to read the value of an %ENV element from a CLI symbol table, and found a resultant string longer than 1024 characters. The return value has been truncated to 1024 characters.
Variable "%s" is not available (W closure) During compilation, an inner named subroutine or eval is attempting to capture an outer lexical that is not currently available. This can happen for one of two reasons. First, the outer lexical may be declared in an outer anonymous subroutine that has not yet been created. (Remember that named subs are created at compile time, while anonymous subs are created at run-time.) For example,
```
sub { my $a; sub f { $a } }
```
At the time that f is created, it can't capture the current value of $a, since the anonymous subroutine hasn't been created yet. Conversely, the following won't give a warning since the anonymous subroutine has by now been created and is live:
```
sub { my $a; eval 'sub f { $a }' }->();
```
The second situation is caused by an eval accessing a variable that has gone out of scope, for example,
```
sub f {
my $a;
sub { eval '$a' }
}
f()->();
```
Here, when the '$a' in the eval is being compiled, f() is not currently being executed, so its $a is not available for capture.
Variable "%s" is not imported%s (S misc) With "use strict" in effect, you referred to a global variable that you apparently thought was imported from another module, because something else of the same name (usually a subroutine) is exported by that module. It usually means you put the wrong funny character on the front of your variable. It is also possible you used an "our" variable whose scope has ended.
Variable length lookbehind not implemented in regex m/%s/ (F) **This message no longer should be raised as of Perl 5.30.** It is retained in this document as a convenience for people using an earlier Perl version.
In Perl 5.30 and earlier, lookbehind is allowed only for subexpressions whose length is fixed and known at compile time. For positive lookbehind, you can use the `\K` regex construct as a way to get the equivalent functionality. See [(?<=pattern) and \K in perlre](perlre#%5CK).
Starting in Perl 5.18, there are non-obvious Unicode rules under `/i` that can match variably, but which you might not think could. For example, the substring `"ss"` can match the single character LATIN SMALL LETTER SHARP S. Here's a complete list of the current ones affecting ASCII characters:
```
ASCII
sequence Matches single letter under /i
FF U+FB00 LATIN SMALL LIGATURE FF
FFI U+FB03 LATIN SMALL LIGATURE FFI
FFL U+FB04 LATIN SMALL LIGATURE FFL
FI U+FB01 LATIN SMALL LIGATURE FI
FL U+FB02 LATIN SMALL LIGATURE FL
SS U+00DF LATIN SMALL LETTER SHARP S
U+1E9E LATIN CAPITAL LETTER SHARP S
ST U+FB06 LATIN SMALL LIGATURE ST
U+FB05 LATIN SMALL LIGATURE LONG S T
```
This list is subject to change, but is quite unlikely to. Each ASCII sequence can be any combination of upper- and lowercase.
You can avoid this by using a bracketed character class in the lookbehind assertion, like
```
(?<![sS]t)
(?<![fF]f[iI])
```
This fools Perl into not matching the ligatures.
Another option for Perls starting with 5.16, if you only care about ASCII matches, is to add the `/aa` modifier to the regex. This will exclude all these non-obvious matches, thus getting rid of this message. You can also say
```
use if $] ge 5.016, re => '/aa';
```
to apply `/aa` to all regular expressions compiled within its scope. See <re>.
Variable length positive lookbehind with capturing is experimental in regex m/%s/ (W) Variable length positive lookbehind with capturing is not well defined. This warning alerts you to the fact that you are using a construct which may change in a future version of perl. See the [documentation of Positive Lookbehind in perlre](perlre#%28%3F%3C%3Dpattern%29) for details. You may silence this warning with the following:
```
no warnings 'experimental::vlb';
```
Variable length negative lookbehind with capturing is experimental in regex m/%s/ (W) Variable length negative lookbehind with capturing is not well defined. This warning alerts you to the fact that you are using a construct which may change in a future version of perl. See the [documentation of Negative Lookbehind in perlre](perlre#%28%3F%3C%21pattern%29) for details. You may silence this warning with the following:
```
no warnings 'experimental::vlb';
```
"%s" variable %s masks earlier declaration in same %s (W shadow) A "my", "our" or "state" variable has been redeclared in the current scope or statement, effectively eliminating all access to the previous instance. This is almost always a typographical error. Note that the earlier variable will still exist until the end of the scope or until all closure references to it are destroyed.
Variable syntax (A) You've accidentally run your script through **csh** instead of Perl. Check the #! line, or manually feed your script into Perl yourself.
Variable "%s" will not stay shared (W closure) An inner (nested) *named* subroutine is referencing a lexical variable defined in an outer named subroutine.
When the inner subroutine is called, it will see the value of the outer subroutine's variable as it was before and during the \*first\* call to the outer subroutine; in this case, after the first call to the outer subroutine is complete, the inner and outer subroutines will no longer share a common value for the variable. In other words, the variable will no longer be shared.
This problem can usually be solved by making the inner subroutine anonymous, using the `sub {}` syntax. When inner anonymous subs that reference variables in outer subroutines are created, they are automatically rebound to the current values of such variables.
vector argument not supported with alpha versions (S printf) The %vd (s)printf format does not support version objects with alpha parts.
Verb pattern '%s' has a mandatory argument in regex; marked by <-- HERE in m/%s/ (F) You used a verb pattern that requires an argument. Supply an argument or check that you are using the right verb.
Verb pattern '%s' may not have an argument in regex; marked by <-- HERE in m/%s/ (F) You used a verb pattern that is not allowed an argument. Remove the argument or check that you are using the right verb.
Version control conflict marker (F) The parser found a line starting with `<<<<<<<`, `>>>>>>>`, or `=======`. These may be left by a version control system to mark conflicts after a failed merge operation.
Version number must be a constant number (P) The attempt to translate a `use Module n.n LIST` statement into its equivalent `BEGIN` block found an internal inconsistency with the version number.
Version string '%s' contains invalid data; ignoring: '%s' (W misc) The version string contains invalid characters at the end, which are being ignored.
Warning: something's wrong (W) You passed warn() an empty string (the equivalent of `warn ""`) or you called it with no args and `$@` was empty.
Warning: unable to close filehandle %s properly (S) The implicit close() done by an open() got an error indication on the close(). This usually indicates your file system ran out of disk space.
Warning: unable to close filehandle properly: %s
Warning: unable to close filehandle %s properly: %s (S io) There were errors during the implicit close() done on a filehandle when its reference count reached zero while it was still open, e.g.:
```
{
open my $fh, '>', $file or die "open: '$file': $!\n";
print $fh $data or die "print: $!";
} # implicit close here
```
Because various errors may only be detected by close() (e.g. buffering could allow the `print` in this example to return true even when the disk is full), it is dangerous to ignore its result. So when it happens implicitly, perl will signal errors by warning.
**Prior to version 5.22.0, perl ignored such errors**, so the common idiom shown above was liable to cause **silent data loss**.
Warning: Use of "%s" without parentheses is ambiguous (S ambiguous) You wrote a unary operator followed by something that looks like a binary operator that could also have been interpreted as a term or unary operator. For instance, if you know that the rand function has a default argument of 1.0, and you write
```
rand + 5;
```
you may THINK you wrote the same thing as
```
rand() + 5;
```
but in actual fact, you got
```
rand(+5);
```
So put in parentheses to say what you really mean.
when is experimental (S experimental::smartmatch) `when` depends on smartmatch, which is experimental. Additionally, it has several special cases that may not be immediately obvious, and their behavior may change or even be removed in any future release of perl. See the explanation under ["Experimental Details on given and when" in perlsyn](perlsyn#Experimental-Details-on-given-and-when).
Wide character in %s (S utf8) Perl met a wide character (ordinal >255) when it wasn't expecting one. This warning is by default on for I/O (like print).
If this warning does come from I/O, the easiest way to quiet it is simply to add the `:utf8` layer, *e.g.*, `binmode STDOUT, ':utf8'`. Another way to turn off the warning is to add `no warnings 'utf8';` but that is often closer to cheating. In general, you are supposed to explicitly mark the filehandle with an encoding, see <open> and ["binmode" in perlfunc](perlfunc#binmode).
If the warning comes from other than I/O, this diagnostic probably indicates that incorrect results are being obtained. You should examine your code to determine how a wide character is getting to an operation that doesn't handle them.
Wide character (U+%X) in %s (W locale) While in a single-byte locale (*i.e.*, a non-UTF-8 one), a multi-byte character was encountered. Perl considers this character to be the specified Unicode code point. Combining non-UTF-8 locales and Unicode is dangerous. Almost certainly some characters will have two different representations. For example, in the ISO 8859-7 (Greek) locale, the code point 0xC3 represents a Capital Gamma. But so also does 0x393. This will make string comparisons unreliable.
You likely need to figure out how this multi-byte character got mixed up with your single-byte locale (or perhaps you thought you had a UTF-8 locale, but Perl disagrees).
Within []-length '%c' not allowed (F) The count in the (un)pack template may be replaced by `[TEMPLATE]` only if `TEMPLATE` always matches the same amount of packed bytes that can be determined from the template alone. This is not possible if it contains any of the codes @, /, U, u, w or a \*-length. Redesign the template.
While trying to resolve method call %s->%s() can not locate package "%s" yet it is mentioned in @%s::ISA (perhaps you forgot to load "%s"?) (W syntax) It is possible that the `@ISA` contains a misspelled or never loaded package name, which can result in perl choosing an unexpected parent class's method to resolve the method call. If this is deliberate you can do something like
```
@Missing::Package::ISA = ();
```
to silence the warnings, otherwise you should correct the package name, or ensure that the package is loaded prior to the method call.
%s() with negative argument (S misc) Certain operations make no sense with negative arguments. Warning is given and the operation is not done.
write() on closed filehandle %s (W closed) The filehandle you're writing to got itself closed sometime before now. Check your control flow.
%s "\x%X" does not map to Unicode (S utf8) When reading in different encodings, Perl tries to map everything into Unicode characters. The bytes you read in are not legal in this encoding. For example
```
utf8 "\xE4" does not map to Unicode
```
if you try to read in the a-diaereses Latin-1 as UTF-8.
'X' outside of string (F) You had a (un)pack template that specified a relative position before the beginning of the string being (un)packed. See ["pack" in perlfunc](perlfunc#pack).
'x' outside of string in unpack (F) You had a pack template that specified a relative position after the end of the string being unpacked. See ["pack" in perlfunc](perlfunc#pack).
YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET! (F) And you probably never will, because you probably don't have the sources to your kernel, and your vendor probably doesn't give a rip about what you want. There is a vulnerability anywhere that you have a set-id script, and to close it you need to remove the set-id bit from the script that you're attempting to run. To actually run the script set-id, your best bet is to put a set-id C wrapper around your script.
You need to quote "%s" (W syntax) You assigned a bareword as a signal handler name. Unfortunately, you already have a subroutine of that name declared, which means that Perl 5 will try to call the subroutine when the assignment is executed, which is probably not what you want. (If it IS what you want, put an & in front.)
Your random numbers are not that random (F) When trying to initialize the random seed for hashes, Perl could not get any randomness out of your system. This usually indicates Something Very Wrong.
Zero length \N{} in regex; marked by <-- HERE in m/%s/ (F) Named Unicode character escapes (`\N{...}`) may return a zero-length sequence. Such an escape was used in an extended character class, i.e. `(?[...])`, or under `use re 'strict'`, which is not permitted. Check that the correct escape has been used, and the correct charnames handler is in scope. The <-- HERE shows whereabouts in the regular expression the problem was discovered.
SEE ALSO
---------
<warnings>, <diagnostics>.
| programming_docs |
perl Text::ParseWords Text::ParseWords
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Text::ParseWords - parse text into an array of tokens or array of arrays
SYNOPSIS
--------
```
use Text::ParseWords;
@lists = nested_quotewords($delim, $keep, @lines);
@words = quotewords($delim, $keep, @lines);
@words = shellwords(@lines);
@words = parse_line($delim, $keep, $line);
@words = old_shellwords(@lines); # DEPRECATED!
```
DESCRIPTION
-----------
The `nested_quotewords()` and `quotewords()` functions accept a delimiter (which can be a regular expression) and a list of lines and then breaks those lines up into a list of words ignoring delimiters that appear inside quotes. `quotewords()` returns all of the tokens in a single long list, while `nested_quotewords()` returns a list of token lists corresponding to the elements of `@lines`. `parse_line()` does tokenizing on a single string. The `*quotewords()` functions simply call `parse_line()`, so if you're only splitting one line you can call `parse_line()` directly and save a function call.
The `$keep` controls what happens with delimters and special characters:
true If true, then the tokens are split on the specified delimiter, but all other characters (including quotes and backslashes) are kept in the tokens.
false If $keep is false then the `*quotewords()` functions remove all quotes and backslashes that are not themselves backslash-escaped or inside of single quotes (i.e., `quotewords()` tries to interpret these characters just like the Bourne shell). NB: these semantics are significantly different from the original version of this module shipped with Perl 5.000 through 5.004.
`"delimiters"`
As an additional feature, $keep may be the keyword "delimiters" which causes the functions to preserve the delimiters in each string as tokens in the token lists, in addition to preserving quote and backslash characters.
`shellwords()` is written as a special case of `quotewords()`, and it does token parsing with whitespace as a delimiter-- similar to most Unix shells.
EXAMPLES
--------
The sample program:
```
use Text::ParseWords;
@words = quotewords('\s+', 0, q{this is "a test" of\ quotewords \"for you});
$i = 0;
foreach (@words) {
print "$i: <$_>\n";
$i++;
}
```
produces:
```
0: <this>
1: <is>
2: <a test>
3: <of quotewords>
4: <"for>
5: <you>
```
demonstrating:
0 a simple word
1 multiple spaces are skipped because of our $delim
2 use of quotes to include a space in a word
3 use of a backslash to include a space in a word
4 use of a backslash to remove the special meaning of a double-quote
5 another simple word (note the lack of effect of the backslashed double-quote)
Replacing `quotewords('\s+', 0, q{this is...})` with `shellwords(q{this is...})` is a simpler way to accomplish the same thing.
SEE ALSO
---------
<Text::CSV> - for parsing CSV files
AUTHORS
-------
The original author is unknown, but presumably this evolved from `shellwords.pl` in Perl 4.
Much of the code for `parse_line()` (including the primary regexp) came from Joerk Behrends <[email protected]>.
Examples section and other documentation provided by John Heidemann <[email protected]>.
Hal Pomeranz <[email protected]> maintained this from 1994 through 1999, and did the first CPAN release.
Alexandr Ciornii <alexchornyATgmail.com> maintained this from 2008 to 2015.
Many other people have contributed, with special thanks due to Michael Schwern <[email protected]> and Jeff Friedl <[email protected]>.
COPYRIGHT AND LICENSE
----------------------
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
perl DB DB
==
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Global Variables](#Global-Variables)
+ [API Methods](#API-Methods)
+ [Client Callback Methods](#Client-Callback-Methods)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
DB - programmatic interface to the Perl debugging API
SYNOPSIS
--------
```
package CLIENT;
use DB;
@ISA = qw(DB);
# these (inherited) methods can be called by the client
CLIENT->register() # register a client package name
CLIENT->done() # de-register from the debugging API
CLIENT->skippkg('hide::hide') # ask DB not to stop in this package
CLIENT->cont([WHERE]) # run some more (until BREAK or
# another breakpointt)
CLIENT->step() # single step
CLIENT->next() # step over
CLIENT->ret() # return from current subroutine
CLIENT->backtrace() # return the call stack description
CLIENT->ready() # call when client setup is done
CLIENT->trace_toggle() # toggle subroutine call trace mode
CLIENT->subs([SUBS]) # return subroutine information
CLIENT->files() # return list of all files known to DB
CLIENT->lines() # return lines in currently loaded file
CLIENT->loadfile(FILE,LINE) # load a file and let other clients know
CLIENT->lineevents() # return info on lines with actions
CLIENT->set_break([WHERE],[COND])
CLIENT->set_tbreak([WHERE])
CLIENT->clr_breaks([LIST])
CLIENT->set_action(WHERE,ACTION)
CLIENT->clr_actions([LIST])
CLIENT->evalcode(STRING) # eval STRING in executing code's context
CLIENT->prestop([STRING]) # execute in code context before stopping
CLIENT->poststop([STRING])# execute in code context before resuming
# These methods will be called at the appropriate times.
# Stub versions provided do nothing.
# None of these can block.
CLIENT->init() # called when debug API inits itself
CLIENT->stop(FILE,LINE) # when execution stops
CLIENT->idle() # while stopped (can be a client event loop)
CLIENT->cleanup() # just before exit
CLIENT->output(LIST) # called to print any output that
# the API must show
```
DESCRIPTION
-----------
Perl debug information is frequently required not just by debuggers, but also by modules that need some "special" information to do their job properly, like profilers.
This module abstracts and provides all of the hooks into Perl internal debugging functionality, so that various implementations of Perl debuggers (or packages that want to simply get at the "privileged" debugging data) can all benefit from the development of this common code. Currently used by Swat, the perl/Tk GUI debugger.
Note that multiple "front-ends" can latch into this debugging API simultaneously. This is intended to facilitate things like debugging with a command line and GUI at the same time, debugging debuggers etc. [Sounds nice, but this needs some serious support -- GSAR]
In particular, this API does **not** provide the following functions:
* data display
* command processing
* command alias management
* user interface (tty or graphical)
These are intended to be services performed by the clients of this API.
This module attempts to be squeaky clean w.r.t `use strict;` and when warnings are enabled.
###
Global Variables
The following "public" global names can be read by clients of this API. Beware that these should be considered "readonly".
$DB::sub Name of current executing subroutine.
%DB::sub The keys of this hash are the names of all the known subroutines. Each value is an encoded string that has the sprintf(3) format `("%s:%d-%d", filename, fromline, toline)`.
$DB::single Single-step flag. Will be true if the API will stop at the next statement.
$DB::signal Signal flag. Will be set to a true value if a signal was caught. Clients may check for this flag to abort time-consuming operations.
$DB::trace This flag is set to true if the API is tracing through subroutine calls.
@DB::args Contains the arguments of current subroutine, or the `@ARGV` array if in the toplevel context.
@DB::dbline List of lines in currently loaded file.
%DB::dbline Actions in current file (keys are line numbers). The values are strings that have the sprintf(3) format `("%s\000%s", breakcondition, actioncode)`.
$DB::package Package namespace of currently executing code.
$DB::filename Currently loaded filename.
$DB::subname Fully qualified name of currently executing subroutine.
$DB::lineno Line number that will be executed next.
###
API Methods
The following are methods in the DB base class. A client must access these methods by inheritance (\*not\* by calling them directly), since the API keeps track of clients through the inheritance mechanism.
CLIENT->register() register a client object/package
CLIENT->evalcode(STRING) eval STRING in executing code context
CLIENT->skippkg('D::hide') ask DB not to stop in these packages
CLIENT->run() run some more (until a breakpt is reached)
CLIENT->step() single step
CLIENT->next() step over
CLIENT->done() de-register from the debugging API
###
Client Callback Methods
The following "virtual" methods can be defined by the client. They will be called by the API at appropriate points. Note that unless specified otherwise, the debug API only defines empty, non-functional default versions of these methods.
CLIENT->init() Called after debug API inits itself.
CLIENT->prestop([STRING]) Usually inherited from DB package. If no arguments are passed, returns the prestop action string.
CLIENT->stop() Called when execution stops (w/ args file, line).
CLIENT->idle() Called while stopped (can be a client event loop).
CLIENT->poststop([STRING]) Usually inherited from DB package. If no arguments are passed, returns the poststop action string.
CLIENT->evalcode(STRING) Usually inherited from DB package. Ask for a STRING to be `eval`-ed in executing code context.
CLIENT->cleanup() Called just before exit.
CLIENT->output(LIST) Called when API must show a message (warnings, errors etc.).
BUGS
----
The interface defined by this module is missing some of the later additions to perl's debugging functionality. As such, this interface should be considered highly experimental and subject to change.
AUTHOR
------
Gurusamy Sarathy [email protected]
This code heavily adapted from an early version of perl5db.pl attributable to Larry Wall and the Perl Porters.
perl Test2::Util::Trace Test2::Util::Trace
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Util::Trace - Legacy wrapper fro <Test2::EventFacet::Trace>.
DESCRIPTION
-----------
All the functionality for this class has been moved to <Test2::EventFacet::Trace>.
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 encoding encoding
========
CONTENTS
--------
* [NAME](#NAME)
* [WARNING](#WARNING)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
+ [Setting STDIN and/or STDOUT individually](#Setting-STDIN-and/or-STDOUT-individually)
+ [The :locale sub-pragma](#The-:locale-sub-pragma)
* [CAVEATS](#CAVEATS)
+ [SIDE EFFECTS](#SIDE-EFFECTS)
+ [DO NOT MIX MULTIPLE ENCODINGS](#DO-NOT-MIX-MULTIPLE-ENCODINGS)
+ [Prior to Perl v5.22](#Prior-to-Perl-v5.22)
+ [Prior to Encode version 1.87](#Prior-to-Encode-version-1.87)
+ [Prior to Perl v5.8.1](#Prior-to-Perl-v5.8.1)
* [EXAMPLE - Greekperl](#EXAMPLE-Greekperl)
* [BUGS](#BUGS)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
NAME
----
encoding - allows you to write your script in non-ASCII and non-UTF-8
WARNING
-------
This module has been deprecated since perl v5.18. See ["DESCRIPTION"](#DESCRIPTION) and ["BUGS"](#BUGS).
SYNOPSIS
--------
```
use encoding "greek"; # Perl like Greek to you?
use encoding "euc-jp"; # Jperl!
# or you can even do this if your shell supports your native encoding
perl -Mencoding=latin2 -e'...' # Feeling centrally European?
perl -Mencoding=euc-kr -e'...' # Or Korean?
# more control
# A simple euc-cn => utf-8 converter
use encoding "euc-cn", STDOUT => "utf8"; while(<>){print};
# "no encoding;" supported
no encoding;
# an alternate way, Filter
use encoding "euc-jp", Filter=>1;
# now you can use kanji identifiers -- in euc-jp!
# encode based on the current locale - specialized purposes only;
# fraught with danger!!
use encoding ':locale';
```
DESCRIPTION
-----------
This pragma is used to enable a Perl script to be written in encodings that aren't strictly ASCII nor UTF-8. It translates all or portions of the Perl program script from a given encoding into UTF-8, and changes the PerlIO layers of `STDIN` and `STDOUT` to the encoding specified.
This pragma dates from the days when UTF-8-enabled editors were uncommon. But that was long ago, and the need for it is greatly diminished. That, coupled with the fact that it doesn't work with threads, along with other problems, (see ["BUGS"](#BUGS)) have led to its being deprecated. It is planned to remove this pragma in a future Perl version. New code should be written in UTF-8, and the `use utf8` pragma used instead (see <perluniintro> and <utf8> for details). Old code should be converted to UTF-8, via something like the recipe in the ["SYNOPSIS"](#SYNOPSIS) (though this simple approach may require manual adjustments afterwards).
If UTF-8 is not an option, it is recommended that one use a simple source filter, such as that provided by <Filter::Encoding> on CPAN or this pragma's own `Filter` option (see below).
The only legitimate use of this pragma is almost certainly just one per file, near the top, with file scope, as the file is likely going to only be written in one encoding. Further restrictions apply in Perls before v5.22 (see ["Prior to Perl v5.22"](#Prior-to-Perl-v5.22)).
There are two basic modes of operation (plus turning if off):
`use encoding ['*ENCNAME*'] ;`
Please note: This mode of operation is no longer supported as of Perl v5.26.
This is the normal operation. It translates various literals encountered in the Perl source file from the encoding *ENCNAME* into UTF-8, and similarly converts character code points. This is used when the script is a combination of ASCII (for the variable names and punctuation, *etc*), but the literal data is in the specified encoding.
*ENCNAME* is optional. If omitted, the encoding specified in the environment variable [`PERL_ENCODING`](perlrun#PERL_ENCODING) is used. If this isn't set, or the resolved-to encoding is not known to `[Encode](encode)`, the error `Unknown encoding '*ENCNAME*'` will be thrown.
Starting in Perl v5.8.6 (`Encode` version 2.0.1), *ENCNAME* may be the name `:locale`. This is for very specialized applications, and is documented in ["The `:locale` sub-pragma"](#The-%3Alocale-sub-pragma) below.
The literals that are converted are `q//, qq//, qr//, qw///, qx//`, and starting in v5.8.1, `tr///`. Operations that do conversions include `chr`, `ord`, `utf8::upgrade` (but not `utf8::downgrade`), and `chomp`.
Also starting in v5.8.1, the `DATA` pseudo-filehandle is translated from the encoding into UTF-8.
For example, you can write code in EUC-JP as follows:
```
my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
#<-char-><-char-> # 4 octets
s/\bCamel\b/$Rakuda/;
```
And with `use encoding "euc-jp"` in effect, it is the same thing as that code in UTF-8:
```
my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
s/\bCamel\b/$Rakuda/;
```
See ["EXAMPLE"](#EXAMPLE) below for a more complete example.
Unless `${^UNICODE}` (available starting in v5.8.2) exists and is non-zero, the PerlIO layers of `STDIN` and `STDOUT` are set to "`:encoding(*ENCNAME*)`". Therefore,
```
use encoding "euc-jp";
my $message = "Camel is the symbol of perl.\n";
my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
$message =~ s/\bCamel\b/$Rakuda/;
print $message;
```
will print
```
"\xF1\xD1\xF1\xCC is the symbol of perl.\n"
```
not
```
"\x{99F1}\x{99DD} is the symbol of perl.\n"
```
You can override this by giving extra arguments; see below.
Note that `STDERR` WILL NOT be changed, regardless.
Also note that non-STD file handles remain unaffected. Use `use open` or `binmode` to change the layers of those.
`use encoding *ENCNAME*, Filter=>1;`
This operates as above, but the `Filter` argument with a non-zero value causes the entire script, and not just literals, to be translated from the encoding into UTF-8. This allows identifiers in the source to be in that encoding as well. (Problems may occur if the encoding is not a superset of ASCII; imagine all your semi-colons being translated into something different.) One can use this form to make
```
${"\x{4eba}"}++
```
work. (This is equivalent to `$*human*++`, where *human* is a single Han ideograph).
This effectively means that your source code behaves as if it were written in UTF-8 with `'use utf8`' in effect. So even if your editor only supports Shift\_JIS, for example, you can still try examples in Chapter 15 of `Programming Perl, 3rd Ed.`.
This option is significantly slower than the other one.
`no encoding;`
Unsets the script encoding. The layers of `STDIN`, `STDOUT` are reset to "`:raw`" (the default unprocessed raw stream of bytes).
OPTIONS
-------
###
Setting `STDIN` and/or `STDOUT` individually
The encodings of `STDIN` and `STDOUT` are individually settable by parameters to the pragma:
```
use encoding 'euc-tw', STDIN => 'greek' ...;
```
In this case, you cannot omit the first *ENCNAME*. `STDIN => undef` turns the I/O transcoding completely off for that filehandle.
When `${^UNICODE}` (available starting in v5.8.2) exists and is non-zero, these options will be completely ignored. See ["`${^UNICODE}`" in perlvar](perlvar#%24%7B%5EUNICODE%7D) and ["`-C`" in perlrun](perlrun#-C-%5Bnumber%2Flist%5D) for details.
###
The `:locale` sub-pragma
Starting in v5.8.6, the encoding name may be `:locale`. This means that the encoding is taken from the current locale, and not hard-coded by the pragma. Since a script really can only be encoded in exactly one encoding, this option is dangerous. It makes sense only if the script itself is written in ASCII, and all the possible locales that will be in use when the script is executed are supersets of ASCII. That means that the script itself doesn't get changed, but the I/O handles have the specified encoding added, and the operations like `chr` and `ord` use that encoding.
The logic of finding which locale `:locale` uses is as follows:
1. If the platform supports the `langinfo(CODESET)` interface, the codeset returned is used as the default encoding for the open pragma.
2. If 1. didn't work but we are under the locale pragma, the environment variables `LC_ALL` and `LANG` (in that order) are matched for encodings (the part after "`.`", if any), and if any found, that is used as the default encoding for the open pragma.
3. If 1. and 2. didn't work, the environment variables `LC_ALL` and `LANG` (in that order) are matched for anything looking like UTF-8, and if any found, `:utf8` is used as the default encoding for the open pragma.
If your locale environment variables (`LC_ALL`, `LC_CTYPE`, `LANG`) contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching), the default encoding of your `STDIN`, `STDOUT`, and `STDERR`, and of **any subsequent file open**, is UTF-8.
CAVEATS
-------
###
SIDE EFFECTS
* If the `encoding` pragma is in scope then the lengths returned are calculated from the length of `$/` in Unicode characters, which is not always the same as the length of `$/` in the native encoding.
* Without this pragma, if strings operating under byte semantics and strings with Unicode character data are concatenated, the new string will be created by decoding the byte strings as *ISO 8859-1 (Latin-1)*.
The **encoding** pragma changes this to use the specified encoding instead. For example:
```
use encoding 'utf8';
my $string = chr(20000); # a Unicode string
utf8::encode($string); # now it's a UTF-8 encoded byte string
# concatenate with another Unicode string
print length($string . chr(20000));
```
Will print `2`, because `$string` is upgraded as UTF-8. Without `use encoding 'utf8';`, it will print `4` instead, since `$string` is three octets when interpreted as Latin-1.
###
DO NOT MIX MULTIPLE ENCODINGS
Notice that only literals (string or regular expression) having only legacy code points are affected: if you mix data like this
```
\x{100}\xDF
\xDF\x{100}
```
the data is assumed to be in (Latin 1 and) Unicode, not in your native encoding. In other words, this will match in "greek":
```
"\xDF" =~ /\x{3af}/
```
but this will not
```
"\xDF\x{100}" =~ /\x{3af}\x{100}/
```
since the `\xDF` (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on the left will **not** be upgraded to `\x{3af}` (Unicode GREEK SMALL LETTER IOTA WITH TONOS) because of the `\x{100}` on the left. You should not be mixing your legacy data and Unicode in the same string.
This pragma also affects encoding of the 0x80..0xFF code point range: normally characters in that range are left as eight-bit bytes (unless they are combined with characters with code points 0x100 or larger, in which case all characters need to become UTF-8 encoded), but if the `encoding` pragma is present, even the 0x80..0xFF range always gets UTF-8 encoded.
After all, the best thing about this pragma is that you don't have to resort to \x{....} just to spell your name in a native encoding. So feel free to put your strings in your encoding in quotes and regexes.
###
Prior to Perl v5.22
The pragma was a per script, not a per block lexical. Only the last `use encoding` or `no encoding` mattered, and it affected **the whole script**. However, the `no encoding` pragma was supported and `use encoding` could appear as many times as you want in a given script (though only the last was effective).
Since the scope wasn't lexical, other modules' use of `chr`, `ord`, *etc.* were affected. This leads to spooky, incorrect action at a distance that is hard to debug.
This means you would have to be very careful of the load order:
```
# called module
package Module_IN_BAR;
use encoding "bar";
# stuff in "bar" encoding here
1;
# caller script
use encoding "foo"
use Module_IN_BAR;
# surprise! use encoding "bar" is in effect.
```
The best way to avoid this oddity is to use this pragma RIGHT AFTER other modules are loaded. i.e.
```
use Module_IN_BAR;
use encoding "foo";
```
###
Prior to Encode version 1.87
* `STDIN` and `STDOUT` were not set under the filter option. And `STDIN=>*ENCODING*` and `STDOUT=>*ENCODING*` didn't work like non-filter version.
* `use utf8` wasn't implicitly declared so you have to `use utf8` to do
```
${"\x{4eba}"}++
```
###
Prior to Perl v5.8.1
"NON-EUC" doublebyte encodings Because perl needs to parse the script before applying this pragma, such encodings as Shift\_JIS and Big-5 that may contain `'\'` (BACKSLASH; `\x5c`) in the second byte fail because the second byte may accidentally escape the quoting character that follows.
`tr///`
The **encoding** pragma works by decoding string literals in `q//,qq//,qr//,qw///, qx//` and so forth. In perl v5.8.0, this does not apply to `tr///`. Therefore,
```
use encoding 'euc-jp';
#....
$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
# -------- -------- -------- --------
```
Does not work as
```
$kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;
```
Legend of characters above
```
utf8 euc-jp charnames::viacode()
-----------------------------------------
\x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
\x{3093} \xA4\xF3 HIRAGANA LETTER N
\x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
\x{30f3} \xA5\xF3 KATAKANA LETTER N
```
This counterintuitive behavior has been fixed in perl v5.8.1.
In perl v5.8.0, you can work around this as follows;
```
use encoding 'euc-jp';
# ....
eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };
```
Note the `tr//` expression is surrounded by `qq{}`. The idea behind this is the same as the classic idiom that makes `tr///` 'interpolate':
```
tr/$from/$to/; # wrong!
eval qq{ tr/$from/$to/ }; # workaround.
```
EXAMPLE - Greekperl
--------------------
```
use encoding "iso 8859-7";
# \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.
$a = "\xDF";
$b = "\x{100}";
printf "%#x\n", ord($a); # will print 0x3af, not 0xdf
$c = $a . $b;
# $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".
# chr() is affected, and ...
print "mega\n" if ord(chr(0xdf)) == 0x3af;
# ... ord() is affected by the encoding pragma ...
print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;
# ... as are eq and cmp ...
print "peta\n" if "\x{3af}" eq pack("C", 0xdf);
print "exa\n" if "\x{3af}" cmp pack("C", 0xdf) == 0;
# ... but pack/unpack C are not affected, in case you still
# want to go back to your native encoding
print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;
```
BUGS
----
Thread safety `use encoding ...` is not thread-safe (i.e., do not use in threaded applications).
Can't be used by more than one module in a single program. Only one encoding is allowed. If you combine modules in a program that have different encodings, only one will be actually used.
Other modules using `STDIN` and `STDOUT` get the encoded stream They may be expecting something completely different.
literals in regex that are longer than 127 bytes For native multibyte encodings (either fixed or variable length), the current implementation of the regular expressions may introduce recoding errors for regular expression literals longer than 127 bytes.
EBCDIC The encoding pragma is not supported on EBCDIC platforms.
`format` This pragma doesn't work well with `format` because PerlIO does not get along very well with it. When `format` contains non-ASCII characters it prints funny or gets "wide character warnings". To understand it, try the code below.
```
# Save this one in utf8
# replace *non-ascii* with a non-ascii string
my $camel;
format STDOUT =
*non-ascii*@>>>>>>>
$camel
.
$camel = "*non-ascii*";
binmode(STDOUT=>':encoding(utf8)'); # bang!
write; # funny
print $camel, "\n"; # fine
```
Without binmode this happens to work but without binmode, print() fails instead of write().
At any rate, the very use of `format` is questionable when it comes to unicode characters since you have to consider such things as character width (i.e. double-width for ideographs) and directions (i.e. BIDI for Arabic and Hebrew).
See also ["CAVEATS"](#CAVEATS)
HISTORY
-------
This pragma first appeared in Perl v5.8.0. It has been enhanced in later releases as specified above.
SEE ALSO
---------
<perlunicode>, [Encode](encode), <open>, <Filter::Util::Call>,
Ch. 15 of `Programming Perl (3rd Edition)` by Larry Wall, Tom Christiansen, Jon Orwant; O'Reilly & Associates; ISBN 0-596-00027-8
| programming_docs |
perl Math::Complex Math::Complex
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPERATIONS](#OPERATIONS)
* [CREATION](#CREATION)
* [DISPLAYING](#DISPLAYING)
+ [CHANGED IN PERL 5.6](#CHANGED-IN-PERL-5.6)
* [USAGE](#USAGE)
* [CONSTANTS](#CONSTANTS)
+ [PI](#PI)
+ [Inf](#Inf)
* [ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO](#ERRORS-DUE-TO-DIVISION-BY-ZERO-OR-LOGARITHM-OF-ZERO)
* [ERRORS DUE TO INDIGESTIBLE ARGUMENTS](#ERRORS-DUE-TO-INDIGESTIBLE-ARGUMENTS)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [LICENSE](#LICENSE)
NAME
----
Math::Complex - complex numbers and associated mathematical functions
SYNOPSIS
--------
```
use Math::Complex;
$z = Math::Complex->make(5, 6);
$t = 4 - 3*i + $z;
$j = cplxe(1, 2*pi/3);
```
DESCRIPTION
-----------
This package lets you create and manipulate complex numbers. By default, *Perl* limits itself to real numbers, but an extra `use` statement brings full complex support, along with a full set of mathematical functions typically associated with and/or extended to complex numbers.
If you wonder what complex numbers are, they were invented to be able to solve the following equation:
```
x*x = -1
```
and by definition, the solution is noted *i* (engineers use *j* instead since *i* usually denotes an intensity, but the name does not matter). The number *i* is a pure *imaginary* number.
The arithmetics with pure imaginary numbers works just like you would expect it with real numbers... you just have to remember that
```
i*i = -1
```
so you have:
```
5i + 7i = i * (5 + 7) = 12i
4i - 3i = i * (4 - 3) = i
4i * 2i = -8
6i / 2i = 3
1 / i = -i
```
Complex numbers are numbers that have both a real part and an imaginary part, and are usually noted:
```
a + bi
```
where `a` is the *real* part and `b` is the *imaginary* part. The arithmetic with complex numbers is straightforward. You have to keep track of the real and the imaginary parts, but otherwise the rules used for real numbers just apply:
```
(4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
(2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i
```
A graphical representation of complex numbers is possible in a plane (also called the *complex plane*, but it's really a 2D plane). The number
```
z = a + bi
```
is the point whose coordinates are (a, b). Actually, it would be the vector originating from (0, 0) to (a, b). It follows that the addition of two complex numbers is a vectorial addition.
Since there is a bijection between a point in the 2D plane and a complex number (i.e. the mapping is unique and reciprocal), a complex number can also be uniquely identified with polar coordinates:
```
[rho, theta]
```
where `rho` is the distance to the origin, and `theta` the angle between the vector and the *x* axis. There is a notation for this using the exponential form, which is:
```
rho * exp(i * theta)
```
where *i* is the famous imaginary number introduced above. Conversion between this form and the cartesian form `a + bi` is immediate:
```
a = rho * cos(theta)
b = rho * sin(theta)
```
which is also expressed by this formula:
```
z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)
```
In other words, it's the projection of the vector onto the *x* and *y* axes. Mathematicians call *rho* the *norm* or *modulus* and *theta* the *argument* of the complex number. The *norm* of `z` is marked here as `abs(z)`.
The polar notation (also known as the trigonometric representation) is much more handy for performing multiplications and divisions of complex numbers, whilst the cartesian notation is better suited for additions and subtractions. Real numbers are on the *x* axis, and therefore *y* or *theta* is zero or *pi*.
All the common operations that can be performed on a real number have been defined to work on complex numbers as well, and are merely *extensions* of the operations defined on real numbers. This means they keep their natural meaning when there is no imaginary part, provided the number is within their definition set.
For instance, the `sqrt` routine which computes the square root of its argument is only defined for non-negative real numbers and yields a non-negative real number (it is an application from **R+** to **R+**). If we allow it to return a complex number, then it can be extended to negative real numbers to become an application from **R** to **C** (the set of complex numbers):
```
sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i
```
It can also be extended to be an application from **C** to **C**, whilst its restriction to **R** behaves as defined above by using the following definition:
```
sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)
```
Indeed, a negative real number can be noted `[x,pi]` (the modulus *x* is always non-negative, so `[x,pi]` is really `-x`, a negative number) and the above definition states that
```
sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i
```
which is exactly what we had defined for negative real numbers above. The `sqrt` returns only one of the solutions: if you want the both, use the `root` function.
All the common mathematical functions defined on real numbers that are extended to complex numbers share that same property of working *as usual* when the imaginary part is zero (otherwise, it would not be called an extension, would it?).
A *new* operation possible on a complex number that is the identity for real numbers is called the *conjugate*, and is noted with a horizontal bar above the number, or `~z` here.
```
z = a + bi
~z = a - bi
```
Simple... Now look:
```
z * ~z = (a + bi) * (a - bi) = a*a + b*b
```
We saw that the norm of `z` was noted `abs(z)` and was defined as the distance to the origin, also known as:
```
rho = abs(z) = sqrt(a*a + b*b)
```
so
```
z * ~z = abs(z) ** 2
```
If z is a pure real number (i.e. `b == 0`), then the above yields:
```
a * a = abs(a) ** 2
```
which is true (`abs` has the regular meaning for real number, i.e. stands for the absolute value). This example explains why the norm of `z` is noted `abs(z)`: it extends the `abs` function to complex numbers, yet is the regular `abs` we know when the complex number actually has no imaginary part... This justifies *a posteriori* our use of the `abs` notation for the norm.
OPERATIONS
----------
Given the following notations:
```
z1 = a + bi = r1 * exp(i * t1)
z2 = c + di = r2 * exp(i * t2)
z = <any complex or real number>
```
the following (overloaded) operations are supported on complex numbers:
```
z1 + z2 = (a + c) + i(b + d)
z1 - z2 = (a - c) + i(b - d)
z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
z1 ** z2 = exp(z2 * log z1)
~z = a - bi
abs(z) = r1 = sqrt(a*a + b*b)
sqrt(z) = sqrt(r1) * exp(i * t/2)
exp(z) = exp(a) * exp(i * b)
log(z) = log(r1) + i*t
sin(z) = 1/2i (exp(i * z1) - exp(-i * z))
cos(z) = 1/2 (exp(i * z1) + exp(-i * z))
atan2(y, x) = atan(y / x) # Minding the right quadrant, note the order.
```
The definition used for complex arguments of atan2() is
```
-i log((x + iy)/sqrt(x*x+y*y))
```
Note that atan2(0, 0) is not well-defined.
The following extra operations are supported on both real and complex numbers:
```
Re(z) = a
Im(z) = b
arg(z) = t
abs(z) = r
cbrt(z) = z ** (1/3)
log10(z) = log(z) / log(10)
logn(z, n) = log(z) / log(n)
tan(z) = sin(z) / cos(z)
csc(z) = 1 / sin(z)
sec(z) = 1 / cos(z)
cot(z) = 1 / tan(z)
asin(z) = -i * log(i*z + sqrt(1-z*z))
acos(z) = -i * log(z + i*sqrt(1-z*z))
atan(z) = i/2 * log((i+z) / (i-z))
acsc(z) = asin(1 / z)
asec(z) = acos(1 / z)
acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i))
sinh(z) = 1/2 (exp(z) - exp(-z))
cosh(z) = 1/2 (exp(z) + exp(-z))
tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
csch(z) = 1 / sinh(z)
sech(z) = 1 / cosh(z)
coth(z) = 1 / tanh(z)
asinh(z) = log(z + sqrt(z*z+1))
acosh(z) = log(z + sqrt(z*z-1))
atanh(z) = 1/2 * log((1+z) / (1-z))
acsch(z) = asinh(1 / z)
asech(z) = acosh(1 / z)
acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))
```
*arg*, *abs*, *log*, *csc*, *cot*, *acsc*, *acot*, *csch*, *coth*, *acosech*, *acotanh*, have aliases *rho*, *theta*, *ln*, *cosec*, *cotan*, *acosec*, *acotan*, *cosech*, *cotanh*, *acosech*, *acotanh*, respectively. `Re`, `Im`, `arg`, `abs`, `rho`, and `theta` can be used also as mutators. The `cbrt` returns only one of the solutions: if you want all three, use the `root` function.
The *root* function is available to compute all the *n* roots of some complex, where *n* is a strictly positive integer. There are exactly *n* such roots, returned as a list. Getting the number mathematicians call `j` such that:
```
1 + j + j*j = 0;
```
is a simple matter of writing:
```
$j = ((root(1, 3))[1];
```
The *k*th root for `z = [r,t]` is given by:
```
(root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)
```
You can return the *k*th root directly by `root(z, n, k)`, indexing starting from *zero* and ending at *n - 1*.
The *spaceship* numeric comparison operator, <=>, is also defined. In order to ensure its restriction to real numbers is conform to what you would expect, the comparison is run on the real part of the complex number first, and imaginary parts are compared only when the real parts match.
CREATION
--------
To create a complex number, use either:
```
$z = Math::Complex->make(3, 4);
$z = cplx(3, 4);
```
if you know the cartesian form of the number, or
```
$z = 3 + 4*i;
```
if you like. To create a number using the polar form, use either:
```
$z = Math::Complex->emake(5, pi/3);
$x = cplxe(5, pi/3);
```
instead. The first argument is the modulus, the second is the angle (in radians, the full circle is 2\*pi). (Mnemonic: `e` is used as a notation for complex numbers in the polar form).
It is possible to write:
```
$x = cplxe(-3, pi/4);
```
but that will be silently converted into `[3,-3pi/4]`, since the modulus must be non-negative (it represents the distance to the origin in the complex plane).
It is also possible to have a complex number as either argument of the `make`, `emake`, `cplx`, and `cplxe`: the appropriate component of the argument will be used.
```
$z1 = cplx(-2, 1);
$z2 = cplx($z1, 4);
```
The `new`, `make`, `emake`, `cplx`, and `cplxe` will also understand a single (string) argument of the forms
```
2-3i
-3i
[2,3]
[2,-3pi/4]
[2]
```
in which case the appropriate cartesian and exponential components will be parsed from the string and used to create new complex numbers. The imaginary component and the theta, respectively, will default to zero.
The `new`, `make`, `emake`, `cplx`, and `cplxe` will also understand the case of no arguments: this means plain zero or (0, 0).
DISPLAYING
----------
When printed, a complex number is usually shown under its cartesian style *a+bi*, but there are legitimate cases where the polar style *[r,t]* is more appropriate. The process of converting the complex number into a string that can be displayed is known as *stringification*.
By calling the class method `Math::Complex::display_format` and supplying either `"polar"` or `"cartesian"` as an argument, you override the default display style, which is `"cartesian"`. Not supplying any argument returns the current settings.
This default can be overridden on a per-number basis by calling the `display_format` method instead. As before, not supplying any argument returns the current display style for this number. Otherwise whatever you specify will be the new display style for *this* particular number.
For instance:
```
use Math::Complex;
Math::Complex::display_format('polar');
$j = (root(1, 3))[1];
print "j = $j\n"; # Prints "j = [1,2pi/3]"
$j->display_format('cartesian');
print "j = $j\n"; # Prints "j = -0.5+0.866025403784439i"
```
The polar style attempts to emphasize arguments like *k\*pi/n* (where *n* is a positive integer and *k* an integer within [-9, +9]), this is called *polar pretty-printing*.
For the reverse of stringifying, see the `make` and `emake`.
###
CHANGED IN PERL 5.6
The `display_format` class method and the corresponding `display_format` object method can now be called using a parameter hash instead of just a one parameter.
The old display format style, which can have values `"cartesian"` or `"polar"`, can be changed using the `"style"` parameter.
```
$j->display_format(style => "polar");
```
The one parameter calling convention also still works.
```
$j->display_format("polar");
```
There are two new display parameters.
The first one is `"format"`, which is a sprintf()-style format string to be used for both numeric parts of the complex number(s). The is somewhat system-dependent but most often it corresponds to `"%.15g"`. You can revert to the default by setting the `format` to `undef`.
```
# the $j from the above example
$j->display_format('format' => '%.5f');
print "j = $j\n"; # Prints "j = -0.50000+0.86603i"
$j->display_format('format' => undef);
print "j = $j\n"; # Prints "j = -0.5+0.86603i"
```
Notice that this affects also the return values of the `display_format` methods: in list context the whole parameter hash will be returned, as opposed to only the style parameter value. This is a potential incompatibility with earlier versions if you have been calling the `display_format` method in list context.
The second new display parameter is `"polar_pretty_print"`, which can be set to true or false, the default being true. See the previous section for what this means.
USAGE
-----
Thanks to overloading, the handling of arithmetics with complex numbers is simple and almost transparent.
Here are some examples:
```
use Math::Complex;
$j = cplxe(1, 2*pi/3); # $j ** 3 == 1
print "j = $j, j**3 = ", $j ** 3, "\n";
print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";
$z = -16 + 0*i; # Force it to be a complex
print "sqrt($z) = ", sqrt($z), "\n";
$k = exp(i * 2*pi/3);
print "$j - $k = ", $j - $k, "\n";
$z->Re(3); # Re, Im, arg, abs,
$j->arg(2); # (the last two aka rho, theta)
# can be used also as mutators.
```
CONSTANTS
---------
### PI
The constant `pi` and some handy multiples of it (pi2, pi4, and pip2 (pi/2) and pip4 (pi/4)) are also available if separately exported:
```
use Math::Complex ':pi';
$third_of_circle = pi2 / 3;
```
### Inf
The floating point infinity can be exported as a subroutine Inf():
```
use Math::Complex qw(Inf sinh);
my $AlsoInf = Inf() + 42;
my $AnotherInf = sinh(1e42);
print "$AlsoInf is $AnotherInf\n" if $AlsoInf == $AnotherInf;
```
Note that the stringified form of infinity varies between platforms: it can be for example any of
```
inf
infinity
INF
1.#INF
```
or it can be something else.
Also note that in some platforms trying to use the infinity in arithmetic operations may result in Perl crashing because using an infinity causes SIGFPE or its moral equivalent to be sent. The way to ignore this is
```
local $SIG{FPE} = sub { };
```
ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO
----------------------------------------------------
The division (/) and the following functions
```
log ln log10 logn
tan sec csc cot
atan asec acsc acot
tanh sech csch coth
atanh asech acsch acoth
```
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 logarithmic functions and the `atanh`, `acoth`, the argument cannot be `1` (one). For the `atanh`, `acoth`, the argument cannot be `-1` (minus one). For the `atan`, `acot`, the argument cannot be `i` (the imaginary unit). For the `atan`, `acoth`, the argument cannot be `-i` (the negative imaginary unit). For the `tan`, `sec`, `tanh`, the argument cannot be *pi/2 + k \* pi*, where *k* is any integer. atan2(0, 0) is undefined, and if the complex arguments are used for atan2(), a division by zero will happen if z1\*\*2+z2\*\*2 == 0.
Note that because we are operating on approximations of real numbers, these errors can happen when merely `too close' to the singularities listed above.
ERRORS DUE TO INDIGESTIBLE ARGUMENTS
-------------------------------------
The `make` and `emake` accept both real and complex arguments. When they cannot recognize the arguments they will die with error messages like the following
```
Math::Complex::make: Cannot take real part of ...
Math::Complex::make: Cannot take real part of ...
Math::Complex::emake: Cannot take rho of ...
Math::Complex::emake: Cannot take theta of ...
```
BUGS
----
Saying `use Math::Complex;` exports many mathematical routines in the caller environment and even overrides some (`sqrt`, `log`, `atan2`). This is construed as a feature by the Authors, actually... ;-)
All routines expect to be given real or complex numbers. Don't attempt to use BigFloat, since Perl has currently no rule to disambiguate a '+' operation (for instance) between two overloaded entities.
In Cray UNICOS there is some strange numerical instability that results in root(), cos(), sin(), cosh(), sinh(), losing accuracy fast. Beware. The bug may be in UNICOS math libs, in UNICOS C compiler, in Math::Complex. Whatever it is, it does not manifest itself anywhere else where Perl runs.
SEE ALSO
---------
<Math::Trig>
AUTHORS
-------
Daniel S. Lewart <*lewart!at!uiuc.edu*>, 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 ExtUtils::Typemaps ExtUtils::Typemaps
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [file](#file)
+ [add\_typemap](#add_typemap)
+ [add\_inputmap](#add_inputmap)
+ [add\_outputmap](#add_outputmap)
+ [add\_string](#add_string)
+ [remove\_typemap](#remove_typemap)
+ [remove\_inputmap](#remove_inputmap)
+ [remove\_inputmap](#remove_inputmap1)
+ [get\_typemap](#get_typemap)
+ [get\_inputmap](#get_inputmap)
+ [get\_outputmap](#get_outputmap)
+ [write](#write)
+ [as\_string](#as_string)
+ [as\_embedded\_typemap](#as_embedded_typemap)
+ [merge](#merge)
+ [is\_empty](#is_empty)
+ [list\_mapped\_ctypes](#list_mapped_ctypes)
+ [\_get\_typemap\_hash](#_get_typemap_hash)
+ [\_get\_inputmap\_hash](#_get_inputmap_hash)
+ [\_get\_outputmap\_hash](#_get_outputmap_hash)
+ [\_get\_prototype\_hash](#_get_prototype_hash)
+ [clone](#clone)
+ [tidy\_type](#tidy_type)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
ExtUtils::Typemaps - Read/Write/Modify Perl/XS typemap files
SYNOPSIS
--------
```
# read/create file
my $typemap = ExtUtils::Typemaps->new(file => 'typemap');
# alternatively create an in-memory typemap
# $typemap = ExtUtils::Typemaps->new();
# alternatively create an in-memory typemap by parsing a string
# $typemap = ExtUtils::Typemaps->new(string => $sometypemap);
# add a mapping
$typemap->add_typemap(ctype => 'NV', xstype => 'T_NV');
$typemap->add_inputmap(
xstype => 'T_NV', code => '$var = ($type)SvNV($arg);'
);
$typemap->add_outputmap(
xstype => 'T_NV', code => 'sv_setnv($arg, (NV)$var);'
);
$typemap->add_string(string => $typemapstring);
# will be parsed and merged
# remove a mapping (same for remove_typemap and remove_outputmap...)
$typemap->remove_inputmap(xstype => 'SomeType');
# save a typemap to a file
$typemap->write(file => 'anotherfile.map');
# merge the other typemap into this one
$typemap->merge(typemap => $another_typemap);
```
DESCRIPTION
-----------
This module can read, modify, create and write Perl XS typemap files. If you don't know what a typemap is, please confer the <perlxstut> and <perlxs> manuals.
The module is not entirely round-trip safe: For example it currently simply strips all comments. The order of entries in the maps is, however, preserved.
We check for duplicate entries in the typemap, but do not check for missing `TYPEMAP` entries for `INPUTMAP` or `OUTPUTMAP` entries since these might be hidden in a different typemap.
METHODS
-------
### new
Returns a new typemap object. Takes an optional `file` parameter. If set, the given file will be read. If the file doesn't exist, an empty typemap is returned.
Alternatively, if the `string` parameter is given, the supplied string will be parsed instead of a file.
### file
Get/set the file that the typemap is written to when the `write` method is called.
### add\_typemap
Add a `TYPEMAP` entry to the typemap.
Required named arguments: The `ctype` (e.g. `ctype => 'double'`) and the `xstype` (e.g. `xstype => 'T_NV'`).
Optional named arguments: `replace => 1` forces removal/replacement of existing `TYPEMAP` entries of the same `ctype`. `skip => 1` triggers a *"first come first serve"* logic by which new entries that conflict with existing entries are silently ignored.
As an alternative to the named parameters usage, you may pass in an `ExtUtils::Typemaps::Type` object as first argument, a copy of which will be added to the typemap. In that case, only the `replace` or `skip` named parameters may be used after the object. Example:
```
$map->add_typemap($type_obj, replace => 1);
```
### add\_inputmap
Add an `INPUT` entry to the typemap.
Required named arguments: The `xstype` (e.g. `xstype => 'T_NV'`) and the `code` to associate with it for input.
Optional named arguments: `replace => 1` forces removal/replacement of existing `INPUT` entries of the same `xstype`. `skip => 1` triggers a *"first come first serve"* logic by which new entries that conflict with existing entries are silently ignored.
As an alternative to the named parameters usage, you may pass in an `ExtUtils::Typemaps::InputMap` object as first argument, a copy of which will be added to the typemap. In that case, only the `replace` or `skip` named parameters may be used after the object. Example:
```
$map->add_inputmap($type_obj, replace => 1);
```
### add\_outputmap
Add an `OUTPUT` entry to the typemap. Works exactly the same as `add_inputmap`.
### add\_string
Parses a string as a typemap and merge it into the typemap object.
Required named argument: `string` to specify the string to parse.
### remove\_typemap
Removes a `TYPEMAP` entry from the typemap.
Required named argument: `ctype` to specify the entry to remove from the typemap.
Alternatively, you may pass a single `ExtUtils::Typemaps::Type` object.
### remove\_inputmap
Removes an `INPUT` entry from the typemap.
Required named argument: `xstype` to specify the entry to remove from the typemap.
Alternatively, you may pass a single `ExtUtils::Typemaps::InputMap` object.
### remove\_inputmap
Removes an `OUTPUT` entry from the typemap.
Required named argument: `xstype` to specify the entry to remove from the typemap.
Alternatively, you may pass a single `ExtUtils::Typemaps::OutputMap` object.
### get\_typemap
Fetches an entry of the TYPEMAP section of the typemap.
Mandatory named arguments: The `ctype` of the entry.
Returns the `ExtUtils::Typemaps::Type` object for the entry if found.
### get\_inputmap
Fetches an entry of the INPUT section of the typemap.
Mandatory named arguments: The `xstype` of the entry or the `ctype` of the typemap that can be used to find the `xstype`. To wit, the following pieces of code are equivalent:
```
my $type = $typemap->get_typemap(ctype => $ctype)
my $input_map = $typemap->get_inputmap(xstype => $type->xstype);
my $input_map = $typemap->get_inputmap(ctype => $ctype);
```
Returns the `ExtUtils::Typemaps::InputMap` object for the entry if found.
### get\_outputmap
Fetches an entry of the OUTPUT section of the typemap.
Mandatory named arguments: The `xstype` of the entry or the `ctype` of the typemap that can be used to resolve the `xstype`. (See above for an example.)
Returns the `ExtUtils::Typemaps::InputMap` object for the entry if found.
### write
Write the typemap to a file. Optionally takes a `file` argument. If given, the typemap will be written to the specified file. If not, the typemap is written to the currently stored file name (see ["file"](#file) above, this defaults to the file it was read from if any).
### as\_string
Generates and returns the string form of the typemap.
### as\_embedded\_typemap
Generates and returns the string form of the typemap with the appropriate prefix around it for verbatim inclusion into an XS file as an embedded typemap. This will return a string like
```
TYPEMAP: <<END_OF_TYPEMAP
... typemap here (see as_string) ...
END_OF_TYPEMAP
```
The method takes care not to use a HERE-doc end marker that appears in the typemap string itself.
### merge
Merges a given typemap into the object. Note that a failed merge operation leaves the object in an inconsistent state so clone it if necessary.
Mandatory named arguments: Either `typemap => $another_typemap_obj` or `file => $path_to_typemap_file` but not both.
Optional arguments: `replace => 1` to force replacement of existing typemap entries without warning or `skip => 1` to skip entries that exist already in the typemap.
### is\_empty
Returns a bool indicating whether this typemap is entirely empty.
### list\_mapped\_ctypes
Returns a list of the C types that are mappable by this typemap object.
###
\_get\_typemap\_hash
Returns a hash mapping the C types to the XS types:
```
{
'char **' => 'T_PACKEDARRAY',
'bool_t' => 'T_IV',
'AV *' => 'T_AVREF',
'InputStream' => 'T_IN',
'double' => 'T_DOUBLE',
# ...
}
```
This is documented because it is used by `ExtUtils::ParseXS`, but it's not intended for general consumption. May be removed at any time.
###
\_get\_inputmap\_hash
Returns a hash mapping the XS types (identifiers) to the corresponding INPUT code:
```
{
'T_CALLBACK' => ' $var = make_perl_cb_$type($arg)
',
'T_OUT' => ' $var = IoOFP(sv_2io($arg))
',
'T_REF_IV_PTR' => ' if (sv_isa($arg, \\"${ntype}\\")) {
# ...
}
```
This is documented because it is used by `ExtUtils::ParseXS`, but it's not intended for general consumption. May be removed at any time.
###
\_get\_outputmap\_hash
Returns a hash mapping the XS types (identifiers) to the corresponding OUTPUT code:
```
{
'T_CALLBACK' => ' sv_setpvn($arg, $var.context.value().chp(),
$var.context.value().size());
',
'T_OUT' => ' {
GV *gv = (GV *)sv_newmortal();
gv_init_pvn(gv, gv_stashpvs("$Package",1),
"__ANONIO__",10,0);
if ( do_open(gv, "+>&", 3, FALSE, 0, 0, $var) )
sv_setsv(
$arg,
sv_bless(newRV((SV*)gv), gv_stashpv("$Package",1))
);
else
$arg = &PL_sv_undef;
}
',
# ...
}
```
This is documented because it is used by `ExtUtils::ParseXS`, but it's not intended for general consumption. May be removed at any time.
###
\_get\_prototype\_hash
Returns a hash mapping the C types of the typemap to their corresponding prototypes.
```
{
'char **' => '$',
'bool_t' => '$',
'AV *' => '$',
'InputStream' => '$',
'double' => '$',
# ...
}
```
This is documented because it is used by `ExtUtils::ParseXS`, but it's not intended for general consumption. May be removed at any time.
### clone
Creates and returns a clone of a full typemaps object.
Takes named parameters: If `shallow` is true, the clone will share the actual individual type/input/outputmap objects, but not share their storage. Use with caution. Without `shallow`, the clone will be fully independent.
### tidy\_type
Function to (heuristically) canonicalize a C type. Works to some degree with C++ types.
```
$halfway_canonical_type = tidy_type($ctype);
```
Moved from `ExtUtils::ParseXS`.
CAVEATS
-------
Inherits some evil code from `ExtUtils::ParseXS`.
SEE ALSO
---------
The parser is heavily inspired from the one in <ExtUtils::ParseXS>.
For details on typemaps: <perlxstut>, <perlxs>.
AUTHOR
------
Steffen Mueller `<[email protected]`>
COPYRIGHT & LICENSE
--------------------
Copyright 2009, 2010, 2011, 2012, 2013 Steffen Mueller
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl GDBM_File GDBM\_File
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tie](#Tie)
* [STATIC METHODS](#STATIC-METHODS)
+ [GDBM\_version](#GDBM_version)
* [ERROR HANDLING](#ERROR-HANDLING)
+ [$GDBM\_File::gdbm\_errno](#%24GDBM_File::gdbm_errno)
+ [gdbm\_check\_syserr](#gdbm_check_syserr)
* [DATABASE METHODS](#DATABASE-METHODS)
+ [close](#close)
+ [errno](#errno)
+ [syserrno](#syserrno)
+ [strerror](#strerror)
+ [clear\_error](#clear_error)
+ [needs\_recovery](#needs_recovery)
+ [reorganize](#reorganize)
+ [sync](#sync)
+ [count](#count)
+ [flags](#flags)
+ [dbname](#dbname)
+ [cache\_size](#cache_size)
+ [block\_size](#block_size)
+ [sync\_mode](#sync_mode)
+ [centfree](#centfree)
+ [coalesce](#coalesce)
+ [mmap](#mmap)
+ [mmapsize](#mmapsize)
+ [recover](#recover)
+ [convert](#convert)
+ [dump](#dump)
+ [load](#load)
* [CRASH TOLERANCE](#CRASH-TOLERANCE)
+ [crash\_tolerance\_status](#crash_tolerance_status)
+ [failure\_atomic](#failure_atomic)
+ [latest\_snapshot](#latest_snapshot)
* [AVAILABILITY](#AVAILABILITY)
* [SECURITY AND PORTABILITY](#SECURITY-AND-PORTABILITY)
* [SEE ALSO](#SEE-ALSO)
NAME
----
GDBM\_File - Perl5 access to the gdbm library.
SYNOPSIS
--------
```
use GDBM_File;
[$db =] tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640
or die "$GDBM_File::gdbm_errno";
# Use the %hash...
$e = $db->errno;
$e = $db->syserrno;
$str = $db->strerror;
$bool = $db->needs_recovery;
$db->clear_error;
$db->reorganize;
$db->sync;
$n = $db->count;
$n = $db->flags;
$str = $db->dbname;
$db->cache_size;
$db->cache_size($newsize);
$n = $db->block_size;
$bool = $db->sync_mode;
$db->sync_mode($bool);
$bool = $db->centfree;
$db->centfree($bool);
$bool = $db->coalesce;
$db->coalesce($bool);
$bool = $db->mmap;
$size = $db->mmapsize;
$db->mmapsize($newsize);
$db->recover(%args);
untie %hash ;
```
DESCRIPTION
-----------
**GDBM\_File** is a module which allows Perl programs to make use of the facilities provided by the GNU gdbm library. If you intend to use this module you should really have a copy of the **GDBM manual** at hand. The manual is avaialble online at <https://www.gnu.org.ua/software/gdbm/manual>.
Most of the **gdbm** functions are available through the **GDBM\_File** interface.
Unlike Perl's built-in hashes, it is not safe to `delete` the current item from a GDBM\_File tied hash while iterating over it with `each`. This is a limitation of the gdbm library.
### Tie
Use the Perl built-in **tie** to associate a **GDBM** database with a Perl hash:
```
tie %hash, 'GDBM_File', $filename, $flags, $mode;
```
Here, *$filename* is the name of the database file to open or create. *$flags* is a bitwise OR of *access mode* and optional *modifiers*. Access mode is one of:
**GDBM\_READER** Open existing database file in read-only mode.
**GDBM\_WRITER** Open existing database file in read-write mode.
**GDBM\_WRCREAT** If the database file exists, open it in read-write mode. If it doesn't, create it first and open read-write.
**GDBM\_NEWDB** Create new database and open it read-write. If the database already exists, truncate it first.
A number of modifiers can be OR'd to the access mode. Most of them are rarely needed (see <https://www.gnu.org.ua/software/gdbm/manual/Open.html> for a complete list), but one is worth mentioning. The **GDBM\_NUMSYNC** modifier, when used with **GDBM\_NEWDB**, instructs **GDBM** to create the database in *extended* (so called *numsync*) format. This format is best suited for crash-tolerant implementations. See **CRASH TOLERANCE** below for more information.
The *$mode* parameter is the file mode for creating new database file. Use an octal constant or a combination of `S_I*` constants from the **Fcntl** module. This parameter is used if *$flags* is **GDBM\_NEWDB** or **GDBM\_WRCREAT**.
On success, **tie** returns an object of class **GDBM\_File**. On failure, it returns **undef**. It is recommended to always check the return value, to make sure your hash is successfully associated with the database file. See **ERROR HANDLING** below for examples.
STATIC METHODS
---------------
### GDBM\_version
```
$str = GDBM_File->GDBM_version;
@ar = GDBM_File->GDBM_version;
```
Returns the version number of the underlying **libgdbm** library. In scalar context, returns the library version formatted as string:
```
MINOR.MAJOR[.PATCH][ (GUESS)]
```
where *MINOR*, *MAJOR*, and *PATCH* are version numbers, and *GUESS* is a guess level (see below).
In list context, returns a list:
```
( MINOR, MAJOR, PATCH [, GUESS] )
```
The *GUESS* component is present only if **libgdbm** version is 1.8.3 or earlier. This is because earlier releases of **libgdbm** did not include information about their version and the **GDBM\_File** module has to implement certain guesswork in order to determine it. *GUESS* is a textual description in string context, and a positive number indicating how rough the guess is in list context. Possible values are:
1 - exact guess The major and minor version numbers are guaranteed to be correct. The actual patchlevel is most probably guessed right, but can be 1-2 less than indicated.
2 - approximate The major and minor number are guaranteed to be correct. The patchlevel is set to the upper bound.
3 - rough guess The version is guaranteed to be not newer than ***MAJOR*.*MINOR***.
ERROR HANDLING
---------------
###
$GDBM\_File::gdbm\_errno
When referenced in numeric context, retrieves the current value of the **gdbm\_errno** variable, i.e. a numeric code describing the state of the most recent operation on any **gdbm** database. Each numeric code has a symbolic name associated with it. For a comprehensive list of these, see <https://www.gnu.org.ua/software/gdbm/manual/Error-codes.html>. Notice, that this list includes all error codes defined for the most recent version of **gdbm**. Depending on the actual version of the library **GDBM\_File** is built with, some of these may be missing.
In string context, **$gdbm\_errno** returns a human-readable description of the error. If necessary, this description includes the value of **$!**. This makes it possible to use it in diagnostic messages. For example, the usual tying sequence is
```
tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640
or die "$GDBM_File::gdbm_errno";
```
The following, more complex, example illustrates how you can fall back to read-only mode if the database file permissions forbid read-write access:
```
use Errno qw(EACCES);
unless (tie(%hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640)) {
if ($GDBM_File::gdbm_errno == GDBM_FILE_OPEN_ERROR
&& $!{EACCES}) {
if (tie(%hash, 'GDBM_File', $filename, GDBM_READER, 0640)) {
die "$GDBM_File::gdbm_errno";
}
} else {
die "$GDBM_File::gdbm_errno";
}
}
```
### gdbm\_check\_syserr
```
if (gdbm_check_syserr(gdbm_errno)) ...
```
Returns true if the system error number (**$!**) gives more information on the cause of the error.
DATABASE METHODS
-----------------
### close
```
$db->close;
```
Closes the database. Normally you would just do **untie**. However, you will need to use this function if you have explicitly assigned the result of **tie** to a variable, and wish to release the database to another users. Consider the following code:
```
$db = tie %hash, 'GDBM_File', $filename, GDBM_WRCREAT, 0640;
# Do something with %hash or $db...
untie %hash;
$db->close;
```
In this example, doing **untie** alone is not enough, since the database would remain referenced by **$db**, and, as a consequence, the database file would remain locked. Calling **$db->close** ensures the database file is closed and unlocked.
### errno
```
$db->errno
```
Returns the last error status associated with this database. In string context, returns a human-readable description of the error. See also **$GDBM\_File::gdbm\_errno** variable above.
### syserrno
```
$db->syserrno
```
Returns the last system error status (C `errno` variable), associated with this database,
### strerror
```
$db->strerror
```
Returns textual description of the last error that occurred in this database.
### clear\_error
```
$db->clear_error
```
Clear error status.
### needs\_recovery
```
$db->needs_recovery
```
Returns true if the database needs recovery.
### reorganize
```
$db->reorganize;
```
Reorganizes the database.
### sync
```
$db->sync;
```
Synchronizes recent changes to the database with its disk copy.
### count
```
$n = $db->count;
```
Returns number of keys in the database.
### flags
```
$db->flags;
```
Returns flags passed as 4th argument to **tie**.
### dbname
```
$db->dbname;
```
Returns the database name (i.e. 3rd argument to **tie**.
### cache\_size
```
$db->cache_size;
$db->cache_size($newsize);
```
Returns the size of the internal **GDBM** cache for that database.
Called with argument, sets the size to *$newsize*.
### block\_size
```
$db->block_size;
```
Returns the block size of the database.
### sync\_mode
```
$db->sync_mode;
$db->sync_mode($bool);
```
Returns the status of the automatic synchronization mode. Called with argument, enables or disables the sync mode, depending on whether $bool is **true** or **false**.
When synchronization mode is on (**true**), any changes to the database are immediately written to the disk. This ensures database consistency in case of any unforeseen errors (e.g. power failures), at the expense of considerable slowdown of operation.
Synchronization mode is off by default.
### centfree
```
$db->centfree;
$db->centfree($bool);
```
Returns status of the central free block pool (**0** - disabled, **1** - enabled).
With argument, changes its status.
By default, central free block pool is disabled.
### coalesce
```
$db->coalesce;
$db->coalesce($bool);
```
### mmap
```
$db->mmap;
```
Returns true if memory mapping is enabled.
This method will **croak** if the **libgdbm** library is complied without memory mapping support.
### mmapsize
```
$db->mmapsize;
$db->mmapsize($newsize);
```
If memory mapping is enabled, returns the size of memory mapping. With argument, sets the size to **$newsize**.
This method will **croak** if the **libgdbm** library is complied without memory mapping support.
### recover
```
$db->recover(%args);
```
Recovers data from a failed database. **%args** is optional and can contain following keys:
err => sub { ... } Reference to code for detailed error reporting. Upon encountering an error, **recover** will call this sub with a single argument - a description of the error.
backup => \$str Creates a backup copy of the database before recovery and returns its filename in **$str**.
max\_failed\_keys => $n Maximum allowed number of failed keys. If the actual number becomes equal to *$n*, **recover** aborts and returns error.
max\_failed\_buckets => $n Maximum allowed number of failed buckets. If the actual number becomes equal to *$n*, **recover** aborts and returns error.
max\_failures => $n Maximum allowed number of failures during recovery.
stat => \%hash Return recovery statistics in *%hash*. Upon return, the following keys will be present:
recovered\_keys Number of successfully recovered keys.
recovered\_buckets Number of successfully recovered buckets.
failed\_keys Number of keys that failed to be retrieved.
failed\_buckets Number of buckets that failed to be retrieved.
### convert
```
$db->convert($format);
```
Changes the format of the database file referred to by **$db**.
Starting from version 1.20, **gdbm** supports two database file formats: *standard* and *extended*. The former is the traditional database format, used by previous **gdbm** versions. The *extended* format contains additional data and is recommended for use in crash tolerant applications.
<https://www.gnu.org.ua/software/gdbm/manual/Numsync.html>, for the discussion of both formats.
The **$format** argument sets the new desired database format. It is **GDBM\_NUMSYNC** to convert the database from standard to extended format, and **0** to convert it from extended to standard format.
If the database is already in the requested format, the function returns success without doing anything.
### dump
```
$db->dump($filename, %options)
```
Creates a dump of the database file in *$filename*. Such file can be used as a backup copy or sent over a wire to recreate the database on another machine. To create a database from the dump file, use the **load** method.
**GDBM** supports two dump formats: old *binary* and new *ascii*. The binary format is not portable across architectures and is deprecated. It is supported for backward compatibility. The ascii format is portable and stores additional meta-data about the file. It was introduced with the **gdbm** version 1.11 and is the preferred dump format. The **dump** method creates ascii dumps by default.
If the named file already exists, the function will refuse to overwrite and will croak an error. If it doesn't exist, it will be created with the mode **0666** modified by the current **umask**.
These defaults can be altered using the following *%options*:
**binary** => 1 Create dump in *binary* format.
**mode** => *MODE*
Set file mode to *MODE*.
**overwrite** => 1 Silently overwrite existing files.
### load
```
$db->load($filename, %options)
```
Load the data from the dump file *$filename* into the database *$db*. The file must have been previously created using the **dump** method. File format is recognized automatically. By default, the function will croak if the dump contains a key that already exists in the database. It will silently ignore the failure to restore database mode and/or ownership. These defaults can be altered using the following *%options*:
**replace** => 1 Replace existing keys.
**restore\_mode** => 0 | 1 If *0*, don't try to restore the mode of the database file to that stored in the dump.
**restore\_owner** => 0 | 1 If *0*, don't try to restore the owner of the database file to that stored in the dump.
**strict\_errors** => 1 Croak if failed to restore ownership and/or mode.
The usual sequence to recreate a database from the dump file is:
```
my %hash;
my $db = tie %hash, 'GDBM_File', 'a.db', GDBM_NEWDB, 0640;
$db->load('a.dump');
```
CRASH TOLERANCE
----------------
Crash tolerance is a new feature that, given appropriate support from the OS and the filesystem, guarantees that a logically consistent recent state of the database can be recovered following a crash, such as power outage, OS kernel panic, or the like.
Crash tolerance support appeared in **gdbm** version 1.21. The theory behind it is explained in "Crashproofing the Original NoSQL Key-Value Store", by Terence Kelly (<https://queue.acm.org/detail.cfm?id=3487353>). A detailed discussion of the **gdbm** implementation is available in the **GDBM Manual** (<https://www.gnu.org.ua/software/gdbm/manual/Crash-Tolerance.html>). The information below describes the Perl interface.
For maximum robustness, we recommend to use *extended database format* for crash tolerant databases. To create a database in extended format, use the **GDBM\_NEWDB|GDBM\_NUMSYNC** when opening the database, e.g.:
```
$db = tie %hash, 'GDBM_File', $filename,
GDBM_NEWDB|GDBM_NUMSYNC, 0640;
```
To convert existing database to the extended format, use the **convert** method, described above, e.g.:
```
$db->convert(GDBM_NUMSYNC);
```
### crash\_tolerance\_status
```
GDBM_File->crash_tolerance_status;
```
This static method returns the status of crash tolerance support. A non-zero value means crash tolerance is compiled in and supported by the operating system.
### failure\_atomic
```
$db->failure_atomic($even, $odd)
```
Enables crash tolerance for the database **$db**, Arguments are the pathnames of two files that will be created and filled with *snapshots* of the database file. The two files must not exist when this method is called and must reside on the same filesystem as the database file. This filesystem must be support the *reflink* operation (https://www.gnu.org.ua/software/gdbm/manual/Filesystems-supporting-crash-tolerance.html>.
After a successful call to **failure\_atomic**, every call to **$db-**sync> method will make an efficient reflink snapshot of the database file in one of these files; consecutive calls to **sync** alternate between the two, hence the names.
The most recent of these files can be used to recover the database after a crash. To select the right snapshot, use the **latest\_snapshot** static method.
### latest\_snapshot
```
$file = GDBM_File->latest_snapshot($even, $odd);
($file, $error) = GDBM_File->latest_snapshot($even, $odd);
```
Given the two snapshot names (the ones used previously in a call to **failure\_atomic**), this method selects the one suitable for database recovery, i.e. the file which contains the most recent database snapshot.
In scalar context, it returns the selected file name or **undef** in case of failure.
In array context, the returns a list of two elements: the file name and status code. On success, the file name is defined and the code is **GDBM\_SNAPSHOT\_OK**. On error, the file name is **undef**, and the status is one of the following:
GDBM\_SNAPSHOT\_BAD Neither snapshot file is applicable. This means that the crash has occurred before a call to **failure\_atomic** completed. In this case, it is best to fall back on a safe backup copy of the data file.
GDBM\_SNAPSHOT\_ERR A system error occurred. Examine **$!** for details. See <https://www.gnu.org.ua/software/gdbm/manual/Crash-recovery.html> for a comprehensive list of error codes and their meaning.
GDBM\_SNAPSHOT\_SAME The file modes and modification dates of both snapshot files are exactly the same. This can happen only for databases in standard format.
GDBM\_SNAPSHOT\_SUSPICIOUS The *numsync* counters of the two snapshots differ by more than one. The most probable reason is programmer's error: the two parameters refer to snapshots belonging to different database files.
AVAILABILITY
------------
gdbm is available from any GNU archive. The master site is `ftp.gnu.org`, but you are strongly urged to use one of the many mirrors. You can obtain a list of mirror sites from <http://www.gnu.org/order/ftp.html>.
SECURITY AND PORTABILITY
-------------------------
GDBM files are not portable across platforms. If you wish to transfer a GDBM file over the wire, dump it to a portable format first.
**Do not accept GDBM files from untrusted sources.**
Robustness of GDBM against corrupted databases depends highly on its version. Versions prior to 1.15 did not implement any validity checking, so that a corrupted or maliciously crafted database file could cause perl to crash or even expose a security vulnerability. Versions between 1.15 and 1.20 were progressively strengthened against invalid inputs. Finally, version 1.21 had undergone extensive fuzzy checking which proved its ability to withstand any kinds of inputs without crashing.
SEE ALSO
---------
[perl(1)](http://man.he.net/man1/perl), [DB\_File(3)](http://man.he.net/man3/DB_File), <perldbmfilter>, [gdbm(3)](http://man.he.net/man3/gdbm), <https://www.gnu.org.ua/software/gdbm/manual.html>.
perl AutoSplit AutoSplit
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Multiple packages](#Multiple-packages)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
AutoSplit - split a package for autoloading
SYNOPSIS
--------
```
autosplit($file, $dir, $keep, $check, $modtime);
autosplit_lib_modules(@modules);
```
DESCRIPTION
-----------
This function will split up your program into files that the AutoLoader module can handle. It is used by both the standard perl libraries and by the MakeMaker utility, to automatically configure libraries for autoloading.
The `autosplit` interface splits the specified file into a hierarchy rooted at the directory `$dir`. It creates directories as needed to reflect class hierarchy, and creates the file *autosplit.ix*. This file acts as both forward declaration of all package routines, and as timestamp for the last update of the hierarchy.
The remaining three arguments to `autosplit` govern other options to the autosplitter.
$keep If the third argument, *$keep*, is false, then any pre-existing `*.al` files in the autoload directory are removed if they are no longer part of the module (obsoleted functions). $keep defaults to 0.
$check The fourth argument, *$check*, instructs `autosplit` to check the module currently being split to ensure that it includes a `use` specification for the AutoLoader module, and skips the module if AutoLoader is not detected. $check defaults to 1.
$modtime Lastly, the *$modtime* argument specifies that `autosplit` is to check the modification time of the module against that of the `autosplit.ix` file, and only split the module if it is newer. $modtime defaults to 1.
Typical use of AutoSplit in the perl MakeMaker utility is via the command-line with:
```
perl -e 'use AutoSplit; autosplit($ARGV[0], $ARGV[1], 0, 1, 1)'
```
Defined as a Make macro, it is invoked with file and directory arguments; `autosplit` will split the specified file into the specified directory and delete obsolete `.al` files, after checking first that the module does use the AutoLoader, and ensuring that the module is not already currently split in its current form (the modtime test).
The `autosplit_lib_modules` form is used in the building of perl. It takes as input a list of files (modules) that are assumed to reside in a directory **lib** relative to the current directory. Each file is sent to the autosplitter one at a time, to be split into the directory **lib/auto**.
In both usages of the autosplitter, only subroutines defined following the perl *\_\_END\_\_* token are split out into separate files. Some routines may be placed prior to this marker to force their immediate loading and parsing.
###
Multiple packages
As of version 1.01 of the AutoSplit module it is possible to have multiple packages within a single file. Both of the following cases are supported:
```
package NAME;
__END__
sub AAA { ... }
package NAME::option1;
sub BBB { ... }
package NAME::option2;
sub BBB { ... }
package NAME;
__END__
sub AAA { ... }
sub NAME::option1::BBB { ... }
sub NAME::option2::BBB { ... }
```
DIAGNOSTICS
-----------
`AutoSplit` will inform the user if it is necessary to create the top-level directory specified in the invocation. It is preferred that the script or installation process that invokes `AutoSplit` have created the full directory path ahead of time. This warning may indicate that the module is being split into an incorrect path.
`AutoSplit` will warn the user of all subroutines whose name causes potential file naming conflicts on machines with drastically limited (8 characters or less) file name length. Since the subroutine name is used as the file name, these warnings can aid in portability to such systems.
Warnings are issued and the file skipped if `AutoSplit` cannot locate either the *\_\_END\_\_* marker or a "package Name;"-style specification.
`AutoSplit` will also emit general diagnostics for inability to create directories or files.
AUTHOR
------
`AutoSplit` 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
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., 59 Temple Place, Suite 330, Boston, MA
02111-1307, 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 Test2::IPC::Driver::Files Test2::IPC::Driver::Files
=========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ENVIRONMENT VARIABLES](#ENVIRONMENT-VARIABLES)
* [SEE ALSO](#SEE-ALSO)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::IPC::Driver::Files - Temp dir + Files concurrency model.
DESCRIPTION
-----------
This is the default, and fallback concurrency model for [Test2](test2). This sends events between processes and threads using serialized files in a temporary directory. This is not particularly fast, but it works everywhere.
SYNOPSIS
--------
```
use Test2::IPC::Driver::Files;
# IPC is now enabled
```
ENVIRONMENT VARIABLES
----------------------
T2\_KEEP\_TEMPDIR=0 When true, the tempdir used by the IPC driver will not be deleted when the test is done.
T2\_TEMPDIR\_TEMPLATE='test2-XXXXXX' This can be used to set the template for the IPC temp dir. The template should follow template specifications from <File::Temp>.
SEE ALSO
---------
See <Test2::IPC::Driver> for methods.
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 perltie perltie
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tying Scalars](#Tying-Scalars)
+ [Tying Arrays](#Tying-Arrays)
+ [Tying Hashes](#Tying-Hashes)
+ [Tying FileHandles](#Tying-FileHandles)
+ [UNTIE this](#UNTIE-this4)
+ [The untie Gotcha](#The-untie-Gotcha)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
perltie - how to hide an object class in a simple variable
SYNOPSIS
--------
```
tie VARIABLE, CLASSNAME, LIST
$object = tied VARIABLE
untie VARIABLE
```
DESCRIPTION
-----------
Prior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database in the standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl was either built with one particular dbm library or another, but not both, and you couldn't extend this mechanism to other packages or types of variables.
Now you can.
The tie() function binds a variable to a class (package) that will provide the implementation for access methods for that variable. Once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. The complexity of the class is hidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that Perl uses to indicate that they're called implicitly rather than explicitly--just like the BEGIN() and END() functions.
In the tie() call, `VARIABLE` is the name of the variable to be enchanted. `CLASSNAME` is the name of a class implementing objects of the correct type. Any additional arguments in the `LIST` are passed to the appropriate constructor method for that class--meaning TIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might be passed to the dbminit() function of C.) The object returned by the "new" method is also returned by the tie() function, which would be useful if you wanted to access other methods in `CLASSNAME`. (You don't actually have to return a reference to a right "type" (e.g., HASH or `CLASSNAME`) so long as it's a properly blessed object.) You can also retrieve a reference to the underlying object using the tied() function.
Unlike dbmopen(), the tie() function will not `use` or `require` a module for you--you need to do that explicitly yourself.
###
Tying Scalars
A class implementing a tied scalar should define the following methods: TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
Let's look at each in turn, using as an example a tie class for scalars that allows the user to do something like:
```
tie $his_speed, 'Nice', getppid();
tie $my_speed, 'Nice', $$;
```
And now whenever either of those variables is accessed, its current system priority is retrieved and returned. If those variables are set, then the process's priority is changed!
We'll use Jarkko Hietaniemi <*[email protected]*>'s BSD::Resource class (not included) to access the PRIO\_PROCESS, PRIO\_MIN, and PRIO\_MAX constants from your system, as well as the getpriority() and setpriority() system calls. Here's the preamble of the class.
```
package Nice;
use Carp;
use BSD::Resource;
use strict;
$Nice::DEBUG = 0 unless defined $Nice::DEBUG;
```
TIESCALAR classname, LIST This is the constructor for the class. That means it is expected to return a blessed reference to a new scalar (probably anonymous) that it's creating. For example:
```
sub TIESCALAR {
my $class = shift;
my $pid = shift || $$; # 0 means me
if ($pid !~ /^\d+$/) {
carp "Nice::Tie::Scalar got non-numeric pid $pid" if $^W;
return undef;
}
unless (kill 0, $pid) { # EPERM or ERSCH, no doubt
carp "Nice::Tie::Scalar got bad pid $pid: $!" if $^W;
return undef;
}
return bless \$pid, $class;
}
```
This tie class has chosen to return an error rather than raising an exception if its constructor should fail. While this is how dbmopen() works, other classes may well not wish to be so forgiving. It checks the global variable `$^W` to see whether to emit a bit of noise anyway.
FETCH this This method will be triggered every time the tied variable is accessed (read). It takes no arguments beyond its self reference, which is the object representing the scalar we're dealing with. Because in this case we're using just a SCALAR ref for the tied scalar object, a simple $$self allows the method to get at the real value stored there. In our example below, that real value is the process ID to which we've tied our variable.
```
sub FETCH {
my $self = shift;
confess "wrong type" unless ref $self;
croak "usage error" if @_;
my $nicety;
local($!) = 0;
$nicety = getpriority(PRIO_PROCESS, $$self);
if ($!) { croak "getpriority failed: $!" }
return $nicety;
}
```
This time we've decided to blow up (raise an exception) if the renice fails--there's no place for us to return an error otherwise, and it's probably the right thing to do.
STORE this, value This method will be triggered every time the tied variable is set (assigned). Beyond its self reference, it also expects one (and only one) argument: the new value the user is trying to assign. Don't worry about returning a value from STORE; the semantic of assignment returning the assigned value is implemented with FETCH.
```
sub STORE {
my $self = shift;
confess "wrong type" unless ref $self;
my $new_nicety = shift;
croak "usage error" if @_;
if ($new_nicety < PRIO_MIN) {
carp sprintf
"WARNING: priority %d less than minimum system priority %d",
$new_nicety, PRIO_MIN if $^W;
$new_nicety = PRIO_MIN;
}
if ($new_nicety > PRIO_MAX) {
carp sprintf
"WARNING: priority %d greater than maximum system priority %d",
$new_nicety, PRIO_MAX if $^W;
$new_nicety = PRIO_MAX;
}
unless (defined setpriority(PRIO_PROCESS,
$$self,
$new_nicety))
{
confess "setpriority failed: $!";
}
}
```
UNTIE this This method will be triggered when the `untie` occurs. This can be useful if the class needs to know when no further calls will be made. (Except DESTROY of course.) See ["The `untie` Gotcha"](#The-untie-Gotcha) below for more details.
DESTROY this This method will be triggered when the tied variable needs to be destructed. As with other object classes, such a method is seldom necessary, because Perl deallocates its moribund object's memory for you automatically--this isn't C++, you know. We'll use a DESTROY method here for debugging purposes only.
```
sub DESTROY {
my $self = shift;
confess "wrong type" unless ref $self;
carp "[ Nice::DESTROY pid $$self ]" if $Nice::DEBUG;
}
```
That's about all there is to it. Actually, it's more than all there is to it, because we've done a few nice things here for the sake of completeness, robustness, and general aesthetics. Simpler TIESCALAR classes are certainly possible.
###
Tying Arrays
A class implementing a tied ordinary array should define the following methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE, CLEAR and perhaps UNTIE and/or DESTROY.
FETCHSIZE and STORESIZE are used to provide `$#array` and equivalent `scalar(@array)` access.
The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are required if the perl operator with the corresponding (but lowercase) name is to operate on the tied array. The **Tie::Array** class can be used as a base class to implement the first five of these in terms of the basic methods above. The default implementations of DELETE and EXISTS in **Tie::Array** simply `croak`.
In addition EXTEND will be called when perl would have pre-extended allocation in a real array.
For this discussion, we'll implement an array whose elements are a fixed size at creation. If you try to create an element larger than the fixed size, you'll take an exception. For example:
```
use FixedElem_Array;
tie @array, 'FixedElem_Array', 3;
$array[0] = 'cat'; # ok.
$array[1] = 'dogs'; # exception, length('dogs') > 3.
```
The preamble code for the class is as follows:
```
package FixedElem_Array;
use Carp;
use strict;
```
TIEARRAY classname, LIST This is the constructor for the class. That means it is expected to return a blessed reference through which the new array (probably an anonymous ARRAY ref) will be accessed.
In our example, just to show you that you don't *really* have to return an ARRAY reference, we'll choose a HASH reference to represent our object. A HASH works out well as a generic record type: the `{ELEMSIZE}` field will store the maximum element size allowed, and the `{ARRAY}` field will hold the true ARRAY ref. If someone outside the class tries to dereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up. This just goes to show you that you should respect an object's privacy.
```
sub TIEARRAY {
my $class = shift;
my $elemsize = shift;
if ( @_ || $elemsize =~ /\D/ ) {
croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
}
return bless {
ELEMSIZE => $elemsize,
ARRAY => [],
}, $class;
}
```
FETCH this, index This method will be triggered every time an individual element the tied array is accessed (read). It takes one argument beyond its self reference: the index whose value we're trying to fetch.
```
sub FETCH {
my $self = shift;
my $index = shift;
return $self->{ARRAY}->[$index];
}
```
If a negative array index is used to read from an array, the index will be translated to a positive one internally by calling FETCHSIZE before being passed to FETCH. You may disable this feature by assigning a true value to the variable `$NEGATIVE_INDICES` in the tied array class.
As you may have noticed, the name of the FETCH method (et al.) is the same for all accesses, even though the constructors differ in names (TIESCALAR vs TIEARRAY). While in theory you could have the same class servicing several tied types, in practice this becomes cumbersome, and it's easiest to keep them at simply one tie type per class.
STORE this, index, value This method will be triggered every time an element in the tied array is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something and the value we're trying to put there.
In our example, `undef` is really `$self->{ELEMSIZE}` number of spaces so we have a little more work to do here:
```
sub STORE {
my $self = shift;
my( $index, $value ) = @_;
if ( length $value > $self->{ELEMSIZE} ) {
croak "length of $value is greater than $self->{ELEMSIZE}";
}
# fill in the blanks
$self->STORESIZE( $index ) if $index > $self->FETCHSIZE();
# right justify to keep element size for smaller elements
$self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
}
```
Negative indexes are treated the same as with FETCH.
FETCHSIZE this Returns the total number of items in the tied array associated with object *this*. (Equivalent to `scalar(@array)`). For example:
```
sub FETCHSIZE {
my $self = shift;
return scalar $self->{ARRAY}->@*;
}
```
STORESIZE this, count Sets the total number of items in the tied array associated with object *this* to be *count*. If this makes the array larger then class's mapping of `undef` should be returned for new positions. If the array becomes smaller then entries beyond count should be deleted.
In our example, 'undef' is really an element containing `$self->{ELEMSIZE}` number of spaces. Observe:
```
sub STORESIZE {
my $self = shift;
my $count = shift;
if ( $count > $self->FETCHSIZE() ) {
foreach ( $count - $self->FETCHSIZE() .. $count ) {
$self->STORE( $_, '' );
}
} elsif ( $count < $self->FETCHSIZE() ) {
foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
$self->POP();
}
}
}
```
EXTEND this, count Informative call that array is likely to grow to have *count* entries. Can be used to optimize allocation. This method need do nothing.
In our example there is no reason to implement this method, so we leave it as a no-op. This method is only relevant to tied array implementations where there is the possibility of having the allocated size of the array be larger than is visible to a perl programmer inspecting the size of the array. Many tied array implementations will have no reason to implement it.
```
sub EXTEND {
my $self = shift;
my $count = shift;
# nothing to see here, move along.
}
```
**NOTE:** It is generally an error to make this equivalent to STORESIZE. Perl may from time to time call EXTEND without wanting to actually change the array size directly. Any tied array should function correctly if this method is a no-op, even if perhaps they might not be as efficient as they would if this method was implemented.
EXISTS this, key Verify that the element at index *key* exists in the tied array *this*.
In our example, we will determine that if an element consists of `$self->{ELEMSIZE}` spaces only, it does not exist:
```
sub EXISTS {
my $self = shift;
my $index = shift;
return 0 if ! defined $self->{ARRAY}->[$index] ||
$self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
return 1;
}
```
DELETE this, key Delete the element at index *key* from the tied array *this*.
In our example, a deleted item is `$self->{ELEMSIZE}` spaces:
```
sub DELETE {
my $self = shift;
my $index = shift;
return $self->STORE( $index, '' );
}
```
CLEAR this Clear (remove, delete, ...) all values from the tied array associated with object *this*. For example:
```
sub CLEAR {
my $self = shift;
return $self->{ARRAY} = [];
}
```
PUSH this, LIST Append elements of *LIST* to the array. For example:
```
sub PUSH {
my $self = shift;
my @list = @_;
my $last = $self->FETCHSIZE();
$self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
return $self->FETCHSIZE();
}
```
POP this Remove last element of the array and return it. For example:
```
sub POP {
my $self = shift;
return pop $self->{ARRAY}->@*;
}
```
SHIFT this Remove the first element of the array (shifting other elements down) and return it. For example:
```
sub SHIFT {
my $self = shift;
return shift $self->{ARRAY}->@*;
}
```
UNSHIFT this, LIST Insert LIST elements at the beginning of the array, moving existing elements up to make room. For example:
```
sub UNSHIFT {
my $self = shift;
my @list = @_;
my $size = scalar( @list );
# make room for our list
$self->{ARRAY}[ $size .. $self->{ARRAY}->$#* + $size ]->@*
= $self->{ARRAY}->@*
$self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
}
```
SPLICE this, offset, length, LIST Perform the equivalent of `splice` on the array.
*offset* is optional and defaults to zero, negative values count back from the end of the array.
*length* is optional and defaults to rest of the array.
*LIST* may be empty.
Returns a list of the original *length* elements at *offset*.
In our example, we'll use a little shortcut if there is a *LIST*:
```
sub SPLICE {
my $self = shift;
my $offset = shift || 0;
my $length = shift || $self->FETCHSIZE() - $offset;
my @list = ();
if ( @_ ) {
tie @list, __PACKAGE__, $self->{ELEMSIZE};
@list = @_;
}
return splice $self->{ARRAY}->@*, $offset, $length, @list;
}
```
UNTIE this Will be called when `untie` happens. (See ["The `untie` Gotcha"](#The-untie-Gotcha) below.)
DESTROY this This method will be triggered when the tied variable needs to be destructed. As with the scalar tie class, this is almost never needed in a language that does its own garbage collection, so this time we'll just leave it out.
###
Tying Hashes
Hashes were the first Perl data type to be tied (see dbmopen()). A class implementing a tied hash should define the following methods: TIEHASH is the constructor. FETCH and STORE access the key and value pairs. EXISTS reports whether a key is present in the hash, and DELETE deletes one. CLEAR empties the hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY implement the keys() and each() functions to iterate over all the keys. SCALAR is triggered when the tied hash is evaluated in scalar context, and in 5.28 onwards, by `keys` in boolean context. UNTIE is called when `untie` happens, and DESTROY is called when the tied variable is garbage collected.
If this seems like a lot, then feel free to inherit from merely the standard Tie::StdHash module for most of your methods, redefining only the interesting ones. See <Tie::Hash> for details.
Remember that Perl distinguishes between a key not existing in the hash, and the key existing in the hash but having a corresponding value of `undef`. The two possibilities can be tested with the `exists()` and `defined()` functions.
Here's an example of a somewhat interesting tied hash class: it gives you a hash representing a particular user's dot files. You index into the hash with the name of the file (minus the dot) and you get back that dot file's contents. For example:
```
use DotFiles;
tie %dot, 'DotFiles';
if ( $dot{profile} =~ /MANPATH/ ||
$dot{login} =~ /MANPATH/ ||
$dot{cshrc} =~ /MANPATH/ )
{
print "you seem to set your MANPATH\n";
}
```
Or here's another sample of using our tied class:
```
tie %him, 'DotFiles', 'daemon';
foreach $f ( keys %him ) {
printf "daemon dot file %s is size %d\n",
$f, length $him{$f};
}
```
In our tied hash DotFiles example, we use a regular hash for the object containing several important fields, of which only the `{LIST}` field will be what the user thinks of as the real hash.
USER whose dot files this object represents
HOME where those dot files live
CLOBBER whether we should try to change or remove those dot files
LIST the hash of dot file names and content mappings
Here's the start of *Dotfiles.pm*:
```
package DotFiles;
use Carp;
sub whowasi { (caller(1))[3] . '()' }
my $DEBUG = 0;
sub debug { $DEBUG = @_ ? shift : 1 }
```
For our example, we want to be able to emit debugging info to help in tracing during development. We keep also one convenience function around internally to help print out warnings; whowasi() returns the function name that calls it.
Here are the methods for the DotFiles tied hash.
TIEHASH classname, LIST This is the constructor for the class. That means it is expected to return a blessed reference through which the new object (probably but not necessarily an anonymous hash) will be accessed.
Here's the constructor:
```
sub TIEHASH {
my $class = shift;
my $user = shift || $>;
my $dotdir = shift || '';
croak "usage: @{[&whowasi]} [USER [DOTDIR]]" if @_;
$user = getpwuid($user) if $user =~ /^\d+$/;
my $dir = (getpwnam($user))[7]
|| croak "@{[&whowasi]}: no user $user";
$dir .= "/$dotdir" if $dotdir;
my $node = {
USER => $user,
HOME => $dir,
LIST => {},
CLOBBER => 0,
};
opendir(DIR, $dir)
|| croak "@{[&whowasi]}: can't opendir $dir: $!";
foreach $dot ( grep /^\./ && -f "$dir/$_", readdir(DIR)) {
$dot =~ s/^\.//;
$node->{LIST}{$dot} = undef;
}
closedir DIR;
return bless $node, $class;
}
```
It's probably worth mentioning that if you're going to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir() there, it would have been testing the wrong file.
FETCH this, key This method will be triggered every time an element in the tied hash is accessed (read). It takes one argument beyond its self reference: the key whose value we're trying to fetch.
Here's the fetch for our DotFiles example.
```
sub FETCH {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $dir = $self->{HOME};
my $file = "$dir/.$dot";
unless (exists $self->{LIST}->{$dot} || -f $file) {
carp "@{[&whowasi]}: no $dot file" if $DEBUG;
return undef;
}
if (defined $self->{LIST}->{$dot}) {
return $self->{LIST}->{$dot};
} else {
return $self->{LIST}->{$dot} = `cat $dir/.$dot`;
}
}
```
It was easy to write by having it call the Unix cat(1) command, but it would probably be more portable to open the file manually (and somewhat more efficient). Of course, because dot files are a Unixy concept, we're not that concerned.
STORE this, key, value This method will be triggered every time an element in the tied hash is set (written). It takes two arguments beyond its self reference: the index at which we're trying to store something, and the value we're trying to put there.
Here in our DotFiles example, we'll be careful not to let them try to overwrite the file unless they've called the clobber() method on the original object reference returned by tie().
```
sub STORE {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $value = shift;
my $file = $self->{HOME} . "/.$dot";
my $user = $self->{USER};
croak "@{[&whowasi]}: $file not clobberable"
unless $self->{CLOBBER};
open(my $f, '>', $file) || croak "can't open $file: $!";
print $f $value;
close($f);
}
```
If they wanted to clobber something, they might say:
```
$ob = tie %daemon_dots, 'daemon';
$ob->clobber(1);
$daemon_dots{signature} = "A true daemon\n";
```
Another way to lay hands on a reference to the underlying object is to use the tied() function, so they might alternately have set clobber using:
```
tie %daemon_dots, 'daemon';
tied(%daemon_dots)->clobber(1);
```
The clobber method is simply:
```
sub clobber {
my $self = shift;
$self->{CLOBBER} = @_ ? shift : 1;
}
```
DELETE this, key This method is triggered when we remove an element from the hash, typically by using the delete() function. Again, we'll be careful to check whether they really want to clobber files.
```
sub DELETE {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
my $file = $self->{HOME} . "/.$dot";
croak "@{[&whowasi]}: won't remove file $file"
unless $self->{CLOBBER};
delete $self->{LIST}->{$dot};
my $success = unlink($file);
carp "@{[&whowasi]}: can't unlink $file: $!" unless $success;
$success;
}
```
The value returned by DELETE becomes the return value of the call to delete(). If you want to emulate the normal behavior of delete(), you should return whatever FETCH would have returned for this key. In this example, we have chosen instead to return a value which tells the caller whether the file was successfully deleted.
CLEAR this This method is triggered when the whole hash is to be cleared, usually by assigning the empty list to it.
In our example, that would remove all the user's dot files! It's such a dangerous thing that they'll have to set CLOBBER to something higher than 1 to make it happen.
```
sub CLEAR {
carp &whowasi if $DEBUG;
my $self = shift;
croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
unless $self->{CLOBBER} > 1;
my $dot;
foreach $dot ( keys $self->{LIST}->%* ) {
$self->DELETE($dot);
}
}
```
EXISTS this, key This method is triggered when the user uses the exists() function on a particular hash. In our example, we'll look at the `{LIST}` hash element for this:
```
sub EXISTS {
carp &whowasi if $DEBUG;
my $self = shift;
my $dot = shift;
return exists $self->{LIST}->{$dot};
}
```
FIRSTKEY this This method will be triggered when the user is going to iterate through the hash, such as via a keys(), values(), or each() call.
```
sub FIRSTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
my $a = keys $self->{LIST}->%*; # reset each() iterator
each $self->{LIST}->%*
}
```
FIRSTKEY is always called in scalar context and it should just return the first key. values(), and each() in list context, will call FETCH for the returned keys.
NEXTKEY this, lastkey This method gets triggered during a keys(), values(), or each() iteration. It has a second argument which is the last key that had been accessed. This is useful if you're caring about ordering or calling the iterator from more than one sequence, or not really storing things in a hash anywhere.
NEXTKEY is always called in scalar context and it should just return the next key. values(), and each() in list context, will call FETCH for the returned keys.
For our example, we're using a real hash so we'll do just the simple thing, but we'll have to go through the LIST field indirectly.
```
sub NEXTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
return each $self->{LIST}->%*
}
```
If the object underlying your tied hash isn't a real hash and you don't have `each` available, then you should return `undef` or the empty list once you've reached the end of your list of keys. See [`each's own documentation`](perlfunc#each) for more details.
SCALAR this This is called when the hash is evaluated in scalar context, and in 5.28 onwards, by `keys` in boolean context. In order to mimic the behaviour of untied hashes, this method must return a value which when used as boolean, indicates whether the tied hash is considered empty. If this method does not exist, perl will make some educated guesses and return true when the hash is inside an iteration. If this isn't the case, FIRSTKEY is called, and the result will be a false value if FIRSTKEY returns the empty list, true otherwise.
However, you should **not** blindly rely on perl always doing the right thing. Particularly, perl will mistakenly return true when you clear the hash by repeatedly calling DELETE until it is empty. You are therefore advised to supply your own SCALAR method when you want to be absolutely sure that your hash behaves nicely in scalar context.
In our example we can just call `scalar` on the underlying hash referenced by `$self->{LIST}`:
```
sub SCALAR {
carp &whowasi if $DEBUG;
my $self = shift;
return scalar $self->{LIST}->%*
}
```
NOTE: In perl 5.25 the behavior of scalar %hash on an untied hash changed to return the count of keys. Prior to this it returned a string containing information about the bucket setup of the hash. See ["bucket\_ratio" in Hash::Util](Hash::Util#bucket_ratio) for a backwards compatibility path.
UNTIE this This is called when `untie` occurs. See ["The `untie` Gotcha"](#The-untie-Gotcha) below.
DESTROY this This method is triggered when a tied hash is about to go out of scope. You don't really need it unless you're trying to add debugging or have auxiliary state to clean up. Here's a very simple function:
```
sub DESTROY {
carp &whowasi if $DEBUG;
}
```
Note that functions such as keys() and values() may return huge lists when used on large objects, like DBM files. You may prefer to use the each() function to iterate over such. Example:
```
# print out history file offsets
use NDBM_File;
tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
while (($key,$val) = each %HIST) {
print $key, ' = ', unpack('L',$val), "\n";
}
untie(%HIST);
```
###
Tying FileHandles
This is partially implemented now.
A class implementing a tied filehandle should define the following methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC, READ, and possibly CLOSE, UNTIE and DESTROY. The class can also provide: BINMODE, OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are used on the handle.
When STDERR is tied, its PRINT method will be called to issue warnings and error messages. This feature is temporarily disabled during the call, which means you can use `warn()` inside PRINT without starting a recursive loop. And just like `__WARN__` and `__DIE__` handlers, STDERR's PRINT method may be called to report parser errors, so the caveats mentioned under ["%SIG" in perlvar](perlvar#%25SIG) apply.
All of this is especially useful when perl is embedded in some other program, where output to STDOUT and STDERR may have to be redirected in some special way. See nvi and the Apache module for examples.
When tying a handle, the first argument to `tie` should begin with an asterisk. So, if you are tying STDOUT, use `*STDOUT`. If you have assigned it to a scalar variable, say `$handle`, use `*$handle`. `tie $handle` ties the scalar variable `$handle`, not the handle inside it.
In our example we're going to create a shouting handle.
```
package Shout;
```
TIEHANDLE classname, LIST This is the constructor for the class. That means it is expected to return a blessed reference of some sort. The reference can be used to hold some internal information.
```
sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
```
WRITE this, LIST This method will be called when the handle is written to via the `syswrite` function.
```
sub WRITE {
$r = shift;
my($buf,$len,$offset) = @_;
print "WRITE called, \$buf=$buf, \$len=$len, \$offset=$offset";
}
```
PRINT this, LIST This method will be triggered every time the tied handle is printed to with the `print()` or `say()` functions. Beyond its self reference it also expects the list that was passed to the print function.
```
sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
```
`say()` acts just like `print()` except $\ will be localized to `\n` so you need do nothing special to handle `say()` in `PRINT()`.
PRINTF this, LIST This method will be triggered every time the tied handle is printed to with the `printf()` function. Beyond its self reference it also expects the format and list that was passed to the printf function.
```
sub PRINTF {
shift;
my $fmt = shift;
print sprintf($fmt, @_);
}
```
READ this, LIST This method will be called when the handle is read from via the `read` or `sysread` functions.
```
sub READ {
my $self = shift;
my $bufref = \$_[0];
my(undef,$len,$offset) = @_;
print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
# add to $$bufref, set $len to number of characters read
$len;
}
```
READLINE this This method is called when the handle is read via `<HANDLE>` or `readline HANDLE`.
As per [`readline`](perlfunc#readline), in scalar context it should return the next line, or `undef` for no more data. In list context it should return all remaining lines, or an empty list for no more data. The strings returned should include the input record separator `$/` (see <perlvar>), unless it is `undef` (which means "slurp" mode).
```
sub READLINE {
my $r = shift;
if (wantarray) {
return ("all remaining\n",
"lines up\n",
"to eof\n");
} else {
return "READLINE called " . ++$$r . " times\n";
}
}
```
GETC this This method will be called when the `getc` function is called.
```
sub GETC { print "Don't GETC, Get Perl"; return "a"; }
```
EOF this This method will be called when the `eof` function is called.
Starting with Perl 5.12, an additional integer parameter will be passed. It will be zero if `eof` is called without parameter; `1` if `eof` is given a filehandle as a parameter, e.g. `eof(FH)`; and `2` in the very special case that the tied filehandle is `ARGV` and `eof` is called with an empty parameter list, e.g. `eof()`.
```
sub EOF { not length $stringbuf }
```
CLOSE this This method will be called when the handle is closed via the `close` function.
```
sub CLOSE { print "CLOSE called.\n" }
```
UNTIE this As with the other types of ties, this method will be called when `untie` happens. It may be appropriate to "auto CLOSE" when this occurs. See ["The `untie` Gotcha"](#The-untie-Gotcha) below.
DESTROY this As with the other types of ties, this method will be called when the tied handle is about to be destroyed. This is useful for debugging and possibly cleaning up.
```
sub DESTROY { print "</shout>\n" }
```
Here's how to use our little example:
```
tie(*FOO,'Shout');
print FOO "hello\n";
$a = 4; $b = 6;
print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
print <FOO>;
```
###
UNTIE this
You can define for all tie types an UNTIE method that will be called at untie(). See ["The `untie` Gotcha"](#The-untie-Gotcha) below.
###
The `untie` Gotcha
If you intend making use of the object returned from either tie() or tied(), and if the tie's target class defines a destructor, there is a subtle gotcha you *must* guard against.
As setup, consider this (admittedly rather contrived) example of a tie; all it does is use a file to keep a log of the values assigned to a scalar.
```
package Remember;
use v5.36;
use IO::File;
sub TIESCALAR {
my $class = shift;
my $filename = shift;
my $handle = IO::File->new( "> $filename" )
or die "Cannot open $filename: $!\n";
print $handle "The Start\n";
bless {FH => $handle, Value => 0}, $class;
}
sub FETCH {
my $self = shift;
return $self->{Value};
}
sub STORE {
my $self = shift;
my $value = shift;
my $handle = $self->{FH};
print $handle "$value\n";
$self->{Value} = $value;
}
sub DESTROY {
my $self = shift;
my $handle = $self->{FH};
print $handle "The End\n";
close $handle;
}
1;
```
Here is an example that makes use of this tie:
```
use strict;
use Remember;
my $fred;
tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
$fred = 5;
untie $fred;
system "cat myfile.txt";
```
This is the output when it is executed:
```
The Start
1
4
5
The End
```
So far so good. Those of you who have been paying attention will have spotted that the tied object hasn't been used so far. So lets add an extra method to the Remember class to allow comments to be included in the file; say, something like this:
```
sub comment {
my $self = shift;
my $text = shift;
my $handle = $self->{FH};
print $handle $text, "\n";
}
```
And here is the previous example modified to use the `comment` method (which requires the tied object):
```
use strict;
use Remember;
my ($fred, $x);
$x = tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
comment $x "changing...";
$fred = 5;
untie $fred;
system "cat myfile.txt";
```
When this code is executed there is no output. Here's why:
When a variable is tied, it is associated with the object which is the return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This object normally has only one reference, namely, the implicit reference from the tied variable. When untie() is called, that reference is destroyed. Then, as in the first example above, the object's destructor (DESTROY) is called, which is normal for objects that have no more valid references; and thus the file is closed.
In the second example, however, we have stored another reference to the tied object in $x. That means that when untie() gets called there will still be a valid reference to the object in existence, so the destructor is not called at that time, and thus the file is not closed. The reason there is no output is because the file buffers have not been flushed to disk.
Now that you know what the problem is, what can you do to avoid it? Prior to the introduction of the optional UNTIE method the only way was the good old `-w` flag. Which will spot any instances where you call untie() and there are still valid references to the tied object. If the second script above this near the top `use warnings 'untie'` or was run with the `-w` flag, Perl prints this warning message:
```
untie attempted while 1 inner references still exist
```
To get the script to work properly and silence the warning make sure there are no valid references to the tied object *before* untie() is called:
```
undef $x;
untie $fred;
```
Now that UNTIE exists the class designer can decide which parts of the class functionality are really associated with `untie` and which with the object being destroyed. What makes sense for a given class depends on whether the inner references are being kept so that non-tie-related methods can be called on the object. But in most cases it probably makes sense to move the functionality that would have been in DESTROY to the UNTIE method.
If the UNTIE method exists then the warning above does not occur. Instead the UNTIE method is passed the count of "extra" references and can issue its own warning if appropriate. e.g. to replicate the no UNTIE case this method can be used:
```
sub UNTIE
{
my ($obj,$count) = @_;
carp "untie attempted while $count inner references still exist"
if $count;
}
```
SEE ALSO
---------
See [DB\_File](db_file) or [Config](config) for some interesting tie() implementations. A good starting point for many tie() implementations is with one of the modules <Tie::Scalar>, <Tie::Array>, <Tie::Hash>, or <Tie::Handle>.
BUGS
----
The normal return provided by `scalar(%hash)` is not available. What this means is that using %tied\_hash in boolean context doesn't work right (currently this always tests false, regardless of whether the hash is empty or hash elements). [ This paragraph needs review in light of changes in 5.25 ]
Localizing tied arrays or hashes does not work. After exiting the scope the arrays or the hashes are not restored.
Counting the number of entries in a hash via `scalar(keys(%hash))` or `scalar(values(%hash)`) is inefficient since it needs to iterate through all the entries with FIRSTKEY/NEXTKEY.
Tied hash/array slices cause multiple FETCH/STORE pairs, there are no tie methods for slice operations.
You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also have problems with how references are to be represented on disk. One module that does attempt to address this need is DBM::Deep. Check your nearest CPAN site as described in <perlmodlib> for source code. Note that despite its name, DBM::Deep does not use dbm. Another earlier attempt at solving the problem is MLDBM, which is also available on the CPAN, but which has some fairly serious limitations.
Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X can't currently be trapped.
AUTHOR
------
Tom Christiansen
TIEHANDLE by Sven Verdoolaege <*[email protected]*> and Doug MacEachern <*[email protected]*>
UNTIE by Nick Ing-Simmons <*[email protected]*>
SCALAR by Tassilo von Parseval <*[email protected]*>
Tying Arrays by Casey West <*[email protected]*>
| programming_docs |
perl CPAN::Plugin CPAN::Plugin
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Alpha Status](#Alpha-Status)
+ [How Plugins work?](#How-Plugins-work?)
* [METHODS](#METHODS)
+ [plugin\_requires](#plugin_requires)
+ [distribution\_object](#distribution_object)
+ [distribution](#distribution)
+ [distribution\_info](#distribution_info)
+ [build\_dir](#build_dir)
+ [is\_xs](#is_xs)
* [AUTHOR](#AUTHOR)
NAME
----
CPAN::Plugin - Base class for CPAN shell extensions
SYNOPSIS
--------
```
package CPAN::Plugin::Flurb;
use parent 'CPAN::Plugin';
sub post_test {
my ($self, $distribution_object) = @_;
$self = $self->new (distribution_object => $distribution_object);
...;
}
```
DESCRIPTION
-----------
###
Alpha Status
The plugin system in the CPAN shell was introduced in version 2.07 and is still considered experimental.
###
How Plugins work?
See ["Plugin support" in CPAN](cpan#Plugin-support).
METHODS
-------
### plugin\_requires
returns list of packages given plugin requires for functionality. This list is evaluated using `CPAN->use_inst` method.
### distribution\_object
Get current distribution object.
### distribution
### distribution\_info
### build\_dir
Simple delegatees for misc parameters derived from distribution
### is\_xs
Predicate to detect whether package contains XS.
AUTHOR
------
Branislav Zahradnik <[email protected]>
perl ptardiff ptardiff
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS](#OPTIONS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ptardiff - program that diffs an extracted archive against an unextracted one
DESCRIPTION
-----------
```
ptardiff is a small program that diffs an extracted archive
against an unextracted one, using the perl module Archive::Tar.
This effectively lets you view changes made to an archives contents.
Provide the progam with an ARCHIVE_FILE and it will look up all
the files with in the archive, scan the current working directory
for a file with the name and diff it against the contents of the
archive.
```
SYNOPSIS
--------
```
ptardiff ARCHIVE_FILE
ptardiff -h
$ tar -xzf Acme-Buffy-1.3.tar.gz
$ vi Acme-Buffy-1.3/README
[...]
$ ptardiff Acme-Buffy-1.3.tar.gz > README.patch
```
OPTIONS
-------
```
h Prints this help message
```
SEE ALSO
---------
tar(1), <Archive::Tar>.
perl perlwin32 perlwin32
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Setting Up Perl on Windows](#Setting-Up-Perl-on-Windows)
+ [Building](#Building)
+ [Testing Perl on Windows](#Testing-Perl-on-Windows)
+ [Installation of Perl on Windows](#Installation-of-Perl-on-Windows)
+ [Usage Hints for Perl on Windows](#Usage-Hints-for-Perl-on-Windows)
+ [Running Perl Scripts](#Running-Perl-Scripts)
+ [Miscellaneous Things](#Miscellaneous-Things)
* [BUGS AND CAVEATS](#BUGS-AND-CAVEATS)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
perlwin32 - Perl under Windows
SYNOPSIS
--------
These are instructions for building Perl under Windows 7 and later.
DESCRIPTION
-----------
Before you start, you should glance through the README file found in the top-level directory to which the Perl distribution was extracted. Make sure you read and understand the terms under which this software is being distributed.
Also make sure you read ["BUGS AND CAVEATS"](#BUGS-AND-CAVEATS) below for the known limitations of this port.
The INSTALL file in the perl top-level has much information that is only relevant to people building Perl on Unix-like systems. In particular, you can safely ignore any information that talks about "Configure".
You may also want to look at one other option for building a perl that will work on Windows: the README.cygwin file, which give a different set of rules to build a perl for Windows. This method will probably enable you to build a more Unix-compatible perl, but you will also need to download and use various other build-time and run-time support software described in that file.
This set of instructions is meant to describe a so-called "native" port of Perl to the Windows platform. This includes both 32-bit and 64-bit Windows operating systems. The resulting Perl requires no additional software to run (other than what came with your operating system). Currently, this port is capable of using one of the following compilers on the Intel x86 and x86\_64 architectures:
```
Microsoft Visual C++ version 12.0 or later
Intel C++ Compiler (experimental)
Gcc by mingw.org gcc version 3.4.5-5.3.0
Gcc by mingw-w64.org gcc version 4.4.3 or later
```
Note that the last two of these are actually competing projects both delivering complete gcc toolchain for MS Windows:
<https://osdn.net/projects/mingw/>
Delivers gcc toolchain building 32-bit executables (which can be used both 32 and 64 bit Windows platforms)
<http://mingw-w64.org>
Delivers gcc toolchain targeting both 64-bit Windows and 32-bit Windows platforms (despite the project name "mingw-w64" they are not only 64-bit oriented). They deliver the native gcc compilers and cross-compilers that are also supported by perl's makefile.
The Microsoft Visual C++ compilers are also now being given away free. They are available as "Visual C++ 2013-2022 Community Edition" and are the same compilers that ship with "Visual C++ 2013-2022 Professional".
Visual C++ 2013 is capable of **targeting** XP and Windows Server 2003 but the build host requirement is Windows 7/Windows Server 2012. For more details see https://docs.microsoft.com/en-us/visualstudio/productinfo/vs2013-compatibility-vs and https://docs.microsoft.com/en-us/visualstudio/productinfo/vs2013-sysrequirements-vs
The MinGW64 compiler is available at <http://mingw-w64.org>. The latter is actually a cross-compiler targeting Win64. There's also a trimmed down compiler (no java, or gfortran) suitable for building perl available at: <http://strawberryperl.com/package/kmx/64_gcctoolchain/>
NOTE: If you're using a 32-bit compiler to build perl on a 64-bit Windows operating system, then you should set the WIN64 environment variable to "undef". Also, the trimmed down compiler only passes tests when USE\_ITHREADS \*= define (as opposed to undef) and when the CFG \*= Debug line is commented out.
This port fully supports MakeMaker (the set of modules that is used to build extensions to perl). Therefore, you should be able to build and install most extensions found in the CPAN sites. See ["Usage Hints for Perl on Windows"](#Usage-Hints-for-Perl-on-Windows) below for general hints about this.
###
Setting Up Perl on Windows
Make You need a "make" program to build the sources. If you are using Visual C++, you can use nmake supplied with Visual C++. You may also use gmake instead of nmake. Builds using gcc need gmake. nmake is not supported for gcc builds. Parallel building is only supported with gmake, not nmake.
Command Shell Use the default "cmd" shell that comes with Windows. Some versions of the popular 4DOS/NT shell have incompatibilities that may cause you trouble. If the build fails under that shell, try building again with the cmd shell.
Make sure the path to the build directory does not contain spaces. The build usually works in this circumstance, but some tests will fail.
Microsoft Visual C++ The nmake that comes with Visual C++ will suffice for building. Visual C++ requires that certain things be set up in the console before Visual C++ will successfully run. To make a console box be able to run the C compiler, you will need to beforehand, run `vcvarsall.bat x86` to compile for x86-32 and for x86-64 `vcvarsall.bat amd64`. On a typical install of a Microsoft C++ compiler product, these batch files will already be in your `PATH` environment variable so you may just type them without an absolute path into your console. If you need to find the absolute path to the batch file, it is usually found somewhere like C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC. With some newer Microsoft C products (released after ~2004), the installer will put a shortcut in the start menu to launch a new console window with the console already set up for your target architecture (x86-32 or x86-64 or IA64). With the newer compilers, you may also use the older batch files if you choose so.
Microsoft Visual C++ 2013-2022 Community Edition These free versions of Visual C++ 2013-2022 Professional contain the same compilers and linkers that ship with the full versions, and also contain everything necessary to build Perl.
These packages can be downloaded by searching in the Download Center at <https://www.microsoft.com/downloads/search.aspx?displaylang=en>. (Providing exact links to these packages has proven a pointless task because the links keep on changing so often.)
Install Visual C++ 2013-2022 Community, then setup your environment using, e.g.
```
C:\Program Files\Microsoft Visual Studio 12.0\Common7\Tools\vsvars32.bat
```
(assuming the default installation location was chosen).
Perl should now build using the win32/Makefile. You will need to edit that file to set CCTYPE to one of MSVC120-MSVC142 first.
GCC Perl can be compiled with gcc from MinGW (version 3.4.5 or later) or from MinGW64 (version 4.4.3 or later). It can be downloaded here:
<https://osdn.net/projects/mingw/> <http://www.mingw-w64.org/>
You also need gmake. Usually it comes with MinGW but its executable may have a different name, such as mingw32-make.exe.
Note that the MinGW build currently fails with version 6.3.0 or later.
Note also that the C++ mode build currently fails with MinGW 3.4.5 and 4.7.2 or later, and with MinGW64 64-bit 6.3.0 or later.
Intel C++ Compiler Experimental support for using Intel C++ Compiler has been added. Edit win32/Makefile and pick the correct CCTYPE for the Visual C that Intel C was installed into. Also uncomment \_\_ICC to enable Intel C on Visual C support. To set up the build environment, from the Start Menu run IA-32 Visual Studio 20\_\_ mode or Intel 64 Visual Studio 20\_\_ mode as appropriate. Then run nmake as usually in that prompt box.
Only Intel C++ Compiler v12.1 has been tested. Other versions probably will work. Using Intel C++ Compiler instead of Visual C has the benefit of C99 compatibility which is needed by some CPAN XS modules, while maintaining compatibility with Visual C object code and Visual C debugging infrastructure unlike GCC.
### Building
* Make sure you are in the "win32" subdirectory under the perl toplevel. This directory contains a "Makefile" that will work with versions of nmake that come with Visual C++, and a GNU make "GNUmakefile" that will work for all supported compilers. The defaults in the gmake makefile are setup to build using MinGW/gcc.
* Edit the GNUmakefile (or Makefile, if you're using nmake) and change the values of INST\_DRV and INST\_TOP. You can also enable various build flags. These are explained in the makefiles.
Note that it is generally not a good idea to try to build a perl with INST\_DRV and INST\_TOP set to a path that already exists from a previous build. In particular, this may cause problems with the lib/ExtUtils/t/Embed.t test, which attempts to build a test program and may end up building against the installed perl's lib/CORE directory rather than the one being tested.
You will have to make sure that CCTYPE is set correctly and that CCHOME points to wherever you installed your compiler. For GCC this should be the directory that contains the *bin*, *include* and *lib* directories.
If building with the cross-compiler provided by mingw-w64.org you'll need to uncomment the line that sets GCCCROSS in the GNUmakefile. Do this only if it's the cross-compiler - ie only if the bin folder doesn't contain a gcc.exe. (The cross-compiler does not provide a gcc.exe, g++.exe, ar.exe, etc. Instead, all of these executables are prefixed with 'x86\_64-w64-mingw32-'.)
The default value for CCHOME in the makefiles for Visual C++ may not be correct for some versions. Make sure the default exists and is valid.
If you want build some core extensions statically into perl's dll, specify them in the STATIC\_EXT macro.
Be sure to read the instructions near the top of the makefiles carefully.
* Type "gmake" (or "nmake" if you are using that make).
This should build everything. Specifically, it will create perl.exe, perl536.dll at the perl toplevel, and various other extension dll's under the lib\auto directory. If the build fails for any reason, make sure you have done the previous steps correctly.
To try gmake's parallel mode, type "gmake -j2", where 2, is the maximum number of parallel jobs you want to run. A number of things in the build process will run in parallel, but there are serialization points where you will see just 1 CPU maxed out. This is normal.
If you are advanced enough with building C code, here is a suggestion to speed up building perl, and the later `make test`. Try to keep your PATH environmental variable with the least number of folders possible (remember to keep your C compiler's folders there). `C:\WINDOWS\system32` or `C:\WINNT\system32` depending on your OS version should be first folder in PATH, since "cmd.exe" is the most commonly launched program during the build and later testing.
###
Testing Perl on Windows
Type "gmake test" (or "nmake test"). This will run most of the tests from the testsuite (many tests will be skipped).
There should be no test failures.
If you build with Visual C++ 2013 then three tests currently may fail with Daylight Saving Time related problems: *t/io/fs.t*, *cpan/HTTP-Tiny/t/110\_mirror.t* and *lib/File/Copy.t*. The failures are caused by bugs in the CRT in VC++ 2013 which are fixed in VC++2015 and later, as explained by Microsoft here: <https://connect.microsoft.com/VisualStudio/feedback/details/811534/utime-sometimes-fails-to-set-the-correct-file-times-in-visual-c-2013>. In the meantime, if you need fixed `stat` and `utime` functions then have a look at the CPAN distribution Win32::UTCFileTime.
If you build with Visual C++ 2015 or later then *ext/XS-APItest/t/locale.t* may crash (after all its tests have passed). This is due to a regression in the Universal CRT introduced in the Windows 10 April 2018 Update, and will be fixed in the May 2019 Update, as explained here: <https://developercommunity.visualstudio.com/content/problem/519486/setlocalelc-numeric-iso-latin-16-fails-then-succee.html>.
If you build with certain versions (e.g. 4.8.1) of gcc from mingw then *ext/POSIX/t/time.t* may fail test 17 due to a known bug in those gcc builds: see <https://sourceforge.net/p/mingw/bugs/2152/>.
Some test failures may occur if you use a command shell other than the native "cmd.exe", or if you are building from a path that contains spaces. So don't do that.
If you are running the tests from a emacs shell window, you may see failures in op/stat.t. Run "gmake test-notty" in that case.
Furthermore, you should make sure that during `make test` you do not have any GNU tool packages in your path: some toolkits like Unixutils include some tools (`type` for instance) which override the Windows ones and makes tests fail. Remove them from your path while testing to avoid these errors.
To see the output of specific failing tests run the harness from the t directory:
```
# assuming you're starting from the win32 directory
cd ..\win32
.\perl harness <list of tests>
```
Please report any other failures as described under ["BUGS AND CAVEATS"](#BUGS-AND-CAVEATS).
###
Installation of Perl on Windows
Type "gmake install" ("nmake install"). This will put the newly built perl and the libraries under whatever `INST_TOP` points to in the Makefile. It will also install the pod documentation under `$INST_TOP\$INST_VER\lib\pod` and HTML versions of the same under `$INST_TOP\$INST_VER\lib\pod\html`.
To use the Perl you just installed you will need to add a new entry to your PATH environment variable: `$INST_TOP\bin`, e.g.
```
set PATH=c:\perl\bin;%PATH%
```
If you opted to uncomment `INST_VER` and `INST_ARCH` in the makefile then the installation structure is a little more complicated and you will need to add two new PATH components instead: `$INST_TOP\$INST_VER\bin` and `$INST_TOP\$INST_VER\bin\$ARCHNAME`, e.g.
```
set PATH=c:\perl\5.6.0\bin;c:\perl\5.6.0\bin\MSWin32-x86;%PATH%
```
###
Usage Hints for Perl on Windows
Environment Variables The installation paths that you set during the build get compiled into perl, so you don't have to do anything additional to start using that perl (except add its location to your PATH variable).
If you put extensions in unusual places, you can set PERL5LIB to a list of paths separated by semicolons where you want perl to look for libraries. Look for descriptions of other environment variables you can set in <perlrun>.
You can also control the shell that perl uses to run system() and backtick commands via PERL5SHELL. See <perlrun>.
Perl does not depend on the registry, but it can look up certain default values if you choose to put them there unless disabled at build time with USE\_NO\_REGISTRY. On Perl process start Perl checks if `HKEY_CURRENT_USER\Software\Perl` and `HKEY_LOCAL_MACHINE\Software\Perl` exist. If the keys exists, they will be checked for remainder of the Perl process's run life for certain entries. Entries in `HKEY_CURRENT_USER\Software\Perl` override entries in `HKEY_LOCAL_MACHINE\Software\Perl`. One or more of the following entries (of type REG\_SZ or REG\_EXPAND\_SZ) may be set in the keys:
```
lib-$] version-specific standard library path to add to @INC
lib standard library path to add to @INC
sitelib-$] version-specific site library path to add to @INC
sitelib site library path to add to @INC
vendorlib-$] version-specific vendor library path to add to @INC
vendorlib vendor library path to add to @INC
PERL* fallback for all %ENV lookups that begin with "PERL"
```
Note the `$]` in the above is not literal. Substitute whatever version of perl you want to honor that entry, e.g. `5.6.0`. Paths must be separated with semicolons, as usual on Windows.
File Globbing By default, perl handles file globbing using the File::Glob extension, which provides portable globbing.
If you want perl to use globbing that emulates the quirks of DOS filename conventions, you might want to consider using File::DosGlob to override the internal glob() implementation. See <File::DosGlob> for details.
Using perl from the command line If you are accustomed to using perl from various command-line shells found in UNIX environments, you will be less than pleased with what Windows offers by way of a command shell.
The crucial thing to understand about the Windows environment is that the command line you type in is processed twice before Perl sees it. First, your command shell (usually CMD.EXE) preprocesses the command line, to handle redirection, environment variable expansion, and location of the executable to run. Then, the perl executable splits the remaining command line into individual arguments, using the C runtime library upon which Perl was built.
It is particularly important to note that neither the shell nor the C runtime do any wildcard expansions of command-line arguments (so wildcards need not be quoted). Also, the quoting behaviours of the shell and the C runtime are rudimentary at best (and may, if you are using a non-standard shell, be inconsistent). The only (useful) quote character is the double quote ("). It can be used to protect spaces and other special characters in arguments.
The Windows documentation describes the shell parsing rules here: <https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmd> and the C runtime parsing rules here: <https://msdn.microsoft.com/en-us/library/17w5ykft%28v=VS.100%29.aspx>.
Here are some further observations based on experiments: The C runtime breaks arguments at spaces and passes them to programs in argc/argv. Double quotes can be used to prevent arguments with spaces in them from being split up. You can put a double quote in an argument by escaping it with a backslash and enclosing the whole argument within double quotes. The backslash and the pair of double quotes surrounding the argument will be stripped by the C runtime.
The file redirection characters "<", ">", and "|" can be quoted by double quotes (although there are suggestions that this may not always be true). Single quotes are not treated as quotes by the shell or the C runtime, they don't get stripped by the shell (just to make this type of quoting completely useless). The caret "^" has also been observed to behave as a quoting character, but this appears to be a shell feature, and the caret is not stripped from the command line, so Perl still sees it (and the C runtime phase does not treat the caret as a quote character).
Here are some examples of usage of the "cmd" shell:
This prints two doublequotes:
```
perl -e "print '\"\"' "
```
This does the same:
```
perl -e "print \"\\\"\\\"\" "
```
This prints "bar" and writes "foo" to the file "blurch":
```
perl -e "print 'foo'; print STDERR 'bar'" > blurch
```
This prints "foo" ("bar" disappears into nowhereland):
```
perl -e "print 'foo'; print STDERR 'bar'" 2> nul
```
This prints "bar" and writes "foo" into the file "blurch":
```
perl -e "print 'foo'; print STDERR 'bar'" 1> blurch
```
This pipes "foo" to the "less" pager and prints "bar" on the console:
```
perl -e "print 'foo'; print STDERR 'bar'" | less
```
This pipes "foo\nbar\n" to the less pager:
```
perl -le "print 'foo'; print STDERR 'bar'" 2>&1 | less
```
This pipes "foo" to the pager and writes "bar" in the file "blurch":
```
perl -e "print 'foo'; print STDERR 'bar'" 2> blurch | less
```
Discovering the usefulness of the "command.com" shell on Windows 9x is left as an exercise to the reader :)
One particularly pernicious problem with the 4NT command shell for Windows is that it (nearly) always treats a % character as indicating that environment variable expansion is needed. Under this shell, it is therefore important to always double any % characters which you want Perl to see (for example, for hash variables), even when they are quoted.
Building Extensions The Comprehensive Perl Archive Network (CPAN) offers a wealth of extensions, some of which require a C compiler to build. Look in <https://www.cpan.org/> for more information on CPAN.
Note that not all of the extensions available from CPAN may work in the Windows environment; you should check the information at <https://www.cpantesters.org/> before investing too much effort into porting modules that don't readily build.
Most extensions (whether they require a C compiler or not) can be built, tested and installed with the standard mantra:
```
perl Makefile.PL
$MAKE
$MAKE test
$MAKE install
```
where $MAKE is whatever 'make' program you have configured perl to use. Use "perl -V:make" to find out what this is. Some extensions may not provide a testsuite (so "$MAKE test" may not do anything or fail), but most serious ones do.
It is important that you use a supported 'make' program, and ensure Config.pm knows about it.
Note that MakeMaker actually emits makefiles with different syntax depending on what 'make' it thinks you are using. Therefore, it is important that one of the following values appears in Config.pm:
```
make='nmake' # MakeMaker emits nmake syntax
any other value # MakeMaker emits generic make syntax
(e.g GNU make, or Perl make)
```
If the value doesn't match the 'make' program you want to use, edit Config.pm to fix it.
If a module implements XSUBs, you will need one of the supported C compilers. You must make sure you have set up the environment for the compiler for command-line compilation before running `perl Makefile.PL` or any invocation of make.
If a module does not build for some reason, look carefully for why it failed, and report problems to the module author. If it looks like the extension building support is at fault, report that with full details of how the build failed using the GitHub issue tracker at <https://github.com/Perl/perl5/issues>.
Command-line Wildcard Expansion The default command shells on DOS descendant operating systems (such as they are) usually do not expand wildcard arguments supplied to programs. They consider it the application's job to handle that. This is commonly achieved by linking the application (in our case, perl) with startup code that the C runtime libraries usually provide. However, doing that results in incompatible perl versions (since the behavior of the argv expansion code differs depending on the compiler, and it is even buggy on some compilers). Besides, it may be a source of frustration if you use such a perl binary with an alternate shell that \*does\* expand wildcards.
Instead, the following solution works rather well. The nice things about it are 1) you can start using it right away; 2) it is more powerful, because it will do the right thing with a pattern like \*/\*/\*.c; 3) you can decide whether you do/don't want to use it; and 4) you can extend the method to add any customizations (or even entirely different kinds of wildcard expansion).
```
C:\> copy con c:\perl\lib\Wild.pm
# Wild.pm - emulate shell @ARGV expansion on shells that don't
use File::DosGlob;
@ARGV = map {
my @g = File::DosGlob::glob($_) if /[*?]/;
@g ? @g : $_;
} @ARGV;
1;
^Z
C:\> set PERL5OPT=-MWild
C:\> perl -le "for (@ARGV) { print }" */*/perl*.c
p4view/perl/perl.c
p4view/perl/perlio.c
p4view/perl/perly.c
perl5.005/win32/perlglob.c
perl5.005/win32/perllib.c
perl5.005/win32/perlglob.c
perl5.005/win32/perllib.c
perl5.005/win32/perlglob.c
perl5.005/win32/perllib.c
```
Note there are two distinct steps there: 1) You'll have to create Wild.pm and put it in your perl lib directory. 2) You'll need to set the PERL5OPT environment variable. If you want argv expansion to be the default, just set PERL5OPT in your default startup environment.
If you are using the Visual C compiler, you can get the C runtime's command line wildcard expansion built into perl binary. The resulting binary will always expand unquoted command lines, which may not be what you want if you use a shell that does that for you. The expansion done is also somewhat less powerful than the approach suggested above.
Notes on 64-bit Windows Windows .NET Server supports the LLP64 data model on the Intel Itanium architecture.
The LLP64 data model is different from the LP64 data model that is the norm on 64-bit Unix platforms. In the former, `int` and `long` are both 32-bit data types, while pointers are 64 bits wide. In addition, there is a separate 64-bit wide integral type, `__int64`. In contrast, the LP64 data model that is pervasive on Unix platforms provides `int` as the 32-bit type, while both the `long` type and pointers are of 64-bit precision. Note that both models provide for 64-bits of addressability.
64-bit Windows running on Itanium is capable of running 32-bit x86 binaries transparently. This means that you could use a 32-bit build of Perl on a 64-bit system. Given this, why would one want to build a 64-bit build of Perl? Here are some reasons why you would bother:
* A 64-bit native application will run much more efficiently on Itanium hardware.
* There is no 2GB limit on process size.
* Perl automatically provides large file support when built under 64-bit Windows.
* Embedding Perl inside a 64-bit application.
###
Running Perl Scripts
Perl scripts on UNIX use the "#!" (a.k.a "shebang") line to indicate to the OS that it should execute the file using perl. Windows has no comparable means to indicate arbitrary files are executables.
Instead, all available methods to execute plain text files on Windows rely on the file "extension". There are three methods to use this to execute perl scripts:
1. There is a facility called "file extension associations". This can be manipulated via the two commands "assoc" and "ftype" that come standard with Windows. Type "ftype /?" for a complete example of how to set this up for perl scripts (Say what? You thought Windows wasn't perl-ready? :).
2. Since file associations don't work everywhere, and there are reportedly bugs with file associations where it does work, the old method of wrapping the perl script to make it look like a regular batch file to the OS, may be used. The install process makes available the "pl2bat.bat" script which can be used to wrap perl scripts into batch files. For example:
```
pl2bat foo.pl
```
will create the file "FOO.BAT". Note "pl2bat" strips any .pl suffix and adds a .bat suffix to the generated file.
If you use the 4DOS/NT or similar command shell, note that "pl2bat" uses the "%\*" variable in the generated batch file to refer to all the command line arguments, so you may need to make sure that construct works in batch files. As of this writing, 4DOS/NT users will need a "ParameterChar = \*" statement in their 4NT.INI file or will need to execute "setdos /p\*" in the 4DOS/NT startup file to enable this to work.
3. Using "pl2bat" has a few problems: the file name gets changed, so scripts that rely on `$0` to find what they must do may not run properly; running "pl2bat" replicates the contents of the original script, and so this process can be maintenance intensive if the originals get updated often. A different approach that avoids both problems is possible.
A script called "runperl.bat" is available that can be copied to any filename (along with the .bat suffix). For example, if you call it "foo.bat", it will run the file "foo" when it is executed. Since you can run batch files on Windows platforms simply by typing the name (without the extension), this effectively runs the file "foo", when you type either "foo" or "foo.bat". With this method, "foo.bat" can even be in a different location than the file "foo", as long as "foo" is available somewhere on the PATH. If your scripts are on a filesystem that allows symbolic links, you can even avoid copying "runperl.bat".
Here's a diversion: copy "runperl.bat" to "runperl", and type "runperl". Explain the observed behavior, or lack thereof. :) Hint: .gnidnats llits er'uoy fi ,"lrepnur" eteled :tniH
###
Miscellaneous Things
A full set of HTML documentation is installed, so you should be able to use it if you have a web browser installed on your system.
`perldoc` is also a useful tool for browsing information contained in the documentation, especially in conjunction with a pager like `less` (recent versions of which have Windows support). You may have to set the PAGER environment variable to use a specific pager. "perldoc -f foo" will print information about the perl operator "foo".
One common mistake when using this port with a GUI library like `Tk` is assuming that Perl's normal behavior of opening a command-line window will go away. This isn't the case. If you want to start a copy of `perl` without opening a command-line window, use the `wperl` executable built during the installation process. Usage is exactly the same as normal `perl` on Windows, except that options like `-h` don't work (since they need a command-line window to print to).
If you find bugs in perl, you can report them to <https://github.com/Perl/perl5/issues>.
BUGS AND CAVEATS
-----------------
Norton AntiVirus interferes with the build process, particularly if set to "AutoProtect, All Files, when Opened". Unlike large applications the perl build process opens and modifies a lot of files. Having the AntiVirus scan each and every one slows build the process significantly. Worse, with PERLIO=stdio the build process fails with peculiar messages as the virus checker interacts badly with miniperl.exe writing configure files (it seems to either catch file part written and treat it as suspicious, or virus checker may have it "locked" in a way which inhibits miniperl updating it). The build does complete with
```
set PERLIO=perlio
```
but that may be just luck. Other AntiVirus software may have similar issues.
A git GUI shell extension for Windows such as TortoiseGit will cause the build and later `make test` to run much slower since every file is checked for its git status as soon as it is created and/or modified. TortoiseGit doesn't cause any test failures or build problems unlike the antivirus software described above, but it does cause similar slowness. It is suggested to use Task Manager to look for background processes which use high CPU amounts during the building process.
Some of the built-in functions do not act exactly as documented in <perlfunc>, and a few are not implemented at all. To avoid surprises, particularly if you have had prior exposure to Perl in other operating environments or if you intend to write code that will be portable to other environments, see <perlport> for a reasonably definitive list of these differences.
Not all extensions available from CPAN may build or work properly in the Windows environment. See ["Building Extensions"](#Building-Extensions).
Most `socket()` related calls are supported, but they may not behave as on Unix platforms. See <perlport> for the full list.
Signal handling may not behave as on Unix platforms (where it doesn't exactly "behave", either :). For instance, calling `die()` or `exit()` from signal handlers will cause an exception, since most implementations of `signal()` on Windows are severely crippled. Thus, signals may work only for simple things like setting a flag variable in the handler. Using signals under this port should currently be considered unsupported.
Please report detailed descriptions of any problems and solutions that you may find at <<https://github.com/Perl/perl5/issues>>, along with the output produced by `perl -V`.
ACKNOWLEDGEMENTS
----------------
The use of a camel with the topic of Perl is a trademark of O'Reilly and Associates, Inc. Used with permission.
AUTHORS
-------
Gary Ng <[email protected]>
Gurusamy Sarathy <[email protected]>
Nick Ing-Simmons <[email protected]>
Jan Dubois <[email protected]>
Steve Hay <[email protected]> This document is maintained by Jan Dubois.
SEE ALSO
---------
<perl>
HISTORY
-------
This port was originally contributed by Gary Ng around 5.003\_24, and borrowed from the Hip Communications port that was available at the time. Various people have made numerous and sundry hacks since then.
GCC/mingw32 support was added in 5.005 (Nick Ing-Simmons).
Support for PERL\_OBJECT was added in 5.005 (ActiveState Tool Corp).
Support for fork() emulation was added in 5.6 (ActiveState Tool Corp).
Win9x support was added in 5.6 (Benjamin Stuhl).
Support for 64-bit Windows added in 5.8 (ActiveState Corp).
Last updated: 06 October 2021
| programming_docs |
perl filetest filetest
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Consider this carefully](#Consider-this-carefully)
+ [The "access" sub-pragma](#The-%22access%22-sub-pragma)
+ [Limitation with regard to \_](#Limitation-with-regard-to-_)
NAME
----
filetest - Perl pragma to control the filetest permission operators
SYNOPSIS
--------
```
$can_perhaps_read = -r "file"; # use the mode bits
{
use filetest 'access'; # intuit harder
$can_really_read = -r "file";
}
$can_perhaps_read = -r "file"; # use the mode bits again
```
DESCRIPTION
-----------
This pragma tells the compiler to change the behaviour of the filetest permission operators, `-r` `-w` `-x` `-R` `-W` `-X` (see <perlfunc>).
The default behaviour of file test operators is to use the simple mode bits as returned by the stat() family of system calls. However, many operating systems have additional features to define more complex access rights, for example ACLs (Access Control Lists). For such environments, `use filetest` may help the permission operators to return results more consistent with other tools.
The `use filetest` or `no filetest` statements affect file tests defined in their block, up to the end of the closest enclosing block (they are lexically block-scoped).
Currently, only the `access` sub-pragma is implemented. It enables (or disables) the use of access() when available, that is, on most UNIX systems and other POSIX environments. See details below.
###
Consider this carefully
The stat() mode bits are probably right for most of the files and directories found on your system, because few people want to use the additional features offered by access(). But you may encounter surprises if your program runs on a system that uses ACLs, since the stat() information won't reflect the actual permissions.
There may be a slight performance decrease in the filetest operations when the filetest pragma is in effect, because checking bits is very cheap.
Also, note that using the file tests for security purposes is a lost cause from the start: there is a window open for race conditions (who is to say that the permissions will not change between the test and the real operation?). Therefore if you are serious about security, just try the real operation and test for its success - think in terms of atomic operations. Filetests are more useful for filesystem administrative tasks, when you have no need for the content of the elements on disk.
###
The "access" sub-pragma
UNIX and POSIX systems provide an abstract access() operating system call, which should be used to query the read, write, and execute rights. This function hides various distinct approaches in additional operating system specific security features, like Access Control Lists (ACLs)
The extended filetest functionality is used by Perl only when the argument of the operators is a filename, not when it is a filehandle.
###
Limitation with regard to `_`
Because access() does not invoke stat() (at least not in a way visible to Perl), **the stat result cache "\_" is not set**. This means that the outcome of the following two tests is different. The first has the stat bits of */etc/passwd* in `_`, and in the second case this still contains the bits of `/etc`.
```
{ -d '/etc';
-w '/etc/passwd';
print -f _ ? 'Yes' : 'No'; # Yes
}
{ use filetest 'access';
-d '/etc';
-w '/etc/passwd';
print -f _ ? 'Yes' : 'No'; # No
}
```
Of course, unless your OS does not implement access(), in which case the pragma is simply ignored. Best not to use `_` at all in a file where the filetest pragma is active!
As a side effect, as `_` doesn't work, stacked filetest operators (`-f -w $file`) won't work either.
This limitation might be removed in a future version of perl.
perl Module::Load::Conditional Module::Load::Conditional
=========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Methods](#Methods)
+ [$href = check\_install( module => NAME [, version => VERSION, verbose => BOOL ] );](#%24href-=-check_install(-module-=%3E-NAME-%5B,-version-=%3E-VERSION,-verbose-=%3E-BOOL-%5D-);)
+ [$bool = can\_load( modules => { NAME => VERSION [,NAME => VERSION] }, [verbose => BOOL, nocache => BOOL, autoload => BOOL] )](#%24bool-=-can_load(-modules-=%3E-%7B-NAME-=%3E-VERSION-%5B,NAME-=%3E-VERSION%5D-%7D,-%5Bverbose-=%3E-BOOL,-nocache-=%3E-BOOL,-autoload-=%3E-BOOL%5D-))
+ [@list = requires( MODULE );](#@list-=-requires(-MODULE-);)
* [Global Variables](#Global-Variables)
+ [$Module::Load::Conditional::VERBOSE](#%24Module::Load::Conditional::VERBOSE)
+ [$Module::Load::Conditional::FIND\_VERSION](#%24Module::Load::Conditional::FIND_VERSION)
+ [$Module::Load::Conditional::CHECK\_INC\_HASH](#%24Module::Load::Conditional::CHECK_INC_HASH)
+ [$Module::Load::Conditional::FORCE\_SAFE\_INC](#%24Module::Load::Conditional::FORCE_SAFE_INC)
+ [$Module::Load::Conditional::CACHE](#%24Module::Load::Conditional::CACHE)
+ [$Module::Load::Conditional::ERROR](#%24Module::Load::Conditional::ERROR)
+ [$Module::Load::Conditional::DEPRECATED](#%24Module::Load::Conditional::DEPRECATED)
* [See Also](#See-Also)
* [BUG REPORTS](#BUG-REPORTS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Module::Load::Conditional - Looking up module information / loading at runtime
SYNOPSIS
--------
```
use Module::Load::Conditional qw[can_load check_install requires];
my $use_list = {
CPANPLUS => 0.05,
LWP => 5.60,
'Test::More' => undef,
};
print can_load( modules => $use_list )
? 'all modules loaded successfully'
: 'failed to load required modules';
my $rv = check_install( module => 'LWP', version => 5.60 )
or print 'LWP is not installed!';
print 'LWP up to date' if $rv->{uptodate};
print "LWP version is $rv->{version}\n";
print "LWP is installed as file $rv->{file}\n";
print "LWP requires the following modules to be installed:\n";
print join "\n", requires('LWP');
### allow M::L::C to peek in your %INC rather than just
### scanning @INC
$Module::Load::Conditional::CHECK_INC_HASH = 1;
### reset the 'can_load' cache
undef $Module::Load::Conditional::CACHE;
### don't have Module::Load::Conditional issue warnings --
### default is '1'
$Module::Load::Conditional::VERBOSE = 0;
### The last error that happened during a call to 'can_load'
my $err = $Module::Load::Conditional::ERROR;
```
DESCRIPTION
-----------
Module::Load::Conditional provides simple ways to query and possibly load any of the modules you have installed on your system during runtime.
It is able to load multiple modules at once or none at all if one of them was not able to load. It also takes care of any error checking and so forth.
Methods
-------
###
$href = check\_install( module => NAME [, version => VERSION, verbose => BOOL ] );
`check_install` allows you to verify if a certain module is installed or not. You may call it with the following arguments:
module The name of the module you wish to verify -- this is a required key
version The version this module needs to be -- this is optional
verbose Whether or not to be verbose about what it is doing -- it will default to $Module::Load::Conditional::VERBOSE
It will return undef if it was not able to find where the module was installed, or a hash reference with the following keys if it was able to find the file:
file Full path to the file that contains the module
dir Directory, or more exact the `@INC` entry, where the module was loaded from.
version The version number of the installed module - this will be `undef` if the module had no (or unparsable) version number, or if the variable `$Module::Load::Conditional::FIND_VERSION` was set to true. (See the `GLOBAL VARIABLES` section below for details)
uptodate A boolean value indicating whether or not the module was found to be at least the version you specified. If you did not specify a version, uptodate will always be true if the module was found. If no parsable version was found in the module, uptodate will also be true, since `check_install` had no way to verify clearly.
See also `$Module::Load::Conditional::DEPRECATED`, which affects the outcome of this value.
###
$bool = can\_load( modules => { NAME => VERSION [,NAME => VERSION] }, [verbose => BOOL, nocache => BOOL, autoload => BOOL] )
`can_load` will take a list of modules, optionally with version numbers and determine if it is able to load them. If it can load \*ALL\* of them, it will. If one or more are unloadable, none will be loaded.
This is particularly useful if you have More Than One Way (tm) to solve a problem in a program, and only wish to continue down a path if all modules could be loaded, and not load them if they couldn't.
This function uses the `load` function or the `autoload_remote` function from Module::Load under the hood.
`can_load` takes the following arguments:
modules This is a hashref of module/version pairs. The version indicates the minimum version to load. If no version is provided, any version is assumed to be good enough.
verbose This controls whether warnings should be printed if a module failed to load. The default is to use the value of $Module::Load::Conditional::VERBOSE.
nocache `can_load` keeps its results in a cache, so it will not load the same module twice, nor will it attempt to load a module that has already failed to load before. By default, `can_load` will check its cache, but you can override that by setting `nocache` to true.
autoload This controls whether imports the functions of a loaded modules to the caller package. The default is no importing any functions.
See the `autoload` function and the `autoload_remote` function from <Module::Load> for details.
###
@list = requires( MODULE );
`requires` can tell you what other modules a particular module requires. This is particularly useful when you're intending to write a module for public release and are listing its prerequisites.
`requires` takes but one argument: the name of a module. It will then first check if it can actually load this module, and return undef if it can't. Otherwise, it will return a list of modules and pragmas that would have been loaded on the module's behalf.
Note: The list `require` returns has originated from your current perl and your current install.
Global Variables
-----------------
The behaviour of Module::Load::Conditional can be altered by changing the following global variables:
###
$Module::Load::Conditional::VERBOSE
This controls whether Module::Load::Conditional will issue warnings and explanations as to why certain things may have failed. If you set it to 0, Module::Load::Conditional will not output any warnings. The default is 0;
###
$Module::Load::Conditional::FIND\_VERSION
This controls whether Module::Load::Conditional will try to parse (and eval) the version from the module you're trying to load.
If you don't wish to do this, set this variable to `false`. Understand then that version comparisons are not possible, and Module::Load::Conditional can not tell you what module version you have installed. This may be desirable from a security or performance point of view. Note that `$FIND_VERSION` code runs safely under `taint mode`.
The default is 1;
###
$Module::Load::Conditional::CHECK\_INC\_HASH
This controls whether `Module::Load::Conditional` checks your `%INC` hash to see if a module is available. By default, only `@INC` is scanned to see if a module is physically on your filesystem, or available via an `@INC-hook`. Setting this variable to `true` will trust any entries in `%INC` and return them for you.
The default is 0;
###
$Module::Load::Conditional::FORCE\_SAFE\_INC
This controls whether `Module::Load::Conditional` sanitises `@INC` by removing "`.`". The current default setting is `0`, but this may change in a future release.
###
$Module::Load::Conditional::CACHE
This holds the cache of the `can_load` function. If you explicitly want to remove the current cache, you can set this variable to `undef`
###
$Module::Load::Conditional::ERROR
This holds a string of the last error that happened during a call to `can_load`. It is useful to inspect this when `can_load` returns `undef`.
###
$Module::Load::Conditional::DEPRECATED
This controls whether `Module::Load::Conditional` checks if a dual-life core module has been deprecated. If this is set to true `check_install` will return false to `uptodate`, if a dual-life module is found to be loaded from `$Config{privlibexp}`
The default is 0;
See Also
---------
`Module::Load`
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 pod2text pod2text
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [EXIT STATUS](#EXIT-STATUS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
pod2text - Convert POD data to formatted ASCII text
SYNOPSIS
--------
pod2text [**-aclostu**] [**--code**] [**--errors**=*style*] [**-i** *indent*] [**-q** *quotes*] [**--nourls**] [**--stderr**] [**-w** *width*] [*input* [*output* ...]]
pod2text **-h**
DESCRIPTION
-----------
**pod2text** is a front-end for Pod::Text and its subclasses. It uses them to generate formatted ASCII text from POD source. It can optionally use either termcap sequences or ANSI color escape sequences to format the text.
*input* is the file to read for POD source (the POD can be embedded in code). If *input* isn't given, it defaults to `STDIN`. *output*, if given, is the file to which to write the formatted output. If *output* isn't given, the formatted output is written to `STDOUT`. Several POD files can be processed in the same **pod2text** invocation (saving module load and compile times) by providing multiple pairs of *input* and *output* files on the command line.
OPTIONS
-------
**-a**, **--alt**
Use an alternate output format that, among other things, uses a different heading style and marks `=item` entries with a colon in the left margin.
**--code**
Include any non-POD text from the input file in the output as well. Useful for viewing code documented with POD blocks with the POD rendered and the code left intact.
**-c**, **--color**
Format the output with ANSI color escape sequences. Using this option requires that Term::ANSIColor be installed on your system.
**--errors**=*style*
Set the error handling style. `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 `die`.
**-i** *indent*, **--indent=***indent*
Set the number of spaces to indent regular text, and the default indentation for `=over` blocks. Defaults to 4 spaces if this option isn't given.
**-h**, **--help**
Print out usage information and exit.
**-l**, **--loose**
Print a blank line after a `=head1` heading. Normally, no blank line is printed after `=head1`, although one is still printed after `=head2`, because this is the expected formatting for manual pages; if you're formatting arbitrary text documents, using this option is recommended.
**-m** *width*, **--left-margin**=*width*, **--margin**=*width*
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 **-i** 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 flag, if given, 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.
**-o**, **--overstrike**
Format the output with overstrike printing. Bold text is rendered as character, backspace, character. Italics and file names are rendered as underscore, backspace, character. Many pagers, such as **less**, know how to convert this to bold or underlined text.
**-q** *quotes*, **--quotes**=*quotes*
Sets the quote marks used to surround C<> text to *quotes*. If *quotes* 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.
*quotes* may also be set to the special value `none`, in which case no quote marks are added around C<> text.
**-s**, **--sentence**
Assume each sentence ends with two spaces and try to preserve that spacing. Without this option, all consecutive whitespace in non-verbatim paragraphs is compressed into a single space.
**--stderr**
By default, **pod2text** dies if any errors are detected in the POD input. If **--stderr** is given and no **--errors** flag is present, errors are sent to standard error, but **pod2text** does not abort. This is equivalent to `--errors=stderr` and is supported for backward compatibility.
**-t**, **--termcap**
Try to determine the width of the screen and the bold and underline sequences for the terminal from termcap, and use that information in formatting the output. Output will be wrapped at two columns less than the width of your terminal device. Using this option requires that your system have a termcap file somewhere where Term::Cap can find it and requires that your system support termios. With this option, the output of **pod2text** will contain terminal control sequences for your current terminal type.
**-u**, **--utf8**
By default, **pod2text** tries to use the same output encoding as its input encoding (to be backward-compatible with older versions). This option says to instead force the output encoding 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 warn, which by default results in a **pod2text** failure. Use the `=encoding` command to declare the encoding. See [perlpod(1)](http://man.he.net/man1/perlpod) for more information.
**-w**, **--width=***width*, **-***width*
The column at which to wrap text on the right-hand side. Defaults to 76, unless **-t** is given, in which case it's two columns less than the width of your terminal device.
EXIT STATUS
------------
As long as all documents processed result in some output, even if that output includes errata (a `POD ERRORS` section generated with `--errors=pod`), **pod2text** will exit with status 0. If any of the documents being processed do not result in an output document, **pod2text** will exit with status 1. If there are syntax errors in a POD document being processed and the error handling style is set to the default of `die`, **pod2text** will abort immediately with exit status 255.
DIAGNOSTICS
-----------
If **pod2text** fails with errors, see <Pod::Text> and <Pod::Simple> for information about what those errors might mean. Internally, it can also produce the following diagnostics:
-c (--color) requires Term::ANSIColor be installed (F) **-c** or **--color** were given, but Term::ANSIColor could not be loaded.
Unknown option: %s (F) An unknown command line option was given.
In addition, other <Getopt::Long> error messages may result from invalid command-line options.
ENVIRONMENT
-----------
COLUMNS If **-t** is given, **pod2text** will take the current width of your screen from this environment variable, if available. It overrides terminal width information in TERMCAP.
TERMCAP If **-t** is given, **pod2text** will use the contents of this environment variable if available to determine the correct formatting sequences for your current terminal device.
AUTHOR
------
Russ Allbery <[email protected]>.
COPYRIGHT AND LICENSE
----------------------
Copyright 1999-2001, 2004, 2006, 2008, 2010, 2012-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::Text::Color>, <Pod::Text::Overstrike>, <Pod::Text::Termcap>, <Pod::Simple>, [perlpod(1)](http://man.he.net/man1/perlpod)
The current version of this script 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.
| programming_docs |
perl Win32 Win32
=====
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Alphabetical Listing of Win32 Functions](#Alphabetical-Listing-of-Win32-Functions)
* [CAVEATS](#CAVEATS)
+ [Short Path Names](#Short-Path-Names)
NAME
----
Win32 - Interfaces to some Win32 API Functions
DESCRIPTION
-----------
The Win32 module contains functions to access Win32 APIs.
###
Alphabetical Listing of Win32 Functions
It is recommended to `use Win32;` before any of these functions; however, for backwards compatibility, those marked as [CORE] will automatically do this for you.
In the function descriptions below the term *Unicode string* is used to indicate that the string may contain characters outside the system codepage. The caveat *If supported by the core Perl version* generally means Perl 5.8.9 and later, though some Unicode pathname functionality may work on earlier versions.
Win32::AbortSystemShutdown(MACHINE) Aborts a system shutdown (started by the InitiateSystemShutdown function) on the specified MACHINE.
Win32::BuildNumber() [CORE] Returns the ActivePerl build number. This function is only available in the ActivePerl binary distribution.
Win32::CopyFile(FROM, TO, OVERWRITE) [CORE] The Win32::CopyFile() function copies an existing file to a new file. All file information like creation time and file attributes will be copied to the new file. However it will **not** copy the security information. If the destination file already exists it will only be overwritten when the OVERWRITE parameter is true. But even this will not overwrite a read-only file; you have to unlink() it first yourself.
Win32::CreateDirectory(DIRECTORY) Creates the DIRECTORY and returns a true value on success. Check $^E on failure for extended error information.
DIRECTORY may contain Unicode characters outside the system codepage. Once the directory has been created you can use Win32::GetANSIPathName() to get a name that can be passed to system calls and external programs.
Win32::CreateFile(FILE) Creates the FILE and returns a true value on success. Check $^E on failure for extended error information.
FILE may contain Unicode characters outside the system codepage. Once the file has been created you can use Win32::GetANSIPathName() to get a name that can be passed to system calls and external programs.
Win32::DomainName() [CORE] Returns the name of the Microsoft Network domain or workgroup that the owner of the current perl process is logged into. The "Workstation" service must be running to determine this information. This function does **not** work on Windows 9x.
Win32::ExpandEnvironmentStrings(STRING) Takes STRING and replaces all referenced environment variable names with their defined values. References to environment variables take the form `%VariableName%`. Case is ignored when looking up the VariableName in the environment. If the variable is not found then the original `%VariableName%` text is retained. Has the same effect as the following:
```
$string =~ s/%([^%]*)%/$ENV{$1} || "%$1%"/eg
```
However, this function may return a Unicode string if the environment variable being expanded hasn't been assigned to via %ENV. Access to %ENV is currently always using byte semantics.
Win32::FormatMessage(ERRORCODE) [CORE] Converts the supplied Win32 error number (e.g. returned by Win32::GetLastError()) to a descriptive string. Analogous to the perror() standard-C library function. Note that `$^E` used in a string context has much the same effect.
```
C:\> perl -e "$^E = 26; print $^E;"
The specified disk or diskette cannot be accessed
```
Win32::FsType() [CORE] Returns the name of the filesystem of the currently active drive (like 'FAT' or 'NTFS'). In list context it returns three values: (FSTYPE, FLAGS, MAXCOMPLEN). FSTYPE is the filesystem type as before. FLAGS is a combination of values of the following table:
```
0x00000001 supports case-sensitive filenames
0x00000002 preserves the case of filenames
0x00000004 supports Unicode in filenames
0x00000008 preserves and enforces ACLs
0x00000010 supports file-based compression
0x00000020 supports disk quotas
0x00000040 supports sparse files
0x00000080 supports reparse points
0x00000100 supports remote storage
0x00008000 is a compressed volume (e.g. DoubleSpace)
0x00010000 supports object identifiers
0x00020000 supports the Encrypted File System (EFS)
```
MAXCOMPLEN is the maximum length of a filename component (the part between two backslashes) on this file system.
Win32::FreeLibrary(HANDLE) Unloads a previously loaded dynamic-link library. The HANDLE is no longer valid after this call. See LoadLibrary for information on dynamically loading a library.
Win32::GetACP() Returns the current Windows ANSI code page identifier for the operating system. See also GetOEMCP(), GetConsoleCP() and GetConsoleOutputCP().
Win32::GetANSIPathName(FILENAME) Returns an ANSI version of FILENAME. This may be the short name if the long name cannot be represented in the system codepage.
While not currently implemented, it is possible that in the future this function will convert only parts of the path to FILENAME to a short form.
If FILENAME doesn't exist on the filesystem, or if the filesystem doesn't support short ANSI filenames, then this function will translate the Unicode name into the system codepage using replacement characters.
Win32::GetArchName() Use of this function is deprecated. It is equivalent with $ENV{PROCESSOR\_ARCHITECTURE}. This might not work on Win9X.
Win32::GetChipName() Returns the processor type: 386, 486 or 586 for x86 processors, 8664 for the x64 processor and 2200 for the Itanium. For arm/arm64 processor, the value is marked as "Reserved" (not specified, but usually 0) in Microsoft documentation, so it's better to use GetChipArch(). Since it returns the native processor type it will return a 64-bit processor type even when called from a 32-bit Perl running on 64-bit Windows.
Win32::GetChipArch() Returns the processor architecture: 0 for x86 processors, 5 for arm, 6 for Itanium, 9 for x64 and 12 for arm64, and 0xFFFF for unknown architecture.
Win32::GetConsoleCP() Returns the input code page used by the console associated with the calling process. To set the console's input code page, see SetConsoleCP(). See also GetConsoleOutputCP(), GetACP() and GetOEMCP().
Win32::GetConsoleOutputCP() Returns the output code page used by the console associated with the calling process. To set the console's output code page, see SetConsoleOutputCP(). See also GetConsoleCP(), GetACP(), and GetOEMCP().
Win32::GetCwd() [CORE] Returns the current active drive and directory. This function does not return a UNC path, since the functionality required for such a feature is not available under Windows 95.
If supported by the core Perl version, this function will return an ANSI path name for the current directory if the long pathname cannot be represented in the system codepage.
Win32::GetCurrentProcessId() Returns the process identifier of the current process. Until the process terminates, the process identifier uniquely identifies the process throughout the system.
The current process identifier is normally also available via the predefined $$ variable. Under fork() emulation however $$ may contain a pseudo-process identifier that is only meaningful to the Perl kill(), wait() and waitpid() functions. The Win32::GetCurrentProcessId() function will always return the regular Windows process id, even when called from inside a pseudo-process.
Win32::GetCurrentThreadId() Returns the thread identifier of the calling thread. Until the thread terminates, the thread identifier uniquely identifies the thread throughout the system.
Win32::GetFileVersion(FILENAME) Returns the file version number from the VERSIONINFO resource of the executable file or DLL. This is a tuple of four 16 bit numbers. In list context these four numbers will be returned. In scalar context they are concatenated into a string, separated by dots.
Win32::GetFolderPath(FOLDER [, CREATE]) Returns the full pathname of one of the Windows special folders. The folder will be created if it doesn't exist and the optional CREATE argument is true. The following FOLDER constants are defined by the Win32 module, but only exported on demand:
```
CSIDL_ADMINTOOLS
CSIDL_APPDATA
CSIDL_CDBURN_AREA
CSIDL_COMMON_ADMINTOOLS
CSIDL_COMMON_APPDATA
CSIDL_COMMON_DESKTOPDIRECTORY
CSIDL_COMMON_DOCUMENTS
CSIDL_COMMON_FAVORITES
CSIDL_COMMON_MUSIC
CSIDL_COMMON_PICTURES
CSIDL_COMMON_PROGRAMS
CSIDL_COMMON_STARTMENU
CSIDL_COMMON_STARTUP
CSIDL_COMMON_TEMPLATES
CSIDL_COMMON_VIDEO
CSIDL_COOKIES
CSIDL_DESKTOP
CSIDL_DESKTOPDIRECTORY
CSIDL_FAVORITES
CSIDL_FONTS
CSIDL_HISTORY
CSIDL_INTERNET_CACHE
CSIDL_LOCAL_APPDATA
CSIDL_MYMUSIC
CSIDL_MYPICTURES
CSIDL_MYVIDEO
CSIDL_NETHOOD
CSIDL_PERSONAL
CSIDL_PRINTHOOD
CSIDL_PROFILE
CSIDL_PROGRAMS
CSIDL_PROGRAM_FILES
CSIDL_PROGRAM_FILES_COMMON
CSIDL_RECENT
CSIDL_RESOURCES
CSIDL_RESOURCES_LOCALIZED
CSIDL_SENDTO
CSIDL_STARTMENU
CSIDL_STARTUP
CSIDL_SYSTEM
CSIDL_TEMPLATES
CSIDL_WINDOWS
```
Note that not all folders are defined on all versions of Windows.
Please refer to the MSDN documentation of the CSIDL constants, currently available at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp
This function will return an ANSI folder path if the long name cannot be represented in the system codepage. Use Win32::GetLongPathName() on the result of Win32::GetFolderPath() if you want the Unicode version of the folder name.
Win32::GetFullPathName(FILENAME) [CORE] GetFullPathName combines the FILENAME with the current drive and directory name and returns a fully qualified (aka, absolute) path name. In list context it returns two elements: (PATH, FILE) where PATH is the complete pathname component (including trailing backslash) and FILE is just the filename part. Note that no attempt is made to convert 8.3 components in the supplied FILENAME to longnames or vice-versa. Compare with Win32::GetShortPathName() and Win32::GetLongPathName().
If supported by the core Perl version, this function will return an ANSI path name if the full pathname cannot be represented in the system codepage.
Win32::GetLastError() [CORE] Returns the last error value generated by a call to a Win32 API function. Note that `$^E` used in a numeric context amounts to the same value.
Win32::GetLongPathName(PATHNAME) [CORE] Returns a representation of PATHNAME composed of longname components (if any). The result may not necessarily be longer than PATHNAME. No attempt is made to convert PATHNAME to the absolute path. Compare with Win32::GetShortPathName() and Win32::GetFullPathName().
This function may return the pathname in Unicode if it cannot be represented in the system codepage. Use Win32::GetANSIPathName() before passing the path to a system call or another program.
Win32::GetNextAvailDrive() [CORE] Returns a string in the form of "<d>:" where <d> is the first available drive letter.
Win32::GetOEMCP() Returns the current original equipment manufacturer (OEM) code page identifier for the operating system. See also GetACP(), GetConsoleCP() and GetConsoleOutputCP().
Win32::GetOSDisplayName() Returns the "marketing" name of the Windows operating system version being used. It returns names like these (random samples):
```
Windows 2000 Datacenter Server
Windows XP Professional
Windows XP Tablet PC Edition
Windows Home Server
Windows Server 2003 Enterprise Edition for Itanium-based Systems
Windows Vista Ultimate (32-bit)
Windows Small Business Server 2008 R2 (64-bit)
```
The display name describes the native Windows version, so even on a 32-bit Perl this function may return a "Windows ... (64-bit)" name when running on a 64-bit Windows.
This function should only be used to display the actual OS name to the user; it should not be used to determine the class of operating systems this system belongs to. The Win32::GetOSName(), Win32::GetOSVersion, Win32::GetProductInfo() and Win32::GetSystemMetrics() functions provide the base information to check for certain capabilities, or for families of OS releases.
Win32::GetOSName() In scalar context returns the name of the Win32 operating system being used. In list context returns a two element list of the OS name and whatever edition information is known about the particular build (for Win9X boxes) and whatever service packs have been installed. The latter is roughly equivalent to the first item returned by GetOSVersion() in list context.
The description will also include tags for other special editions, like "R2", "Media Center", "Tablet PC", or "Starter Edition".
In the Windows 10 / Server Semi-Annual Channel era, the description may contain the relevant ReleaseId value, but this is only inferred from the build number, not determined absolutely.
Currently the possible values for the OS name are
```
WinWin32s
Win95
Win98
WinMe
WinNT3.51
WinNT4
Win2000
WinXP/.Net
Win2003
WinHomeSvr
WinVista
Win2008
Win7
Win8
Win8.1
Win10
Win2016
Win2019
WinSAC
```
This routine is just a simple interface into GetOSVersion(). More specific or demanding situations should use that instead. Another option would be to use POSIX::uname(), however the latter appears to report only the OS family name and not the specific OS. In scalar context it returns just the ID.
The name "WinXP/.Net" is used for historical reasons only, to maintain backwards compatibility of the Win32 module. Windows .NET Server has been renamed as Windows 2003 Server before final release and uses a different major/minor version number than Windows XP.
Similarly the name "WinWin32s" should have been "Win32s" but has been kept as-is for backwards compatibility reasons too.
Win32::GetOSVersion() [CORE] Returns the list (STRING, MAJOR, MINOR, BUILD, ID), where the elements are, respectively: An arbitrary descriptive string, the major version number of the operating system, the minor version number, the build number, and a digit indicating the actual operating system. For the ID, the values are 0 for Win32s, 1 for Windows 9X/Me and 2 for Windows NT/2000/XP/2003/Vista/2008/7. In scalar context it returns just the ID.
Currently known values for ID MAJOR MINOR and BUILD are as follows:
```
OS ID MAJOR MINOR BUILD
Win32s 0 - - -
Windows 95 1 4 0 -
Windows 98 1 4 10 -
Windows Me 1 4 90 -
Windows NT 3.51 2 3 51 -
Windows NT 4 2 4 0 -
Windows 2000 2 5 0 -
Windows XP 2 5 1 -
Windows Server 2003 2 5 2 -
Windows Server 2003 R2 2 5 2 -
Windows Home Server 2 5 2 -
Windows Vista 2 6 0 -
Windows Server 2008 2 6 0 -
Windows 7 2 6 1 -
Windows Server 2008 R2 2 6 1 -
Windows 8 2 6 2 -
Windows Server 2012 2 6 2 -
Windows 8.1 2 6 2 -
Windows Server 2012 R2 2 6 2 -
Windows 10 2 10 0 -
Windows Server 2016 2 10 0 14393
Windows Server 2019 2 10 0 17677
```
On Windows NT 4 SP6 and later this function returns the following additional values: SPMAJOR, SPMINOR, SUITEMASK, PRODUCTTYPE.
The version numbers for Windows 2003 and Windows Home Server are identical; the SUITEMASK field must be used to differentiate between them.
The version numbers for Windows Vista and Windows Server 2008 are identical; the PRODUCTTYPE field must be used to differentiate between them.
The version numbers for Windows 7 and Windows Server 2008 R2 are identical; the PRODUCTTYPE field must be used to differentiate between them.
The version numbers for Windows 8 and Windows Server 2012 are identical; the PRODUCTTYPE field must be used to differentiate between them.
For modern Windows releases, the major and minor version numbers are identical. The PRODUCTTYPE field must be used to differentiate between Windows 10 and Server releases. The BUILD field is used to differentiate Windows Server versions: currently 2016, 2019, and Semi-Annual Channel releases.
SPMAJOR and SPMINOR are the version numbers of the latest installed service pack. (In the Windows 10 era, these are unused.)
SUITEMASK is a bitfield identifying the product suites available on the system. Known bits are:
```
VER_SUITE_SMALLBUSINESS 0x00000001
VER_SUITE_ENTERPRISE 0x00000002
VER_SUITE_BACKOFFICE 0x00000004
VER_SUITE_COMMUNICATIONS 0x00000008
VER_SUITE_TERMINAL 0x00000010
VER_SUITE_SMALLBUSINESS_RESTRICTED 0x00000020
VER_SUITE_EMBEDDEDNT 0x00000040
VER_SUITE_DATACENTER 0x00000080
VER_SUITE_SINGLEUSERTS 0x00000100
VER_SUITE_PERSONAL 0x00000200
VER_SUITE_BLADE 0x00000400
VER_SUITE_EMBEDDED_RESTRICTED 0x00000800
VER_SUITE_SECURITY_APPLIANCE 0x00001000
VER_SUITE_STORAGE_SERVER 0x00002000
VER_SUITE_COMPUTE_SERVER 0x00004000
VER_SUITE_WH_SERVER 0x00008000
VER_SUITE_MULTIUSERTS 0x00020000
```
The VER\_SUITE\_xxx names are listed here to cross reference the Microsoft documentation. The Win32 module does not provide symbolic names for these constants.
PRODUCTTYPE provides additional information about the system. It should be one of the following integer values:
```
1 - Workstation (NT 4, 2000 Pro, XP Home, XP Pro, Vista, etc)
2 - Domaincontroller
3 - Server (2000 Server, Server 2003, Server 2008, etc)
```
Note that a server that is also a domain controller is reported as PRODUCTTYPE 2 (Domaincontroller) and not PRODUCTTYPE 3 (Server).
Win32::GetShortPathName(PATHNAME) [CORE] Returns a representation of PATHNAME that is composed of short (8.3) path components where available. For path components where the file system has not generated the short form the returned path will use the long form, so this function might still for instance return a path containing spaces. Returns `undef` when the PATHNAME does not exist. Compare with Win32::GetFullPathName() and Win32::GetLongPathName().
Win32::GetSystemMetrics(INDEX) Retrieves the specified system metric or system configuration setting. Please refer to the Microsoft documentation of the GetSystemMetrics() function for a reference of available INDEX values. All system metrics return integer values.
Win32::GetProcAddress(INSTANCE, PROCNAME) Returns the address of a function inside a loaded library. The information about what you can do with this address has been lost in the mist of time. Use the Win32::API module instead of this deprecated function.
Win32::GetProcessPrivileges([PID]) Returns a reference to a hash holding the information about the privileges held by the specified process. The keys are privilege names, and the values are booleans indicating whether a given privilege is currently enabled or not.
If the optional PID parameter is omitted, the function queries the current process.
Example return value:
```
{
SeTimeZonePrivilege => 0,
SeShutdownPrivilege => 0,
SeUndockPrivilege => 0,
SeIncreaseWorkingSetPrivilege => 0,
SeChangeNotifyPrivilege => 1
}
```
Win32::GetProductInfo(OSMAJOR, OSMINOR, SPMAJOR, SPMINOR) Retrieves the product type for the operating system on the local computer, and maps the type to the product types supported by the specified operating system. Please refer to the Microsoft documentation of the GetProductInfo() function for more information about the parameters and return value. This function requires Windows Vista or later.
See also the Win32::GetOSName() and Win32::GetOSDisplayName() functions which provide a higher level abstraction of the data returned by this function.
Win32::GetTickCount() [CORE] Returns the number of milliseconds elapsed since the last system boot. Resolution is limited to system timer ticks (about 10ms on WinNT and 55ms on Win9X).
Win32::GuidGen() Creates a globally unique 128 bit integer that can be used as a persistent identifier in a distributed setting. To a very high degree of certainty this function returns a unique value. No other invocation, on the same or any other system (networked or not), should return the same value.
The return value is formatted according to OLE conventions, as groups of hex digits with surrounding braces. For example:
```
{09531CF1-D0C7-4860-840C-1C8C8735E2AD}
```
Win32::HttpGetFile(URL, FILENAME [, IGNORE\_CERT\_ERRORS]) Uses the WinHttp library to download the file specified by the URL parameter to the local file specified by FILENAME. The optional third parameter, if true, indicates that certficate errors are to be ignored for https connections; please use with caution in a safe environment, such as when testing locally using a self-signed certificate.
Only http and https protocols are supported. Authentication is not supported. The function is not available when building with gcc prior to 4.8.0 because the WinHttp library is not available.
In scalar context returns a boolean success or failure, and in list context also returns, in addition to the boolean status, a second value containing message text related to the status.
If the call fails, `Win32::GetLastError()` will return a numeric error code, which may be a system error, a WinHttp error, or a user-defined error composed of 1e9 plus the HTTP status code.
Scalar context example:
```
print Win32::GetLastError()
unless Win32::HttpGetFile('http://example.com/somefile.tar.gz',
'.\file.tgz');
```
List context example:
```
my ($ok, $msg) = Win32::HttpGetFile('http://example.com/somefile.tar.gz',
'.\file.tgz');
if ($ok) {
print "Success!: $msg\n";
}
else {
print "Failure!: $msg\n";
my $err = Win32::GetLastError();
if ($err > 1e9) {
printf "HTTP status: %d\n", ($err - 1e9);
}
}
```
Win32::InitiateSystemShutdown (MACHINE, MESSAGE, TIMEOUT, FORCECLOSE, REBOOT)
Shuts down the specified MACHINE, notifying users with the supplied MESSAGE, within the specified TIMEOUT interval. Forces closing of all documents without prompting the user if FORCECLOSE is true, and reboots the machine if REBOOT is true. This function works only on WinNT.
Win32::IsAdminUser() Returns non zero if the account in whose security context the current process/thread is running belongs to the local group of Administrators in the built-in system domain; returns 0 if not. On Windows Vista it will only return non-zero if the process is actually running with elevated privileges. Returns `undef` and prints a warning if an error occurred. This function always returns 1 on Win9X.
Win32::IsDeveloperModeEnabled() Returns true if the developer mode is currently enabled. It always returns false on Windows versions older than Windows 10.
Win32::IsSymlinkCreationAllowed() Returns true if the current process is allowed to create symbolic links. This function is a convenience wrapper around Win32::GetProcessPrivileges() and Win32::IsDeveloperModeEnabled().
Win32::IsWinNT() [CORE] Returns non zero if the Win32 subsystem is Windows NT.
Win32::IsWin95() [CORE] Returns non zero if the Win32 subsystem is Windows 95.
Win32::LoadLibrary(LIBNAME) Loads a dynamic link library into memory and returns its module handle. This handle can be used with Win32::GetProcAddress() and Win32::FreeLibrary(). This function is deprecated. Use the Win32::API module instead.
Win32::LoginName() [CORE] Returns the username of the owner of the current perl process. The return value may be a Unicode string.
Win32::LookupAccountName(SYSTEM, ACCOUNT, DOMAIN, SID, SIDTYPE) Looks up ACCOUNT on SYSTEM and returns the domain name the SID and the SID type.
Win32::LookupAccountSID(SYSTEM, SID, ACCOUNT, DOMAIN, SIDTYPE) Looks up SID on SYSTEM and returns the account name, domain name, and the SID type.
Win32::MsgBox(MESSAGE [, FLAGS [, TITLE]]) Create a dialog box containing MESSAGE. FLAGS specifies the required icon and buttons according to the following table:
```
0 = OK
1 = OK and Cancel
2 = Abort, Retry, and Ignore
3 = Yes, No and Cancel
4 = Yes and No
5 = Retry and Cancel
MB_ICONSTOP "X" in a red circle
MB_ICONQUESTION question mark in a bubble
MB_ICONEXCLAMATION exclamation mark in a yellow triangle
MB_ICONINFORMATION "i" in a bubble
```
TITLE specifies an optional window title. The default is "Perl".
The function returns the menu id of the selected push button:
```
0 Error
1 OK
2 Cancel
3 Abort
4 Retry
5 Ignore
6 Yes
7 No
```
Win32::NodeName() [CORE] Returns the Microsoft Network node-name of the current machine.
Win32::OutputDebugString(STRING) Sends a string to the application or system debugger for display. The function does nothing if there is no active debugger.
Alternatively one can use the *Debug Viewer* application to watch the OutputDebugString() output:
http://www.microsoft.com/technet/sysinternals/utilities/debugview.mspx
Win32::RegisterServer(LIBRARYNAME) Loads the DLL LIBRARYNAME and calls the function DllRegisterServer.
Win32::SetChildShowWindow(SHOWWINDOW) [CORE] Sets the *ShowMode* of child processes started by system(). By default system() will create a new console window for child processes if Perl itself is not running from a console. Calling SetChildShowWindow(0) will make these new console windows invisible. Calling SetChildShowWindow() without arguments reverts system() to the default behavior. The return value of SetChildShowWindow() is the previous setting or `undef`.
The following symbolic constants for SHOWWINDOW are available (but not exported) from the Win32 module: SW\_HIDE, SW\_SHOWNORMAL, SW\_SHOWMINIMIZED, SW\_SHOWMAXIMIZED and SW\_SHOWNOACTIVATE.
Win32::SetConsoleCP(ID) Sets the input code page used by the console associated with the calling process. The return value of SetConsoleCP() is nonzero on success or zero on failure. To get the console's input code page, see GetConsoleCP().
Win32::SetConsoleOutputCP(ID) Sets the output code page used by the console associated with the calling process. The return value of SetConsoleOutputCP() is nonzero on success or zero on failure. To get the console's output code page, see GetConsoleOutputCP().
Win32::SetCwd(NEWDIRECTORY) [CORE] Sets the current active drive and directory. This function does not work with UNC paths, since the functionality required to required for such a feature is not available under Windows 95.
Win32::SetLastError(ERROR) [CORE] Sets the value of the last error encountered to ERROR. This is that value that will be returned by the Win32::GetLastError() function.
Win32::Sleep(TIME) [CORE] Pauses for TIME milliseconds. The timeslices are made available to other processes and threads.
Win32::Spawn(COMMAND, ARGS, PID) [CORE] Spawns a new process using the supplied COMMAND, passing in arguments in the string ARGS. The pid of the new process is stored in PID. This function is deprecated. Please use the Win32::Process module instead.
Win32::UnregisterServer(LIBRARYNAME) Loads the DLL LIBRARYNAME and calls the function DllUnregisterServer.
CAVEATS
-------
###
Short Path Names
There are many situations in which modern Windows systems will not have the [short path name](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#short-vs-long-names) (also called 8.3 or MS-DOS) alias for long file names available.
Short path support can be configured system-wide via the registry, but the default on modern systems is to configure short path usage per volume. The configuration for a volume can be queried in a number of ways, but these may either be unreliable or require elevated (administrator) privileges.
Typically, the configuration for a volume can be queried using the `fsutil` utility, e.g. `fsutil 8dot3name query d:`. On the C level, it can be queried with a `FSCTL_QUERY_PERSISTENT_VOLUME_STATE` request to the `DeviceIOControl` API call, as described in [this article](https://www.codeproject.com/Articles/304374/Query-Volume-Setting-for-State-Windows). However, both of these methods require administrator privileges to work.
The Win32 module does not perform any per-volume check and simply fetches short path names in the same manner as the underlying Windows API call it uses: If short path names are disabled, the call will still succeed but the long name will actually be returned.
Note that on volumes where this happens, `GetANSIPathName` usually cannot be used to return useful filenames for files that contain unicode characters. (In code page 65001, this may still work.) Handling unicode filenames in this legacy manner relies upon `GetShortPathName` returning 8.3 filenames, but without short name support, it will return the filename with all unicode characters replaced by question mark characters.
| programming_docs |
perl bignum bignum
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Literal numeric constants](#Literal-numeric-constants)
+ [Upgrading and downgrading](#Upgrading-and-downgrading)
+ [Overloading](#Overloading)
+ [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
----
bignum - transparent big number support for Perl
SYNOPSIS
--------
```
use bignum;
$x = 2 + 4.5; # Math::BigFloat 6.5
print 2 ** 512 * 0.1; # Math::BigFloat 134...09.6
print 2 ** 512; # Math::BigInt 134...096
print inf + 42; # Math::BigInt inf
print NaN * 7; # Math::BigInt NaN
print hex("0x1234567890123490"); # Perl v5.10.0 or later
{
no bignum;
print 2 ** 256; # a normal Perl scalar now
}
# for older Perls, import into current package:
use bignum qw/hex oct/;
print hex("0x1234567890123490");
print oct("01234567890123490");
```
DESCRIPTION
-----------
###
Literal numeric constants
By default, every literal integer becomes a Math::BigInt object, and literal non-integer becomes a Math::BigFloat object. Whether a numeric literal is considered an integer or non-integers depends only on the value of the constant, not on how it is represented. For instance, the constants 3.14e2 and 0x1.3ap8 become Math::BigInt objects, because they both represent the integer value decimal 314.
The default `use bignum;` is equivalent to
```
use bignum downgrade => "Math::BigInt", upgrade => "Math::BigFloat";
```
The classes used for integers and non-integers can be set at compile time with the `downgrade` and `upgrade` options, for example
```
# use Math::BigInt for integers and Math::BigRat for non-integers
use bignum upgrade => "Math::BigRat";
```
Note that disabling downgrading and upgrading does not affect how numeric literals are converted to objects
```
# disable both downgrading and upgrading
use bignum downgrade => undef, upgrade => undef;
$x = 2.4; # becomes 2.4 as a Math::BigFloat
$y = 2; # becomes 2 as a Math::BigInt
```
###
Upgrading and downgrading
By default, when the result of a computation is an integer, an Inf, or a NaN, the result is downgraded even when all the operands are instances of the upgrade class.
```
use bignum;
$x = 2.4; # becomes 2.4 as a Math::BigFloat
$y = 1.2; # becomes 1.2 as a Math::BigFloat
$z = $x / $y; # becomes 2 as a Math::BigInt due to downgrading
```
Equivalently, by default, when the result of a computation is a finite non-integer, the result is upgraded even when all the operands are instances of the downgrade class.
```
use bignum;
$x = 7; # becomes 7 as a Math::BigInt
$y = 2; # becomes 2 as a Math::BigInt
$z = $x / $y; # becomes 3.5 as a Math::BigFloat due to upgrading
```
The classes used for downgrading and upgrading can be set at runtime with the ["downgrade()"](#downgrade%28%29) and ["upgrade()"](#upgrade%28%29) methods, but see ["CAVEATS"](#CAVEATS) below.
The upgrade and downgrade classes don't have to be Math::BigInt and Math::BigFloat. For example, to use Math::BigRat as the upgrade class, use
```
use bignum upgrade => "Math::BigRat";
$x = 2; # becomes 2 as a Math::BigInt
$y = 3.6; # becomes 18/5 as a Math::BigRat
```
The upgrade and downgrade classes can be modified at runtime
```
use bignum;
$x = 3; # becomes 3 as a Math::BigInt
$y = 2; # becomes 2 as a Math::BigInt
$z = $x / $y; # becomes 1.5 as a Math::BigFlaot
bignum -> upgrade("Math::BigRat");
$w = $x / $y; # becomes 3/2 as a Math::BigRat
```
Disabling downgrading doesn't change the fact that literal constant integers are converted to the downgrade class, it only prevents downgrading as a result of a computation. E.g.,
```
use bignum downgrade => undef;
$x = 2; # becomes 2 as a Math::BigInt
$y = 2.4; # becomes 2.4 as a Math::BigFloat
$z = 1.2; # becomes 1.2 as a Math::BigFloat
$w = $x / $y; # becomes 2 as a Math::BigFloat due to no downgrading
```
If you want all numeric literals, both integers and non-integers, to become Math::BigFloat objects, use the <bigfloat> pragma.
Equivalently, disabling upgrading doesn't change the fact that literal constant non-integers are converted to the upgrade class, it only prevents upgrading as a result of a computation. E.g.,
```
use bignum upgrade => undef;
$x = 2.5; # becomes 2.5 as a Math::BigFloat
$y = 7; # becomes 7 as a Math::BigInt
$z = 2; # becomes 2 as a Math::BigInt
$w = $x / $y; # becomes 3 as a Math::BigInt due to no upgrading
```
If you want all numeric literals, both integers and non-integers, to become Math::BigInt objects, use the <bigint> pragma.
You can even do
```
use bignum upgrade => "Math::BigRat", upgrade => undef;
```
which converts all integer literals to Math::BigInt objects and all non-integer literals to Math::BigRat objects. However, when the result of a computation involving two Math::BigInt objects results in a non-integer (e.g., 7/2), the result will be truncted to a Math::BigInt rather than being upgraded to a Math::BigRat, since upgrading is disabled.
### Overloading
Since all numeric literals become objects, you can call all the usual methods from Math::BigInt and Math::BigFloat on them. This even works to some extent on expressions:
```
perl -Mbignum -le '$x = 1234; print $x->bdec()'
perl -Mbignum -le 'print 1234->copy()->binc();'
perl -Mbignum -le 'print 1234->copy()->binc()->badd(6);'
```
### Options
`bignum` recognizes some options that can be passed while loading it via 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 -Mbignum=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 -Mbignum=p,-50 -le 'print sqrt(20)'
```
Note that setting precision and accuracy at the same time is not possible.
l, lib, try, or only Load a different math lib, see ["Math Library"](#Math-Library).
```
perl -Mbignum=l,GMP -e 'print 2 ** 512'
perl -Mbignum=lib,GMP -e 'print 2 ** 512'
perl -Mbignum=try,GMP -e 'print 2 ** 512'
perl -Mbignum=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 `bignum` 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 `bignum` pragma is active.
v or version this prints out the name and version of the modules and then exits.
```
perl -Mbignum=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 bignum lib => 'Calc';
```
you can change this by using:
```
use bignum 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 bignum lib => 'Foo,Math::BigInt::Bar';
```
Using c<lib> warns if none of the specified libraries can be found and <Math::BigInt> and <Math::BigFloat> fell back to one of the default libraries. To suppress this warning, use `try` instead:
```
use bignum try => 'GMP';
```
If you want the code to die instead of falling back, use `only` instead:
```
use bignum only => 'GMP';
```
Please see respective module documentation for further details.
###
Method calls
Since all numbers are now objects, you can use the methods that are part of the Math::BigInt and Math::BigFloat 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 `inf` as an object. Useful because Perl does not always handle bareword `inf` properly.
NaN() A shortcut to return `NaN` as an object. Useful because Perl does not always handle bareword `NaN` properly.
e
```
# perl -Mbignum=e -wle 'print e'
```
Returns Euler's number `e`, aka exp(1) (= 2.7182818284...).
PI
```
# perl -Mbignum=PI -wle 'print PI'
```
Returns PI (= 3.1415926532..).
bexp()
```
bexp($power, $accuracy);
```
Returns Euler's number `e` raised to the appropriate power, to the wanted accuracy.
Example:
```
# perl -Mbignum=bexp -wle 'print bexp(1,80)'
```
bpi()
```
bpi($accuracy);
```
Returns PI to the wanted accuracy.
Example:
```
# perl -Mbignum=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.
upgrade() Set or get the class that the downgrade class upgrades to, if any. Set the upgrade class to `undef` to disable upgrading. See `/CAVEATS` below.
downgrade() Set or get the class that the upgrade class downgrades to, if any. Set the downgrade class to `undef` to disable upgrading. See ["CAVEATS"](#CAVEATS) below.
in\_effect()
```
use bignum;
print "in effect\n" if bignum::in_effect; # true
{
no bignum;
print "in effect\n" if bignum::in_effect; # false
}
```
Returns true or false if `bignum` is in effect in the current scope.
This method only works on Perl v5.9.4 or later.
CAVEATS
-------
The upgrade() and downgrade() methods Note that setting both the upgrade and downgrade classes at runtime with the ["upgrade()"](#upgrade%28%29) and ["downgrade()"](#downgrade%28%29) methods, might not do what you expect:
```
# Assuming that downgrading and upgrading hasn't been modified so far, so
# the downgrade and upgrade classes are Math::BigInt and Math::BigFloat,
# respectively, the following sets the upgrade class to Math::BigRat, i.e.,
# makes Math::BigInt upgrade to Math::BigRat:
bignum -> upgrade("Math::BigRat");
# The following sets the downgrade class to Math::BigInt::Lite, i.e., makes
# the new upgrade class Math::BigRat downgrade to Math::BigInt::Lite
bignum -> downgrade("Math::BigInt::Lite");
# Note that at this point, it is still Math::BigInt, not Math::BigInt::Lite,
# that upgrades to Math::BigRat, so to get Math::BigInt::Lite to upgrade to
# Math::BigRat, we need to do the following (again):
bignum -> upgrade("Math::BigRat");
```
A simpler way to do this at runtime is to use import(),
```
bignum -> import(upgrade => "Math::BigRat",
downgrade => "Math::BigInt::Lite");
```
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 `bignum` never sees the string literals. To ensure the expression is all treated as `Math::BigFloat` 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 `bignum` endpoints, nor is the iterator variable a `Math::BigFloat`.
```
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() `bignum` 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 bignum`:
```
use bignum qw/hex oct/;
print hex("0x1234567890123456");
{
no bignum;
print hex("0x1234567890123456");
}
```
The second call to hex() will warn about a non-portable constant.
Compare this to:
```
use bignum;
# will warn only under Perl older than v5.9.4
print hex("0x1234567890123456");
```
EXAMPLES
--------
Some cool command line examples to impress the Python crowd ;)
```
perl -Mbignum -le 'print sqrt(33)'
perl -Mbignum -le 'print 2**255'
perl -Mbignum -le 'print 4.5+2**255'
perl -Mbignum -le 'print 3/7 + 5/7 + 8/3'
perl -Mbignum -le 'print 123->is_odd()'
perl -Mbignum -le 'print log(2)'
perl -Mbignum -le 'print exp(1)'
perl -Mbignum -le 'print 2 ** 0.5'
perl -Mbignum=a,65 -le 'print 2 ** 0.2'
perl -Mbignum=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 bignum
```
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
---------
<bigint> and <bigrat>.
<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-.
perl subs subs
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
subs - Perl pragma to predeclare subroutine names
SYNOPSIS
--------
```
use subs qw(frob);
frob 3..10;
```
DESCRIPTION
-----------
This will predeclare all the subroutines whose names are in the list, allowing you to use them without parentheses (as list operators) even before they're declared.
Unlike pragmas that affect the `$^H` hints variable, the `use vars` and `use subs` declarations are not lexically scoped to the block they appear in: they affect the entire package in which they appear. It is not possible to rescind these declarations with `no vars` or `no subs`.
See ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules) and ["strict subs" in strict](strict#strict-subs).
perl XS::APItest XS::APItest
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
+ [EXPORT](#EXPORT)
* [KEYWORDS](#KEYWORDS)
+ [RPN expression syntax](#RPN-expression-syntax)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
XS::APItest - Test the perl C API
SYNOPSIS
--------
```
use XS::APItest;
print_double(4);
use XS::APItest qw(rpn calcrpn);
$triangle = rpn($n $n 1 + * 2 /);
calcrpn $triangle { $n $n 1 + * 2 / }
```
ABSTRACT
--------
This module tests the perl C API. Also exposes various bit of the perl internals for the use of core test scripts.
DESCRIPTION
-----------
This module can be used to check that the perl C API is behaving correctly. This module provides test functions and an associated test script that verifies the output.
This module is not meant to be installed.
### EXPORT
Exports all the test functions:
**print\_double** Test that a double-precision floating point number is formatted correctly by `printf`.
```
print_double( $val );
```
Output is sent to STDOUT.
**print\_long\_double** Test that a `long double` is formatted correctly by `printf`. Takes no arguments - the test value is hard-wired into the function (as "7").
```
print_long_double();
```
Output is sent to STDOUT.
**have\_long\_double** Determine whether a `long double` is supported by Perl. This should be used to determine whether to test `print_long_double`.
```
print_long_double() if have_long_double;
```
**print\_nv** Test that an `NV` is formatted correctly by `printf`.
```
print_nv( $val );
```
Output is sent to STDOUT.
**print\_iv** Test that an `IV` is formatted correctly by `printf`.
```
print_iv( $val );
```
Output is sent to STDOUT.
**print\_uv** Test that an `UV` is formatted correctly by `printf`.
```
print_uv( $val );
```
Output is sent to STDOUT.
**print\_int** Test that an `int` is formatted correctly by `printf`.
```
print_int( $val );
```
Output is sent to STDOUT.
**print\_long** Test that an `long` is formatted correctly by `printf`.
```
print_long( $val );
```
Output is sent to STDOUT.
**print\_float** Test that a single-precision floating point number is formatted correctly by `printf`.
```
print_float( $val );
```
Output is sent to STDOUT.
**filter** Installs a source filter that substitutes "e" for "o" (witheut regard fer what it might be medifying).
**call\_sv**, **call\_pv**, **call\_method**
These exercise the C calls of the same names. Everything after the flags arg is passed as the args to the called function. They return whatever the C function itself pushed onto the stack, plus the return value from the function; for example
```
call_sv( sub { @_, 'c' }, G_LIST, 'a', 'b');
# returns 'a', 'b', 'c', 3
call_sv( sub { @_ }, G_SCALAR, 'a', 'b');
# returns 'b', 1
```
**eval\_sv** Evaluates the passed SV. Result handling is done the same as for `call_sv()` etc.
**eval\_pv** Exercises the C function of the same name in scalar context. Returns the same SV that the C function returns.
**require\_pv** Exercises the C function of the same name. Returns nothing.
KEYWORDS
--------
These are not supplied by default, but must be explicitly imported. They are lexically scoped.
DEFSV Behaves like `$_`.
rpn(EXPRESSION) This construct is a Perl expression. *EXPRESSION* must be an RPN arithmetic expression, as described below. The RPN expression is evaluated, and its value is returned as the value of the Perl expression.
calcrpn VARIABLE { EXPRESSION } This construct is a complete Perl statement. (No semicolon should follow the closing brace.) *VARIABLE* must be a Perl scalar `my` variable, and *EXPRESSION* must be an RPN arithmetic expression as described below. The RPN expression is evaluated, and its value is assigned to the variable.
###
RPN expression syntax
Tokens of an RPN expression may be separated by whitespace, but such separation is usually not required. It is required only where unseparated tokens would look like a longer token. For example, `12 34 +` can be written as `12 34+`, but not as `1234 +`.
An RPN expression may be any of:
`1234`
A sequence of digits is an unsigned decimal literal number.
`$foo`
An alphanumeric name preceded by dollar sign refers to a Perl scalar variable. Only variables declared with `my` or `state` are supported. If the variable's value is not a native integer, it will be converted to an integer, by Perl's usual mechanisms, at the time it is evaluated.
*A* *B* `+`
Sum of *A* and *B*.
*A* *B* `-`
Difference of *A* and *B*, the result of subtracting *B* from *A*.
*A* *B* `*`
Product of *A* and *B*.
*A* *B* `/`
Quotient when *A* is divided by *B*, rounded towards zero. Division by zero generates an exception.
*A* *B* `%`
Remainder when *A* is divided by *B* with the quotient rounded towards zero. Division by zero generates an exception.
Because the arithmetic operators all have fixed arity and are postfixed, there is no need for operator precedence, nor for a grouping operator to override precedence. This is half of the point of RPN.
An RPN expression can also be interpreted in another way, as a sequence of operations on a stack, one operation per token. A literal or variable token pushes a value onto the stack. A binary operator pulls two items off the stack, performs a calculation with them, and pushes the result back onto the stack. The stack starts out empty, and at the end of the expression there must be exactly one value left on the stack.
SEE ALSO
---------
<XS::Typemap>, <perlapi>.
AUTHORS
-------
Tim Jenness, <[email protected]>, Christian Soeller, <[email protected]>, Hugo van der Sanden <[email protected]>, Andrew Main (Zefram) <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2002,2004 Tim Jenness, Christian Soeller, Hugo van der Sanden. All Rights Reserved.
Copyright (C) 2009 Andrew Main (Zefram) <[email protected]>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Thread Thread
======
CONTENTS
--------
* [NAME](#NAME)
* [DEPRECATED](#DEPRECATED)
* [HISTORY](#HISTORY)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
* [METHODS](#METHODS)
* [DEFUNCT](#DEFUNCT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Thread - Manipulate threads in Perl (for old code only)
DEPRECATED
----------
The `Thread` module served as the frontend to the old-style thread model, called *5005threads*, that was introduced in release 5.005. That model was deprecated, and has been removed in version 5.10.
For old code and interim backwards compatibility, the `Thread` module has been reworked to function as a frontend for the new interpreter threads (*ithreads*) model. However, some previous functionality is not available. Further, the data sharing models between the two thread models are completely different, and anything to do with data sharing has to be thought differently. With *ithreads*, you must explicitly `share()` variables between the threads.
You are strongly encouraged to migrate any existing threaded code to the new model (i.e., use the `threads` and `threads::shared` modules) as soon as possible.
HISTORY
-------
In Perl 5.005, the thread model was that all data is implicitly shared, and shared access to data has to be explicitly synchronized. This model is called *5005threads*.
In Perl 5.6, a new model was introduced in which all is was thread local and shared access to data has to be explicitly declared. This model is called *ithreads*, for "interpreter threads".
In Perl 5.6, the *ithreads* model was not available as a public API; only as an internal API that was available for extension writers, and to implement fork() emulation on Win32 platforms.
In Perl 5.8, the *ithreads* model became available through the `threads` module, and the *5005threads* model was deprecated.
In Perl 5.10, the *5005threads* model was removed from the Perl interpreter.
SYNOPSIS
--------
```
use Thread qw(:DEFAULT async yield);
my $t = Thread->new(\&start_sub, @start_args);
$result = $t->join;
$t->detach;
if ($t->done) {
$t->join;
}
if($t->equal($another_thread)) {
# ...
}
yield();
my $tid = Thread->self->tid;
lock($scalar);
lock(@array);
lock(%hash);
my @list = Thread->list;
```
DESCRIPTION
-----------
The `Thread` module provides multithreading support for Perl.
FUNCTIONS
---------
$thread = Thread->new(\&start\_sub)
$thread = Thread->new(\&start\_sub, LIST) `new` starts a new thread of execution in the referenced subroutine. The optional list is passed as parameters to the subroutine. Execution continues in both the subroutine and the code after the `new` call.
`Thread->new` returns a thread object representing the newly created thread.
lock VARIABLE `lock` places a lock on a variable until the lock goes out of scope.
If the variable is locked by another thread, the `lock` call will block until it's available. `lock` is recursive, so multiple calls to `lock` are safe--the variable will remain locked until the outermost lock on the variable goes out of scope.
Locks on variables only affect `lock` calls--they do *not* affect normal access to a variable. (Locks on subs are different, and covered in a bit.) If you really, *really* want locks to block access, then go ahead and tie them to something and manage this yourself. This is done on purpose. While managing access to variables is a good thing, Perl doesn't force you out of its living room...
If a container object, such as a hash or array, is locked, all the elements of that container are not locked. For example, if a thread does a `lock @a`, any other thread doing a `lock($a[12])` won't block.
Finally, `lock` will traverse up references exactly *one* level. `lock(\$a)` is equivalent to `lock($a)`, while `lock(\\$a)` is not.
async BLOCK; `async` creates a thread to execute the block immediately following it. This block is treated as an anonymous sub, and so must have a semi-colon after the closing brace. Like `Thread->new`, `async` returns a thread object.
Thread->self The `Thread->self` function returns a thread object that represents the thread making the `Thread->self` call.
Thread->list Returns a list of all non-joined, non-detached Thread objects.
cond\_wait VARIABLE The `cond_wait` function takes a **locked** variable as a parameter, unlocks the variable, and blocks until another thread does a `cond_signal` or `cond_broadcast` for that same locked variable. The variable that `cond_wait` blocked on is relocked after the `cond_wait` is satisfied. If there are multiple threads `cond_wait`ing on the same variable, all but one will reblock waiting to re-acquire the lock on the variable. (So if you're only using `cond_wait` for synchronization, give up the lock as soon as possible.)
cond\_signal VARIABLE The `cond_signal` function takes a locked variable as a parameter and unblocks one thread that's `cond_wait`ing on that variable. If more than one thread is blocked in a `cond_wait` on that variable, only one (and which one is indeterminate) will be unblocked.
If there are no threads blocked in a `cond_wait` on the variable, the signal is discarded.
cond\_broadcast VARIABLE The `cond_broadcast` function works similarly to `cond_signal`. `cond_broadcast`, though, will unblock **all** the threads that are blocked in a `cond_wait` on the locked variable, rather than only one.
yield The `yield` function allows another thread to take control of the CPU. The exact results are implementation-dependent.
METHODS
-------
join `join` waits for a thread to end and returns any values the thread exited with. `join` will block until the thread has ended, though it won't block if the thread has already terminated.
If the thread being `join`ed `die`d, the error it died with will be returned at this time. If you don't want the thread performing the `join` to die as well, you should either wrap the `join` in an `eval` or use the `eval` thread method instead of `join`.
detach `detach` tells a thread that it is never going to be joined i.e. that all traces of its existence can be removed once it stops running. Errors in detached threads will not be visible anywhere - if you want to catch them, you should use $SIG{\_\_DIE\_\_} or something like that.
equal `equal` tests whether two thread objects represent the same thread and returns true if they do.
tid The `tid` method returns the tid of a thread. The tid is a monotonically increasing integer assigned when a thread is created. The main thread of a program will have a tid of zero, while subsequent threads will have tids assigned starting with one.
done The `done` method returns true if the thread you're checking has finished, and false otherwise.
DEFUNCT
-------
The following were implemented with *5005threads*, but are no longer available with *ithreads*.
lock(\&sub) With 5005threads, you could also `lock` a sub such that any calls to that sub from another thread would block until the lock was released.
Also, subroutines could be declared with the `:locked` attribute which would serialize access to the subroutine, but allowed different threads non-simultaneous access.
eval The `eval` method wrapped an `eval` around a `join`, and so waited for a thread to exit, passing along any values the thread might have returned and placing any errors into `$@`.
flags The `flags` method returned the flags for the thread - an integer value corresponding to the internal flags for the thread.
SEE ALSO
---------
<threads>, <threads::shared>, <Thread::Queue>, <Thread::Semaphore>
perl File::Spec::Cygwin File::Spec::Cygwin
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
File::Spec::Cygwin - methods for Cygwin file specs
SYNOPSIS
--------
```
require File::Spec::Cygwin; # 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.
This module is still in beta. Cygwin-knowledgeable folks are invited to offer patches and suggestions.
canonpath Any `\` (backslashes) are converted to `/` (forward slashes), and then File::Spec::Unix canonpath() is called on the result.
file\_name\_is\_absolute True is returned if the file name begins with `drive_letter:`, and if not, File::Spec::Unix file\_name\_is\_absolute() is called.
tmpdir (override) Returns a string representation of the first existing directory from the following list:
```
$ENV{TMPDIR}
/tmp
$ENV{'TMP'}
$ENV{'TEMP'}
C:/temp
```
If running under taint mode, and if the environment variables are tainted, they are not used.
case\_tolerant Override Unix. Cygwin case-tolerance depends on managed mount settings and as with MsWin32 on GetVolumeInformation() $ouFsFlags == FS\_CASE\_SENSITIVE, indicating the case significance when comparing file specifications. Default: 1
COPYRIGHT
---------
Copyright (c) 2004,2007 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 corelist corelist
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS](#OPTIONS)
* [EXAMPLES](#EXAMPLES)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
corelist - a commandline frontend to Module::CoreList
DESCRIPTION
-----------
See <Module::CoreList> for one.
SYNOPSIS
--------
```
corelist -v
corelist [-a|-d] <ModuleName> | /<ModuleRegex>/ [<ModuleVersion>] ...
corelist [-v <PerlVersion>] [ <ModuleName> | /<ModuleRegex>/ ] ...
corelist [-r <PerlVersion>] ...
corelist --utils [-d] <UtilityName> [<UtilityName>] ...
corelist --utils -v <PerlVersion>
corelist --feature <FeatureName> [<FeatureName>] ...
corelist --diff PerlVersion PerlVersion
corelist --upstream <ModuleName>
```
OPTIONS
-------
-a lists all versions of the given module (or the matching modules, in case you used a module regexp) in the perls Module::CoreList knows about.
```
corelist -a Unicode
Unicode was first released with perl v5.6.2
v5.6.2 3.0.1
v5.8.0 3.2.0
v5.8.1 4.0.0
v5.8.2 4.0.0
v5.8.3 4.0.0
v5.8.4 4.0.1
v5.8.5 4.0.1
v5.8.6 4.0.1
v5.8.7 4.1.0
v5.8.8 4.1.0
v5.8.9 5.1.0
v5.9.0 4.0.0
v5.9.1 4.0.0
v5.9.2 4.0.1
v5.9.3 4.1.0
v5.9.4 4.1.0
v5.9.5 5.0.0
v5.10.0 5.0.0
v5.10.1 5.1.0
v5.11.0 5.1.0
v5.11.1 5.1.0
v5.11.2 5.1.0
v5.11.3 5.2.0
v5.11.4 5.2.0
v5.11.5 5.2.0
v5.12.0 5.2.0
v5.12.1 5.2.0
v5.12.2 5.2.0
v5.12.3 5.2.0
v5.12.4 5.2.0
v5.13.0 5.2.0
v5.13.1 5.2.0
v5.13.2 5.2.0
v5.13.3 5.2.0
v5.13.4 5.2.0
v5.13.5 5.2.0
v5.13.6 5.2.0
v5.13.7 6.0.0
v5.13.8 6.0.0
v5.13.9 6.0.0
v5.13.10 6.0.0
v5.13.11 6.0.0
v5.14.0 6.0.0
v5.14.1 6.0.0
v5.15.0 6.0.0
```
-d finds the first perl version where a module has been released by date, and not by version number (as is the default).
--diff Given two versions of perl, this prints a human-readable table of all module changes between the two. The output format may change in the future, and is meant for *humans*, not programs. For programs, use the <Module::CoreList> API.
-? or -help help! help! help! to see more help, try --man.
-man all of the help
-v lists all of the perl release versions we got the CoreList for.
If you pass a version argument (value of `$]`, like `5.00503` or `5.008008`), you get a list of all the modules and their respective versions. (If you have the `version` module, you can also use new-style version numbers, like `5.8.8`.)
In module filtering context, it can be used as Perl version filter.
-r lists all of the perl releases and when they were released
If you pass a perl version you get the release date for that version only.
--utils lists the first version of perl each named utility program was released with
May be used with -d to modify the first release criteria.
If used with -v <version> then all utilities released with that version of perl are listed, and any utility programs named on the command line are ignored.
--feature, -f lists the first version bundle of each named feature given
--upstream, -u Shows if the given module is primarily maintained in perl core or on CPAN and bug tracker URL.
As a special case, if you specify the module name `Unicode`, you'll get the version number of the Unicode Character Database bundled with the requested perl versions.
EXAMPLES
--------
```
$ corelist File::Spec
File::Spec was first released with perl 5.005
$ corelist File::Spec 0.83
File::Spec 0.83 was released with perl 5.007003
$ corelist File::Spec 0.89
File::Spec 0.89 was not in CORE (or so I think)
$ corelist File::Spec::Aliens
File::Spec::Aliens was not in CORE (or so I think)
$ corelist /IPC::Open/
IPC::Open2 was first released with perl 5
IPC::Open3 was first released with perl 5
$ corelist /MANIFEST/i
ExtUtils::Manifest was first released with perl 5.001
$ corelist /Template/
/Template/ has no match in CORE (or so I think)
$ corelist -v 5.8.8 B
B 1.09_01
$ corelist -v 5.8.8 /^B::/
B::Asmdata 1.01
B::Assembler 0.07
B::Bblock 1.02_01
B::Bytecode 1.01_01
B::C 1.04_01
B::CC 1.00_01
B::Concise 0.66
B::Debug 1.02_01
B::Deparse 0.71
B::Disassembler 1.05
B::Lint 1.03
B::O 1.00
B::Showlex 1.02
B::Stackobj 1.00
B::Stash 1.00
B::Terse 1.03_01
B::Xref 1.01
```
COPYRIGHT
---------
Copyright (c) 2002-2007 by D.H. aka PodMaster
Currently maintained by the perl 5 porters <[email protected]>.
This program is distributed under the same terms as perl itself. See http://perl.org/ or http://cpan.org/ for more info on that.
perl TAP::Formatter::Session TAP::Formatter::Session
=======================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [header](#header)
- [result](#result)
- [close\_test](#close_test)
- [clear\_for\_close](#clear_for_close)
- [time\_report](#time_report)
NAME
----
TAP::Formatter::Session - Abstract base class for harness output delegate
VERSION
-------
Version 3.44
METHODS
-------
###
Class Methods
#### `new`
```
my %args = (
formatter => $self,
)
my $harness = TAP::Formatter::Console::Session->new( \%args );
```
The constructor returns a new `TAP::Formatter::Console::Session` object.
* `formatter`
* `parser`
* `name`
* `show_count`
#### `header`
Output test preamble
#### `result`
Called by the harness for each line of TAP it receives.
#### `close_test`
Called to close a test session.
#### `clear_for_close`
Called by `close_test` to clear the line showing test progress, or the parallel test ruler, prior to printing the final test result.
#### `time_report`
Return a formatted string about the elapsed (wall-clock) time and about the consumed CPU time.
perl ExtUtils::Typemaps::InputMap ExtUtils::Typemaps::InputMap
============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [code](#code)
+ [xstype](#xstype)
+ [cleaned\_code](#cleaned_code)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
ExtUtils::Typemaps::InputMap - Entry in the INPUT section of a typemap
SYNOPSIS
--------
```
use ExtUtils::Typemaps;
...
my $input = $typemap->get_input_map('T_NV');
my $code = $input->code();
$input->code("...");
```
DESCRIPTION
-----------
Refer to <ExtUtils::Typemaps> for details.
METHODS
-------
### new
Requires `xstype` and `code` parameters.
### code
Returns or sets the INPUT mapping code for this entry.
### xstype
Returns the name of the XS type of the INPUT map.
### cleaned\_code
Returns a cleaned-up copy of the code to which certain transformations have been applied to make it more ANSI compliant.
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 perlfaq4 perlfaq4
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [Data: Numbers](#Data:-Numbers)
+ [Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?](#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-is-int()-broken?)
+ [Why isn't my octal data interpreted correctly?](#Why-isn't-my-octal-data-interpreted-correctly?)
+ [Does Perl have a round() function? What about ceil() and floor()? Trig functions?](#Does-Perl-have-a-round()-function?-What-about-ceil()-and-floor()?-Trig-functions?)
+ [How do I convert between numeric representations/bases/radixes?](#How-do-I-convert-between-numeric-representations/bases/radixes?)
+ [Why doesn't & work the way I want it to?](#Why-doesn't-&-work-the-way-I-want-it-to?)
+ [How do I multiply matrices?](#How-do-I-multiply-matrices?)
+ [How do I perform an operation on a series of integers?](#How-do-I-perform-an-operation-on-a-series-of-integers?)
+ [How can I output Roman numerals?](#How-can-I-output-Roman-numerals?)
+ [Why aren't my random numbers random?](#Why-aren't-my-random-numbers-random?)
+ [How do I get a random number between X and Y?](#How-do-I-get-a-random-number-between-X-and-Y?)
* [Data: Dates](#Data:-Dates)
+ [How do I find the day or week of the year?](#How-do-I-find-the-day-or-week-of-the-year?)
+ [How do I find the current century or millennium?](#How-do-I-find-the-current-century-or-millennium?)
+ [How can I compare two dates and find the difference?](#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-take-a-string-and-turn-it-into-epoch-seconds?)
+ [How can I find the Julian Day?](#How-can-I-find-the-Julian-Day?)
+ [How do I find yesterday's date?](#How-do-I-find-yesterday's-date?)
+ [Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?](#Does-Perl-have-a-Year-2000-or-2038-problem?-Is-Perl-Y2K-compliant?)
* [Data: Strings](#Data:-Strings)
+ [How do I validate input?](#How-do-I-validate-input?)
+ [How do I unescape a string?](#How-do-I-unescape-a-string?)
+ [How do I remove consecutive pairs of characters?](#How-do-I-remove-consecutive-pairs-of-characters?)
+ [How do I expand function calls in a string?](#How-do-I-expand-function-calls-in-a-string?)
+ [How do I find matching/nesting anything?](#How-do-I-find-matching/nesting-anything?)
+ [How do I reverse a string?](#How-do-I-reverse-a-string?)
+ [How do I expand tabs in a string?](#How-do-I-expand-tabs-in-a-string?)
+ [How do I reformat a paragraph?](#How-do-I-reformat-a-paragraph?)
+ [How can I access or change N characters of a string?](#How-can-I-access-or-change-N-characters-of-a-string?)
+ [How do I change the Nth occurrence of something?](#How-do-I-change-the-Nth-occurrence-of-something?)
+ [How can I count the number of occurrences of a substring within a string?](#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-do-I-capitalize-all-the-words-on-one-line?)
+ [How can I split a [character]-delimited string except when inside [character]?](#How-can-I-split-a-%5Bcharacter%5D-delimited-string-except-when-inside-%5Bcharacter%5D?)
+ [How do I strip blank space from the beginning/end of a string?](#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-pad-a-string-with-blanks-or-pad-a-number-with-zeroes?)
+ [How do I extract selected columns from a string?](#How-do-I-extract-selected-columns-from-a-string?)
+ [How do I find the soundex value of a string?](#How-do-I-find-the-soundex-value-of-a-string?)
+ [How can I expand variables in text strings?](#How-can-I-expand-variables-in-text-strings?)
+ [Does Perl have anything like Ruby's #{} or Python's f string?](#Does-Perl-have-anything-like-Ruby's-%23%7B%7D-or-Python's-f-string?)
+ [What's wrong with always quoting "$vars"?](#What's-wrong-with-always-quoting-%22%24vars%22?)
+ [Why don't my <<HERE documents work?](#Why-don't-my-%3C%3CHERE-documents-work?)
* [Data: Arrays](#Data:-Arrays)
+ [What is the difference between a list and an array?](#What-is-the-difference-between-a-list-and-an-array?)
+ [What is the difference between $array[1] and @array[1]?](#What-is-the-difference-between-%24array%5B1%5D-and-@array%5B1%5D?)
+ [How can I remove duplicate elements from a list or array?](#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-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-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-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-find-the-first-array-element-for-which-a-condition-is-true?)
+ [How do I handle linked lists?](#How-do-I-handle-linked-lists?)
+ [How do I handle circular lists?](#How-do-I-handle-circular-lists?)
+ [How do I shuffle an array randomly?](#How-do-I-shuffle-an-array-randomly?)
+ [How do I process/modify each element of an array?](#How-do-I-process/modify-each-element-of-an-array?)
+ [How do I select a random element from an array?](#How-do-I-select-a-random-element-from-an-array?)
+ [How do I permute N elements of a list?](#How-do-I-permute-N-elements-of-a-list?)
+ [How do I sort an array by (anything)?](#How-do-I-sort-an-array-by-(anything)?)
+ [How do I manipulate arrays of bits?](#How-do-I-manipulate-arrays-of-bits?)
+ [Why does defined() return true on empty arrays and hashes?](#Why-does-defined()-return-true-on-empty-arrays-and-hashes?)
* [Data: Hashes (Associative Arrays)](#Data:-Hashes-(Associative-Arrays))
+ [How do I process an entire hash?](#How-do-I-process-an-entire-hash?)
+ [How do I merge two hashes?](#How-do-I-merge-two-hashes?)
+ [What happens if I add or remove keys from a hash while iterating over it?](#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-do-I-look-up-a-hash-element-by-value?)
+ [How can I know how many entries are in a hash?](#How-can-I-know-how-many-entries-are-in-a-hash?)
+ [How do I sort a hash (optionally by value instead of key)?](#How-do-I-sort-a-hash-(optionally-by-value-instead-of-key)?)
+ [How can I always keep my hash sorted?](#How-can-I-always-keep-my-hash-sorted?)
+ [What's the difference between "delete" and "undef" with hashes?](#What's-the-difference-between-%22delete%22-and-%22undef%22-with-hashes?)
+ [Why don't my tied hashes make the defined/exists distinction?](#Why-don't-my-tied-hashes-make-the-defined/exists-distinction?)
+ [How do I reset an each() operation part-way through?](#How-do-I-reset-an-each()-operation-part-way-through?)
+ [How can I get the unique keys from two hashes?](#How-can-I-get-the-unique-keys-from-two-hashes?)
+ [How can I store a multidimensional array in a DBM file?](#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?](#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?](#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-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-use-a-reference-as-a-hash-key?)
+ [How can I check if a key exists in a multilevel hash?](#How-can-I-check-if-a-key-exists-in-a-multilevel-hash?)
+ [How can I prevent addition of unwanted keys into a hash?](#How-can-I-prevent-addition-of-unwanted-keys-into-a-hash?)
* [Data: Misc](#Data:-Misc)
+ [How do I handle binary data correctly?](#How-do-I-handle-binary-data-correctly?)
+ [How do I determine whether a scalar is a number/whole/integer/float?](#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-keep-persistent-data-across-program-calls?)
+ [How do I print out or copy a recursive data structure?](#How-do-I-print-out-or-copy-a-recursive-data-structure?)
+ [How do I define methods for every class/object?](#How-do-I-define-methods-for-every-class/object?)
+ [How do I verify a credit card checksum?](#How-do-I-verify-a-credit-card-checksum?)
+ [How do I pack arrays of doubles or floats for XS code?](#How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq4 - Data Manipulation
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
This section of the FAQ answers questions related to manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
Data: Numbers
--------------
###
Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
For the long explanation, see David Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic" (<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).
Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl.
<perlnumber> shows the gory details of number representations and conversions.
To limit the number of decimal places in your numbers, you can use the `printf` or `sprintf` function. See ["Floating-point Arithmetic" in perlop](perlop#Floating-point-Arithmetic) for more details.
```
printf "%.2f", 10/3;
my $number = sprintf "%.2f", 10/3;
```
###
Why is int() broken?
Your `int()` is most probably working just fine. It's the numbers that aren't quite what you think.
First, see the answer to "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?".
For example, this
```
print int(0.6/0.2-2), "\n";
```
will in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot be presented exactly by floating-point numbers. What you think in the above as 'three' is really more like 2.9999999999999995559.
###
Why isn't my octal data interpreted correctly?
(contributed by brian d foy)
You're probably trying to convert a string to a number, which Perl only converts as a decimal number. When Perl converts a string to a number, it ignores leading spaces and zeroes, then assumes the rest of the digits are in base 10:
```
my $string = '0644';
print $string + 0; # prints 644
print $string + 44; # prints 688, certainly not octal!
```
This problem usually involves one of the Perl built-ins that has the same name a Unix command that uses octal numbers as arguments on the command line. In this example, `chmod` on the command line knows that its first argument is octal because that's what it does:
```
%prompt> chmod 644 file
```
If you want to use the same literal digits (644) in Perl, you have to tell Perl to treat them as octal numbers either by prefixing the digits with a `0` or using `oct`:
```
chmod( 0644, $filename ); # right, has leading zero
chmod( oct(644), $filename ); # also correct
```
The problem comes in when you take your numbers from something that Perl thinks is a string, such as a command line argument in `@ARGV`:
```
chmod( $ARGV[0], $filename ); # wrong, even if "0644"
chmod( oct($ARGV[0]), $filename ); # correct, treat string as octal
```
You can always check the value you're using by printing it in octal notation to ensure it matches what you think it should be. Print it in octal and decimal format:
```
printf "0%o %d", $number, $number;
```
###
Does Perl have a round() function? What about ceil() and floor()? Trig functions?
Remember that `int()` merely truncates toward 0. For rounding to a certain number of digits, `sprintf()` or `printf()` is usually the easiest route.
```
printf("%.3f", 3.1415926535); # prints 3.142
```
The [POSIX](posix) module (part of the standard Perl distribution) implements `ceil()`, `floor()`, and a number of other mathematical and trigonometric functions.
```
use POSIX;
my $ceil = ceil(3.5); # 4
my $floor = floor(3.5); # 3
```
In 5.000 to 5.003 perls, trigonometry was done in the <Math::Complex> module. With 5.004, the <Math::Trig> module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the <Math::Complex> module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2.
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 of rounding is being used by Perl, but instead to implement the rounding function you need yourself.
To see why, notice how you'll still have an issue on half-way-point alternation:
```
for (my $i = -5; $i <= 5; $i += 0.5) { printf "%.0f ",$i }
-5 -4 -4 -4 -3 -2 -2 -2 -1 -0 0 0 1 2 2 2 3 4 4 4 5
```
Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2\*\*31 (on 32-bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.
###
How do I convert between numeric representations/bases/radixes?
As always with Perl there is more than one way to do it. Below are a few examples of approaches to making common conversions between number representations. This is intended to be representational rather than exhaustive.
Some of the examples later in <perlfaq4> use the <Bit::Vector> module from CPAN. The reason you might choose <Bit::Vector> over the perl built-in functions is that it works with numbers of ANY size, that it is optimized for speed on some operations, and for at least some programmers the notation might be familiar.
How do I convert hexadecimal into decimal Using perl's built in conversion of `0x` notation:
```
my $dec = 0xDEADBEEF;
```
Using the `hex` function:
```
my $dec = hex("DEADBEEF");
```
Using `pack`:
```
my $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8)));
```
Using the CPAN module `Bit::Vector`:
```
use Bit::Vector;
my $vec = Bit::Vector->new_Hex(32, "DEADBEEF");
my $dec = $vec->to_Dec();
```
How do I convert from decimal to hexadecimal Using `sprintf`:
```
my $hex = sprintf("%X", 3735928559); # upper case A-F
my $hex = sprintf("%x", 3735928559); # lower case a-f
```
Using `unpack`:
```
my $hex = unpack("H*", pack("N", 3735928559));
```
Using <Bit::Vector>:
```
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $hex = $vec->to_Hex();
```
And <Bit::Vector> supports odd bit counts:
```
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(33, 3735928559);
$vec->Resize(32); # suppress leading 0 if unwanted
my $hex = $vec->to_Hex();
```
How do I convert from octal to decimal Using Perl's built in conversion of numbers with leading zeros:
```
my $dec = 033653337357; # note the leading 0!
```
Using the `oct` function:
```
my $dec = oct("33653337357");
```
Using <Bit::Vector>:
```
use Bit::Vector;
my $vec = Bit::Vector->new(32);
$vec->Chunk_List_Store(3, split(//, reverse "33653337357"));
my $dec = $vec->to_Dec();
```
How do I convert from decimal to octal Using `sprintf`:
```
my $oct = sprintf("%o", 3735928559);
```
Using <Bit::Vector>:
```
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $oct = reverse join('', $vec->Chunk_List_Read(3));
```
How do I convert from binary to decimal Perl 5.6 lets you write binary numbers directly with the `0b` notation:
```
my $number = 0b10110110;
```
Using `oct`:
```
my $input = "10110110";
my $decimal = oct( "0b$input" );
```
Using `pack` and `ord`:
```
my $decimal = ord(pack('B8', '10110110'));
```
Using `pack` and `unpack` for larger strings:
```
my $int = unpack("N", pack("B32",
substr("0" x 32 . "11110101011011011111011101111", -32)));
my $dec = sprintf("%d", $int);
# substr() is used to left-pad a 32-character string with zeros.
```
Using <Bit::Vector>:
```
my $vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111");
my $dec = $vec->to_Dec();
```
How do I convert from decimal to binary Using `sprintf` (perl 5.6+):
```
my $bin = sprintf("%b", 3735928559);
```
Using `unpack`:
```
my $bin = unpack("B*", pack("N", 3735928559));
```
Using <Bit::Vector>:
```
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $bin = $vec->to_Bin();
```
The remaining transformations (e.g. hex -> oct, bin -> hex, etc.) are left as an exercise to the inclined reader.
###
Why doesn't & work the way I want it to?
The behavior of binary arithmetic operators depends on whether they're used on numbers or strings. The operators treat a string as a series of bits and work with that (the string `"3"` is the bit pattern `00110011`). The operators work with the binary form of a number (the number `3` is treated as the bit pattern `00000011`).
So, saying `11 & 3` performs the "and" operation on numbers (yielding `3`). Saying `"11" & "3"` performs the "and" operation on strings (yielding `"1"`).
Most problems with `&` and `|` arise because the programmer thinks they have a number but really it's a string or vice versa. To avoid this, stringify the arguments explicitly (using `""` or `qq()`) or convert them to numbers explicitly (using `0+$arg`). The rest arise because the programmer says:
```
if ("\020\020" & "\101\101") {
# ...
}
```
but a string consisting of two null bytes (the result of `"\020\020" & "\101\101"`) is not a false value in Perl. You need:
```
if ( ("\020\020" & "\101\101") !~ /[^\000]/) {
# ...
}
```
###
How do I multiply matrices?
Use the <Math::Matrix> or <Math::MatrixReal> modules (available from CPAN) or the [PDL](pdl) extension (also available from CPAN).
###
How do I perform an operation on a series of integers?
To call a function on each element in an array, and collect the results, use:
```
my @results = map { my_func($_) } @array;
```
For example:
```
my @triple = map { 3 * $_ } @single;
```
To call a function on each element of an array, but ignore the results:
```
foreach my $iterator (@array) {
some_func($iterator);
}
```
To call a function on each integer in a (small) range, you **can** use:
```
my @results = map { some_func($_) } (5 .. 25);
```
but you should be aware that in this form, the `..` operator creates a list of all integers in the range, which can take a lot of memory for large ranges. However, the problem does not occur when using `..` within a `for` loop, because in that case the range operator is optimized to *iterate* over the range, without creating the entire list. So
```
my @results = ();
for my $i (5 .. 500_005) {
push(@results, some_func($i));
}
```
or even
```
push(@results, some_func($_)) for 5 .. 500_005;
```
will not create an intermediate list of 500,000 integers.
###
How can I output Roman numerals?
Get the <http://www.cpan.org/modules/by-module/Roman> module.
###
Why aren't my random numbers random?
If you're using a version of Perl before 5.004, you must call `srand` once at the start of your program to seed the random number generator.
```
BEGIN { srand() if $] < 5.004 }
```
5.004 and later automatically call `srand` at the beginning. Don't call `srand` more than once--you make your numbers less random, rather than more.
Computers are good at being predictable and bad at being random (despite appearances caused by bugs in your programs :-). The *random* article in the "Far More Than You Ever Wanted To Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy of Tom Phoenix, talks more about this. John von Neumann said, "Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin."
Perl relies on the underlying system for the implementation of `rand` and `srand`; on some systems, the generated numbers are not random enough (especially on Windows : see <http://www.perlmonks.org/?node_id=803632>). Several CPAN modules in the `Math` namespace implement better pseudorandom generators; see for example <Math::Random::MT> ("Mersenne Twister", fast), or <Math::TrulyRandom> (uses the imperfections in the system's timer to generate random numbers, which is rather slow). More algorithms for random numbers are described in "Numerical Recipes in C" at <http://www.nr.com/>
###
How do I get a random number between X and Y?
To get a random number between two values, you can use the `rand()` built-in to get a random number between 0 and 1. From there, you shift that into the range that you want.
`rand($x)` returns a number such that `0 <= rand($x) < $x`. Thus what you want to have perl figure out is a random number in the range from 0 to the difference between your *X* and *Y*.
That is, to get a number between 10 and 15, inclusive, you want a random number between 0 and 5 that you can then add to 10.
```
my $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )
```
Hence you derive the following simple function to abstract that. It selects a random integer between the two given integers (inclusive). For example: `random_int_between(50,120)`.
```
sub random_int_between {
my($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}
```
Data: Dates
------------
###
How do I find the day or week of the year?
The day of the year is in the list returned by the `localtime` function. Without an argument `localtime` uses the current time.
```
my $day_of_year = (localtime)[7];
```
The [POSIX](posix) module can also format a date as the day of the year or week of the year.
```
use POSIX qw/strftime/;
my $day_of_year = strftime "%j", localtime;
my $week_of_year = strftime "%W", localtime;
```
To get the day of year for any date, use [POSIX](posix)'s `mktime` to get a time in epoch seconds for the argument to `localtime`.
```
use POSIX qw/mktime strftime/;
my $week_of_year = strftime "%W",
localtime( mktime( 0, 0, 0, 18, 11, 87 ) );
```
You can also use <Time::Piece>, which comes with Perl and provides a `localtime` that returns an object:
```
use Time::Piece;
my $day_of_year = localtime->yday;
my $week_of_year = localtime->week;
```
The <Date::Calc> module provides two functions to calculate these, too:
```
use Date::Calc;
my $day_of_year = Day_of_Year( 1987, 12, 18 );
my $week_of_year = Week_of_Year( 1987, 12, 18 );
```
###
How do I find the current century or millennium?
Use the following simple functions:
```
sub get_century {
return int((((localtime(shift || time))[5] + 1999))/100);
}
sub get_millennium {
return 1+int((((localtime(shift || time))[5] + 1899))/1000);
}
```
On some systems, the [POSIX](posix) module's `strftime()` function has been extended in a non-standard way to use a `%C` format, which they sometimes claim is the "century". It isn't, because on most such systems, this is only the first two digits of the four-digit year, and thus cannot be used to determine reliably the current century or millennium.
###
How can I compare two dates and find the difference?
(contributed by brian d foy)
You could just store all your dates as a number and then subtract. Life isn't always that simple though.
The <Time::Piece> module, which comes with Perl, replaces <localtime> with a version that returns an object. It also overloads the comparison operators so you can compare them directly:
```
use Time::Piece;
my $date1 = localtime( $some_time );
my $date2 = localtime( $some_other_time );
if( $date1 < $date2 ) {
print "The date was in the past\n";
}
```
You can also get differences with a subtraction, which returns a <Time::Seconds> object:
```
my $date_diff = $date1 - $date2;
print "The difference is ", $date_diff->days, " days\n";
```
If you want to work with formatted dates, the <Date::Manip>, <Date::Calc>, or [DateTime](datetime) modules can help you.
###
How can I take a string and turn it into epoch seconds?
If it's a regular enough string that it always has the same format, you can split it up and pass the parts to `timelocal` in the standard <Time::Local> module. Otherwise, you should look into the <Date::Calc>, <Date::Parse>, and <Date::Manip> modules from CPAN.
###
How can I find the Julian Day?
(contributed by brian d foy and Dave Cross)
You can use the <Time::Piece> module, part of the Standard Library, which can convert a date/time to a Julian Day:
```
$ perl -MTime::Piece -le 'print localtime->julian_day'
2455607.7959375
```
Or the modified Julian Day:
```
$ perl -MTime::Piece -le 'print localtime->mjd'
55607.2961226851
```
Or even the day of the year (which is what some people think of as a Julian day):
```
$ perl -MTime::Piece -le 'print localtime->yday'
45
```
You can also do the same things with the [DateTime](datetime) module:
```
$ perl -MDateTime -le'print DateTime->today->jd'
2453401.5
$ perl -MDateTime -le'print DateTime->today->mjd'
53401
$ perl -MDateTime -le'print DateTime->today->doy'
31
```
You can use the <Time::JulianDay> module available on CPAN. Ensure that you really want to find a Julian day, though, as many people have different ideas about Julian days (see <http://www.hermetic.ch/cal_stud/jdn.htm> for instance):
```
$ perl -MTime::JulianDay -le 'print local_julian_day( time )'
55608
```
###
How do I find yesterday's date?
(contributed by brian d foy)
To do it correctly, you can use one of the `Date` modules since they work with calendars instead of times. The [DateTime](datetime) module makes it simple, and give you the same time of day, only the day before, despite daylight saving time changes:
```
use DateTime;
my $yesterday = DateTime->now->subtract( days => 1 );
print "Yesterday was $yesterday\n";
```
You can also use the <Date::Calc> module using its `Today_and_Now` function.
```
use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 );
print "@date_time\n";
```
Most people try to use the time rather than the calendar to figure out dates, but that assumes that days are twenty-four hours each. For most people, there are two days a year when they aren't: the switch to and from summer time throws this off. For example, the rest of the suggestions will be wrong sometimes:
Starting with Perl 5.10, <Time::Piece> and <Time::Seconds> are part of the standard distribution, so you might think that you could do something like this:
```
use Time::Piece;
use Time::Seconds;
my $yesterday = localtime() - ONE_DAY; # WRONG
print "Yesterday was $yesterday\n";
```
The <Time::Piece> module exports a new `localtime` that returns an object, and <Time::Seconds> exports the `ONE_DAY` constant that is a set number of seconds. This means that it always gives the time 24 hours ago, which is not always yesterday. This can cause problems around the end of daylight saving time when there's one day that is 25 hours long.
You have the same problem with <Time::Local>, which will give the wrong answer for those same special cases:
```
# contributed by Gunnar Hjalmarsson
use Time::Local;
my $today = timelocal 0, 0, 12, ( localtime )[3..5];
my ($d, $m, $y) = ( localtime $today-86400 )[3..5]; # WRONG
printf "Yesterday: %d-%02d-%02d\n", $y+1900, $m+1, $d;
```
###
Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?
(contributed by brian d foy)
Perl itself never had a Y2K problem, although that never stopped people from creating Y2K problems on their own. See the documentation for `localtime` for its proper use.
Starting with Perl 5.12, `localtime` and `gmtime` can handle dates past 03:14:08 January 19, 2038, when a 32-bit based time would overflow. You still might get a warning on a 32-bit `perl`:
```
% perl5.12 -E 'say scalar localtime( 0x9FFF_FFFFFFFF )'
Integer overflow in hexadecimal number at -e line 1.
Wed Nov 1 19:42:39 5576711
```
On a 64-bit `perl`, you can get even larger dates for those really long running projects:
```
% perl5.12 -E 'say scalar gmtime( 0x9FFF_FFFFFFFF )'
Thu Nov 2 00:42:39 5576711
```
You're still out of luck if you need to keep track of decaying protons though.
Data: Strings
--------------
###
How do I validate input?
(contributed by brian d foy)
There are many ways to ensure that values are what you expect or want to accept. Besides the specific examples that we cover in the perlfaq, you can also look at the modules with "Assert" and "Validate" in their names, along with other modules such as <Regexp::Common>.
Some modules have validation for particular types of input, such as <Business::ISBN>, <Business::CreditCard>, <Email::Valid>, and <Data::Validate::IP>.
###
How do I unescape a string?
It depends just what you mean by "escape". URL escapes are dealt with in <perlfaq9>. Shell escapes with the backslash (`\`) character are removed with
```
s/\\(.)/$1/g;
```
This won't expand `"\n"` or `"\t"` or any other special escapes.
###
How do I remove consecutive pairs of characters?
(contributed by brian d foy)
You can use the substitution operator to find pairs of characters (or runs of characters) and replace them with a single instance. In this substitution, we find a character in `(.)`. The memory parentheses store the matched character in the back-reference `\g1` and we use that to require that the same thing immediately follow it. We replace that part of the string with the character in `$1`.
```
s/(.)\g1/$1/g;
```
We can also use the transliteration operator, `tr///`. In this example, the search list side of our `tr///` contains nothing, but the `c` option complements that so it contains everything. The replacement list also contains nothing, so the transliteration is almost a no-op since it won't do any replacements (or more exactly, replace the character with itself). However, the `s` option squashes duplicated and consecutive characters in the string so a character does not show up next to itself
```
my $str = 'Haarlem'; # in the Netherlands
$str =~ tr///cs; # Now Harlem, like in New York
```
###
How do I expand function calls in a string?
(contributed by brian d foy)
This is documented in <perlref>, and although it's not the easiest thing to read, it does work. In each of these examples, we call the function inside the braces used to dereference a reference. If we have more than one return value, we can construct and dereference an anonymous array. In this case, we call the function in list context.
```
print "The time values are @{ [localtime] }.\n";
```
If we want to call the function in scalar context, we have to do a bit more work. We can really have any code we like inside the braces, so we simply have to end with the scalar reference, although how you do that is up to you, and you can use code inside the braces. Note that the use of parens creates a list context, so we need `scalar` to force the scalar context on the function:
```
print "The time is ${\(scalar localtime)}.\n"
print "The time is ${ my $x = localtime; \$x }.\n";
```
If your function already returns a reference, you don't need to create the reference yourself.
```
sub timestamp { my $t = localtime; \$t }
print "The time is ${ timestamp() }.\n";
```
The `Interpolation` module can also do a lot of magic for you. You can specify a variable name, in this case `E`, to set up a tied hash that does the interpolation for you. It has several other methods to do this as well.
```
use Interpolation E => 'eval';
print "The time values are $E{localtime()}.\n";
```
In most cases, it is probably easier to simply use string concatenation, which also forces scalar context.
```
print "The time is " . localtime() . ".\n";
```
###
How do I find matching/nesting anything?
To find something between two single characters, a pattern like `/x([^x]*)x/` will get the intervening bits in $1. For multiple ones, then something more like `/alpha(.*?)omega/` would be needed. For nested patterns and/or balanced expressions, see the so-called [(?PARNO)](perlre#%28%3FPARNO%29-%28%3F-PARNO%29-%28%3F%2BPARNO%29-%28%3FR%29-%28%3F0%29) construct (available since perl 5.10). The CPAN module <Regexp::Common> can help to build such regular expressions (see in particular <Regexp::Common::balanced> and <Regexp::Common::delimited>).
More complex cases will require to write a parser, probably using a parsing module from CPAN, like <Regexp::Grammars>, <Parse::RecDescent>, <Parse::Yapp>, <Text::Balanced>, or <Marpa::R2>.
###
How do I reverse a string?
Use `reverse()` in scalar context, as documented in ["reverse" in perlfunc](perlfunc#reverse).
```
my $reversed = reverse $string;
```
###
How do I expand tabs in a string?
You can do it yourself:
```
1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
```
Or you can just use the <Text::Tabs> module (part of the standard Perl distribution).
```
use Text::Tabs;
my @expanded_lines = expand(@lines_with_tabs);
```
###
How do I reformat a paragraph?
Use <Text::Wrap> (part of the standard Perl distribution):
```
use Text::Wrap;
print wrap("\t", ' ', @paragraphs);
```
The paragraphs you give to <Text::Wrap> should not contain embedded newlines. <Text::Wrap> doesn't justify the lines (flush-right).
Or use the CPAN module <Text::Autoformat>. Formatting files can be easily done by making a shell alias, like so:
```
alias fmt="perl -i -MText::Autoformat -n0777 \
-e 'print autoformat $_, {all=>1}' $*"
```
See the documentation for <Text::Autoformat> to appreciate its many capabilities.
###
How can I access or change N characters of a string?
You can access the first characters of a string with substr(). To get the first character, for example, start at position 0 and grab the string of length 1.
```
my $string = "Just another Perl Hacker";
my $first_char = substr( $string, 0, 1 ); # 'J'
```
To change part of a string, you can use the optional fourth argument which is the replacement string.
```
substr( $string, 13, 4, "Perl 5.8.0" );
```
You can also use substr() as an lvalue.
```
substr( $string, 13, 4 ) = "Perl 5.8.0";
```
###
How do I change the Nth occurrence of something?
You have to keep track of N yourself. For example, let's say you want to change the fifth occurrence of `"whoever"` or `"whomever"` into `"whosoever"` or `"whomsoever"`, case insensitively. These all assume that $\_ contains the string to be altered.
```
$count = 0;
s{((whom?)ever)}{
++$count == 5 # is it the 5th?
? "${2}soever" # yes, swap
: $1 # renege and leave it there
}ige;
```
In the more general case, you can use the `/g` modifier in a `while` loop, keeping count of matches.
```
$WANT = 3;
$count = 0;
$_ = "One fish two fish red fish blue fish";
while (/(\w+)\s+fish\b/gi) {
if (++$count == $WANT) {
print "The third fish is a $1 one.\n";
}
}
```
That prints out: `"The third fish is a red one."` You can also use a repetition count and repeated pattern like this:
```
/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;
```
###
How can I count the number of occurrences of a substring within a string?
There are a number of ways, with varying efficiency. If you want a count of a certain single character (X) within a string, you can use the `tr///` function like so:
```
my $string = "ThisXlineXhasXsomeXx'sXinXit";
my $count = ($string =~ tr/X//);
print "There are $count X characters in the string";
```
This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a larger string, `tr///` won't work. What you can do is wrap a while() loop around a global pattern match. For example, let's count negative integers:
```
my $string = "-9 55 48 -2 23 -76 4 14 -44";
my $count = 0;
while ($string =~ /-\d+/g) { $count++ }
print "There are $count negative numbers in the string";
```
Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches.
```
my $count = () = $string =~ /-\d+/g;
```
###
How do I capitalize all the words on one line?
(contributed by brian d foy)
Damian Conway's <Text::Autoformat> handles all of the thinking for you.
```
use Text::Autoformat;
my $x = "Dr. Strangelove or: How I Learned to Stop ".
"Worrying and Love the Bomb";
print $x, "\n";
for my $style (qw( sentence title highlight )) {
print autoformat($x, { case => $style }), "\n";
}
```
How do you want to capitalize those words?
```
FRED AND BARNEY'S LODGE # all uppercase
Fred And Barney's Lodge # title case
Fred and Barney's Lodge # highlight case
```
It's not as easy a problem as it looks. How many words do you think are in there? Wait for it... wait for it.... If you answered 5 you're right. Perl words are groups of `\w+`, but that's not what you want to capitalize. How is Perl supposed to know not to capitalize that `s` after the apostrophe? You could try a regular expression:
```
$string =~ s/ (
(^\w) #at the beginning of the line
| # or
(\s\w) #preceded by whitespace
)
/\U$1/xg;
$string =~ s/([\w']+)/\u\L$1/g;
```
Now, what if you don't want to capitalize that "and"? Just use <Text::Autoformat> and get on with the next problem. :)
###
How can I split a [character]-delimited string except when inside [character]?
Several modules can handle this sort of parsing--<Text::Balanced>, <Text::CSV>, <Text::CSV_XS>, and <Text::ParseWords>, among others.
Take the example case of trying to split a string that is comma-separated into its different fields. You can't use `split(/,/)` because you shouldn't split if the comma is inside quotes. For example, take a data line like this:
```
SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
```
Due to the restriction of the quotes, this is a fairly complex problem. Thankfully, we have Jeffrey Friedl, author of *Mastering Regular Expressions*, to handle these for us. He suggests (assuming your string is contained in `$text`):
```
my @new = ();
push(@new, $+) while $text =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
| ([^,]+),?
| ,
}gx;
push(@new, undef) if substr($text,-1,1) eq ',';
```
If you want to represent quotation marks inside a quotation-mark-delimited field, escape them with backslashes (eg, `"like \"this\""`.
Alternatively, the <Text::ParseWords> module (part of the standard Perl distribution) lets you say:
```
use Text::ParseWords;
@new = quotewords(",", 0, $text);
```
For parsing or generating CSV, though, using <Text::CSV> rather than implementing it yourself is highly recommended; you'll save yourself odd bugs popping up later by just using code which has already been tried and tested in production for years.
###
How do I strip blank space from the beginning/end of a string?
(contributed by brian d foy)
A substitution can do this for you. For a single line, you want to replace all the leading or trailing whitespace with nothing. You can do that with a pair of substitutions:
```
s/^\s+//;
s/\s+$//;
```
You can also write that as a single substitution, although it turns out the combined statement is slower than the separate ones. That might not matter to you, though:
```
s/^\s+|\s+$//g;
```
In this regular expression, the alternation matches either at the beginning or the end of the string since the anchors have a lower precedence than the alternation. With the `/g` flag, the substitution makes all possible matches, so it gets both. Remember, the trailing newline matches the `\s+`, and the `$` anchor can match to the absolute end of the string, so the newline disappears too. Just add the newline to the output, which has the added benefit of preserving "blank" (consisting entirely of whitespace) lines which the `^\s+` would remove all by itself:
```
while( <> ) {
s/^\s+|\s+$//g;
print "$_\n";
}
```
For a multi-line string, you can apply the regular expression to each logical line in the string by adding the `/m` flag (for "multi-line"). With the `/m` flag, the `$` matches *before* an embedded newline, so it doesn't remove it. This pattern still removes the newline at the end of the string:
```
$string =~ s/^\s+|\s+$//gm;
```
Remember that lines consisting entirely of whitespace will disappear, since the first part of the alternation can match the entire string and replace it with nothing. If you need to keep embedded blank lines, you have to do a little more work. Instead of matching any whitespace (since that includes a newline), just match the other whitespace:
```
$string =~ s/^[\t\f ]+|[\t\f ]+$//mg;
```
###
How do I pad a string with blanks or pad a number with zeroes?
In the following examples, `$pad_len` is the length to which you wish to pad the string, `$text` or `$num` contains the string to be padded, and `$pad_char` contains the padding character. You can use a single character string constant instead of the `$pad_char` variable if you know what it is in advance. And in the same way you can use an integer in place of `$pad_len` if you know the pad length in advance.
The simplest method uses the `sprintf` function. It can pad on the left or right with blanks and on the left with zeroes and it will not truncate the result. The `pack` function can only pad strings on the right with blanks and it will truncate the result to a maximum length of `$pad_len`.
```
# Left padding a string with blanks (no truncation):
my $padded = sprintf("%${pad_len}s", $text);
my $padded = sprintf("%*s", $pad_len, $text); # same thing
# Right padding a string with blanks (no truncation):
my $padded = sprintf("%-${pad_len}s", $text);
my $padded = sprintf("%-*s", $pad_len, $text); # same thing
# Left padding a number with 0 (no truncation):
my $padded = sprintf("%0${pad_len}d", $num);
my $padded = sprintf("%0*d", $pad_len, $num); # same thing
# Right padding a string with blanks using pack (will truncate):
my $padded = pack("A$pad_len",$text);
```
If you need to pad with a character other than blank or zero you can use one of the following methods. They all generate a pad string with the `x` operator and combine that with `$text`. These methods do not truncate `$text`.
Left and right padding with any character, creating a new string:
```
my $padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
my $padded = $text . $pad_char x ( $pad_len - length( $text ) );
```
Left and right padding with any character, modifying `$text` directly:
```
substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
$text .= $pad_char x ( $pad_len - length( $text ) );
```
###
How do I extract selected columns from a string?
(contributed by brian d foy)
If you know the columns that contain the data, you can use `substr` to extract a single column.
```
my $column = substr( $line, $start_column, $length );
```
You can use `split` if the columns are separated by whitespace or some other delimiter, as long as whitespace or the delimiter cannot appear as part of the data.
```
my $line = ' fred barney betty ';
my @columns = split /\s+/, $line;
# ( '', 'fred', 'barney', 'betty' );
my $line = 'fred||barney||betty';
my @columns = split /\|/, $line;
# ( 'fred', '', 'barney', '', 'betty' );
```
If you want to work with comma-separated values, don't do this since that format is a bit more complicated. Use one of the modules that handle that format, such as <Text::CSV>, <Text::CSV_XS>, or <Text::CSV_PP>.
If you want to break apart an entire line of fixed columns, you can use `unpack` with the A (ASCII) format. By using a number after the format specifier, you can denote the column width. See the `pack` and `unpack` entries in <perlfunc> for more details.
```
my @fields = unpack( $line, "A8 A8 A8 A16 A4" );
```
Note that spaces in the format argument to `unpack` do not denote literal spaces. If you have space separated data, you may want `split` instead.
###
How do I find the soundex value of a string?
(contributed by brian d foy)
You can use the `Text::Soundex` module. If you want to do fuzzy or close matching, you might also try the <String::Approx>, and <Text::Metaphone>, and <Text::DoubleMetaphone> modules.
###
How can I expand variables in text strings?
(contributed by brian d foy)
If you can avoid it, don't, or if you can use a templating system, such as <Text::Template> or [Template](template) Toolkit, do that instead. You might even be able to get the job done with `sprintf` or `printf`:
```
my $string = sprintf 'Say hello to %s and %s', $foo, $bar;
```
However, for the one-off simple case where I don't want to pull out a full templating system, I'll use a string that has two Perl scalar variables in it. In this example, I want to expand `$foo` and `$bar` to their variable's values:
```
my $foo = 'Fred';
my $bar = 'Barney';
$string = 'Say hello to $foo and $bar';
```
One way I can do this involves the substitution operator and a double `/e` flag. The first `/e` evaluates `$1` on the replacement side and turns it into `$foo`. The second /e starts with `$foo` and replaces it with its value. `$foo`, then, turns into 'Fred', and that's finally what's left in the string:
```
$string =~ s/(\$\w+)/$1/eeg; # 'Say hello to Fred and Barney'
```
The `/e` will also silently ignore violations of strict, replacing undefined variable names with the empty string. Since I'm using the `/e` flag (twice even!), I have all of the same security problems I have with `eval` in its string form. If there's something odd in `$foo`, perhaps something like `@{[ system "rm -rf /" ]}`, then I could get myself in trouble.
To get around the security problem, I could also pull the values from a hash instead of evaluating variable names. Using a single `/e`, I can check the hash to ensure the value exists, and if it doesn't, I can replace the missing value with a marker, in this case `???` to signal that I missed something:
```
my $string = 'This has $foo and $bar';
my %Replacements = (
foo => 'Fred',
);
# $string =~ s/\$(\w+)/$Replacements{$1}/g;
$string =~ s/\$(\w+)/
exists $Replacements{$1} ? $Replacements{$1} : '???'
/eg;
print $string;
```
###
Does Perl have anything like Ruby's #{} or Python's f string?
Unlike the others, Perl allows you to embed a variable naked in a double quoted string, e.g. `"variable $variable"`. When there isn't whitespace or other non-word characters following the variable name, you can add braces (e.g. `"foo ${foo}bar"`) to ensure correct parsing.
An array can also be embedded directly in a string, and will be expanded by default with spaces between the elements. The default [LIST\_SEPARATOR](perlvar#%24LIST_SEPARATOR) can be changed by assigning a different string to the special variable `$"`, such as `local $" = ', ';`.
Perl also supports references within a string providing the equivalent of the features in the other two languages.
`${\ ... }` embedded within a string will work for most simple statements such as an object->method call. More complex code can be wrapped in a do block `${\ do{...} }`.
When you want a list to be expanded per `$"`, use `@{[ ... ]}`.
```
use Time::Piece;
use Time::Seconds;
my $scalar = 'STRING';
my @array = ( 'zorro', 'a', 1, 'B', 3 );
# Print the current date and time and then Tommorrow
my $t = Time::Piece->new;
say "Now is: ${\ $t->cdate() }";
say "Tomorrow: ${\ do{ my $T=Time::Piece->new + ONE_DAY ; $T->fullday }}";
# some variables in strings
say "This is some scalar I have $scalar, this is an array @array.";
say "You can also write it like this ${scalar} @{array}.";
# Change the $LIST_SEPARATOR
local $" = ':';
say "Set \$\" to delimit with ':' and sort the Array @{[ sort @array ]}";
```
You may also want to look at the module <Quote::Code>, and templating tools such as <Template::Toolkit> and <Mojo::Template>.
See also: ["How can I expand variables in text strings?"](#How-can-I-expand-variables-in-text-strings%3F) and ["How do I expand function calls in a string?"](#How-do-I-expand-function-calls-in-a-string%3F) in this FAQ.
###
What's wrong with always quoting "$vars"?
The problem is that those double-quotes force stringification--coercing numbers and references into strings--even when you don't want them to be strings. Think of it this way: double-quote expansion is used to produce new strings. If you already have a string, why do you need more?
If you get used to writing odd things like these:
```
print "$var"; # BAD
my $new = "$old"; # BAD
somefunc("$var"); # BAD
```
You'll be in trouble. Those should (in 99.8% of the cases) be the simpler and more direct:
```
print $var;
my $new = $old;
somefunc($var);
```
Otherwise, besides slowing you down, you're going to break code when the thing in the scalar is actually neither a string nor a number, but a reference:
```
func(\@array);
sub func {
my $aref = shift;
my $oref = "$aref"; # WRONG
}
```
You can also get into subtle problems on those few operations in Perl that actually do care about the difference between a string and a number, such as the magical `++` autoincrement operator or the syscall() function.
Stringification also destroys arrays.
```
my @lines = `command`;
print "@lines"; # WRONG - extra blanks
print @lines; # right
```
###
Why don't my <<HERE documents work?
Here documents are found in <perlop>. Check for these three things:
There must be no space after the << part.
There (probably) should be a semicolon at the end of the opening token
You can't (easily) have any space in front of the tag.
There needs to be at least a line separator after the end token. If you want to indent the text in the here document, you can do this:
```
# all in one
(my $VAR = <<HERE_TARGET) =~ s/^\s+//gm;
your text
goes here
HERE_TARGET
```
But the HERE\_TARGET must still be flush against the margin. If you want that indented also, you'll have to quote in the indentation.
```
(my $quote = <<' FINIS') =~ s/^\s+//gm;
...we will have peace, when you and all your works have
perished--and the works of your dark master to whom you
would deliver us. You are a liar, Saruman, and a corrupter
of men's hearts. --Theoden in /usr/src/perl/taint.c
FINIS
$quote =~ s/\s+--/\n--/;
```
A nice general-purpose fixer-upper function for indented here documents follows. It expects to be called with a here document as its argument. It looks to see whether each line begins with a common substring, and if so, strips that substring off. Otherwise, it takes the amount of leading whitespace found on the first line and removes that much off each subsequent line.
```
sub fix {
local $_ = shift;
my ($white, $leader); # common whitespace and common leading string
if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\g1\g2?.*\n)+$/) {
($white, $leader) = ($2, quotemeta($1));
} else {
($white, $leader) = (/^(\s+)/, '');
}
s/^\s*?$leader(?:$white)?//gm;
return $_;
}
```
This works with leading special strings, dynamically determined:
```
my $remember_the_main = fix<<' MAIN_INTERPRETER_LOOP';
@@@ int
@@@ runops() {
@@@ SAVEI32(runlevel);
@@@ runlevel++;
@@@ while ( op = (*op->op_ppaddr)() );
@@@ TAINT_NOT;
@@@ return 0;
@@@ }
MAIN_INTERPRETER_LOOP
```
Or with a fixed amount of leading whitespace, with remaining indentation correctly preserved:
```
my $poem = fix<<EVER_ON_AND_ON;
Now far ahead the Road has gone,
And I must follow, if I can,
Pursuing it with eager feet,
Until it joins some larger way
Where many paths and errands meet.
And whither then? I cannot say.
--Bilbo in /usr/src/perl/pp_ctl.c
EVER_ON_AND_ON
```
Beginning with Perl version 5.26, a much simpler and cleaner way to write indented here documents has been added to the language: the tilde (~) modifier. See ["Indented Here-docs" in perlop](perlop#Indented-Here-docs) for details.
Data: Arrays
-------------
###
What is the difference between a list and an array?
(contributed by brian d foy)
A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars. An array can supply its collection for list operations, so list operations also work on arrays:
```
# slices
( 'dog', 'cat', 'bird' )[2,3];
@animals[2,3];
# iteration
foreach ( qw( dog cat bird ) ) { ... }
foreach ( @animals ) { ... }
my @three = grep { length == 3 } qw( dog cat bird );
my @three = grep { length == 3 } @animals;
# supply an argument list
wash_animals( qw( dog cat bird ) );
wash_animals( @animals );
```
Array operations, which change the scalars, rearrange them, or add or subtract some scalars, only work on arrays. These can't work on a list, which is fixed. Array operations include `shift`, `unshift`, `push`, `pop`, and `splice`.
An array can also change its length:
```
$#animals = 1; # truncate to two elements
$#animals = 10000; # pre-extend to 10,001 elements
```
You can change an array element, but you can't change a list element:
```
$animals[0] = 'Rottweiler';
qw( dog cat bird )[0] = 'Rottweiler'; # syntax error!
foreach ( @animals ) {
s/^d/fr/; # works fine
}
foreach ( qw( dog cat bird ) ) {
s/^d/fr/; # Error! Modification of read only value!
}
```
However, if the list element is itself a variable, it appears that you can change a list element. However, the list element is the variable, not the data. You're not changing the list element, but something the list element refers to. The list element itself doesn't change: it's still the same variable.
You also have to be careful about context. You can assign an array to a scalar to get the number of elements in the array. This only works for arrays, though:
```
my $count = @animals; # only works with arrays
```
If you try to do the same thing with what you think is a list, you get a quite different result. Although it looks like you have a list on the righthand side, Perl actually sees a bunch of scalars separated by a comma:
```
my $scalar = ( 'dog', 'cat', 'bird' ); # $scalar gets bird
```
Since you're assigning to a scalar, the righthand side is in scalar context. The comma operator (yes, it's an operator!) in scalar context evaluates its lefthand side, throws away the result, and evaluates it's righthand side and returns the result. In effect, that list-lookalike assigns to `$scalar` it's rightmost value. Many people mess this up because they choose a list-lookalike whose last element is also the count they expect:
```
my $scalar = ( 1, 2, 3 ); # $scalar gets 3, accidentally
```
###
What is the difference between $array[1] and @array[1]?
(contributed by brian d foy)
The difference is the sigil, that special character in front of the array name. The `$` sigil means "exactly one item", while the `@` sigil means "zero or more items". The `$` gets you a single scalar, while the `@` gets you a list.
The confusion arises because people incorrectly assume that the sigil denotes the variable type.
The `$array[1]` is a single-element access to the array. It's going to return the item in index 1 (or undef if there is no item there). If you intend to get exactly one element from the array, this is the form you should use.
The `@array[1]` is an array slice, although it has only one index. You can pull out multiple elements simultaneously by specifying additional indices as a list, like `@array[1,4,3,0]`.
Using a slice on the lefthand side of the assignment supplies list context to the righthand side. This can lead to unexpected results. For instance, if you want to read a single line from a filehandle, assigning to a scalar value is fine:
```
$array[1] = <STDIN>;
```
However, in list context, the line input operator returns all of the lines as a list. The first line goes into `@array[1]` and the rest of the lines mysteriously disappear:
```
@array[1] = <STDIN>; # most likely not what you want
```
Either the `use warnings` pragma or the **-w** flag will warn you when you use an array slice with a single index.
###
How can I remove duplicate elements from a list or array?
(contributed by brian d foy)
Use a hash. When you think the words "unique" or "duplicated", think "hash keys".
If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use `keys` to get the unique elements.
```
my %hash = map { $_, 1 } @array;
# or a hash slice: @hash{ @array } = ();
# or a foreach: $hash{$_} = 1 foreach ( @array );
my @unique = keys %hash;
```
If you want to use a module, try the `uniq` function from <List::MoreUtils>. In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements.
```
use List::MoreUtils qw(uniq);
my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7
my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7
```
You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in `%Seen`. The `next` statement creates the key and immediately uses its value, which is `undef`, so the loop continues to the `push` and increments the value for that key. The next time the loop sees that same element, its key exists in the hash *and* the value for that key is true (since it's not 0 or `undef`), so the next skips that iteration and the loop goes to the next element.
```
my @unique = ();
my %seen = ();
foreach my $elem ( @array ) {
next if $seen{ $elem }++;
push @unique, $elem;
}
```
You can write this more briefly using a grep, which does the same thing.
```
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @array;
```
###
How can I tell whether a certain element is contained in a list or array?
(portions of this answer contributed by Anno Siegel and brian d foy)
Hearing the word "in" is an *in*dication that you probably should have used a hash, not a list or array, to store your data. Hashes are designed to answer this question quickly and efficiently. Arrays aren't.
That being said, there are several ways to approach this. If you are going to make this query many times over arbitrary string values, the fastest way is probably to invert the original array and maintain a hash whose keys are the first array's values:
```
my @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
my %is_blue = ();
for (@blues) { $is_blue{$_} = 1 }
```
Now you can check whether `$is_blue{$some_color}`. It might have been a good idea to keep the blues all in a hash in the first place.
If the values are all small integers, you could use a simple indexed array. This kind of an array will take up less space:
```
my @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
my @is_tiny_prime = ();
for (@primes) { $is_tiny_prime[$_] = 1 }
# or simply @istiny_prime[@primes] = (1) x @primes;
```
Now you check whether $is\_tiny\_prime[$some\_number].
If the values in question are integers instead of strings, you can save quite a lot of space by using bit strings instead:
```
my @articles = ( 1..10, 150..2000, 2017 );
undef $read;
for (@articles) { vec($read,$_,1) = 1 }
```
Now check whether `vec($read,$n,1)` is true for some `$n`.
These methods guarantee fast individual tests but require a re-organization of the original list or array. They only pay off if you have to test multiple values against the same array.
If you are testing only once, the standard module <List::Util> exports the function `any` for this purpose. It works by stopping once it finds the element. It's written in C for speed, and its Perl equivalent looks like this subroutine:
```
sub any (&@) {
my $code = shift;
foreach (@_) {
return 1 if $code->();
}
return 0;
}
```
If speed is of little concern, the common idiom uses grep in scalar context (which returns the number of items that passed its condition) to traverse the entire list. This does have the benefit of telling you how many matches it found, though.
```
my $is_there = grep $_ eq $whatever, @array;
```
If you want to actually extract the matching elements, simply use grep in list context.
```
my @matches = grep $_ eq $whatever, @array;
```
###
How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array:
```
my (@union, @intersection, @difference);
my %count = ();
foreach my $element (@array1, @array2) { $count{$element}++ }
foreach my $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
```
Note that this is the *symmetric difference*, that is, all elements in either A or in B but not in both. Think of it as an xor operation.
###
How do I test whether two arrays or hashes are equal?
The following code works for single-level arrays. It uses a stringwise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs.
```
$are_equal = compare_arrays(\@frogs, \@toads);
sub compare_arrays {
my ($first, $second) = @_;
no warnings; # silence spurious -w undef complaints
return 0 unless @$first == @$second;
for (my $i = 0; $i < @$first; $i++) {
return 0 if $first->[$i] ne $second->[$i];
}
return 1;
}
```
For multilevel structures, you may wish to use an approach more like this one. It uses the CPAN module [FreezeThaw](freezethaw):
```
use FreezeThaw qw(cmpStr);
my @a = my @b = ( "this", "that", [ "more", "stuff" ] );
printf "a and b contain %s arrays\n",
cmpStr(\@a, \@b) == 0
? "the same"
: "different";
```
This approach also works for comparing hashes. Here we'll demonstrate two different answers:
```
use FreezeThaw qw(cmpStr cmpStrHard);
my %a = my %b = ( "this" => "that", "extra" => [ "more", "stuff" ] );
$a{EXTRA} = \%b;
$b{EXTRA} = \%a;
printf "a and b contain %s hashes\n",
cmpStr(\%a, \%b) == 0 ? "the same" : "different";
printf "a and b contain %s hashes\n",
cmpStrHard(\%a, \%b) == 0 ? "the same" : "different";
```
The first reports that both those the hashes contain the same data, while the second reports that they do not. Which you prefer is left as an exercise to the reader.
###
How do I find the first array element for which a condition is true?
To find the first array element which satisfies a condition, you can use the `first()` function in the <List::Util> module, which comes with Perl 5.8. This example finds the first element that contains "Perl".
```
use List::Util qw(first);
my $element = first { /Perl/ } @array;
```
If you cannot use <List::Util>, you can make your own loop to do the same thing. Once you find the element, you stop the loop with last.
```
my $found;
foreach ( @array ) {
if( /Perl/ ) { $found = $_; last }
}
```
If you want the array index, use the `firstidx()` function from `List::MoreUtils`:
```
use List::MoreUtils qw(firstidx);
my $index = firstidx { /Perl/ } @array;
```
Or write it yourself, iterating through the indices and checking the array element at each index until you find one that satisfies the condition:
```
my( $found, $index ) = ( undef, -1 );
for( $i = 0; $i < @array; $i++ ) {
if( $array[$i] =~ /Perl/ ) {
$found = $array[$i];
$index = $i;
last;
}
}
```
###
How do I handle linked lists?
(contributed by brian d foy)
Perl's arrays do not have a fixed size, so you don't need linked lists if you just want to add or remove items. You can use array operations such as `push`, `pop`, `shift`, `unshift`, or `splice` to do that.
Sometimes, however, linked lists can be useful in situations where you want to "shard" an array so you have many small arrays instead of a single big array. You can keep arrays longer than Perl's largest array index, lock smaller arrays separately in threaded programs, reallocate less memory, or quickly insert elements in the middle of the chain.
Steve Lembark goes through the details in his YAPC::NA 2009 talk "Perly Linked Lists" ( <http://www.slideshare.net/lembark/perly-linked-lists> ), although you can just use his <LinkedList::Single> module.
###
How do I handle circular lists?
(contributed by brian d foy)
If you want to cycle through an array endlessly, you can increment the index modulo the number of elements in the array:
```
my @array = qw( a b c );
my $i = 0;
while( 1 ) {
print $array[ $i++ % @array ], "\n";
last if $i > 20;
}
```
You can also use <Tie::Cycle> to use a scalar that always has the next element of the circular array:
```
use Tie::Cycle;
tie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];
print $cycle; # FFFFFF
print $cycle; # 000000
print $cycle; # FFFF00
```
The <Array::Iterator::Circular> creates an iterator object for circular arrays:
```
use Array::Iterator::Circular;
my $color_iterator = Array::Iterator::Circular->new(
qw(red green blue orange)
);
foreach ( 1 .. 20 ) {
print $color_iterator->next, "\n";
}
```
###
How do I shuffle an array randomly?
If you either have Perl 5.8.0 or later installed, or if you have Scalar-List-Utils 1.03 or later installed, you can say:
```
use List::Util 'shuffle';
@shuffled = shuffle(@list);
```
If not, you can use a Fisher-Yates shuffle.
```
sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to an array
return unless @$deck; # must not be empty!
my $i = @$deck;
while (--$i) {
my $j = int rand ($i+1);
@$deck[$i,$j] = @$deck[$j,$i];
}
}
# shuffle my mpeg collection
#
my @mpeg = <audio/*/*.mp3>;
fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
print @mpeg;
```
Note that the above implementation shuffles an array in place, unlike the `List::Util::shuffle()` which takes a list and returns a new shuffled list.
You've probably seen shuffling algorithms that work using splice, randomly picking another element to swap the current element with
```
srand;
@new = ();
@old = 1 .. 10; # just a demo
while (@old) {
push(@new, splice(@old, rand @old, 1));
}
```
This is bad because splice is already O(N), and since you do it N times, you just invented a quadratic algorithm; that is, O(N\*\*2). This does not scale, although Perl is so efficient that you probably won't notice this until you have rather largish arrays.
###
How do I process/modify each element of an array?
Use `for`/`foreach`:
```
for (@lines) {
s/foo/bar/; # change that word
tr/XZ/ZX/; # swap those letters
}
```
Here's another; let's compute spherical volumes:
```
my @volumes = @radii;
for (@volumes) { # @volumes has changed parts
$_ **= 3;
$_ *= (4/3) * 3.14159; # this will be constant folded
}
```
which can also be done with `map()` which is made to transform one list into another:
```
my @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;
```
If you want to do the same thing to modify the values of the hash, you can use the `values` function. As of Perl 5.6 the values are not copied, so if you modify $orbit (in this case), you modify the value.
```
for my $orbit ( values %orbits ) {
($orbit **= 3) *= (4/3) * 3.14159;
}
```
Prior to perl 5.6 `values` returned copies of the values, so older perl code often contains constructions such as `@orbits{keys %orbits}` instead of `values %orbits` where the hash is to be modified.
###
How do I select a random element from an array?
Use the `rand()` function (see ["rand" in perlfunc](perlfunc#rand)):
```
my $index = rand @array;
my $element = $array[$index];
```
Or, simply:
```
my $element = $array[ rand @array ];
```
###
How do I permute N elements of a list?
Use the <List::Permutor> module on CPAN. If the list is actually an array, try the <Algorithm::Permute> module (also on CPAN). It's written in XS code and is very efficient:
```
use Algorithm::Permute;
my @array = 'a'..'d';
my $p_iterator = Algorithm::Permute->new ( \@array );
while (my @perm = $p_iterator->next) {
print "next permutation: (@perm)\n";
}
```
For even faster execution, you could do:
```
use Algorithm::Permute;
my @array = 'a'..'d';
Algorithm::Permute::permute {
print "next permutation: (@array)\n";
} @array;
```
Here's a little program that generates all permutations of all the words on each line of input. The algorithm embodied in the `permute()` function is discussed in Volume 4 (still unpublished) of Knuth's *The Art of Computer Programming* and will work on any list:
```
#!/usr/bin/perl -n
# Fischer-Krause ordered permutation generator
sub permute (&@) {
my $code = shift;
my @idx = 0..$#_;
while ( $code->(@_[@idx]) ) {
my $p = $#idx;
--$p while $idx[$p-1] > $idx[$p];
my $q = $p or return;
push @idx, reverse splice @idx, $p;
++$q while $idx[$p-1] > $idx[$q];
@idx[$p-1,$q]=@idx[$q,$p-1];
}
}
permute { print "@_\n" } split;
```
The <Algorithm::Loops> module also provides the `NextPermute` and `NextPermuteNum` functions which efficiently find all unique permutations of an array, even if it contains duplicate values, modifying it in-place: if its elements are in reverse-sorted order then the array is reversed, making it sorted, and it returns false; otherwise the next permutation is returned.
`NextPermute` uses string order and `NextPermuteNum` numeric order, so you can enumerate all the permutations of `0..9` like this:
```
use Algorithm::Loops qw(NextPermuteNum);
my @list= 0..9;
do { print "@list\n" } while NextPermuteNum @list;
```
###
How do I sort an array by (anything)?
Supply a comparison function to sort() (described in ["sort" in perlfunc](perlfunc#sort)):
```
@list = sort { $a <=> $b } @list;
```
The default sort function is cmp, string comparison, which would sort `(1, 2, 10)` into `(1, 10, 2)`. `<=>`, used above, is the numerical comparison operator.
If you have a complicated function needed to pull out the part you want to sort on, then don't do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the same element. Here's an example of how to pull out the first word after the first number on each item, and then sort those words case-insensitively.
```
my @idx;
for (@data) {
my $item;
($item) = /\d+\s*(\S+)/;
push @idx, uc($item);
}
my @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
```
which could also be written this way, using a trick that's come to be known as the Schwartzian Transform:
```
my @sorted = map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;
```
If you need to sort on several fields, the following paradigm is useful.
```
my @sorted = sort {
field1($a) <=> field1($b) ||
field2($a) cmp field2($b) ||
field3($a) cmp field3($b)
} @data;
```
This can be conveniently combined with precalculation of keys as given above.
See the *sort* article in the "Far More Than You Ever Wanted To Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for more about this approach.
See also the question later in <perlfaq4> on sorting hashes.
###
How do I manipulate arrays of bits?
Use `pack()` and `unpack()`, or else `vec()` and the bitwise operations.
For example, you don't have to store individual bits in an array (which would mean that you're wasting a lot of space). To convert an array of bits to a string, use `vec()` to set the right bits. This sets `$vec` to have bit N set only if `$ints[N]` was set:
```
my @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )
my $vec = '';
foreach( 0 .. $#ints ) {
vec($vec,$_,1) = 1 if $ints[$_];
}
```
The string `$vec` only takes up as many bits as it needs. For instance, if you had 16 entries in `@ints`, `$vec` only needs two bytes to store them (not counting the scalar variable overhead).
Here's how, given a vector in `$vec`, you can get those bits into your `@ints` array:
```
sub bitvec_to_list {
my $vec = shift;
my @ints;
# Find null-byte density then select best algorithm
if ($vec =~ tr/\0// / length $vec > 0.95) {
use integer;
my $i;
# This method is faster with mostly null-bytes
while($vec =~ /[^\0]/g ) {
$i = -9 + 8 * pos $vec;
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
}
}
else {
# This method is a fast general algorithm
use integer;
my $bits = unpack "b*", $vec;
push @ints, 0 if $bits =~ s/^(\d)// && $1;
push @ints, pos $bits while($bits =~ /1/g);
}
return \@ints;
}
```
This method gets faster the more sparse the bit vector is. (Courtesy of Tim Bunce and Winfried Koenig.)
You can make the while loop a lot shorter with this suggestion from Benjamin Goldberg:
```
while($vec =~ /[^\0]+/g ) {
push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
}
```
Or use the CPAN module <Bit::Vector>:
```
my $vector = Bit::Vector->new($num_of_bits);
$vector->Index_List_Store(@ints);
my @ints = $vector->Index_List_Read();
```
<Bit::Vector> provides efficient methods for bit vector, sets of small integers and "big int" math.
Here's a more extensive illustration using vec():
```
# vec demo
my $vector = "\xff\x0f\xef\xfe";
print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ",
unpack("N", $vector), "\n";
my $is_set = vec($vector, 23, 1);
print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n";
pvec($vector);
set_vec(1,1,1);
set_vec(3,1,1);
set_vec(23,1,1);
set_vec(3,1,3);
set_vec(3,2,3);
set_vec(3,4,3);
set_vec(3,4,7);
set_vec(3,8,3);
set_vec(3,8,7);
set_vec(0,32,17);
set_vec(1,32,17);
sub set_vec {
my ($offset, $width, $value) = @_;
my $vector = '';
vec($vector, $offset, $width) = $value;
print "offset=$offset width=$width value=$value\n";
pvec($vector);
}
sub pvec {
my $vector = shift;
my $bits = unpack("b*", $vector);
my $i = 0;
my $BASE = 8;
print "vector length in bytes: ", length($vector), "\n";
@bytes = unpack("A8" x length($vector), $bits);
print "bits are: @bytes\n\n";
}
```
###
Why does defined() return true on empty arrays and hashes?
The short story is that you should probably only use defined on scalars or functions, not on aggregates (arrays and hashes). See ["defined" in perlfunc](perlfunc#defined) in the 5.004 release or later of Perl for more detail.
Data: Hashes (Associative Arrays)
----------------------------------
###
How do I process an entire hash?
(contributed by brian d foy)
There are a couple of ways that you can process an entire hash. You can get a list of keys, then go through each key, or grab a one key-value pair at a time.
To go through all of the keys, use the `keys` function. This extracts all of the keys of the hash and gives them back to you as a list. You can then get the value through the particular key you're processing:
```
foreach my $key ( keys %hash ) {
my $value = $hash{$key}
...
}
```
Once you have the list of keys, you can process that list before you process the hash elements. For instance, you can sort the keys so you can process them in lexical order:
```
foreach my $key ( sort keys %hash ) {
my $value = $hash{$key}
...
}
```
Or, you might want to only process some of the items. If you only want to deal with the keys that start with `text:`, you can select just those using `grep`:
```
foreach my $key ( grep /^text:/, keys %hash ) {
my $value = $hash{$key}
...
}
```
If the hash is very large, you might not want to create a long list of keys. To save some memory, you can grab one key-value pair at a time using `each()`, which returns a pair you haven't seen yet:
```
while( my( $key, $value ) = each( %hash ) ) {
...
}
```
The `each` operator returns the pairs in apparently random order, so if ordering matters to you, you'll have to stick with the `keys` method.
The `each()` operator can be a bit tricky though. You can't add or delete keys of the hash while you're using it without possibly skipping or re-processing some pairs after Perl internally rehashes all of the elements. Additionally, a hash has only one iterator, so if you mix `keys`, `values`, or `each` on the same hash, you risk resetting the iterator and messing up your processing. See the `each` entry in <perlfunc> for more details.
###
How do I merge two hashes?
(contributed by brian d foy)
Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.
If you want to preserve the original hashes, copy one hash (`%hash1`) to a new hash (`%new_hash`), then add the keys from the other hash (`%hash2` to the new hash. Checking that the key already exists in `%new_hash` gives you a chance to decide what to do with the duplicates:
```
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 ) {
if( exists $new_hash{$key2} ) {
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else {
$new_hash{$key2} = $hash2{$key2};
}
}
```
If you don't want to create a new hash, you can still use this looping technique; just change the `%new_hash` to `%hash1`.
```
foreach my $key2 ( keys %hash2 ) {
if( exists $hash1{$key2} ) {
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else {
$hash1{$key2} = $hash2{$key2};
}
}
```
If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from `%hash2` replace values from `%hash1` when they have keys in common:
```
@hash1{ keys %hash2 } = values %hash2;
```
###
What happens if I add or remove keys from a hash while iterating over it?
(contributed by brian d foy)
The easy answer is "Don't do that!"
If you iterate through the hash with each(), you can delete the key most recently returned without worrying about it. If you delete or add other keys, the iterator may skip or double up on them since perl may rearrange the hash table. See the entry for `each()` in <perlfunc>.
###
How do I look up a hash element by value?
Create a reverse hash:
```
my %by_value = reverse %by_key;
my $key = $by_value{$value};
```
That's not particularly efficient. It would be more space-efficient to use:
```
while (my ($key, $value) = each %by_key) {
$by_value{$value} = $key;
}
```
If your hash could have repeated values, the methods above will only find one of the associated keys. This may or may not worry you. If it does worry you, you can always reverse the hash into a hash of arrays instead:
```
while (my ($key, $value) = each %by_key) {
push @{$key_list_by_value{$value}}, $key;
}
```
###
How can I know how many entries are in a hash?
(contributed by brian d foy)
This is very similar to "How do I process an entire hash?", also in <perlfaq4>, but a bit simpler in the common cases.
You can use the `keys()` built-in function in scalar context to find out have many entries you have in a hash:
```
my $key_count = keys %hash; # must be scalar context!
```
If you want to find out how many entries have a defined value, that's a bit different. You have to check each value. A `grep` is handy:
```
my $defined_value_count = grep { defined } values %hash;
```
You can use that same structure to count the entries any way that you like. If you want the count of the keys with vowels in them, you just test for that instead:
```
my $vowel_count = grep { /[aeiou]/ } keys %hash;
```
The `grep` in scalar context returns the count. If you want the list of matching items, just use it in list context instead:
```
my @defined_values = grep { defined } values %hash;
```
The `keys()` function also resets the iterator, which means that you may see strange results if you use this between uses of other hash operators such as `each()`.
###
How do I sort a hash (optionally by value instead of key)?
(contributed by brian d foy)
To sort a hash, start with the keys. In this example, we give the list of keys to the sort function which then compares them ASCIIbetically (which might be affected by your locale settings). The output list has the keys in ASCIIbetical order. Once we have the keys, we can go through them to create a report which lists the keys in ASCIIbetical order.
```
my @keys = sort { $a cmp $b } keys %hash;
foreach my $key ( @keys ) {
printf "%-20s %6d\n", $key, $hash{$key};
}
```
We could get more fancy in the `sort()` block though. Instead of comparing the keys, we can compute a value with them and use that value as the comparison.
For instance, to make our report order case-insensitive, we use `lc` to lowercase the keys before comparing them:
```
my @keys = sort { lc $a cmp lc $b } keys %hash;
```
Note: if the computation is expensive or the hash has many elements, you may want to look at the Schwartzian Transform to cache the computation results.
If we want to sort by the hash value instead, we use the hash key to look it up. We still get out a list of keys, but this time they are ordered by their value.
```
my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
```
From there we can get more complex. If the hash values are the same, we can provide a secondary sort on the hash key.
```
my @keys = sort {
$hash{$a} <=> $hash{$b}
or
"\L$a" cmp "\L$b"
} keys %hash;
```
###
How can I always keep my hash sorted?
You can look into using the `DB_File` module and `tie()` using the `$DB_BTREE` hash bindings as documented in ["In Memory Databases" in DB\_File](db_file#In-Memory-Databases). The <Tie::IxHash> module from CPAN might also be instructive. Although this does keep your hash sorted, you might not like the slowdown you suffer from the tie interface. Are you sure you need to do this? :)
###
What's the difference between "delete" and "undef" with hashes?
Hashes contain pairs of scalars: the first is the key, the second is the value. The key will be coerced to a string, although the value can be any kind of scalar: string, number, or reference. If a key `$key` is present in %hash, `exists($hash{$key})` will return true. The value for a given key can be `undef`, in which case `$hash{$key}` will be `undef` while `exists $hash{$key}` will return true. This corresponds to (`$key`, `undef`) being in the hash.
Pictures help... Here's the `%hash` table:
```
keys values
+------+------+
| a | 3 |
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
```
And these conditions hold
```
$hash{'a'} is true
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is true
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true
```
If you now say
```
undef $hash{'a'}
```
your table now reads:
```
keys values
+------+------+
| a | undef|
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
```
and these conditions now hold; changes in caps:
```
$hash{'a'} is FALSE
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is FALSE
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true
```
Notice the last two: you have an undef value, but a defined key!
Now, consider this:
```
delete $hash{'a'}
```
your table now reads:
```
keys values
+------+------+
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
```
and these conditions now hold; changes in caps:
```
$hash{'a'} is false
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is false
exists $hash{'a'} is FALSE (Perl 5 only)
grep ($_ eq 'a', keys %hash) is FALSE
```
See, the whole entry is gone!
###
Why don't my tied hashes make the defined/exists distinction?
This depends on the tied hash's implementation of EXISTS(). For example, there isn't the concept of undef with hashes that are tied to DBM\* files. It also means that exists() and defined() do the same thing with a DBM\* file, and what they end up doing is not what they do with ordinary hashes.
###
How do I reset an each() operation part-way through?
(contributed by brian d foy)
You can use the `keys` or `values` functions to reset `each`. To simply reset the iterator used by `each` without doing anything else, use one of them in void context:
```
keys %hash; # resets iterator, nothing else.
values %hash; # resets iterator, nothing else.
```
See the documentation for `each` in <perlfunc>.
###
How can I get the unique keys from two hashes?
First you extract the keys from the hashes into lists, then solve the "removing duplicates" problem described above. For example:
```
my %seen = ();
for my $element (keys(%foo), keys(%bar)) {
$seen{$element}++;
}
my @uniq = keys %seen;
```
Or more succinctly:
```
my @uniq = keys %{{%foo,%bar}};
```
Or if you really want to save space:
```
my %seen = ();
while (defined ($key = each %foo)) {
$seen{$key}++;
}
while (defined ($key = each %bar)) {
$seen{$key}++;
}
my @uniq = keys %seen;
```
###
How can I store a multidimensional array in a DBM file?
Either stringify the structure yourself (no fun), or else get the MLDBM (which uses Data::Dumper) module from CPAN and layer it on top of either DB\_File or GDBM\_File. You might also try DBM::Deep, but it can be a bit slow.
###
How can I make my hash remember the order I put elements into it?
Use the <Tie::IxHash> from CPAN.
```
use Tie::IxHash;
tie my %myhash, 'Tie::IxHash';
for (my $i=0; $i<20; $i++) {
$myhash{$i} = 2*$i;
}
my @keys = keys %myhash;
# @keys = (0,1,2,3,...)
```
###
Why does passing a subroutine an undefined element in a hash create it?
(contributed by brian d foy)
Are you using a really old version of Perl?
Normally, accessing a hash key's value for a nonexistent key will *not* create the key.
```
my %hash = ();
my $value = $hash{ 'foo' };
print "This won't print\n" if exists $hash{ 'foo' };
```
Passing `$hash{ 'foo' }` to a subroutine used to be a special case, though. Since you could assign directly to `$_[0]`, Perl had to be ready to make that assignment so it created the hash key ahead of time:
```
my_sub( $hash{ 'foo' } );
print "This will print before 5.004\n" if exists $hash{ 'foo' };
sub my_sub {
# $_[0] = 'bar'; # create hash key in case you do this
1;
}
```
Since Perl 5.004, however, this situation is a special case and Perl creates the hash key only when you make the assignment:
```
my_sub( $hash{ 'foo' } );
print "This will print, even after 5.004\n" if exists $hash{ 'foo' };
sub my_sub {
$_[0] = 'bar';
}
```
However, if you want the old behavior (and think carefully about that because it's a weird side effect), you can pass a hash slice instead. Perl 5.004 didn't make this a special case:
```
my_sub( @hash{ qw/foo/ } );
```
###
How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?
Usually a hash ref, perhaps like this:
```
$record = {
NAME => "Jason",
EMPNO => 132,
TITLE => "deputy peon",
AGE => 23,
SALARY => 37_000,
PALS => [ "Norbert", "Rhys", "Phineas"],
};
```
References are documented in <perlref> and <perlreftut>. Examples of complex data structures are given in <perldsc> and <perllol>. Examples of structures and object-oriented classes are in <perlootut>.
###
How can I use a reference as a hash key?
(contributed by brian d foy and Ben Morrow)
Hash keys are strings, so you can't really use a reference as the key. When you try to do that, perl turns the reference into its stringified form (for instance, `HASH(0xDEADBEEF)`). From there you can't get back the reference from the stringified form, at least without doing some extra work on your own.
Remember that the entry in the hash will still be there even if the referenced variable goes out of scope, and that it is entirely possible for Perl to subsequently allocate a different variable at the same address. This will mean a new variable might accidentally be associated with the value for an old.
If you have Perl 5.10 or later, and you just want to store a value against the reference for lookup later, you can use the core Hash::Util::Fieldhash module. This will also handle renaming the keys if you use multiple threads (which causes all variables to be reallocated at new addresses, changing their stringification), and garbage-collecting the entries when the referenced variable goes out of scope.
If you actually need to be able to get a real reference back from each hash entry, you can use the Tie::RefHash module, which does the required work for you.
###
How can I check if a key exists in a multilevel hash?
(contributed by brian d foy)
The trick to this problem is avoiding accidental autovivification. If you want to check three keys deep, you might naรฏvely try this:
```
my %hash;
if( exists $hash{key1}{key2}{key3} ) {
...;
}
```
Even though you started with a completely empty hash, after that call to `exists` you've created the structure you needed to check for `key3`:
```
%hash = (
'key1' => {
'key2' => {}
}
);
```
That's autovivification. You can get around this in a few ways. The easiest way is to just turn it off. The lexical `autovivification` pragma is available on CPAN. Now you don't add to the hash:
```
{
no autovivification;
my %hash;
if( exists $hash{key1}{key2}{key3} ) {
...;
}
}
```
The <Data::Diver> module on CPAN can do it for you too. Its `Dive` subroutine can tell you not only if the keys exist but also get the value:
```
use Data::Diver qw(Dive);
my @exists = Dive( \%hash, qw(key1 key2 key3) );
if( ! @exists ) {
...; # keys do not exist
}
elsif( ! defined $exists[0] ) {
...; # keys exist but value is undef
}
```
You can easily do this yourself too by checking each level of the hash before you move onto the next level. This is essentially what <Data::Diver> does for you:
```
if( check_hash( \%hash, qw(key1 key2 key3) ) ) {
...;
}
sub check_hash {
my( $hash, @keys ) = @_;
return unless @keys;
foreach my $key ( @keys ) {
return unless eval { exists $hash->{$key} };
$hash = $hash->{$key};
}
return 1;
}
```
###
How can I prevent addition of unwanted keys into a hash?
Since version 5.8.0, hashes can be *restricted* to a fixed number of given keys. Methods for creating and dealing with restricted hashes are exported by the <Hash::Util> module.
Data: Misc
-----------
###
How do I handle binary data correctly?
Perl is binary-clean, so it can handle binary data just fine. On Windows or DOS, however, you have to use `binmode` for binary files to avoid conversions for line endings. In general, you should use `binmode` any time you want to work with binary data.
Also see ["binmode" in perlfunc](perlfunc#binmode) or <perlopentut>.
If you're concerned about 8-bit textual data then see <perllocale>. If you want to deal with multibyte characters, however, there are some gotchas. See the section on Regular Expressions.
###
How do I determine whether a scalar is a number/whole/integer/float?
Assuming that you don't care about IEEE notations like "NaN" or "Infinity", you probably just want to use a regular expression (see also <perlretut> and <perlre>):
```
use 5.010;
if ( /\D/ )
{ say "\thas nondigits"; }
if ( /^\d+\z/ )
{ say "\tis a whole number"; }
if ( /^-?\d+\z/ )
{ say "\tis an integer"; }
if ( /^[+-]?\d+\z/ )
{ say "\tis a +/- integer"; }
if ( /^-?(?:\d+\.?|\.\d)\d*\z/ )
{ say "\tis a real number"; }
if ( /^[+-]?(?=\.?\d)\d*\.?\d*(?:e[+-]?\d+)?\z/i )
{ say "\tis a C float" }
```
There are also some commonly used modules for the task. <Scalar::Util> (distributed with 5.8) provides access to perl's internal function `looks_like_number` for determining whether a variable looks like a number. <Data::Types> exports functions that validate data types using both the above and other regular expressions. Thirdly, there is <Regexp::Common> which has regular expressions to match various types of numbers. Those three modules are available from the CPAN.
If you're on a POSIX system, Perl supports the `POSIX::strtod` function for converting strings to doubles (and also `POSIX::strtol` for longs). Its semantics are somewhat cumbersome, so here's a `getnum` wrapper function for more convenient access. This function takes a string and returns the number it found, or `undef` for input that isn't a C float. The `is_numeric` function is a front end to `getnum` if you just want to say, "Is this a float?"
```
sub getnum {
use POSIX qw(strtod);
my $str = shift;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
$! = 0;
my($num, $unparsed) = strtod($str);
if (($str eq '') || ($unparsed != 0) || $!) {
return undef;
}
else {
return $num;
}
}
sub is_numeric { defined getnum($_[0]) }
```
Or you could check out the <String::Scanf> module on the CPAN instead.
###
How do I keep persistent data across program calls?
For some specific applications, you can use one of the DBM modules. See [AnyDBM\_File](anydbm_file). More generically, you should consult the [FreezeThaw](freezethaw) or [Storable](storable) modules from CPAN. Starting from Perl 5.8, [Storable](storable) is part of the standard distribution. Here's one example using [Storable](storable)'s `store` and `retrieve` functions:
```
use Storable;
store(\%hash, "filename");
# later on...
$href = retrieve("filename"); # by ref
%hash = %{ retrieve("filename") }; # direct to hash
```
###
How do I print out or copy a recursive data structure?
The <Data::Dumper> module on CPAN (or the 5.005 release of Perl) is great for printing out data structures. The [Storable](storable) module on CPAN (or the 5.8 release of Perl), provides a function called `dclone` that recursively copies its argument.
```
use Storable qw(dclone);
$r2 = dclone($r1);
```
Where `$r1` can be a reference to any kind of data structure you'd like. It will be deeply copied. Because `dclone` takes and returns references, you'd have to add extra punctuation if you had a hash of arrays that you wanted to copy.
```
%newhash = %{ dclone(\%oldhash) };
```
###
How do I define methods for every class/object?
(contributed by Ben Morrow)
You can use the `UNIVERSAL` class (see [UNIVERSAL](universal)). However, please be very careful to consider the consequences of doing this: adding methods to every object is very likely to have unintended consequences. If possible, it would be better to have all your object inherit from some common base class, or to use an object system like Moose that supports roles.
###
How do I verify a credit card checksum?
Get the <Business::CreditCard> module from CPAN.
###
How do I pack arrays of doubles or floats for XS code?
The arrays.h/arrays.c code in the [PGPLOT](pgplot) module on CPAN does just this. If you're doing a lot of float or double processing, consider using the [PDL](pdl) module from CPAN instead--it makes number-crunching easy.
See <https://metacpan.org/release/PGPLOT> for the code.
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 perlhacktut perlhacktut
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE OF A SIMPLE PATCH](#EXAMPLE-OF-A-SIMPLE-PATCH)
+ [Writing the patch](#Writing-the-patch)
+ [Testing the patch](#Testing-the-patch)
+ [Documenting the patch](#Documenting-the-patch)
+ [Submit](#Submit)
* [AUTHOR](#AUTHOR)
NAME
----
perlhacktut - Walk through the creation of a simple C code patch
DESCRIPTION
-----------
This document takes you through a simple patch example.
If you haven't read <perlhack> yet, go do that first! You might also want to read through <perlsource> too.
Once you're done here, check out <perlhacktips> next.
EXAMPLE OF A SIMPLE PATCH
--------------------------
Let's take a simple patch from start to finish.
Here's something Larry suggested: if a `U` is the first active format during a `pack`, (for example, `pack "U3C8", @stuff`) then the resulting string should be treated as UTF-8 encoded.
If you are working with a git clone of the Perl repository, you will want to create a branch for your changes. This will make creating a proper patch much simpler. See the <perlgit> for details on how to do this.
###
Writing the patch
How do we prepare to fix this up? First we locate the code in question - the `pack` happens at runtime, so it's going to be in one of the *pp* files. Sure enough, `pp_pack` is in *pp.c*. Since we're going to be altering this file, let's copy it to *pp.c~*.
[Well, it was in *pp.c* when this tutorial was written. It has now been split off with `pp_unpack` to its own file, *pp\_pack.c*]
Now let's look over `pp_pack`: we take a pattern into `pat`, and then loop over the pattern, taking each format character in turn into `datum_type`. Then for each possible format character, we swallow up the other arguments in the pattern (a field width, an asterisk, and so on) and convert the next chunk input into the specified format, adding it onto the output SV `cat`.
How do we know if the `U` is the first format in the `pat`? Well, if we have a pointer to the start of `pat` then, if we see a `U` we can test whether we're still at the start of the string. So, here's where `pat` is set up:
```
STRLEN fromlen;
char *pat = SvPVx(*++MARK, fromlen);
char *patend = pat + fromlen;
I32 len;
I32 datumtype;
SV *fromstr;
```
We'll have another string pointer in there:
```
STRLEN fromlen;
char *pat = SvPVx(*++MARK, fromlen);
char *patend = pat + fromlen;
+ char *patcopy;
I32 len;
I32 datumtype;
SV *fromstr;
```
And just before we start the loop, we'll set `patcopy` to be the start of `pat`:
```
items = SP - MARK;
MARK++;
SvPVCLEAR(cat);
+ patcopy = pat;
while (pat < patend) {
```
Now if we see a `U` which was at the start of the string, we turn on the `UTF8` flag for the output SV, `cat`:
```
+ if (datumtype == 'U' && pat==patcopy+1)
+ SvUTF8_on(cat);
if (datumtype == '#') {
while (pat < patend && *pat != '\n')
pat++;
```
Remember that it has to be `patcopy+1` because the first character of the string is the `U` which has been swallowed into `datumtype!`
Oops, we forgot one thing: what if there are spaces at the start of the pattern? `pack(" U*", @stuff)` will have `U` as the first active character, even though it's not the first thing in the pattern. In this case, we have to advance `patcopy` along with `pat` when we see spaces:
```
if (isSPACE(datumtype))
continue;
```
needs to become
```
if (isSPACE(datumtype)) {
patcopy++;
continue;
}
```
OK. That's the C part done. Now we must do two additional things before this patch is ready to go: we've changed the behaviour of Perl, and so we must document that change. We must also provide some more regression tests to make sure our patch works and doesn't create a bug somewhere else along the line.
###
Testing the patch
The regression tests for each operator live in *t/op/*, and so we make a copy of *t/op/pack.t* to *t/op/pack.t~*. Now we can add our tests to the end. First, we'll test that the `U` does indeed create Unicode strings.
t/op/pack.t has a sensible ok() function, but if it didn't we could use the one from t/test.pl.
```
require './test.pl';
plan( tests => 159 );
```
so instead of this:
```
print 'not ' unless "1.20.300.4000" eq sprintf "%vd",
pack("U*",1,20,300,4000);
print "ok $test\n"; $test++;
```
we can write the more sensible (see <Test::More> for a full explanation of is() and other testing functions).
```
is( "1.20.300.4000", sprintf "%vd", pack("U*",1,20,300,4000),
"U* produces Unicode" );
```
Now we'll test that we got that space-at-the-beginning business right:
```
is( "1.20.300.4000", sprintf "%vd", pack(" U*",1,20,300,4000),
" with spaces at the beginning" );
```
And finally we'll test that we don't make Unicode strings if `U` is **not** the first active format:
```
isnt( v1.20.300.4000, sprintf "%vd", pack("C0U*",1,20,300,4000),
"U* not first isn't Unicode" );
```
Mustn't forget to change the number of tests which appears at the top, or else the automated tester will get confused. This will either look like this:
```
print "1..156\n";
```
or this:
```
plan( tests => 156 );
```
We now compile up Perl, and run it through the test suite. Our new tests pass, hooray!
###
Documenting the patch
Finally, the documentation. The job is never done until the paperwork is over, so let's describe the change we've just made. The relevant place is *pod/perlfunc.pod*; again, we make a copy, and then we'll insert this text in the description of `pack`:
```
=item *
If the pattern begins with a C<U>, the resulting string will be treated
as UTF-8-encoded Unicode. You can force UTF-8 encoding on in a string
with an initial C<U0>, and the bytes that follow will be interpreted as
Unicode characters. If you don't want this to happen, you can begin
your pattern with C<C0> (or anything else) to force Perl not to UTF-8
encode your string, and then follow this with a C<U*> somewhere in your
pattern.
```
### Submit
See <perlhack> for details on how to submit this patch.
AUTHOR
------
This document was originally written by Nathan Torkington, and is maintained by the perl5-porters mailing list.
perl TAP::Parser TAP::Parser
===========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [next](#next)
- [run](#run)
- [make\_grammar](#make_grammar)
- [make\_result](#make_result)
- [make\_iterator\_factory](#make_iterator_factory)
* [INDIVIDUAL RESULTS](#INDIVIDUAL-RESULTS)
+ [Result types](#Result-types)
+ [Common type methods](#Common-type-methods)
- [type](#type)
- [as\_string](#as_string)
- [raw](#raw)
- [is\_plan](#is_plan)
- [is\_test](#is_test)
- [is\_comment](#is_comment)
- [is\_bailout](#is_bailout)
- [is\_yaml](#is_yaml)
- [is\_unknown](#is_unknown)
- [is\_ok](#is_ok)
+ [plan methods](#plan-methods)
- [plan](#plan1)
- [directive](#directive)
- [explanation](#explanation)
+ [pragma methods](#pragma-methods)
- [pragmas](#pragmas)
+ [comment methods](#comment-methods)
- [comment](#comment1)
+ [bailout methods](#bailout-methods)
- [explanation](#explanation1)
+ [unknown methods](#unknown-methods)
+ [test methods](#test-methods)
- [ok](#ok)
- [number](#number)
- [description](#description)
- [directive](#directive1)
- [explanation](#explanation2)
- [is\_ok](#is_ok1)
- [is\_actual\_ok](#is_actual_ok)
- [is\_unplanned](#is_unplanned)
- [has\_skip](#has_skip)
- [has\_todo](#has_todo)
- [in\_todo](#in_todo)
* [TOTAL RESULTS](#TOTAL-RESULTS)
+ [Individual Results](#Individual-Results)
- [passed](#passed)
- [failed](#failed)
- [actual\_passed](#actual_passed)
- [actual\_ok](#actual_ok)
- [actual\_failed](#actual_failed)
- [todo](#todo)
- [todo\_passed](#todo_passed)
- [todo\_failed](#todo_failed)
- [skipped](#skipped)
+ [Pragmas](#Pragmas)
- [pragma](#pragma1)
- [pragmas](#pragmas1)
+ [Summary Results](#Summary-Results)
- [plan](#plan2)
- [good\_plan](#good_plan)
- [is\_good\_plan](#is_good_plan)
- [tests\_planned](#tests_planned)
- [tests\_run](#tests_run)
- [skip\_all](#skip_all)
- [start\_time](#start_time)
- [end\_time](#end_time)
- [start\_times](#start_times)
- [end\_times](#end_times)
- [has\_problems](#has_problems)
- [version](#version)
- [exit](#exit)
- [wait](#wait)
+ [ignore\_exit](#ignore_exit)
- [parse\_errors](#parse_errors)
- [get\_select\_handles](#get_select_handles)
- [delete\_spool](#delete_spool)
* [CALLBACKS](#CALLBACKS)
* [TAP GRAMMAR](#TAP-GRAMMAR)
* [BACKWARDS COMPATIBILITY](#BACKWARDS-COMPATIBILITY)
+ [Differences](#Differences)
* [SUBCLASSING](#SUBCLASSING)
+ [Parser Components](#Parser-Components)
- [Sources](#Sources)
- [Iterators](#Iterators)
- [Results](#Results)
- [Grammar](#Grammar)
* [ACKNOWLEDGMENTS](#ACKNOWLEDGMENTS)
* [AUTHORS](#AUTHORS)
* [BUGS](#BUGS)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
TAP::Parser - Parse [TAP](Test::Harness::TAP) output
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser;
my $parser = TAP::Parser->new( { source => $source } );
while ( my $result = $parser->next ) {
print $result->as_string;
}
```
DESCRIPTION
-----------
`TAP::Parser` is designed to produce a proper parse of TAP output. For an example of how to run tests through this module, see the simple harnesses `examples/`.
There's a wiki dedicated to the Test Anything Protocol:
<http://testanything.org>
It includes the TAP::Parser Cookbook:
<http://testanything.org/testing-with-tap/perl/tap::parser-cookbook.html>
METHODS
-------
###
Class Methods
#### `new`
```
my $parser = TAP::Parser->new(\%args);
```
Returns a new `TAP::Parser` object.
The arguments should be a hashref with *one* of the following keys:
* `source`
*CHANGED in 3.18*
This is the preferred method of passing input to the constructor.
The `source` is used to create a <TAP::Parser::Source> that is passed to the ["iterator\_factory\_class"](#iterator_factory_class) which in turn figures out how to handle the source and creates a <TAP::Parser::Iterator> for it. The iterator is used by the parser to read in the TAP stream.
To configure the *IteratorFactory* use the `sources` parameter below.
Note that `source`, `tap` and `exec` are *mutually exclusive*.
* `tap`
*CHANGED in 3.18*
The value should be the complete TAP output.
The *tap* is used to create a <TAP::Parser::Source> that is passed to the ["iterator\_factory\_class"](#iterator_factory_class) which in turn figures out how to handle the source and creates a <TAP::Parser::Iterator> for it. The iterator is used by the parser to read in the TAP stream.
To configure the *IteratorFactory* use the `sources` parameter below.
Note that `source`, `tap` and `exec` are *mutually exclusive*.
* `exec`
Must be passed an array reference.
The *exec* array ref is used to create a <TAP::Parser::Source> that is passed to the ["iterator\_factory\_class"](#iterator_factory_class) which in turn figures out how to handle the source and creates a <TAP::Parser::Iterator> for it. The iterator is used by the parser to read in the TAP stream.
By default the <TAP::Parser::SourceHandler::Executable> class will create a <TAP::Parser::Iterator::Process> object to handle the source. This passes the array reference strings as command arguments to [IPC::Open3::open3](IPC::Open3):
```
exec => [ '/usr/bin/ruby', 't/my_test.rb' ]
```
If any `test_args` are given they will be appended to the end of the command argument list.
To configure the *IteratorFactory* use the `sources` parameter below.
Note that `source`, `tap` and `exec` are *mutually exclusive*.
The following keys are optional.
* `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' },
}
```
This will cause `TAP::Parser` to pass custom configuration to two of the built- in source handlers - <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::File> - and attempt to load the `MyCustom` class. See ["load\_handlers" in TAP::Parser::IteratorFactory](TAP::Parser::IteratorFactory#load_handlers) for more detail.
The `sources` parameter affects how `source`, `tap` and `exec` parameters are handled.
See <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler> and subclasses for more details.
* `callback`
If present, each callback corresponding to a given result type will be called with the result as the argument if the `run` method is used:
```
my %callbacks = (
test => \&test_callback,
plan => \&plan_callback,
comment => \&comment_callback,
bailout => \&bailout_callback,
unknown => \&unknown_callback,
);
my $aggregator = TAP::Parser::Aggregator->new;
for my $file ( @test_files ) {
my $parser = TAP::Parser->new(
{
source => $file,
callbacks => \%callbacks,
}
);
$parser->run;
$aggregator->add( $file, $parser );
}
```
* `switches`
If using a Perl file as a source, optional switches may be passed which will be used when invoking the perl executable.
```
my $parser = TAP::Parser->new( {
source => $test_file,
switches => [ '-Ilib' ],
} );
```
* `test_args`
Used in conjunction with the `source` and `exec` option to supply a reference to an `@ARGV` style array of arguments to pass to the test program.
* `spool`
If passed a filehandle will write a copy of all parsed TAP to that handle.
* `merge`
If false, STDERR is not captured (though it is 'relayed' to keep it somewhat synchronized with STDOUT.)
If true, STDERR and STDOUT are the same filehandle. This may cause breakage if STDERR contains anything resembling TAP format, but does allow exact synchronization.
Subtleties of this behavior may be platform-dependent and may change in the future.
* `grammar_class`
This option was introduced to let you easily customize which *grammar* class the parser should use. It defaults to <TAP::Parser::Grammar>.
See also ["make\_grammar"](#make_grammar).
* `result_factory_class`
This option was introduced to let you easily customize which *result* factory class the parser should use. It defaults to <TAP::Parser::ResultFactory>.
See also ["make\_result"](#make_result).
* `iterator_factory_class`
*CHANGED in 3.18*
This option was introduced to let you easily customize which *iterator* factory class the parser should use. It defaults to <TAP::Parser::IteratorFactory>.
###
Instance Methods
#### `next`
```
my $parser = TAP::Parser->new( { source => $file } );
while ( my $result = $parser->next ) {
print $result->as_string, "\n";
}
```
This method returns the results of the parsing, one result at a time. Note that it is destructive. You can't rewind and examine previous results.
If callbacks are used, they will be issued before this call returns.
Each result returned is a subclass of <TAP::Parser::Result>. See that module and related classes for more information on how to use them.
#### `run`
```
$parser->run;
```
This method merely runs the parser and parses all of the TAP.
#### `make_grammar`
Make a new <TAP::Parser::Grammar> object and return it. Passes through any arguments given.
The `grammar_class` can be customized, as described in ["new"](#new).
#### `make_result`
Make a new <TAP::Parser::Result> object using the parser's <TAP::Parser::ResultFactory>, and return it. Passes through any arguments given.
The `result_factory_class` can be customized, as described in ["new"](#new).
#### `make_iterator_factory`
*NEW to 3.18*.
Make a new <TAP::Parser::IteratorFactory> object and return it. Passes through any arguments given.
`iterator_factory_class` can be customized, as described in ["new"](#new).
INDIVIDUAL RESULTS
-------------------
If you've read this far in the docs, you've seen this:
```
while ( my $result = $parser->next ) {
print $result->as_string;
}
```
Each result returned is a <TAP::Parser::Result> subclass, referred to as *result types*.
###
Result types
Basically, you fetch individual results from the TAP. The six types, with examples of each, are as follows:
* Version
```
TAP version 12
```
* Plan
```
1..42
```
* Pragma
```
pragma +strict
```
* Test
```
ok 3 - We should start with some foobar!
```
* Comment
```
# Hope we don't use up the foobar.
```
* Bailout
```
Bail out! We ran out of foobar!
```
* Unknown
```
... yo, this ain't TAP! ...
```
Each result fetched is a result object of a different type. There are common methods to each result object and different types may have methods unique to their type. Sometimes a type method may be overridden in a subclass, but its use is guaranteed to be identical.
###
Common type methods
#### `type`
Returns the type of result, such as `comment` or `test`.
#### `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.
#### `raw`
Returns the original line of text which was parsed.
#### `is_plan`
Indicates whether or not this is the test plan line.
#### `is_test`
Indicates whether or not this is a test line.
#### `is_comment`
Indicates whether or not this is a comment. Comments will generally only appear in the TAP stream if STDERR is merged to STDOUT. See the `merge` option.
#### `is_bailout`
Indicates whether or not this is bailout line.
#### `is_yaml`
Indicates whether or not the current item is a YAML block.
#### `is_unknown`
Indicates whether or not the current line could be parsed.
#### `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 which allows you to do this:
```
my $parser = TAP::Parser->new( { source => $source } );
while ( my $result = $parser->next ) {
# only print failing results
print $result->as_string unless $result->is_ok;
}
```
###
`plan` methods
```
if ( $result->is_plan ) { ... }
```
If the above evaluates as true, the following methods will be available on the `$result` object.
#### `plan`
```
if ( $result->is_plan ) {
print $result->plan;
}
```
This is merely a synonym for `as_string`.
#### `directive`
```
my $directive = $result->directive;
```
If a SKIP directive is included with the plan, this method will return it.
```
1..0 # SKIP: why bother?
```
#### `explanation`
```
my $explanation = $result->explanation;
```
If a SKIP directive was included with the plan, this method will return the explanation, if any.
###
`pragma` methods
```
if ( $result->is_pragma ) { ... }
```
If the above evaluates as true, the following methods will be available on the `$result` object.
#### `pragmas`
Returns a list of pragmas each of which is a + or - followed by the pragma name.
###
`comment` methods
```
if ( $result->is_comment ) { ... }
```
If the above evaluates as true, the following methods will be available on the `$result` object.
#### `comment`
```
if ( $result->is_comment ) {
my $comment = $result->comment;
print "I have something to say: $comment";
}
```
###
`bailout` methods
```
if ( $result->is_bailout ) { ... }
```
If the above evaluates as true, the following methods will be available on the `$result` object.
#### `explanation`
```
if ( $result->is_bailout ) {
my $explanation = $result->explanation;
print "We bailed out because ($explanation)";
}
```
If, and only if, a token is a bailout token, you can get an "explanation" via this method. The explanation is the text after the mystical "Bail out!" words which appear in the tap output.
###
`unknown` methods
```
if ( $result->is_unknown ) { ... }
```
There are no unique methods for unknown results.
###
`test` methods
```
if ( $result->is_test ) { ... }
```
If the above evaluates as true, the following methods will be available on the `$result` object.
#### `ok`
```
my $ok = $result->ok;
```
Returns the literal text of the `ok` or `not ok` status.
#### `number`
```
my $test_number = $result->number;
```
Returns the number of the test, even if the original TAP output did not supply that number.
#### `description`
```
my $description = $result->description;
```
Returns the description of the test, if any. This is the portion after the test number but before the directive.
#### `directive`
```
my $directive = $result->directive;
```
Returns either `TODO` or `SKIP` if either directive was present for a test line.
#### `explanation`
```
my $explanation = $result->explanation;
```
If a test had either a `TODO` or `SKIP` directive, this method will return the accompanying explanation, if present.
```
not ok 17 - 'Pigs can fly' # TODO not enough acid
```
For the above line, the explanation is *not enough acid*.
#### `is_ok`
```
if ( $result->is_ok ) { ... }
```
Returns a boolean value indicating whether or not the test passed. Remember that for TODO tests, the test always passes.
**Note:** this was formerly `passed`. The latter method is deprecated and will issue a warning.
#### `is_actual_ok`
```
if ( $result->is_actual_ok ) { ... }
```
Returns a boolean value indicating whether or not the test passed, regardless of its TODO status.
**Note:** this was formerly `actual_passed`. The latter method is deprecated and will issue a warning.
#### `is_unplanned`
```
if ( $test->is_unplanned ) { ... }
```
If a test number is greater than the number of planned tests, this method will return true. Unplanned tests will *always* return false for `is_ok`, regardless of whether or not the test `has_todo` (see <TAP::Parser::Result::Test> for more information about this).
#### `has_skip`
```
if ( $result->has_skip ) { ... }
```
Returns a boolean value indicating whether or not this test had a SKIP directive.
#### `has_todo`
```
if ( $result->has_todo ) { ... }
```
Returns a boolean value indicating whether or not this test had a TODO directive.
Note that TODO tests *always* pass. If you need to know whether or not they really passed, check the `is_actual_ok` method.
#### `in_todo`
```
if ( $parser->in_todo ) { ... }
```
True while the most recent result was a TODO. Becomes true before the TODO result is returned and stays true until just before the next non- TODO test is returned.
TOTAL RESULTS
--------------
After parsing the TAP, there are many methods available to let you dig through the results and determine what is meaningful to you.
###
Individual Results
These results refer to individual tests which are run.
#### `passed`
```
my @passed = $parser->passed; # the test numbers which passed
my $passed = $parser->passed; # the number of tests which passed
```
This method lets you know which (or how many) tests passed. If a test failed but had a TODO directive, it will be counted as a passed test.
#### `failed`
```
my @failed = $parser->failed; # the test numbers which failed
my $failed = $parser->failed; # the number of tests which failed
```
This method lets you know which (or how many) tests failed. If a test passed but had a TODO directive, it will **NOT** be counted as a failed test.
#### `actual_passed`
```
# the test numbers which actually passed
my @actual_passed = $parser->actual_passed;
# the number of tests which actually passed
my $actual_passed = $parser->actual_passed;
```
This method lets you know which (or how many) tests actually passed, regardless of whether or not a TODO directive was found.
#### `actual_ok`
This method is a synonym for `actual_passed`.
#### `actual_failed`
```
# the test numbers which actually failed
my @actual_failed = $parser->actual_failed;
# the number of tests which actually failed
my $actual_failed = $parser->actual_failed;
```
This method lets you know which (or how many) tests actually failed, regardless of whether or not a TODO directive was found.
#### `todo`
```
my @todo = $parser->todo; # the test numbers with todo directives
my $todo = $parser->todo; # the number of tests with todo directives
```
This method lets you know which (or how many) tests had TODO directives.
#### `todo_passed`
```
# the test numbers which unexpectedly succeeded
my @todo_passed = $parser->todo_passed;
# the number of tests which unexpectedly succeeded
my $todo_passed = $parser->todo_passed;
```
This method lets you know which (or how many) tests actually passed but were declared as "TODO" tests.
#### `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`.
#### `skipped`
```
my @skipped = $parser->skipped; # the test numbers with SKIP directives
my $skipped = $parser->skipped; # the number of tests with SKIP directives
```
This method lets you know which (or how many) tests had SKIP directives.
### Pragmas
#### `pragma`
Get or set a pragma. To get the state of a pragma:
```
if ( $p->pragma('strict') ) {
# be strict
}
```
To set the state of a pragma:
```
$p->pragma('strict', 1); # enable strict mode
```
#### `pragmas`
Get a list of all the currently enabled pragmas:
```
my @pragmas_enabled = $p->pragmas;
```
###
Summary Results
These results are "meta" information about the total results of an individual test program.
#### `plan`
```
my $plan = $parser->plan;
```
Returns the test plan, if found.
#### `good_plan`
Deprecated. Use `is_good_plan` instead.
#### `is_good_plan`
```
if ( $parser->is_good_plan ) { ... }
```
Returns a boolean value indicating whether or not the number of tests planned matches the number of tests run.
**Note:** this was formerly `good_plan`. The latter method is deprecated and will issue a warning.
And since we're on that subject ...
#### `tests_planned`
```
print $parser->tests_planned;
```
Returns the number of tests planned, according to the plan. For example, a plan of '1..17' will mean that 17 tests were planned.
#### `tests_run`
```
print $parser->tests_run;
```
Returns the number of tests which actually were run. Hopefully this will match the number of `$parser->tests_planned`.
#### `skip_all`
Returns a true value (actually the reason for skipping) if all tests were skipped.
#### `start_time`
Returns the wall-clock time when the Parser was created.
#### `end_time`
Returns the wall-clock time when the end of TAP input was seen.
#### `start_times`
Returns the CPU times (like ["times" in perlfunc](perlfunc#times) when the Parser was created.
#### `end_times`
Returns the CPU times (like ["times" in perlfunc](perlfunc#times) when the end of TAP input was seen.
#### `has_problems`
```
if ( $parser->has_problems ) {
...
}
```
This is a 'catch-all' method which returns true if any tests have currently failed, any TODO tests unexpectedly succeeded, or any parse errors occurred.
#### `version`
```
$parser->version;
```
Once the parser is done, this will return the version number for the parsed TAP. Version numbers were introduced with TAP version 13 so if no version number is found version 12 is assumed.
#### `exit`
```
$parser->exit;
```
Once the parser is done, this will return the exit status. If the parser ran an executable, it returns the exit status of the executable.
#### `wait`
```
$parser->wait;
```
Once the parser is done, this will return the wait status. If the parser ran an executable, it returns the wait status of the executable. Otherwise, this merely returns the `exit` status.
### `ignore_exit`
```
$parser->ignore_exit(1);
```
Tell the parser to ignore the exit status from the test when determining whether the test passed. Normally tests with non-zero exit status are considered to have failed even if all individual tests passed. In cases where it is not possible to control the exit value of the test script use this option to ignore it.
#### `parse_errors`
```
my @errors = $parser->parse_errors; # the parser errors
my $errors = $parser->parse_errors; # the number of parser_errors
```
Fortunately, all TAP output is perfect. In the event that it is not, this method will return parser errors. Note that a junk line which the parser does not recognize is `not` an error. This allows this parser to handle future versions of TAP. The following are all TAP errors reported by the parser:
* Misplaced plan
The plan (for example, '1..5'), must only come at the beginning or end of the TAP output.
* No plan
Gotta have a plan!
* More than one plan
```
1..3
ok 1 - input file opened
not ok 2 - first line of the input valid # todo some data
ok 3 read the rest of the file
1..3
```
Right. Very funny. Don't do that.
* Test numbers out of sequence
```
1..3
ok 1 - input file opened
not ok 2 - first line of the input valid # todo some data
ok 2 read the rest of the file
```
That last test line above should have the number '3' instead of '2'.
Note that it's perfectly acceptable for some lines to have test numbers and others to not have them. However, when a test number is found, it must be in sequence. The following is also an error:
```
1..3
ok 1 - input file opened
not ok - first line of the input valid # todo some data
ok 2 read the rest of the file
```
But this is not:
```
1..3
ok - input file opened
not ok - first line of the input valid # todo some data
ok 3 read the rest of the file
```
#### `get_select_handles`
Get an a list of file handles which can be passed to `select` to determine the readiness of this parser.
#### `delete_spool`
Delete and return the spool.
```
my $fh = $parser->delete_spool;
```
CALLBACKS
---------
As mentioned earlier, a "callback" key may be added to the `TAP::Parser` constructor. If present, each callback corresponding to a given result type will be called with the result as the argument if the `run` method is used. The callback is expected to be a subroutine reference (or anonymous subroutine) which is invoked with the parser result as its argument.
```
my %callbacks = (
test => \&test_callback,
plan => \&plan_callback,
comment => \&comment_callback,
bailout => \&bailout_callback,
unknown => \&unknown_callback,
);
my $aggregator = TAP::Parser::Aggregator->new;
for my $file ( @test_files ) {
my $parser = TAP::Parser->new(
{
source => $file,
callbacks => \%callbacks,
}
);
$parser->run;
$aggregator->add( $file, $parser );
}
```
Callbacks may also be added like this:
```
$parser->callback( test => \&test_callback );
$parser->callback( plan => \&plan_callback );
```
The following keys allowed for callbacks. These keys are case-sensitive.
* `test`
Invoked if `$result->is_test` returns true.
* `version`
Invoked if `$result->is_version` returns true.
* `plan`
Invoked if `$result->is_plan` returns true.
* `comment`
Invoked if `$result->is_comment` returns true.
* `bailout`
Invoked if `$result->is_unknown` returns true.
* `yaml`
Invoked if `$result->is_yaml` returns true.
* `unknown`
Invoked if `$result->is_unknown` returns true.
* `ELSE`
If a result does not have a callback defined for it, this callback will be invoked. Thus, if all of the previous result types are specified as callbacks, this callback will *never* be invoked.
* `ALL`
This callback will always be invoked and this will happen for each result after one of the above callbacks is invoked. For example, if <Term::ANSIColor> is loaded, you could use the following to color your test output:
```
my %callbacks = (
test => sub {
my $test = shift;
if ( $test->is_ok && not $test->directive ) {
# normal passing test
print color 'green';
}
elsif ( !$test->is_ok ) { # even if it's TODO
print color 'white on_red';
}
elsif ( $test->has_skip ) {
print color 'white on_blue';
}
elsif ( $test->has_todo ) {
print color 'white';
}
},
ELSE => sub {
# plan, comment, and so on (anything which isn't a test line)
print color 'black on_white';
},
ALL => sub {
# now print them
print shift->as_string;
print color 'reset';
print "\n";
},
);
```
* `EOF`
Invoked when there are no more lines to be parsed. Since there is no accompanying <TAP::Parser::Result> object the `TAP::Parser` object is passed instead.
TAP GRAMMAR
------------
If you're looking for an EBNF grammar, see <TAP::Parser::Grammar>.
BACKWARDS COMPATIBILITY
------------------------
The Perl-QA list attempted to ensure backwards compatibility with <Test::Harness>. However, there are some minor differences.
### Differences
* TODO plans
A little-known feature of <Test::Harness> is that it supported TODO lists in the plan:
```
1..2 todo 2
ok 1 - We have liftoff
not ok 2 - Anti-gravity device activated
```
Under <Test::Harness>, test number 2 would *pass* because it was listed as a TODO test on the plan line. However, we are not aware of anyone actually using this feature and hard-coding test numbers is discouraged because it's very easy to add a test and break the test number sequence. This makes test suites very fragile. Instead, the following should be used:
```
1..2
ok 1 - We have liftoff
not ok 2 - Anti-gravity device activated # TODO
```
* 'Missing' tests
It rarely happens, but sometimes a harness might encounter 'missing tests:
```
ok 1
ok 2
ok 15
ok 16
ok 17
```
<Test::Harness> would report tests 3-14 as having failed. For the `TAP::Parser`, these tests are not considered failed because they've never run. They're reported as parse failures (tests out of sequence).
SUBCLASSING
-----------
If you find you need to provide custom functionality (as you would have using <Test::Harness::Straps>), you're in luck: `TAP::Parser` and friends are designed to be easily plugged-into and/or subclassed.
Before you start, it's important to know a few things:
1. All `TAP::*` objects inherit from <TAP::Object>.
2. Many `TAP::*` classes have a *SUBCLASSING* section to guide you.
3. Note that `TAP::Parser` is designed to be the central "maker" - ie: it is responsible for creating most new objects in the `TAP::Parser::*` namespace.
This makes it possible for you to have a single point of configuring what subclasses should be used, which means that in many cases you'll find you only need to sub-class one of the parser's components.
The exception to this rule are *SourceHandlers* & *Iterators*, but those are both created with customizable *IteratorFactory*.
4. By subclassing, you may end up overriding undocumented methods. That's not a bad thing per se, but be forewarned that undocumented methods may change without warning from one release to the next - we cannot guarantee backwards compatibility. If any *documented* method needs changing, it will be deprecated first, and changed in a later release.
###
Parser Components
#### Sources
A TAP parser consumes input from a single *raw source* of TAP, which could come from anywhere (a file, an executable, a database, an IO handle, a URI, etc..). The source gets bundled up in a <TAP::Parser::Source> object which gathers some meta data about it. The parser then uses a <TAP::Parser::IteratorFactory> to determine which <TAP::Parser::SourceHandler> to use to turn the raw source into a stream of TAP by way of ["Iterators"](#Iterators).
If you simply want `TAP::Parser` to handle a new source of TAP you probably don't need to subclass `TAP::Parser` itself. Rather, you'll need to create a new <TAP::Parser::SourceHandler> class, and just plug it into the parser using the *sources* param to ["new"](#new). Before you start writing one, read through <TAP::Parser::IteratorFactory> to get a feel for how the system works first.
If you find you really need to use your own iterator factory you can still do so without sub-classing `TAP::Parser` by setting ["iterator\_factory\_class"](#iterator_factory_class).
If you just need to customize the objects on creation, subclass <TAP::Parser> and override ["make\_iterator\_factory"](#make_iterator_factory).
Note that `make_source` & `make_perl_source` have been *DEPRECATED* and are now removed.
#### Iterators
A TAP parser uses *iterators* to loop through the *stream* of TAP read in from the *source* it was given. There are a few types of Iterators available by default, all sub-classes of <TAP::Parser::Iterator>. Choosing which iterator to use is the responsibility of the *iterator factory*, though it simply delegates to the *Source Handler* it uses.
If you're writing your own <TAP::Parser::SourceHandler>, you may need to create your own iterators too. If so you'll need to subclass <TAP::Parser::Iterator>.
Note that ["make\_iterator"](#make_iterator) has been *DEPRECATED* and is now removed.
#### Results
A TAP parser creates <TAP::Parser::Result>s as it iterates through the input *stream*. There are quite a few result types available; choosing which class to use is the responsibility of the *result factory*.
To create your own result types you have two options:
option 1 Subclass <TAP::Parser::Result> and register your new result type/class with the default <TAP::Parser::ResultFactory>.
option 2 Subclass <TAP::Parser::ResultFactory> itself and implement your own <TAP::Parser::Result> creation logic. Then you'll need to customize the class used by your parser by setting the `result_factory_class` parameter. See ["new"](#new) for more details.
If you need to customize the objects on creation, subclass <TAP::Parser> and override ["make\_result"](#make_result).
#### Grammar
<TAP::Parser::Grammar> is the heart of the parser. It tokenizes the TAP input *stream* and produces results. If you need to customize its behaviour you should probably familiarize yourself with the source first. Enough lecturing.
Subclass <TAP::Parser::Grammar> and customize your parser by setting the `grammar_class` parameter. See ["new"](#new) for more details.
If you need to customize the objects on creation, subclass <TAP::Parser> and override ["make\_grammar"](#make_grammar)
ACKNOWLEDGMENTS
---------------
All of the following have helped. Bug reports, patches, (im)moral support, or just words of encouragement have all been forthcoming.
* Michael Schwern
* Andy Lester
* chromatic
* GEOFFR
* Shlomi Fish
* Torsten Schoenfeld
* Jerry Gay
* Aristotle
* Adam Kennedy
* Yves Orton
* Adrian Howard
* Sean & Lil
* Andreas J. Koenig
* Florian Ragwitz
* Corion
* Mark Stosberg
* Matt Kraai
* David Wheeler
* Alex Vandiver
* Cosimo Streppone
* Ville Skyttรค
AUTHORS
-------
Curtis "Ovid" Poe <[email protected]>
Andy Armstong <[email protected]>
Eric Wilhelm @ <ewilhelm at cpan dot org>
Michael Peters <mpeters at plusthree dot com>
Leif Eriksen <leif dot eriksen at bigpond dot com>
Steve Purkis <[email protected]>
Nicholas Clark <[email protected]>
Lee Johnson <notfadeaway at btinternet dot com>
Philippe Bruhat <[email protected]>
BUGS
----
Please report any bugs or feature requests to `[email protected]`, or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Harness>. We will be notified, and then you'll automatically be notified of progress on your bug as we make changes.
Obviously, bugs which include patches are best. If you prefer, you can patch against bleed by via anonymous checkout of the latest version:
```
git clone git://github.com/Perl-Toolchain-Gang/Test-Harness.git
```
COPYRIGHT & LICENSE
--------------------
Copyright 2006-2008 Curtis "Ovid" Poe, 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 perlclib perlclib
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Conventions](#Conventions)
+ [File Operations](#File-Operations)
+ [File Input and Output](#File-Input-and-Output)
+ [File Positioning](#File-Positioning)
+ [Memory Management and String Handling](#Memory-Management-and-String-Handling)
+ [Character Class Tests](#Character-Class-Tests)
+ [stdlib.h functions](#stdlib.h-functions)
+ [Miscellaneous functions](#Miscellaneous-functions)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlclib - Internal replacements for standard C library functions
DESCRIPTION
-----------
One thing Perl porters should note is that *perl* doesn't tend to use that much of the C standard library internally; you'll see very little use of, for example, the *ctype.h* functions in there. This is because Perl tends to reimplement or abstract standard library functions, so that we know exactly how they're going to operate.
This is a reference card for people who are familiar with the C library and who want to do things the Perl way; to tell them which functions they ought to use instead of the more normal C functions.
### Conventions
In the following tables:
`t` is a type.
`p` is a pointer.
`n` is a number.
`s` is a string.
`sv`, `av`, `hv`, etc. represent variables of their respective types.
###
File Operations
Instead of the *stdio.h* functions, you should use the Perl abstraction layer. Instead of `FILE*` types, you need to be handling `PerlIO*` types. Don't forget that with the new PerlIO layered I/O abstraction `FILE*` types may not even be available. See also the `perlapio` documentation for more information about the following functions:
```
Instead Of: Use:
stdin PerlIO_stdin()
stdout PerlIO_stdout()
stderr PerlIO_stderr()
fopen(fn, mode) PerlIO_open(fn, mode)
freopen(fn, mode, stream) PerlIO_reopen(fn, mode, perlio) (Dep-
recated)
fflush(stream) PerlIO_flush(perlio)
fclose(stream) PerlIO_close(perlio)
```
###
File Input and Output
```
Instead Of: Use:
fprintf(stream, fmt, ...) PerlIO_printf(perlio, fmt, ...)
[f]getc(stream) PerlIO_getc(perlio)
[f]putc(stream, n) PerlIO_putc(perlio, n)
ungetc(n, stream) PerlIO_ungetc(perlio, n)
```
Note that the PerlIO equivalents of `fread` and `fwrite` are slightly different from their C library counterparts:
```
fread(p, size, n, stream) PerlIO_read(perlio, buf, numbytes)
fwrite(p, size, n, stream) PerlIO_write(perlio, buf, numbytes)
fputs(s, stream) PerlIO_puts(perlio, s)
```
There is no equivalent to `fgets`; one should use `sv_gets` instead:
```
fgets(s, n, stream) sv_gets(sv, perlio, append)
```
###
File Positioning
```
Instead Of: Use:
feof(stream) PerlIO_eof(perlio)
fseek(stream, n, whence) PerlIO_seek(perlio, n, whence)
rewind(stream) PerlIO_rewind(perlio)
fgetpos(stream, p) PerlIO_getpos(perlio, sv)
fsetpos(stream, p) PerlIO_setpos(perlio, sv)
ferror(stream) PerlIO_error(perlio)
clearerr(stream) PerlIO_clearerr(perlio)
```
###
Memory Management and String Handling
```
Instead Of: Use:
t* p = malloc(n) Newx(p, n, t)
t* p = calloc(n, s) Newxz(p, n, t)
p = realloc(p, n) Renew(p, n, t)
memcpy(dst, src, n) Copy(src, dst, n, t)
memmove(dst, src, n) Move(src, dst, n, t)
memcpy(dst, src, sizeof(t)) StructCopy(src, dst, t)
memset(dst, 0, n * sizeof(t)) Zero(dst, n, t)
memzero(dst, 0) Zero(dst, n, char)
free(p) Safefree(p)
strdup(p) savepv(p)
strndup(p, n) savepvn(p, n) (Hey, strndup doesn't
exist!)
strstr(big, little) instr(big, little)
strcmp(s1, s2) strLE(s1, s2) / strEQ(s1, s2)
/ strGT(s1,s2)
strncmp(s1, s2, n) strnNE(s1, s2, n) / strnEQ(s1, s2, n)
memcmp(p1, p2, n) memNE(p1, p2, n)
!memcmp(p1, p2, n) memEQ(p1, p2, n)
```
Notice the different order of arguments to `Copy` and `Move` than used in `memcpy` and `memmove`.
Most of the time, though, you'll want to be dealing with SVs internally instead of raw `char *` strings:
```
strlen(s) sv_len(sv)
strcpy(dt, src) sv_setpv(sv, s)
strncpy(dt, src, n) sv_setpvn(sv, s, n)
strcat(dt, src) sv_catpv(sv, s)
strncat(dt, src) sv_catpvn(sv, s)
sprintf(s, fmt, ...) sv_setpvf(sv, fmt, ...)
```
Note also the existence of `sv_catpvf` and `sv_vcatpvfn`, combining concatenation with formatting.
Sometimes instead of zeroing the allocated heap by using Newxz() you should consider "poisoning" the data. This means writing a bit pattern into it that should be illegal as pointers (and floating point numbers), and also hopefully surprising enough as integers, so that any code attempting to use the data without forethought will break sooner rather than later. Poisoning can be done using the Poison() macros, which have similar arguments to Zero():
```
PoisonWith(dst, n, t, b) scribble memory with byte b
PoisonNew(dst, n, t) equal to PoisonWith(dst, n, t, 0xAB)
PoisonFree(dst, n, t) equal to PoisonWith(dst, n, t, 0xEF)
Poison(dst, n, t) equal to PoisonFree(dst, n, t)
```
###
Character Class Tests
There are several types of character class tests that Perl implements. The only ones described here are those that directly correspond to C library functions that operate on 8-bit characters, but there are equivalents that operate on wide characters, and UTF-8 encoded strings. All are more fully described in ["Character classification" in perlapi](perlapi#Character-classification) and ["Character case changing" in perlapi](perlapi#Character-case-changing).
The C library routines listed in the table below return values based on the current locale. Use the entries in the final column for that functionality. The other two columns always assume a POSIX (or C) locale. The entries in the ASCII column are only meaningful for ASCII inputs, returning FALSE for anything else. Use these only when you **know** that is what you want. The entries in the Latin1 column assume that the non-ASCII 8-bit characters are as Unicode defines, them, the same as ISO-8859-1, often called Latin 1.
```
Instead Of: Use for ASCII: Use for Latin1: Use for locale:
isalnum(c) isALPHANUMERIC(c) isALPHANUMERIC_L1(c) isALPHANUMERIC_LC(c)
isalpha(c) isALPHA(c) isALPHA_L1(c) isALPHA_LC(u )
isascii(c) isASCII(c) isASCII_LC(c)
isblank(c) isBLANK(c) isBLANK_L1(c) isBLANK_LC(c)
iscntrl(c) isCNTRL(c) isCNTRL_L1(c) isCNTRL_LC(c)
isdigit(c) isDIGIT(c) isDIGIT_L1(c) isDIGIT_LC(c)
isgraph(c) isGRAPH(c) isGRAPH_L1(c) isGRAPH_LC(c)
islower(c) isLOWER(c) isLOWER_L1(c) isLOWER_LC(c)
isprint(c) isPRINT(c) isPRINT_L1(c) isPRINT_LC(c)
ispunct(c) isPUNCT(c) isPUNCT_L1(c) isPUNCT_LC(c)
isspace(c) isSPACE(c) isSPACE_L1(c) isSPACE_LC(c)
isupper(c) isUPPER(c) isUPPER_L1(c) isUPPER_LC(c)
isxdigit(c) isXDIGIT(c) isXDIGIT_L1(c) isXDIGIT_LC(c)
tolower(c) toLOWER(c) toLOWER_L1(c)
toupper(c) toUPPER(c)
```
To emphasize that you are operating only on ASCII characters, you can append `_A` to each of the macros in the ASCII column: `isALPHA_A`, `isDIGIT_A`, and so on.
(There is no entry in the Latin1 column for `isascii` even though there is an `isASCII_L1`, which is identical to `isASCII`; the latter name is clearer. There is no entry in the Latin1 column for `toupper` because the result can be non-Latin1. You have to use `toUPPER_uvchr`, as described in ["Character case changing" in perlapi](perlapi#Character-case-changing).)
###
*stdlib.h* functions
```
Instead Of: Use:
atof(s) Atof(s)
atoi(s) grok_atoUV(s, &uv, &e)
atol(s) grok_atoUV(s, &uv, &e)
strtod(s, &p) Strtod(s, &p)
strtol(s, &p, n) Strtol(s, &p, b)
strtoul(s, &p, n) Strtoul(s, &p, b)
```
Typical use is to do range checks on `uv` before casting:
```
int i; UV uv;
char* end_ptr = input_end;
if (grok_atoUV(input, &uv, &end_ptr)
&& uv <= INT_MAX)
i = (int)uv;
... /* continue parsing from end_ptr */
} else {
... /* parse error: not a decimal integer in range 0 .. MAX_IV */
}
```
Notice also the `grok_bin`, `grok_hex`, and `grok_oct` functions in *numeric.c* for converting strings representing numbers in the respective bases into `NV`s. Note that grok\_atoUV() doesn't handle negative inputs, or leading whitespace (being purposefully strict).
Note that strtol() and strtoul() may be disguised as Strtol(), Strtoul(), Atol(), Atoul(). Avoid those, too.
In theory `Strtol` and `Strtoul` may not be defined if the machine perl is built on doesn't actually have strtol and strtoul. But as those 2 functions are part of the 1989 ANSI C spec we suspect you'll find them everywhere by now.
```
int rand() double Drand01()
srand(n) { seedDrand01((Rand_seed_t)n);
PL_srand_called = TRUE; }
exit(n) my_exit(n)
system(s) Don't. Look at pp_system or use my_popen.
getenv(s) PerlEnv_getenv(s)
setenv(s, val) my_setenv(s, val)
```
###
Miscellaneous functions
You should not even **want** to use *setjmp.h* functions, but if you think you do, use the `JMPENV` stack in *scope.h* instead.
For `signal`/`sigaction`, use `rsignal(signo, handler)`.
SEE ALSO
---------
<perlapi>, <perlapio>, <perlguts>
perl TAP::Parser::SourceHandler::File TAP::Parser::SourceHandler::File
================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [can\_handle](#can_handle)
- [make\_iterator](#make_iterator)
- [iterator\_class](#iterator_class)
* [CONFIGURATION](#CONFIGURATION)
* [SUBCLASSING](#SUBCLASSING)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::SourceHandler::File - Stream TAP from a text file.
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Source;
use TAP::Parser::SourceHandler::File;
my $source = TAP::Parser::Source->new->raw( \'file.tap' );
$source->assemble_meta;
my $class = 'TAP::Parser::SourceHandler::File';
my $vote = $class->can_handle( $source );
my $iter = $class->make_iterator( $source );
```
DESCRIPTION
-----------
This is a *raw TAP stored in a file* <TAP::Parser::SourceHandler> - it has 2 jobs:
1. Figure out if the *raw* source it's given is a file containing raw TAP output. See <TAP::Parser::IteratorFactory> for more details.
2. Takes raw TAP from the text file given, and converts into an 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 regular file. Casts the following votes:
```
0.9 if it's a .tap file
0.9 if it has an extension matching any given in user config.
```
#### `make_iterator`
```
my $iterator = $class->make_iterator( $source );
```
Returns a new <TAP::Parser::Iterator::Stream> for the source. `croak`s on error.
#### `iterator_class`
The class of iterator to use, override if you're sub-classing. Defaults to <TAP::Parser::Iterator::Stream>.
CONFIGURATION
-------------
```
{
extensions => [ @case_insensitive_exts_to_match ]
}
```
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::SourceHandler>, <TAP::Parser::SourceHandler::Executable>, <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::Handle>, <TAP::Parser::SourceHandler::RawTAP>
perl Net::NNTP Net::NNTP
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Class Methods](#Class-Methods)
+ [Object Methods](#Object-Methods)
+ [Extension Methods](#Extension-Methods)
+ [Unsupported](#Unsupported)
+ [Definitions](#Definitions)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::NNTP - NNTP Client class
SYNOPSIS
--------
```
use Net::NNTP;
$nntp = Net::NNTP->new("some.host.name");
$nntp->quit;
# start with SSL, e.g. nntps
$nntp = Net::NNTP->new("some.host.name", SSL => 1);
# start with plain and upgrade to SSL
$nntp = Net::NNTP->new("some.host.name");
$nntp->starttls;
```
DESCRIPTION
-----------
`Net::NNTP` is a class implementing a simple NNTP client in Perl as described in RFC977 and RFC4642. With <IO::Socket::SSL> installed it also provides support for implicit and explicit TLS encryption, i.e. NNTPS or NNTP+STARTTLS.
The Net::NNTP 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::NNTP object. `$host` is the name of the remote host to which a NNTP connection is required. If not given then it may be passed as the `Host` option described below. If no host is passed then two environment variables are checked, first `NNTPSERVER` then `NEWSHOST`, then `Net::Config` is checked, and if a host is not found then `news` is used.
`%options` are passed in a hash like fashion, using key and value pairs. Possible options are:
**Host** - NNTP 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 - 119 for plain NNTP and 563 for immediate SSL (nntps).
**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.
**Timeout** - Maximum time, in seconds, to wait for a response from the NNTP server, a value of zero will cause all IO operations to block. (default: 120)
**Debug** - Enable the printing of debugging information to STDERR
**Reader** - If the remote server is INN then initially the connection will be to innd, by default `Net::NNTP` will issue a `MODE READER` command so that the remote server becomes nnrpd. If the `Reader` option is given with a value of zero, then this command will not be sent and the connection will be left talking to innd.
**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.
###
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::NNTP` inherits from `Net::Cmd` so methods defined in `Net::Cmd` may be used to send commands to the remote NNTP 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.
`starttls()`
Upgrade existing plain connection to SSL. Any arguments necessary for SSL must be given in `new` already.
`article([{$msgid|$msgnum}[, $fh]])`
Retrieve the header, a blank line, then the body (text) of the specified article.
If `$fh` is specified then it is expected to be a valid filehandle and the result will be printed to it, on success a true value will be returned. If `$fh` is not specified then the return value, on success, will be a reference to an array containing the article requested, each entry in the array will contain one line of the article.
If no arguments are passed then the current article in the currently selected newsgroup is fetched.
`$msgnum` is a numeric id of an article in the current newsgroup, and will change the current article pointer. `$msgid` is the message id of an article as shown in that article's header. It is anticipated that the client will obtain the `$msgid` from a list provided by the `newnews` command, from references contained within another article, or from the message-id provided in the response to some other commands.
If there is an error then `undef` will be returned.
`body([{$msgid|$msgnum}[, [$fh]])`
Like `article` but only fetches the body of the article.
`head([{$msgid|$msgnum}[, [$fh]])`
Like `article` but only fetches the headers for the article.
`articlefh([{$msgid|$msgnum}])`
`bodyfh([{$msgid|$msgnum}])`
`headfh([{$msgid|$msgnum}])`
These are similar to article(), body() and head(), but rather than returning the requested data directly, they return a tied filehandle from which to read the article.
`nntpstat([{$msgid|$msgnum}])`
The `nntpstat` command is similar to the `article` command except that no text is returned. When selecting by message number within a group, the `nntpstat` command serves to set the "current article pointer" without sending text.
Using the `nntpstat` command to select by message-id is valid but of questionable value, since a selection by message-id does **not** alter the "current article pointer".
Returns the message-id of the "current article".
`group([$group])`
Set and/or get the current group. If `$group` is not given then information is returned on the current group.
In a scalar context it returns the group name.
In an array context the return value is a list containing, the number of articles in the group, the number of the first article, the number of the last article and the group name.
`help()`
Request help text (a short summary of commands that are understood by this implementation) from the server. Returns the text or undef upon failure.
`ihave($msgid[, $message])`
The `ihave` command informs the server that the client has an article whose id is `$msgid`. If the server desires a copy of that article and `$message` has been given then it will be sent.
Returns *true* if the server desires the article and `$message` was successfully sent, if specified.
If `$message` is not specified then the message must be sent using the `datasend` and `dataend` methods from <Net::Cmd>
`$message` can be either an array of lines or a reference to an array and must be encoded by the caller to octets of whatever encoding is required, e.g. by using the Encode module's `encode()` function.
`last()`
Set the "current article pointer" to the previous article in the current newsgroup.
Returns the message-id of the article.
`date()`
Returns the date on the remote server. This date will be in a UNIX time format (seconds since 1970)
`postok()`
`postok` will return *true* if the servers initial response indicated that it will allow posting.
`authinfo($user, $pass)`
Authenticates to the server (using the original AUTHINFO USER / AUTHINFO PASS form, defined in RFC2980) using the supplied username and password. Please note that the password is sent in clear text to the server. This command should not be used with valuable passwords unless the connection to the server is somehow protected.
`authinfo_simple($user, $pass)`
Authenticates to the server (using the proposed NNTP V2 AUTHINFO SIMPLE form, defined and deprecated in RFC2980) using the supplied username and password. As with ["authinfo"](#authinfo) the password is sent in clear text.
`list()`
Obtain information about all the active newsgroups. The results is a reference to a hash where the key is a group name and each value is a reference to an array. The elements in this array are:- the last article number in the group, the first article number in the group and any information flags about the group.
`newgroups($since[, $distributions])`
`$since` is a time value and `$distributions` is either a distribution pattern or a reference to a list of distribution patterns. The result is the same as `list`, but the groups return will be limited to those created after `$since` and, if specified, in one of the distribution areas in `$distributions`.
`newnews($since[, $groups[, $distributions]])`
`$since` is a time value. `$groups` is either a group pattern or a reference to a list of group patterns. `$distributions` is either a distribution pattern or a reference to a list of distribution patterns.
Returns a reference to a list which contains the message-ids of all news posted after `$since`, that are in a groups which matched `$groups` and a distribution which matches `$distributions`.
`next()`
Set the "current article pointer" to the next article in the current newsgroup.
Returns the message-id of the article.
`post([$message])`
Post a new article to the news server. If `$message` is specified and posting is allowed then the message will be sent.
If `$message` is not specified then the message must be sent using the `datasend` and `dataend` methods from <Net::Cmd>
`$message` can be either an array of lines or a reference to an array and must be encoded by the caller to octets of whatever encoding is required, e.g. by using the Encode module's `encode()` function.
The message, either sent via `datasend` or as the `$message` parameter, must be in the format as described by RFC822 and must contain From:, Newsgroups: and Subject: headers.
`postfh()`
Post a new article to the news server using a tied filehandle. If posting is allowed, this method will return a tied filehandle that you can print() the contents of the article to be posted. You must explicitly close() the filehandle when you are finished posting the article, and the return value from the close() call will indicate whether the message was successfully posted.
`slave()`
Tell the remote server that I am not a user client, but probably another news server.
`quit()`
Quit the remote server and close the socket connection.
`can_inet6()`
Returns whether we can use IPv6.
`can_ssl()`
Returns whether we can use SSL.
###
Extension Methods
These methods use commands that are not part of the RFC977 documentation. Some servers may not support all of them.
`newsgroups([$pattern])`
Returns a reference to a hash where the keys are all the group names which match `$pattern`, or all of the groups if no pattern is specified, and each value contains the description text for the group.
`distributions()`
Returns a reference to a hash where the keys are all the possible distribution names and the values are the distribution descriptions.
`distribution_patterns()`
Returns a reference to an array where each element, itself an array reference, consists of the three fields of a line of the distrib.pats list maintained by some NNTP servers, namely: a weight, a wildmat and a value which the client may use to construct a Distribution header.
`subscriptions()`
Returns a reference to a list which contains a list of groups which are recommended for a new user to subscribe to.
`overview_fmt()`
Returns a reference to an array which contain the names of the fields returned by `xover`.
`active_times()`
Returns a reference to a hash where the keys are the group names and each value is a reference to an array containing the time the groups was created and an identifier, possibly an Email address, of the creator.
`active([$pattern])`
Similar to `list` but only active groups that match the pattern are returned. `$pattern` can be a group pattern.
`xgtitle($pattern)`
Returns a reference to a hash where the keys are all the group names which match `$pattern` and each value is the description text for the group.
`xhdr($header, $message_spec)`
Obtain the header field `$header` for all the messages specified.
The return value will be a reference to a hash where the keys are the message numbers and each value contains the text of the requested header for that message.
`xover($message_spec)`
The return value will be a reference to a hash where the keys are the message numbers and each value contains a reference to an array which contains the overview fields for that message.
The names of the fields can be obtained by calling `overview_fmt`.
`xpath($message_id)`
Returns the path name to the file on the server which contains the specified message.
`xpat($header, $pattern, $message_spec)`
The result is the same as `xhdr` except the is will be restricted to headers where the text of the header matches `$pattern`
`xrover($message_spec)`
The XROVER command returns reference information for the article(s) specified.
Returns a reference to a HASH where the keys are the message numbers and the values are the References: lines from the articles
`listgroup([$group])`
Returns a reference to a list of all the active messages in `$group`, or the current group if `$group` is not specified.
`reader()`
Tell the server that you are a reader and not another server.
This is required by some servers. For example if you are connecting to an INN server and you have transfer permission your connection will be connected to the transfer daemon, not the NNTP daemon. Issuing this command will cause the transfer daemon to hand over control to the NNTP daemon.
Some servers do not understand this command, but issuing it and ignoring the response is harmless.
### Unsupported
The following NNTP command are unsupported by the package, and there are no plans to do so.
```
AUTHINFO GENERIC
XTHREAD
XSEARCH
XINDEX
```
### Definitions
$message\_spec `$message_spec` is either a single message-id, a single message number, or a reference to a list of two message numbers.
If `$message_spec` is a reference to a list of two message numbers and the second number in a range is less than or equal to the first then the range represents all messages in the group after the first message number.
**NOTE** For compatibility reasons only with earlier versions of Net::NNTP a message spec can be passed as a list of two numbers, this is deprecated and a reference to the list should now be passed
$pattern The `NNTP` protocol uses the `WILDMAT` format for patterns. The WILDMAT format was first developed by Rich Salz based on the format used in the UNIX "find" command to articulate file names. It was developed to provide a uniform mechanism for matching patterns in the same manner that the UNIX shell matches filenames.
Patterns are implicitly anchored at the beginning and end of each string when testing for a match.
There are five pattern matching operations other than a strict one-to-one match between the pattern and the source to be checked for a match.
The first is an asterisk `*` to match any sequence of zero or more characters.
The second is a question mark `?` to match any single character. The third specifies a specific set of characters.
The set is specified as a list of characters, or as a range of characters where the beginning and end of the range are separated by a minus (or dash) character, or as any combination of lists and ranges. The dash can also be included in the set as a character it if is the beginning or end of the set. This set is enclosed in square brackets. The close square bracket `]` may be used in a set if it is the first character in the set.
The fourth operation is the same as the logical not of the third operation and is specified the same way as the third with the addition of a caret character `^` at the beginning of the test string just inside the open square bracket.
The final operation uses the backslash character to invalidate the special meaning of an open square bracket `[`, the asterisk, backslash or the question mark. Two backslashes in sequence will result in the evaluation of the backslash as a character with no special meaning.
Examples
`[^]-]`
matches any single character other than a close square bracket or a minus sign/dash.
`*bdc`
matches any string that ends with the string "bdc" including the string "bdc" (without quotes).
`[0-9a-zA-Z]`
matches any single printable alphanumeric ASCII character.
`a??d`
matches any four character string which begins with a and ends with d.
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-1997 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.
| programming_docs |
perl Test2::Event::TAP::Version Test2::Event::TAP::Version
==========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::TAP::Version - Event for TAP version.
DESCRIPTION
-----------
This event is used if a TAP formatter wishes to set a version.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Encoding;
my $ctx = context();
my $event = $ctx->send_event('TAP::Version', version => 42);
```
METHODS
-------
Inherits from <Test2::Event>. Also defines:
$version = $e->version The TAP version being parsed.
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 Class::Struct Class::Struct
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The struct() function](#The-struct()-function)
+ [Class Creation at Compile Time](#Class-Creation-at-Compile-Time)
+ [Element Types and Accessor Methods](#Element-Types-and-Accessor-Methods)
+ [Initializing with new](#Initializing-with-new)
* [EXAMPLES](#EXAMPLES)
* [Author and Modification History](#Author-and-Modification-History)
NAME
----
Class::Struct - declare struct-like datatypes as Perl classes
SYNOPSIS
--------
```
use Class::Struct;
# declare struct, based on array:
struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
# declare struct, based on hash:
struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
package CLASS_NAME;
use Class::Struct;
# declare struct, based on array, implicit class name:
struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
# Declare struct at compile time
use Class::Struct CLASS_NAME => [ELEMENT_NAME => ELEMENT_TYPE, ...];
use Class::Struct CLASS_NAME => {ELEMENT_NAME => ELEMENT_TYPE, ...};
# declare struct at compile time, based on array, implicit
# class name:
package CLASS_NAME;
use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ;
package Myobj;
use Class::Struct;
# declare struct with four types of elements:
struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
$obj = new Myobj; # constructor
# scalar type accessor:
$element_value = $obj->s; # element value
$obj->s('new value'); # assign to element
# array type accessor:
$ary_ref = $obj->a; # reference to whole array
$ary_element_value = $obj->a(2); # array element value
$obj->a(2, 'new value'); # assign to array element
# hash type accessor:
$hash_ref = $obj->h; # reference to whole hash
$hash_element_value = $obj->h('x'); # hash element value
$obj->h('x', 'new value'); # assign to hash element
# class type accessor:
$element_value = $obj->c; # object reference
$obj->c->method(...); # call method of object
$obj->c(new My_Other_Class); # assign a new object
```
DESCRIPTION
-----------
`Class::Struct` exports a single function, `struct`. Given a list of element names and types, and optionally a class name, `struct` creates a Perl 5 class that implements a "struct-like" data structure.
The new class is given a constructor method, `new`, for creating struct objects.
Each element in the struct data has an accessor method, which is used to assign to the element and to fetch its value. The default accessor can be overridden by declaring a `sub` of the same name in the package. (See Example 2.)
Each element's type can be scalar, array, hash, or class.
###
The `struct()` function
The `struct` function has three forms of parameter-list.
```
struct( CLASS_NAME => [ ELEMENT_LIST ]);
struct( CLASS_NAME => { ELEMENT_LIST });
struct( ELEMENT_LIST );
```
The first and second forms explicitly identify the name of the class being created. The third form assumes the current package name as the class name.
An object of a class created by the first and third forms is based on an array, whereas an object of a class created by the second form is based on a hash. The array-based forms will be somewhat faster and smaller; the hash-based forms are more flexible.
The class created by `struct` must not be a subclass of another class other than `UNIVERSAL`.
It can, however, be used as a superclass for other classes. To facilitate this, the generated constructor method uses a two-argument blessing. Furthermore, if the class is hash-based, the key of each element is prefixed with the class name (see *Perl Cookbook*, Recipe 13.12).
A function named `new` must not be explicitly defined in a class created by `struct`.
The *ELEMENT\_LIST* has the form
```
NAME => TYPE, ...
```
Each name-type pair declares one element of the struct. Each element name will be defined as an accessor method unless a method by that name is explicitly defined; in the latter case, a warning is issued if the warning flag (**-w**) is set.
###
Class Creation at Compile Time
`Class::Struct` can create your class at compile time. The main reason for doing this is obvious, so your class acts like every other class in Perl. Creating your class at compile time will make the order of events similar to using any other class ( or Perl module ).
There is no significant speed gain between compile time and run time class creation, there is just a new, more standard order of events.
###
Element Types and Accessor Methods
The four element types -- scalar, array, hash, and class -- are represented by strings -- `'$'`, `'@'`, `'%'`, and a class name -- optionally preceded by a `'*'`.
The accessor method provided by `struct` for an element depends on the declared type of the element.
Scalar (`'$'` or `'*$'`) The element is a scalar, and by default is initialized to `undef` (but see ["Initializing with new"](#Initializing-with-new)).
The accessor's argument, if any, is assigned to the element.
If the element type is `'$'`, the value of the element (after assignment) is returned. If the element type is `'*$'`, a reference to the element is returned.
Array (`'@'` or `'*@'`) The element is an array, initialized by default to `()`.
With no argument, the accessor returns a reference to the element's whole array (whether or not the element was specified as `'@'` or `'*@'`).
With one or two arguments, the first argument is an index specifying one element of the array; the second argument, if present, is assigned to the array element. If the element type is `'@'`, the accessor returns the array element value. If the element type is `'*@'`, a reference to the array element is returned.
As a special case, when the accessor is called with an array reference as the sole argument, this causes an assignment of the whole array element. The object reference is returned.
Hash (`'%'` or `'*%'`) The element is a hash, initialized by default to `()`.
With no argument, the accessor returns a reference to the element's whole hash (whether or not the element was specified as `'%'` or `'*%'`).
With one or two arguments, the first argument is a key specifying one element of the hash; the second argument, if present, is assigned to the hash element. If the element type is `'%'`, the accessor returns the hash element value. If the element type is `'*%'`, a reference to the hash element is returned.
As a special case, when the accessor is called with a hash reference as the sole argument, this causes an assignment of the whole hash element. The object reference is returned.
Class (`'Class_Name'` or `'*Class_Name'`) The element's value must be a reference blessed to the named class or to one of its subclasses. The element is not initialized by default.
The accessor's argument, if any, is assigned to the element. The accessor will `croak` if this is not an appropriate object reference.
If the element type does not start with a `'*'`, the accessor returns the element value (after assignment). If the element type starts with a `'*'`, a reference to the element itself is returned.
###
Initializing with `new`
`struct` always creates a constructor called `new`. That constructor may take a list of initializers for the various elements of the new struct.
Each initializer is a pair of values: *element name* `=>` *value*. The initializer value for a scalar element is just a scalar value. The initializer for an array element is an array reference. The initializer for a hash is a hash reference.
The initializer for a class element is an object of the corresponding class, or of one of it's subclasses, or a reference to a hash containing named arguments to be passed to the element's constructor.
See Example 3 below for an example of initialization.
EXAMPLES
--------
Example 1 Giving a struct element a class type that is also a struct is how structs are nested. Here, `Timeval` represents a time (seconds and microseconds), and `Rusage` has two elements, each of which is of type `Timeval`.
```
use Class::Struct;
struct( Rusage => {
ru_utime => 'Timeval', # user time used
ru_stime => 'Timeval', # system time used
});
struct( Timeval => [
tv_secs => '$', # seconds
tv_usecs => '$', # microseconds
]);
# create an object:
my $t = Rusage->new(ru_utime=>Timeval->new(),
ru_stime=>Timeval->new());
# $t->ru_utime and $t->ru_stime are objects of type Timeval.
# set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
$t->ru_utime->tv_secs(100);
$t->ru_utime->tv_usecs(0);
$t->ru_stime->tv_secs(5);
$t->ru_stime->tv_usecs(0);
```
Example 2 An accessor function can be redefined in order to provide additional checking of values, etc. Here, we want the `count` element always to be nonnegative, so we redefine the `count` accessor accordingly.
```
package MyObj;
use Class::Struct;
# declare the struct
struct ( 'MyObj', { count => '$', stuff => '%' } );
# override the default accessor method for 'count'
sub count {
my $self = shift;
if ( @_ ) {
die 'count must be nonnegative' if $_[0] < 0;
$self->{'MyObj::count'} = shift;
warn "Too many args to count" if @_;
}
return $self->{'MyObj::count'};
}
package main;
$x = new MyObj;
print "\$x->count(5) = ", $x->count(5), "\n";
# prints '$x->count(5) = 5'
print "\$x->count = ", $x->count, "\n";
# prints '$x->count = 5'
print "\$x->count(-5) = ", $x->count(-5), "\n";
# dies due to negative argument!
```
Example 3 The constructor of a generated class can be passed a list of *element*=>*value* pairs, with which to initialize the struct. If no initializer is specified for a particular element, its default initialization is performed instead. Initializers for non-existent elements are silently ignored.
Note that the initializer for a nested class may be specified as an object of that class, or as a reference to a hash of initializers that are passed on to the nested struct's constructor.
```
use Class::Struct;
struct Breed =>
{
name => '$',
cross => '$',
};
struct Cat =>
[
name => '$',
kittens => '@',
markings => '%',
breed => 'Breed',
];
my $cat = Cat->new( name => 'Socks',
kittens => ['Monica', 'Kenneth'],
markings => { socks=>1, blaze=>"white" },
breed => Breed->new(name=>'short-hair', cross=>1),
or: breed => {name=>'short-hair', cross=>1},
);
print "Once a cat called ", $cat->name, "\n";
print "(which was a ", $cat->breed->name, ")\n";
print "had 2 kittens: ", join(' and ', @{$cat->kittens}), "\n";
```
Author and Modification History
--------------------------------
Modified by Damian Conway, 2001-09-10, v0.62.
```
Modified implicit construction of nested objects.
Now will also take an object ref instead of requiring a hash ref.
Also default initializes nested object attributes to undef, rather
than calling object constructor without args
Original over-helpfulness was fraught with problems:
* the class's constructor might not be called 'new'
* the class might not have a hash-like-arguments constructor
* the class might not have a no-argument constructor
* "recursive" data structures didn't work well:
package Person;
struct { mother => 'Person', father => 'Person'};
```
Modified by Casey West, 2000-11-08, v0.59.
```
Added the ability for compile time class creation.
```
Modified by Damian Conway, 1999-03-05, v0.58.
```
Added handling of hash-like arg list to class ctor.
Changed to two-argument blessing in ctor to support
derivation from created classes.
Added classname prefixes to keys in hash-based classes
(refer to "Perl Cookbook", Recipe 13.12 for rationale).
Corrected behaviour of accessors for '*@' and '*%' struct
elements. Package now implements documented behaviour when
returning a reference to an entire hash or array element.
Previously these were returned as a reference to a reference
to the element.
```
Renamed to `Class::Struct` and modified by Jim Miner, 1997-04-02.
```
members() function removed.
Documentation corrected and extended.
Use of struct() in a subclass prohibited.
User definition of accessor allowed.
Treatment of '*' in element types corrected.
Treatment of classes as element types corrected.
Class name to struct() made optional.
Diagnostic checks added.
```
Originally `Class::Template` by Dean Roehrich.
```
# Template.pm --- struct/member template builder
# 12mar95
# Dean Roehrich
#
# changes/bugs fixed since 28nov94 version:
# - podified
# changes/bugs fixed since 21nov94 version:
# - Fixed examples.
# changes/bugs fixed since 02sep94 version:
# - Moved to Class::Template.
# changes/bugs fixed since 20feb94 version:
# - Updated to be a more proper module.
# - Added "use strict".
# - Bug in build_methods, was using @var when @$var needed.
# - Now using my() rather than local().
#
# Uses perl5 classes to create nested data types.
# This is offered as one implementation of Tom Christiansen's
# "structs.pl" idea.
```
perl User::pwent User::pwent
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [System Specifics](#System-Specifics)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
* [HISTORY](#HISTORY)
NAME
----
User::pwent - by-name interface to Perl's built-in getpw\*() functions
SYNOPSIS
--------
```
use User::pwent;
$pw = getpwnam('daemon') || die "No daemon user";
if ( $pw->uid == 1 && $pw->dir =~ m#^/(bin|tmp)?\z#s ) {
print "gid 1 on root dir";
}
$real_shell = $pw->shell || '/bin/sh';
for (($fullname, $office, $workphone, $homephone) =
split /\s*,\s*/, $pw->gecos)
{
s/&/ucfirst(lc($pw->name))/ge;
}
use User::pwent qw(:FIELDS);
getpwnam('daemon') || die "No daemon user";
if ( $pw_uid == 1 && $pw_dir =~ m#^/(bin|tmp)?\z#s ) {
print "gid 1 on root dir";
}
$pw = getpw($whoever);
use User::pwent qw/:DEFAULT pw_has/;
if (pw_has(qw[gecos expire quota])) { .... }
if (pw_has("name uid gid passwd")) { .... }
print "Your struct pwd has: ", scalar pw_has(), "\n";
```
DESCRIPTION
-----------
This module's default exports override the core getpwent(), getpwuid(), and getpwnam() functions, replacing them with versions that return `User::pwent` objects. This object has methods that return the similarly named structure field name from the C's passwd structure from *pwd.h*, stripped of their leading "pw\_" parts, namely `name`, `passwd`, `uid`, `gid`, `change`, `age`, `quota`, `comment`, `class`, `gecos`, `dir`, `shell`, and `expire`. The `passwd`, `gecos`, and `shell` fields are tainted when running in taint mode.
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 `pw_` in front their method names. Thus, `$passwd_obj->shell` corresponds to $pw\_shell if you import the fields.
The getpw() function is a simple front-end that forwards a numeric argument to getpwuid() and the rest to getpwnam().
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. The built-ins are always still available via the `CORE::` pseudo-package.
###
System Specifics
Perl believes that no machine ever has more than one of `change`, `age`, or `quota` implemented, nor more than one of either `comment` or `class`. Some machines do not support `expire`, `gecos`, or allegedly, `passwd`. You may call these methods no matter what machine you're on, but they return `undef` if unimplemented.
You may ask whether one of these was implemented on the system Perl was built on by asking the importable `pw_has` function about them. This function returns true if all parameters are supported fields on the build platform, false if one or more were not, and raises an exception if you asked about a field that Perl never knows how to provide. Parameters may be in a space-separated string, or as separate arguments. If you pass no parameters, the function returns the list of `struct pwd` fields supported by your build platform's C library, as a list in list context, or a space-separated string in scalar context. Note that just because your C library had a field doesn't necessarily mean that it's fully implemented on that system.
Interpretation of the `gecos` field varies between systems, but traditionally holds 4 comma-separated fields containing the user's full name, office location, work phone number, and home phone number. An `&` in the gecos field should be replaced by the user's properly capitalized login `name`. The `shell` field, if blank, must be assumed to be */bin/sh*. Perl does not do this for you. The `passwd` is one-way hashed garble, not clear text, and may not be unhashed save by brute-force guessing. Secure systems use more a more secure hashing than DES. On systems supporting shadow password systems, Perl automatically returns the shadow password entry when called by a suitably empowered user, even if your underlying vendor-provided C library was too short-sighted to realize it should do this.
See passwd(5) and getpwent(3) for details.
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
HISTORY
-------
March 18th, 2000 Reworked internals to support better interface to dodgey fields than normal Perl function provides. Added pw\_has() field. Improved documentation.
perl Text::Abbrev Text::Abbrev
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE](#EXAMPLE)
NAME
----
Text::Abbrev - abbrev - create an abbreviation table from a list
SYNOPSIS
--------
```
use Text::Abbrev;
abbrev $hashref, LIST
```
DESCRIPTION
-----------
Stores all unambiguous truncations of each element of LIST as keys in the associative array referenced by `$hashref`. The values are the original list elements.
EXAMPLE
-------
```
$hashref = abbrev qw(list edit send abort gripe);
%hash = abbrev qw(list edit send abort gripe);
abbrev $hashref, qw(list edit send abort gripe);
abbrev(*hash, qw(list edit send abort gripe));
```
| programming_docs |
perl Pod::Simple::JustPod Pod::Simple::JustPod
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::JustPod -- just the Pod, the whole Pod, and nothing but the Pod
SYNOPSIS
--------
```
my $infile = "mixed_code_and_pod.pm";
my $outfile = "just_the_pod.pod";
open my $fh, ">$outfile" or die "Can't write to $outfile: $!";
my $parser = Pod::Simple::JustPod->new();
$parser->output_fh($fh);
$parser->parse_file($infile);
close $fh or die "Can't close $outfile: $!";
```
DESCRIPTION
-----------
This class returns a copy of its input, translated into Perl's internal encoding (UTF-8), and with all the non-Pod lines removed.
This is a subclass of <Pod::Simple::Methody> and inherits all its methods. And since, that in turn is a subclass of <Pod::Simple>, you can use any of its methods. This means you can output to a string instead of a file, or you can parse from an array.
This class strives to return the Pod lines of the input completely unchanged, except for any necessary translation into Perl's internal encoding, and it makes no effort to return trailing spaces on lines; these likely will be stripped. If the input pod is well-formed with no warnings nor errors generated, the extracted pod should generate the same documentation when formatted by a Pod formatter as the original file does.
By default, warnings are output to STDERR
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::Methody>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the <mailto:[email protected]> mail list. Send an empty email to <mailto:[email protected]> to subscribe.
This module is managed in an open GitHub repository, <https://github.com/theory/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/theory/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to [mailto:<[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]`
Pod::Simple::JustPod was developed by John SJ Anderson `[email protected]`, with contributions from Karl Williamson `[email protected]`.
perl Test2::API::Instance Test2::API::Instance
====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::Instance - Object used by Test2::API under the hood
DESCRIPTION
-----------
This object encapsulates the global shared state tracked by [Test2](test2). A single global instance of this package is stored (and obscured) by the <Test2::API> package.
There is no reason to directly use this package. This package is documented for completeness. This package can change, or go away completely at any time. Directly using, or monkeypatching this package is not supported in any way shape or form.
SYNOPSIS
--------
```
use Test2::API::Instance;
my $obj = Test2::API::Instance->new;
```
$pid = $obj->pid PID of this instance.
$obj->tid Thread ID of this instance.
$obj->reset() Reset the object to defaults.
$obj->load() Set the internal state to loaded, and run and stored post-load callbacks.
$bool = $obj->loaded Check if the state is set to loaded.
$arrayref = $obj->post\_load\_callbacks Get the post-load callbacks.
$obj->add\_post\_load\_callback(sub { ... }) Add a post-load callback. If `load()` has already been called then the callback will be immediately executed. If `load()` has not been called then the callback will be stored and executed later when `load()` is called.
$hashref = $obj->contexts() Get a hashref of all active contexts keyed by hub id.
$arrayref = $obj->context\_acquire\_callbacks Get all context acquire callbacks.
$arrayref = $obj->context\_init\_callbacks Get all context init callbacks.
$arrayref = $obj->context\_release\_callbacks Get all context release callbacks.
$arrayref = $obj->pre\_subtest\_callbacks Get all pre-subtest callbacks.
$obj->add\_context\_init\_callback(sub { ... }) Add a context init callback. Subs are called every time a context is created. Subs get the newly created context as their only argument.
$obj->add\_context\_release\_callback(sub { ... }) Add a context release callback. Subs are called every time a context is released. Subs get the released context as their only argument. These callbacks should not call release on the context.
$obj->add\_pre\_subtest\_callback(sub { ... }) Add a pre-subtest callback. Subs are called every time a subtest is going to be run. Subs get the subtest name, coderef, and any arguments.
$obj->set\_exit() This is intended to be called in an `END { ... }` block. This will look at test state and set $?. This will also call any end callbacks, and wait on child processes/threads.
$obj->set\_ipc\_pending($val) Tell other processes and threads there is a pending event. `$val` should be a unique value no other thread/process will generate.
**Note:** This will also make the current process see a pending event.
$pending = $obj->get\_ipc\_pending() This returns -1 if it is not possible to know.
This returns 0 if there are no pending events.
This returns 1 if there are pending events.
$timeout = $obj->ipc\_timeout;
$obj->set\_ipc\_timeout($timeout); How long to wait for child processes and threads before aborting.
$drivers = $obj->ipc\_drivers Get the list of IPC drivers.
$obj->add\_ipc\_driver($DRIVER\_CLASS) Add an IPC driver to the list. The most recently added IPC driver will become the global one during initialization. If a driver is added after initialization has occurred a warning will be generated:
```
"IPC driver $driver loaded too late to be used as the global ipc driver"
```
$bool = $obj->ipc\_polling Check if polling is enabled.
$obj->enable\_ipc\_polling Turn on polling. This will cull events from other processes and threads every time a context is created.
$obj->disable\_ipc\_polling Turn off IPC polling.
$bool = $obj->no\_wait
$bool = $obj->set\_no\_wait($bool) Get/Set no\_wait. This option is used to turn off process/thread waiting at exit.
$arrayref = $obj->exit\_callbacks Get the exit callbacks.
$obj->add\_exit\_callback(sub { ... }) Add an exit callback. This callback will be called by `set_exit()`.
$bool = $obj->finalized Check if the object is finalized. Finalization happens when either `ipc()`, `stack()`, or `format()` are called on the object. Once finalization happens these fields are considered unchangeable (not enforced here, enforced by [Test2](test2)).
$ipc = $obj->ipc Get the one true IPC instance.
$obj->ipc\_disable Turn IPC off
$bool = $obj->ipc\_disabled Check if IPC is disabled
$stack = $obj->stack Get the one true hub stack.
$formatter = $obj->formatter Get the global formatter. By default this is the `'Test2::Formatter::TAP'` package. This could be any package that implements the `write()` method. This can also be an instantiated object.
$bool = $obj->formatter\_set() Check if a formatter has been set.
$obj->add\_formatter($class)
$obj->add\_formatter($obj) Add a formatter. The most recently added formatter will become the global one during initialization. If a formatter is added after initialization has occurred a warning will be generated:
```
"Formatter $formatter loaded too late to be used as the global formatter"
```
$obj->set\_add\_uuid\_via(sub { ... })
$sub = $obj->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.
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 HTTP::Tiny HTTP::Tiny
==========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [get|head|put|post|patch|delete](#get%7Chead%7Cput%7Cpost%7Cpatch%7Cdelete)
+ [post\_form](#post_form)
+ [mirror](#mirror)
+ [request](#request)
+ [www\_form\_urlencode](#www_form_urlencode)
+ [can\_ssl](#can_ssl)
+ [connected](#connected)
* [SSL SUPPORT](#SSL-SUPPORT)
* [PROXY SUPPORT](#PROXY-SUPPORT)
* [LIMITATIONS](#LIMITATIONS)
* [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
----
HTTP::Tiny - A small, simple, correct HTTP/1.1 client
VERSION
-------
version 0.080
SYNOPSIS
--------
```
use HTTP::Tiny;
my $response = HTTP::Tiny->new->get('http://example.com/');
die "Failed!\n" unless $response->{success};
print "$response->{status} $response->{reason}\n";
while (my ($k, $v) = each %{$response->{headers}}) {
for (ref $v eq 'ARRAY' ? @$v : $v) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
```
DESCRIPTION
-----------
This is a very simple HTTP/1.1 client, designed for doing simple requests without the overhead of a large framework like <LWP::UserAgent>.
It is more correct and more complete than <HTTP::Lite>. It supports proxies and redirection. It also correctly resumes after EINTR.
If <IO::Socket::IP> 0.25 or later is installed, HTTP::Tiny will use it instead of <IO::Socket::INET> for transparent support for both IPv4 and IPv6.
Cookie support requires <HTTP::CookieJar> or an equivalent class.
METHODS
-------
### new
```
$http = HTTP::Tiny->new( %attributes );
```
This constructor returns a new HTTP::Tiny object. Valid attributes include:
* `agent` โ A user-agent string (defaults to 'HTTP-Tiny/$VERSION'). If `agent` โ ends in a space character, the default user-agent string is appended.
* `cookie_jar` โ An instance of <HTTP::CookieJar> โ or equivalent class that supports the `add` and `cookie_header` methods
* `default_headers` โ A hashref of default headers to apply to requests
* `local_address` โ The local IP address to bind to
* `keep_alive` โ Whether to reuse the last connection (if for the same scheme, host and port) (defaults to 1)
* `max_redirect` โ Maximum number of redirects allowed (defaults to 5)
* `max_size` โ Maximum response size in bytes (only when not using a data callback). If defined, requests with responses larger than this will return a 599 status code.
* `http_proxy` โ URL of a proxy server to use for HTTP connections (default is `$ENV{http_proxy}` โ if set)
* `https_proxy` โ URL of a proxy server to use for HTTPS connections (default is `$ENV{https_proxy}` โ if set)
* `proxy` โ URL of a generic proxy server for both HTTP and HTTPS connections (default is `$ENV{all_proxy}` โ if set)
* `no_proxy` โ List of domain suffixes that should not be proxied. Must be a comma-separated string or an array reference. (default is `$ENV{no_proxy}` โ)
* `timeout` โ Request timeout in seconds (default is 60) If a socket open, read or write takes longer than the timeout, the request response status code will be 599.
* `verify_SSL` โ A boolean that indicates whether to validate the SSL certificate of an `https` โ connection (default is false)
* `SSL_options` โ A hashref of `SSL_*` โ options to pass through to <IO::Socket::SSL>
An accessor/mutator method exists for each attribute.
Passing an explicit `undef` for `proxy`, `http_proxy` or `https_proxy` will prevent getting the corresponding proxies from the environment.
Errors during request execution will result in a pseudo-HTTP status code of 599 and a reason of "Internal Exception". The content field in the response will contain the text of the error.
The `keep_alive` parameter enables a persistent connection, but only to a single destination scheme, host and port. If any connection-relevant attributes are modified via accessor, or if the process ID or thread ID change, the persistent connection will be dropped. If you want persistent connections across multiple destinations, use multiple HTTP::Tiny objects.
See ["SSL SUPPORT"](#SSL-SUPPORT) for more on the `verify_SSL` and `SSL_options` attributes.
###
get|head|put|post|patch|delete
```
$response = $http->get($url);
$response = $http->get($url, \%options);
$response = $http->head($url);
```
These methods are shorthand for calling `request()` for the given method. The URL must have unsafe characters escaped and international domain names encoded. See `request()` for valid options and a description of the response.
The `success` field of the response will be true if the status code is 2XX.
### post\_form
```
$response = $http->post_form($url, $form_data);
$response = $http->post_form($url, $form_data, \%options);
```
This method executes a `POST` request and sends the key/value pairs from a form data hash or array reference to the given URL with a `content-type` of `application/x-www-form-urlencoded`. If data is provided as an array reference, the order is preserved; if provided as a hash reference, the terms are sorted on key and value for consistency. See documentation for the `www_form_urlencode` method for details on the encoding.
The URL must have unsafe characters escaped and international domain names encoded. See `request()` for valid options and a description of the response. Any `content-type` header or content in the options hashref will be ignored.
The `success` field of the response will be true if the status code is 2XX.
### mirror
```
$response = $http->mirror($url, $file, \%options)
if ( $response->{success} ) {
print "$file is up to date\n";
}
```
Executes a `GET` request for the URL and saves the response body to the file name provided. The URL must have unsafe characters escaped and international domain names encoded. If the file already exists, the request will include an `If-Modified-Since` header with the modification timestamp of the file. You may specify a different `If-Modified-Since` header yourself in the `$options->{headers}` hash.
The `success` field of the response will be true if the status code is 2XX or if the status code is 304 (unmodified).
If the file was modified and the server response includes a properly formatted `Last-Modified` header, the file modification time will be updated accordingly.
### request
```
$response = $http->request($method, $url);
$response = $http->request($method, $url, \%options);
```
Executes an HTTP request of the given method type ('GET', 'HEAD', 'POST', 'PUT', etc.) on the given URL. The URL must have unsafe characters escaped and international domain names encoded.
**NOTE**: Method names are **case-sensitive** per the HTTP/1.1 specification. Don't use `get` when you really want `GET`. See [LIMITATIONS](limitations) for how this applies to redirection.
If the URL includes a "user:password" stanza, they will be used for Basic-style authorization headers. (Authorization headers will not be included in a redirected request.) For example:
```
$http->request('GET', 'http://Aladdin:open [email protected]/');
```
If the "user:password" stanza contains reserved characters, they must be percent-escaped:
```
$http->request('GET', 'http://john%40example.com:[email protected]/');
```
A hashref of options may be appended to modify the request.
Valid options are:
* `headers` โ A hashref containing headers to include with the request. If the value for a header is an array reference, the header will be output multiple times with each value in the array. These headers over-write any default headers.
* `content` โ A scalar to include as the body of the request OR a code reference that will be called iteratively to produce the body of the request
* `trailer_callback` โ A code reference that will be called if it exists to provide a hashref of trailing headers (only used with chunked transfer-encoding)
* `data_callback` โ A code reference that will be called for each chunks of the response body received.
* `peer` โ Override host resolution and force all connections to go only to a specific peer address, regardless of the URL of the request. This will include any redirections! This options should be used with extreme caution (e.g. debugging or very special circumstances). It can be given as either a scalar or a code reference that will receive the hostname and whose response will be taken as the address.
The `Host` header is generated from the URL in accordance with RFC 2616. It is a fatal error to specify `Host` in the `headers` option. Other headers may be ignored or overwritten if necessary for transport compliance.
If the `content` option is a code reference, it will be called iteratively to provide the content body of the request. It should return the empty string or undef when the iterator is exhausted.
If the `content` option is the empty string, no `content-type` or `content-length` headers will be generated.
If the `data_callback` option is provided, it will be called iteratively until the entire response body is received. The first argument will be a string containing a chunk of the response body, the second argument will be the in-progress response hash reference, as described below. (This allows customizing the action of the callback based on the `status` or `headers` received prior to the content body.)
The `request` method returns a hashref containing the response. The hashref will have the following keys:
* `success` โ Boolean indicating whether the operation returned a 2XX status code
* `url` โ URL that provided the response. This is the URL of the request unless there were redirections, in which case it is the last URL queried in a redirection chain
* `status` โ The HTTP status code of the response
* `reason` โ The response phrase returned by the server
* `content` โ The body of the response. If the response does not have any content or if a data callback is provided to consume the response body, this will be the empty string
* `headers` โ A hashref of header fields. All header field names will be normalized to be lower case. If a header is repeated, the value will be an arrayref; it will otherwise be a scalar string containing the value
* `protocol` - If this field exists, it is the protocol of the response such as HTTP/1.0 or HTTP/1.1
* `redirects` If this field exists, it is an arrayref of response hash references from redirects in the same order that redirections occurred. If it does not exist, then no redirections occurred.
On an error during the execution of the request, the `status` field will contain 599, and the `content` field will contain the text of the error.
### www\_form\_urlencode
```
$params = $http->www_form_urlencode( $data );
$response = $http->get("http://example.com/query?$params");
```
This method converts the key/value pairs from a data hash or array reference into a `x-www-form-urlencoded` string. The keys and values from the data reference will be UTF-8 encoded and escaped per RFC 3986. If a value is an array reference, the key will be repeated with each of the values of the array reference. If data is provided as a hash reference, the key/value pairs in the resulting string will be sorted by key and value for consistent ordering.
### can\_ssl
```
$ok = HTTP::Tiny->can_ssl;
($ok, $why) = HTTP::Tiny->can_ssl;
($ok, $why) = $http->can_ssl;
```
Indicates if SSL support is available. When called as a class object, it checks for the correct version of <Net::SSLeay> and <IO::Socket::SSL>. When called as an object methods, if `SSL_verify` is true or if `SSL_verify_mode` is set in `SSL_options`, it checks that a CA file is available.
In scalar context, returns a boolean indicating if SSL is available. In list context, returns the boolean and a (possibly multi-line) string of errors indicating why SSL isn't available.
### connected
```
$host = $http->connected;
($host, $port) = $http->connected;
```
Indicates if a connection to a peer is being kept alive, per the `keep_alive` option.
In scalar context, returns the peer host and port, joined with a colon, or `undef` (if no peer is connected). In list context, returns the peer host and port or an empty list (if no peer is connected).
**Note**: This method cannot reliably be used to discover whether the remote host has closed its end of the socket.
SSL SUPPORT
------------
Direct `https` connections are supported only if <IO::Socket::SSL> 1.56 or greater and <Net::SSLeay> 1.49 or greater are installed. An error will occur if new enough versions of these modules are not installed or if the SSL encryption fails. You can also use `HTTP::Tiny::can_ssl()` utility function that returns boolean to see if the required modules are installed.
An `https` connection may be made via an `http` proxy that supports the CONNECT command (i.e. RFC 2817). You may not proxy `https` via a proxy that itself requires `https` to communicate.
SSL provides two distinct capabilities:
* Encrypted communication channel
* Verification of server identity
**By default, HTTP::Tiny does not verify server identity**.
Server identity verification is controversial and potentially tricky because it depends on a (usually paid) third-party Certificate Authority (CA) trust model to validate a certificate as legitimate. This discriminates against servers with self-signed certificates or certificates signed by free, community-driven CA's such as [CAcert.org](http://cacert.org).
By default, HTTP::Tiny does not make any assumptions about your trust model, threat level or risk tolerance. It just aims to give you an encrypted channel when you need one.
Setting the `verify_SSL` attribute to a true value will make HTTP::Tiny verify that an SSL connection has a valid SSL certificate corresponding to the host name of the connection and that the SSL certificate has been verified by a CA. Assuming you trust the CA, this will protect against a [man-in-the-middle attack](http://en.wikipedia.org/wiki/Man-in-the-middle_attack). If you are concerned about security, you should enable this option.
Certificate verification requires a file containing trusted CA certificates.
If the environment variable `SSL_CERT_FILE` is present, HTTP::Tiny will try to find a CA certificate file in that location.
If the <Mozilla::CA> module is installed, HTTP::Tiny will use the CA file included with it as a source of trusted CA's. (This means you trust Mozilla, the author of Mozilla::CA, the CPAN mirror where you got Mozilla::CA, the toolchain used to install it, and your operating system security, right?)
If that module is not available, then HTTP::Tiny will search several system-specific default locations for a CA certificate file:
* /etc/ssl/certs/ca-certificates.crt
* /etc/pki/tls/certs/ca-bundle.crt
* /etc/ssl/ca-bundle.pem
An error will be occur if `verify_SSL` is true and no CA certificate file is available.
If you desire complete control over SSL connections, the `SSL_options` attribute lets you provide a hash reference that will be passed through to `IO::Socket::SSL::start_SSL()`, overriding any options set by HTTP::Tiny. For example, to provide your own trusted CA file:
```
SSL_options => {
SSL_ca_file => $file_path,
}
```
The `SSL_options` attribute could also be used for such things as providing a client certificate for authentication to a server or controlling the choice of cipher used for the SSL connection. See <IO::Socket::SSL> documentation for details.
PROXY SUPPORT
--------------
HTTP::Tiny can proxy both `http` and `https` requests. Only Basic proxy authorization is supported and it must be provided as part of the proxy URL: `http://user:[email protected]/`.
HTTP::Tiny supports the following proxy environment variables:
* http\_proxy or HTTP\_PROXY
* https\_proxy or HTTPS\_PROXY
* all\_proxy or ALL\_PROXY
If the `REQUEST_METHOD` environment variable is set, then this might be a CGI process and `HTTP_PROXY` would be set from the `Proxy:` header, which is a security risk. If `REQUEST_METHOD` is set, `HTTP_PROXY` (the upper case variant only) is ignored, but `CGI_HTTP_PROXY` is considered instead.
Tunnelling `https` over an `http` proxy using the CONNECT method is supported. If your proxy uses `https` itself, you can not tunnel `https` over it.
Be warned that proxying an `https` connection opens you to the risk of a man-in-the-middle attack by the proxy server.
The `no_proxy` environment variable is supported in the format of a comma-separated list of domain extensions proxy should not be used for.
Proxy arguments passed to `new` will override their corresponding environment variables.
LIMITATIONS
-----------
HTTP::Tiny is *conditionally compliant* with the [HTTP/1.1 specifications](http://www.w3.org/Protocols/):
* "Message Syntax and Routing" [RFC7230]
* "Semantics and Content" [RFC7231]
* "Conditional Requests" [RFC7232]
* "Range Requests" [RFC7233]
* "Caching" [RFC7234]
* "Authentication" [RFC7235]
It attempts to meet all "MUST" requirements of the specification, but does not implement all "SHOULD" requirements. (Note: it was developed against the earlier RFC 2616 specification and may not yet meet the revised RFC 7230-7235 spec.) Additionally, HTTP::Tiny supports the `PATCH` method of RFC 5789.
Some particular limitations of note include:
* HTTP::Tiny focuses on correct transport. Users are responsible for ensuring that user-defined headers and content are compliant with the HTTP/1.1 specification.
* Users must ensure that URLs are properly escaped for unsafe characters and that international domain names are properly encoded to ASCII. See <URI::Escape>, <URI::_punycode> and <Net::IDN::Encode>.
* Redirection is very strict against the specification. Redirection is only automatic for response codes 301, 302, 307 and 308 if the request method is 'GET' or 'HEAD'. Response code 303 is always converted into a 'GET' redirection, as mandated by the specification. There is no automatic support for status 305 ("Use proxy") redirections.
* There is no provision for delaying a request body using an `Expect` header. Unexpected `1XX` responses are silently ignored as per the specification.
* Only 'chunked' `Transfer-Encoding` is supported.
* There is no support for a Request-URI of '\*' for the 'OPTIONS' request.
* Headers mentioned in the RFCs and some other, well-known headers are generated with their canonical case. Other headers are sent in the case provided by the user. Except for control headers (which are sent first), headers are sent in arbitrary order.
Despite the limitations listed above, HTTP::Tiny is considered feature-complete. New feature requests should be directed to <HTTP::Tiny::UA>.
SEE ALSO
---------
* <HTTP::Tiny::UA> - Higher level UA features for HTTP::Tiny
* <HTTP::Thin> - HTTP::Tiny wrapper with <HTTP::Request>/<HTTP::Response> compatibility
* <HTTP::Tiny::Mech> - Wrap <WWW::Mechanize> instance in HTTP::Tiny compatible interface
* <IO::Socket::IP> - Required for IPv6 support
* <IO::Socket::SSL> - Required for SSL support
* <LWP::UserAgent> - If HTTP::Tiny isn't enough for you, this is the "standard" way to do things
* <Mozilla::CA> - Required if you want to validate SSL certificates
* <Net::SSLeay> - Required for SSL support
SUPPORT
-------
###
Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker at <https://github.com/chansen/p5-http-tiny/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/chansen/p5-http-tiny>
```
git clone https://github.com/chansen/p5-http-tiny.git
```
AUTHORS
-------
* Christian Hansen <[email protected]>
* David Golden <[email protected]>
CONTRIBUTORS
------------
* Alan Gardner <[email protected]>
* Alessandro Ghedini <[email protected]>
* A. Sinan Unur <[email protected]>
* Brad Gilbert <[email protected]>
* brian m. carlson <[email protected]>
* Chris Nehren <[email protected]>
* Chris Weyl <[email protected]>
* Claes Jakobsson <[email protected]>
* Clinton Gormley <[email protected]>
* Craig A. Berry <[email protected]>
* Craig Berry <[email protected]>
* David Golden <[email protected]>
* David Mitchell <[email protected]>
* Dean Pearce <[email protected]>
* Edward Zborowski <[email protected]>
* Felipe Gasper <[email protected]>
* Greg Kennedy <[email protected]>
* James E Keenan <[email protected]>
* James Raspass <[email protected]>
* Jeremy Mates <[email protected]>
* Jess Robinson <[email protected]>
* Karen Etheridge <[email protected]>
* Lukas Eklund <[email protected]>
* Martin J. Evans <[email protected]>
* Martin-Louis Bright <[email protected]>
* Matthew Horsfall <[email protected]>
* Michael R. Davis <[email protected]>
* Mike Doherty <[email protected]>
* Nicolas Rochelemagne <[email protected]>
* Olaf Alders <[email protected]>
* Olivier Menguรฉ <[email protected]>
* Petr Pรญsaล <[email protected]>
* sanjay-cpu <[email protected]>
* Serguei Trouchelle <[email protected]>
* Shoichi Kaji <[email protected]>
* SkyMarshal <[email protected]>
* Sรถren Kornetzki <[email protected]>
* Steve Grazzini <[email protected]>
* Syohei YOSHIDA <[email protected]>
* Tatsuhiko Miyagawa <[email protected]>
* Tom Hukins <[email protected]>
* Tony Cook <[email protected]>
* Xavier Guimard <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2021 by Christian Hansen.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
| programming_docs |
perl if if
==
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [use if](#use-if)
+ [no if](#no-if)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENCE](#COPYRIGHT-AND-LICENCE)
NAME
----
if - `use` a Perl module if a condition holds
SYNOPSIS
--------
```
use if CONDITION, "MODULE", ARGUMENTS;
no if CONDITION, "MODULE", ARGUMENTS;
```
DESCRIPTION
-----------
###
`use if`
The `if` module is used to conditionally load another module. The construct:
```
use if CONDITION, "MODULE", ARGUMENTS;
```
... will load `MODULE` only if `CONDITION` evaluates to true; it has no effect if `CONDITION` evaluates to false. (The module name, assuming it contains at least one `::`, must be quoted when `'use strict "subs";'` is in effect.) If the CONDITION does evaluate to true, then the above line has the same effect as:
```
use MODULE ARGUMENTS;
```
For example, the *Unicode::UCD* module's *charinfo* function will use two functions from *Unicode::Normalize* only if a certain condition is met:
```
use if defined &DynaLoader::boot_DynaLoader,
"Unicode::Normalize" => qw(getCombinClass NFD);
```
Suppose you wanted `ARGUMENTS` to be an empty list, *i.e.*, to have the effect of:
```
use MODULE ();
```
You can't do this with the `if` pragma; however, you can achieve exactly this effect, at compile time, with:
```
BEGIN { require MODULE if CONDITION }
```
###
`no if`
The `no if` construct is mainly used to deactivate categories of warnings when those categories would produce superfluous output under specified versions of *perl*.
For example, the `redundant` category of warnings was introduced in Perl-5.22. This warning flags certain instances of superfluous arguments to `printf` and `sprintf`. But if your code was running warnings-free on earlier versions of *perl* and you don't care about `redundant` warnings in more recent versions, you can call:
```
use warnings;
no if $] >= 5.022, q|warnings|, qw(redundant);
my $test = { fmt => "%s", args => [ qw( x y ) ] };
my $result = sprintf $test->{fmt}, @{$test->{args}};
```
The `no if` construct assumes that a module or pragma has correctly implemented an `unimport()` method -- but most modules and pragmata have not. That explains why the `no if` construct is of limited applicability.
BUGS
----
The current implementation does not allow specification of the required version of the module.
SEE ALSO
---------
<Module::Requires> can be used to conditionally load one or more modules, with constraints based on the version of the module. Unlike `if` though, <Module::Requires> is not a core module.
<Module::Load::Conditional> provides a number of functions you can use to query what modules are available, and then load one or more of them at runtime.
The <provide> module from CPAN can be used to select one of several possible modules to load based on the version of Perl that is running.
AUTHOR
------
Ilya Zakharevich <mailto:[email protected]>.
COPYRIGHT AND LICENCE
----------------------
This software is copyright (c) 2002 by Ilya Zakharevich.
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 perlfaq5 perlfaq5
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [How do I flush/unbuffer an output filehandle? Why must I do this?](#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-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-count-the-number-of-lines-in-a-file?)
+ [How do I delete the last N lines from 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-use-Perl's-i-option-from-within-a-program?)
+ [How can I copy a file?](#How-can-I-copy-a-file?)
+ [How do I make a temporary file name?](#How-do-I-make-a-temporary-file-name?)
+ [How can I manipulate fixed-record-length files?](#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-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-use-a-filehandle-indirectly?)
+ [How can I open a filehandle to a string?](#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-set-up-a-footer-format-to-be-used-with-write()?)
+ [How can I write() into a string?](#How-can-I-write()-into-a-string?)
+ [How can I output my numbers with commas added?](#How-can-I-output-my-numbers-with-commas-added?)
+ [How can I translate tildes (~) in a filename?](#How-can-I-translate-tildes-(~)-in-a-filename?)
+ [How come when I open a file read-write it wipes it out?](#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 <\*>?](#Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3C*%3E?)
+ [How can I open a file named with a leading ">" or trailing blanks?](#How-can-I-open-a-file-named-with-a-leading-%22%3E%22-or-trailing-blanks?)
+ [How can I reliably rename a file?](#How-can-I-reliably-rename-a-file?)
+ [How can I lock a file?](#How-can-I-lock-a-file?)
+ [Why can't I just open(FH, ">file.lock")?](#Why-can't-I-just-open(FH,-%22%3Efile.lock%22)?)
+ [I still don't get locking. I just want to increment the number in the file. How can I do this?](#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?](#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-randomly-update-a-binary-file?)
+ [How do I get a file's timestamp in perl?](#How-do-I-get-a-file's-timestamp-in-perl?)
+ [How do I set 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-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-an-entire-file-all-at-once?)
+ [How can I read in a file by paragraphs?](#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-read-a-single-character-from-a-file?-From-the-keyboard?)
+ [How can I tell whether there's a character waiting on a filehandle?](#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-do-a-tail-f-in-perl?)
+ [How do I dup() a filehandle in Perl?](#How-do-I-dup()-a-filehandle-in-Perl?)
+ [How do I close a file descriptor by number?](#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-can't-I-use-%22C:%5Ctemp%5Cfoo%22-in-DOS-paths?-Why-doesn't-%60C:%5Ctemp%5Cfoo.exe%60-work?)
+ [Why doesn't glob("\*.\*") get all the files?](#Why-doesn't-glob(%22*.*%22)-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?](#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?](#How-do-I-select-a-random-line-from-a-file?)
+ [Why do I get weird spaces when I print an array of lines?](#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines?)
+ [How do I traverse a directory tree?](#How-do-I-traverse-a-directory-tree?)
+ [How do I delete a directory tree?](#How-do-I-delete-a-directory-tree?)
+ [How do I copy an entire directory?](#How-do-I-copy-an-entire-directory?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq5 - Files and Formats
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
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?
(contributed by brian d foy)
You might like to read Mark Jason Dominus's "Suffering From Buffering" at <http://perl.plover.com/FAQs/Buffering.html> .
Perl normally buffers output so it doesn't make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. Instead of seeing a dot for every line, Perl buffers the output and you have a long wait before you see a row of 50 dots all at once:
```
# long wait, then row of dots all at once
while( <> ) {
print ".";
print "\n" unless ++$count % 50;
#... expensive line processing operations
}
```
To get around this, you have to unbuffer the output filehandle, in this case, `STDOUT`. You can set the special variable `$|` to a true value (mnemonic: making your filehandles "piping hot"):
```
$|++;
# dot shown immediately
while( <> ) {
print ".";
print "\n" unless ++$count % 50;
#... expensive line processing operations
}
```
The `$|` is one of the per-filehandle special variables, so each filehandle has its own copy of its value. If you want to merge standard output and standard error for instance, you have to unbuffer each (although STDERR might be unbuffered by default):
```
{
my $previous_default = select(STDOUT); # save previous default
$|++; # autoflush STDOUT
select(STDERR);
$|++; # autoflush STDERR, to be sure
select($previous_default); # restore previous default
}
# now should alternate . and +
while( 1 ) {
sleep 1;
print STDOUT ".";
print STDERR "+";
print STDOUT "\n" unless ++$count % 25;
}
```
Besides the `$|` special variable, you can use `binmode` to give your filehandle a `:unix` layer, which is unbuffered:
```
binmode( STDOUT, ":unix" );
while( 1 ) {
sleep 1;
print ".";
print "\n" unless ++$count % 50;
}
```
For more information on output layers, see the entries for `binmode` and <open> in <perlfunc>, and the [PerlIO](perlio) module documentation.
If you are using <IO::Handle> or one of its subclasses, you can call the `autoflush` method to change the settings of the filehandle:
```
use IO::Handle;
open my( $io_fh ), ">", "output.txt";
$io_fh->autoflush(1);
```
The <IO::Handle> objects also have a `flush` method. You can flush the buffer any time you want without auto-buffering
```
$io_fh->flush;
```
###
How do I change, delete, or insert a line in a file, or append to the beginning of a file?
(contributed by brian d foy)
The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, `$/`, is mutable), although modules such as <Tie::File> can fake it.
A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:
```
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
while( <$in> ) {
print $out $_;
}
close $out;
```
Within that basic form, add the parts that you need to insert, change, or delete lines.
To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.
```
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC
while( <$in> ) {
print $out $_;
}
close $out;
```
To change existing lines, insert the code to modify the lines inside the `while` loop. In this case, the code finds all lowercased versions of "perl" and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line!
```
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
print $out "# Add this line to the top\n";
while( <$in> ) {
s/\b(perl)\b/Perl/g;
print $out $_;
}
close $out;
```
To change only a particular line, the input line number, `$.`, is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:
```
while( <$in> ) { # print the lines before the change
print $out $_;
last if $. == 4; # line number before change
}
my $line = <$in>;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;
while( <$in> ) { # print the rest of the lines
print $out $_;
}
```
To skip lines, use the looping controls. The `next` in this example skips comment lines, and the `last` stops all processing once it encounters either `__END__` or `__DATA__`.
```
while( <$in> ) {
next if /^\s+#/; # skip comment lines
last if /^__(END|DATA)__$/; # stop at end of code marker
print $out $_;
}
```
Do the same sort of thing to delete a particular line by using `next` to skip the lines you don't want to show up in the output. This example skips every fifth line:
```
while( <$in> ) {
next unless $. % 5;
print $out $_;
}
```
If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):
```
open my $in, '<', $file or die "Can't read old file: $!"
open my $out, '>', "$file.new" or die "Can't write new file: $!";
my $content = do { local $/; <$in> }; # slurp!
# do your magic here
print $out $content;
```
Modules such as <Path::Tiny> and <Tie::File> can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes.
You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in *inFile.txt*, overwriting the file with the new contents. With the `-p` switch, Perl wraps a `while` loop around the code you specify with `-e`, and `-i` turns on in-place editing. The current line is in `$_`. With `-p`, Perl automatically prints the value of `$_` at the end of the loop. See <perlrun> for more details.
```
perl -pi -e 's/Fred/Barney/' inFile.txt
```
To make a backup of `inFile.txt`, give `-i` a file extension to add:
```
perl -pi.bak -e 's/Fred/Barney/' inFile.txt
```
To change only the fifth line, you can add a test checking `$.`, the input line number, then only perform the operation when the test passes:
```
perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt
```
To add lines before a certain line, you can add a line (or lines!) before Perl prints `$_`:
```
perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt
```
You can even add a line to the beginning of a file, since the current line prints at the end of the loop:
```
perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt
```
To insert a line after one already in the file, use the `-n` switch. It's just like `-p` except that it doesn't print `$_` at the end of the loop, so you have to do that yourself. In this case, print `$_` first, then print the line that you want to add.
```
perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt
```
To delete lines, only print the ones that you want.
```
perl -ni -e 'print if /d/' inFile.txt
```
###
How do I count the number of lines in a file?
(contributed by brian d foy)
Conceptually, the easiest way to count the lines in a file is to simply read them and count them:
```
my $count = 0;
while( <$fh> ) { $count++; }
```
You don't really have to count them yourself, though, since Perl already does that with the `$.` variable, which is the current line number from the last filehandle read:
```
1 while( <$fh> );
my $count = $.;
```
If you want to use `$.`, you can reduce it to a simple one-liner, like one of these:
```
% perl -lne '} print $.; {' file
% perl -lne 'END { print $. }' file
```
Those can be rather inefficient though. If they aren't fast enough for you, you might just read chunks of data and count the number of newlines:
```
my $lines = 0;
open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ tr/\n// );
}
close $fh;
```
However, that doesn't work if the line ending isn't a newline. You might change that `tr///` to a `s///` so you can count the number of times the input record separator, `$/`, shows up:
```
my $lines = 0;
open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ s|$/||g; );
}
close $fh;
```
If you don't mind shelling out, the `wc` command is usually the fastest, even with the extra interprocess overhead. Ensure that you have an untainted filename though:
```
#!perl -T
$ENV{PATH} = undef;
my $lines;
if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
$lines = `/usr/bin/wc -l $1`
chomp $lines;
}
```
###
How do I delete the last N lines from a file?
(contributed by brian d foy)
The easiest conceptual solution is to count the lines in the file then start at the beginning and print the number of lines (minus the last N) to a new file.
Most often, the real question is how you can delete the last N lines without making more than one pass over the file, or how to do it without a lot of copying. The easy concept is the hard reality when you might have millions of lines in your file.
One trick is to use <File::ReadBackwards>, which starts at the end of the file. That module provides an object that wraps the real filehandle to make it easy for you to move around the file. Once you get to the spot you need, you can get the actual filehandle and work with it as normal. In this case, you get the file position at the end of the last line you want to keep and truncate the file to that point:
```
use File::ReadBackwards;
my $filename = 'test.txt';
my $Lines_to_truncate = 2;
my $bw = File::ReadBackwards->new( $filename )
or die "Could not read backwards in [$filename]: $!";
my $lines_from_end = 0;
until( $bw->eof or $lines_from_end == $Lines_to_truncate ) {
print "Got: ", $bw->readline;
$lines_from_end++;
}
truncate( $filename, $bw->tell );
```
The <File::ReadBackwards> module also has the advantage of setting the input record separator to a regular expression.
You can also use the <Tie::File> module which lets you access the lines through a tied array. You can use normal array operations to modify your file, including setting the last index and using `splice`.
###
How can I use Perl's `-i` option from within a program?
`-i` sets the value of Perl's `$^I` variable, which in turn affects the behavior of `<>`; see <perlrun> for more details. By modifying the appropriate variables directly, you can get the same behavior within a larger program. For example:
```
# ...
{
local($^I, @ARGV) = ('.orig', glob("*.c"));
while (<>) {
if ($. == 1) {
print "This line should appear at the top of each file\n";
}
s/\b(p)earl\b/${1}erl/i; # Correct typos, preserving case
print;
close ARGV if eof; # Reset $.
}
}
# $^I and @ARGV return to their old values here
```
This block modifies all the `.c` files in the current directory, leaving a backup of the original data from each file in a new `.c.orig` file.
###
How can I copy a file?
(contributed by brian d foy)
Use the <File::Copy> module. It comes with Perl and can do a true copy across file systems, and it does its magic in a portable fashion.
```
use File::Copy;
copy( $original, $new_copy ) or die "Copy failed: $!";
```
If you can't use <File::Copy>, you'll have to do the work yourself: open the original file, open the destination file, then print to the destination file as you read the original. You also have to remember to copy the permissions, owner, and group to the new file.
###
How do I make a temporary file name?
If you don't need to know the name of the file, you can use `open()` with `undef` in place of the file name. In Perl 5.8 or later, the `open()` function creates an anonymous temporary file:
```
open my $tmp, '+>', undef or die $!;
```
Otherwise, you can use the File::Temp module.
```
use File::Temp qw/ tempfile tempdir /;
my $dir = tempdir( CLEANUP => 1 );
($fh, $filename) = tempfile( DIR => $dir );
# or if you don't need to know the filename
my $fh = tempfile( DIR => $dir );
```
The File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough Perl installed, use the `new_tmpfile` class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don't need to know the file's name:
```
use IO::File;
my $fh = IO::File->new_tmpfile()
or die "Unable to make new temporary file: $!";
```
If you're committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter:
```
BEGIN {
use Fcntl;
use File::Spec;
my $temp_dir = File::Spec->tmpdir();
my $file_base = sprintf "%d-%d-0000", $$, time;
my $base_name = File::Spec->catfile($temp_dir, $file_base);
sub temp_file {
my $fh;
my $count = 0;
until( defined(fileno($fh)) || $count++ > 100 ) {
$base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
# O_EXCL is required for security reasons.
sysopen $fh, $base_name, O_WRONLY|O_EXCL|O_CREAT;
}
if( defined fileno($fh) ) {
return ($fh, $base_name);
}
else {
return ();
}
}
}
```
###
How can I manipulate fixed-record-length files?
The most efficient way is using [pack()](perlfunc#pack) and [unpack()](perlfunc#unpack). This is faster than using [substr()](perlfunc#substr) when taking many, many strings. It is slower for just a few.
Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps:
```
# sample input line:
# 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what
my $PS_T = 'A6 A4 A7 A5 A*';
open my $ps, '-|', 'ps';
print scalar <$ps>;
my @fields = qw( pid tt stat time command );
while (<$ps>) {
my %process;
@process{@fields} = unpack($PS_T, $_);
for my $field ( @fields ) {
print "$field: <$process{$field}>\n";
}
print 'line=', pack($PS_T, @process{@fields} ), "\n";
}
```
We've used a hash slice in order to easily handle the fields of each row. Storing the keys in an array makes it easy to operate on them as a group or loop over them with `for`. It also avoids polluting the program with global variables and using symbolic references.
###
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?
As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles.
```
open my $fh, $file_name;
open local $fh, $file_name;
print $fh "Hello World!\n";
process_file( $fh );
```
If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren't simple scalars and you need to give `print` a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar.
```
my @fhs = ( $fh1, $fh2, $fh3 );
for( $i = 0; $i <= $#fhs; $i++ ) {
print {$fhs[$i]} "just another Perl answer, \n";
}
```
Before perl5.6, you had to deal with various typeglob idioms which you may see in older code.
```
open FILE, "> $filename";
process_typeglob( *FILE );
process_reference( \*FILE );
sub process_typeglob { local *FH = shift; print FH "Typeglob!" }
sub process_reference { local $fh = shift; print $fh "Reference!" }
```
If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules.
###
How can I use a filehandle indirectly?
An indirect filehandle is the use of something other than a symbol in a place that a filehandle is expected. Here are ways to get indirect filehandles:
```
$fh = SOME_FH; # bareword is strict-subs hostile
$fh = "SOME_FH"; # strict-refs hostile; same package only
$fh = *SOME_FH; # typeglob
$fh = \*SOME_FH; # ref to typeglob (bless-able)
$fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob
```
Or, you can use the `new` method from one of the IO::\* modules to create an anonymous filehandle and store that in a scalar variable.
```
use IO::Handle; # 5.004 or higher
my $fh = IO::Handle->new();
```
Then use any of those as you would a normal filehandle. Anywhere that Perl is expecting a filehandle, an indirect filehandle may be used instead. An indirect filehandle is just a scalar variable that contains a filehandle. Functions like `print`, `open`, `seek`, or the `<FH>` diamond operator will accept either a named filehandle or a scalar variable containing one:
```
($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
print $ofh "Type it: ";
my $got = <$ifh>
print $efh "What was that: $got";
```
If you're passing a filehandle to a function, you can write the function in two ways:
```
sub accept_fh {
my $fh = shift;
print $fh "Sending to indirect filehandle\n";
}
```
Or it can localize a typeglob and use the filehandle directly:
```
sub accept_fh {
local *FH = shift;
print FH "Sending to localized filehandle\n";
}
```
Both styles work with either objects or typeglobs of real filehandles. (They might also work with strings under some circumstances, but this is risky.)
```
accept_fh(*STDOUT);
accept_fh($handle);
```
In the examples above, we assigned the filehandle to a scalar variable before using it. That is because only simple scalar variables, not expressions or subscripts of hashes or arrays, can be used with built-ins like `print`, `printf`, or the diamond operator. Using something other than a simple scalar variable as a filehandle is illegal and won't even compile:
```
my @fd = (*STDIN, *STDOUT, *STDERR);
print $fd[1] "Type it: "; # WRONG
my $got = <$fd[0]> # WRONG
print $fd[2] "What was that: $got"; # WRONG
```
With `print` and `printf`, you get around this by using a block and an expression where you would place the filehandle:
```
print { $fd[1] } "funny stuff\n";
printf { $fd[1] } "Pity the poor %x.\n", 3_735_928_559;
# Pity the poor deadbeef.
```
That block is a proper block like any other, so you can put more complicated code there. This sends the message out to one of two places:
```
my $ok = -x "/bin/cat";
print { $ok ? $fd[1] : $fd[2] } "cat stat $ok\n";
print { $fd[ 1+ ($ok || 0) ] } "cat stat $ok\n";
```
This approach of treating `print` and `printf` like object methods calls doesn't work for the diamond operator. That's because it's a real operator, not just a function with a comma-less argument. Assuming you've been storing typeglobs in your structure as we did above, you can use the built-in function named `readline` to read a record just as `<>` does. Given the initialization shown above for @fd, this would work, but only because readline() requires a typeglob. It doesn't work with objects or strings, which might be a bug we haven't fixed yet.
```
$got = readline($fd[0]);
```
Let it be noted that the flakiness of indirect filehandles is not related to whether they're strings, typeglobs, objects, or anything else. It's the syntax of the fundamental operators. Playing the object game doesn't help you at all here.
###
How can I open a filehandle to a string?
(contributed by Peter J. Holzer, [email protected])
Since Perl 5.8.0 a file handle referring to a string can be created by calling open with a reference to that string instead of the filename. This file handle can then be used to read from or write to the string:
```
open(my $fh, '>', \$string) or die "Could not open string for writing";
print $fh "foo\n";
print $fh "bar\n"; # $string now contains "foo\nbar\n"
open(my $fh, '<', \$string) or die "Could not open string for reading";
my $x = <$fh>; # $x now contains "foo\n"
```
With older versions of Perl, the <IO::String> module provides similar functionality.
###
How can I set up a footer format to be used with write()?
There's no builtin way to do this, but <perlform> has a couple of techniques to make it possible for the intrepid hacker.
###
How can I write() into a string?
(contributed by brian d foy)
If you want to `write` into a string, you just have to <open> a filehandle to a string, which Perl has been able to do since Perl 5.6:
```
open FH, '>', \my $string;
write( FH );
```
Since you want to be a good programmer, you probably want to use a lexical filehandle, even though formats are designed to work with bareword filehandles since the default format names take the filehandle name. However, you can control this with some Perl special per-filehandle variables: `$^`, which names the top-of-page format, and `$~` which shows the line format. You have to change the default filehandle to set these variables:
```
open my($fh), '>', \my $string;
{ # set per-filehandle variables
my $old_fh = select( $fh );
$~ = 'ANIMAL';
$^ = 'ANIMAL_TOP';
select( $old_fh );
}
format ANIMAL_TOP =
ID Type Name
.
format ANIMAL =
@## @<<< @<<<<<<<<<<<<<<
$id, $type, $name
.
```
Although write can work with lexical or package variables, whatever variables you use have to scope in the format. That most likely means you'll want to localize some package variables:
```
{
local( $id, $type, $name ) = qw( 12 cat Buster );
write( $fh );
}
print $string;
```
There are also some tricks that you can play with `formline` and the accumulator variable `$^A`, but you lose a lot of the value of formats since `formline` won't handle paging and so on. You end up reimplementing formats when you use them.
###
How can I output my numbers with commas added?
(contributed by brian d foy and Benjamin Goldberg)
You can use <Number::Format> to separate places in a number. It handles locale information for those of you who want to insert full stops instead (or anything else that they want to use, really).
This subroutine will add commas to your number:
```
sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
```
This regex from Benjamin Goldberg will add commas to numbers:
```
s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
```
It is easier to see with comments:
```
s/(
^[-+]? # beginning of number.
\d+? # first digits before first comma
(?= # followed by, (but not included in the match) :
(?>(?:\d{3})+) # some positive multiple of three digits.
(?!\d) # an *exact* multiple, not x * 3 + 1 or whatever.
)
| # or:
\G\d{3} # after the last group, get three digits
(?=\d) # but they have to have more digits after them.
)/$1,/xg;
```
###
How can I translate tildes (~) in a filename?
Use the <> (`glob()`) operator, documented in <perlfunc>. Versions of Perl older than 5.6 require that you have a shell installed that groks tildes. Later versions of Perl have this feature built in. The <File::KGlob> module (available from CPAN) gives more portable glob functionality.
Within Perl, you may use this directly:
```
$filename =~ s{
^ ~ # find a leading tilde
( # save this in $1
[^/] # a non-slash character
* # repeated 0 or more times (0 means me)
)
}{
$1
? (getpwnam($1))[7]
: ( $ENV{HOME} || $ENV{LOGDIR} )
}ex;
```
###
How come when I open a file read-write it wipes it out?
Because you're using something like this, which truncates the file *then* gives you read-write access:
```
open my $fh, '+>', '/path/name'; # WRONG (almost always)
```
Whoops. You should instead use this, which will fail if the file doesn't exist:
```
open my $fh, '+<', '/path/name'; # open for update
```
Using ">" always clobbers or creates. Using "<" never does either. The "+" doesn't change this.
Here are examples of many kinds of file opens. Those using `sysopen` all assume that you've pulled in the constants from [Fcntl](fcntl):
```
use Fcntl;
```
To open file for reading:
```
open my $fh, '<', $path or die $!;
sysopen my $fh, $path, O_RDONLY or die $!;
```
To open file for writing, create new file if needed or else truncate old file:
```
open my $fh, '>', $path or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666 or die $!;
```
To open file for writing, create new file, file must not exist:
```
sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT, 0666 or die $!;
```
To open file for appending, create if necessary:
```
open my $fh, '>>', $path or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT, 0666 or die $!;
```
To open file for appending, file must exist:
```
sysopen my $fh, $path, O_WRONLY|O_APPEND or die $!;
```
To open file for update, file must exist:
```
open my $fh, '+<', $path or die $!;
sysopen my $fh, $path, O_RDWR or die $!;
```
To open file for update, create file if necessary:
```
sysopen my $fh, $path, O_RDWR|O_CREAT or die $!;
sysopen my $fh, $path, O_RDWR|O_CREAT, 0666 or die $!;
```
To open file for update, file must not exist:
```
sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT or die $!;
sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT, 0666 or die $!;
```
To open a file without blocking, creating if necessary:
```
sysopen my $fh, '/foo/somefile', O_WRONLY|O_NDELAY|O_CREAT
or die "can't open /foo/somefile: $!":
```
Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over NFS. That is, two processes might both successfully create or unlink the same file! Therefore O\_EXCL isn't as exclusive as you might wish.
See also <perlopentut>.
###
Why do I sometimes get an "Argument list too long" when I use <\*>?
The `<>` operator performs a globbing operation (see above). In Perl versions earlier than v5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh can't handle more than 127 items and so gives the error message `Argument list too long`. People who installed tcsh as csh won't have this problem, but their users may be surprised by it.
To get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with readdir() and patterns, or use a module like <File::Glob>, one that doesn't use the shell to do globbing.
###
How can I open a file named with a leading ">" or trailing blanks?
(contributed by Brian McCauley)
The special two-argument form of Perl's open() function ignores trailing blanks in filenames and infers the mode from certain leading characters (or a trailing "|"). In older versions of Perl this was the only version of open() and so it is prevalent in old code and books.
Unless you have a particular reason to use the two-argument form you should use the three-argument form of open() which does not treat any characters in the filename as special.
```
open my $fh, "<", " file "; # filename is " file "
open my $fh, ">", ">file"; # filename is ">file"
```
###
How can I reliably rename a file?
If your operating system supports a proper mv(1) utility or its functional equivalent, this works:
```
rename($old, $new) or system("mv", $old, $new);
```
It may be more portable to use the <File::Copy> module instead. You just copy to the new file to the new name (checking return values), then delete the old one. This isn't really the same semantically as a `rename()`, which preserves meta-information like permissions, timestamps, inode info, etc.
###
How can I lock a file?
Perl's builtin flock() function (see <perlfunc> for details) will call flock(2) if that exists, fcntl(2) if it doesn't (on perl version 5.004 and later), and lockf(3) if neither of the two previous system calls exists. On some systems, it may even use a different form of native locking. Here are some gotchas with Perl's flock():
1. Produces a fatal error if none of the three system calls (or their close equivalent) exists.
2. lockf(3) does not provide shared locking, and requires that the filehandle be open for writing (or appending, or read/writing).
3. Some versions of flock() can't lock files over a network (e.g. on NFS file systems), so you'd need to force the use of fcntl(2) when you build Perl. But even this is dubious at best. See the flock entry of <perlfunc> and the *INSTALL* file in the source distribution for information on building Perl to do this.
Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are *merely advisory*. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Cars that stop for red lights get on well with each other, but not with cars that don't stop for red lights. See the perlport manpage, your port's specific documentation, or your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (If you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called "features"). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.)
For more information on file locking, see also ["File Locking" in perlopentut](perlopentut#File-Locking) if you have it (new for 5.6).
###
Why can't I just open(FH, ">file.lock")?
A common bit of code **NOT TO USE** is this:
```
sleep(3) while -e 'file.lock'; # PLEASE DO NOT USE
open my $lock, '>', 'file.lock'; # THIS BROKEN CODE
```
This is a classic race condition: you take two steps to do something which must be done in one. That's why computer hardware provides an atomic test-and-set instruction. In theory, this "ought" to work:
```
sysopen my $fh, "file.lock", O_WRONLY|O_EXCL|O_CREAT
or die "can't open file.lock: $!";
```
except that lamentably, file creation (and deletion) is not atomic over NFS, so this won't work (at least, not every time) over the net. Various schemes involving link() have been suggested, but these tend to involve busy-wait, which is also less than desirable.
###
I still don't get locking. I just want to increment the number in the file. How can I do this?
Didn't anyone ever tell you web-page hit counters were useless? They don't count number of hits, they're a waste of time, and they serve only to stroke the writer's vanity. It's better to pick a random number; they're more realistic.
Anyway, this is what you can do if you can't help yourself.
```
use Fcntl qw(:DEFAULT :flock);
sysopen my $fh, "numfile", O_RDWR|O_CREAT or die "can't open numfile: $!";
flock $fh, LOCK_EX or die "can't flock numfile: $!";
my $num = <$fh> || 0;
seek $fh, 0, 0 or die "can't rewind numfile: $!";
truncate $fh, 0 or die "can't truncate numfile: $!";
(print $fh $num+1, "\n") or die "can't write numfile: $!";
close $fh or die "can't close numfile: $!";
```
Here's a much better web-page hit counter:
```
$hits = int( (time() - 850_000_000) / rand(1_000) );
```
If the count doesn't impress your friends, then the code might. :-)
###
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?
If you are on a system that correctly implements `flock` and you use the example appending code from "perldoc -f flock" everything will be OK even if the OS you are on doesn't implement append mode correctly (if such a system exists). So if you are happy to restrict yourself to OSs that implement `flock` (and that's not really much of a restriction) then that is what you should do.
If you know you are only going to use a system that does correctly implement appending (i.e. not Win32) then you can omit the `seek` from the code in the previous answer.
If you know you are only writing code to run on an OS and filesystem that does implement append mode correctly (a local filesystem on a modern Unix for example), and you keep the file in block-buffered mode and you write less than one buffer-full of output between each manual flushing of the buffer then each bufferload is almost guaranteed to be written to the end of the file in one chunk without getting intermingled with anyone else's output. You can also use the `syswrite` function which is simply a wrapper around your system's `write(2)` system call.
There is still a small theoretical chance that a signal will interrupt the system-level `write()` operation before completion. There is also a possibility that some STDIO implementations may call multiple system level `write()`s even if the buffer was empty to start. There may be some systems where this probability is reduced to zero, and this is not a concern when using `:perlio` instead of your system's STDIO.
###
How do I randomly update a binary file?
If you're just trying to patch a binary, in many cases something as simple as this works:
```
perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
```
However, if you have fixed sized records, then you might do something more like this:
```
my $RECSIZE = 220; # size of record, in bytes
my $recno = 37; # which record to update
open my $fh, '+<', 'somewhere' or die "can't update somewhere: $!";
seek $fh, $recno * $RECSIZE, 0;
read $fh, $record, $RECSIZE == $RECSIZE or die "can't read record $recno: $!";
# munge the record
seek $fh, -$RECSIZE, 1;
print $fh $record;
close $fh;
```
Locking and error checking are left as an exercise for the reader. Don't forget them or you'll be quite sorry.
###
How do I get a file's timestamp in perl?
If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the **-A**, **-M**, or **-C** file test operations as documented in <perlfunc>. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See <perlport> for details. To retrieve the "raw" time in seconds since the epoch, you would call the stat function, then use `localtime()`, `gmtime()`, or `POSIX::strftime()` to convert this into human-readable form.
Here's an example:
```
my $write_secs = (stat($file))[9];
printf "file %s updated at %s\n", $file,
scalar localtime($write_secs);
```
If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later):
```
# error checking left as an exercise for reader.
use File::stat;
use Time::localtime;
my $date_string = ctime(stat($file)->mtime);
print "file $file updated at $date_string\n";
```
The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See <perllocale> for details.
###
How do I set a file's timestamp in perl?
You use the utime() function documented in ["utime" in perlfunc](perlfunc#utime). By way of example, here's a little program that copies the read and write times from its first argument to all the rest of them.
```
if (@ARGV < 2) {
die "usage: cptimes timestamp_file other_files ...\n";
}
my $timestamp = shift;
my($atime, $mtime) = (stat($timestamp))[8,9];
utime $atime, $mtime, @ARGV;
```
Error checking is, as usual, left as an exercise for the reader.
The perldoc for utime also has an example that has the same effect as touch(1) on files that *already exist*.
Certain file systems have a limited ability to store the times on a file at the expected level of precision. For example, the FAT and HPFS filesystem are unable to create dates on files with a finer granularity than two seconds. This is a limitation of the filesystems, not of utime().
###
How do I print to more than one file at once?
To connect one filehandle to several output filehandles, you can use the <IO::Tee> or <Tie::FileHandle::Multiplex> modules.
If you only have to do this once, you can print individually to each filehandle.
```
for my $fh ($fh1, $fh2, $fh3) { print $fh "whatever\n" }
```
###
How can I read in an entire file all at once?
The customary Perl approach for processing all the lines in a file is to do so one line at a time:
```
open my $input, '<', $file or die "can't open $file: $!";
while (<$input>) {
chomp;
# do something with $_
}
close $input or die "can't close $file: $!";
```
This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this:
```
my @lines = <INPUT>;
```
You should think long and hard about why you need everything loaded at once. It's just not a scalable solution.
If you "mmap" the file with the File::Map module from CPAN, you can virtually load the entire file into a string without actually storing it in memory:
```
use File::Map qw(map_file);
map_file my $string, $filename;
```
Once mapped, you can treat `$string` as you would any other string. Since you don't necessarily have to load the data, mmap-ing can be very fast and may not increase your memory footprint.
You might also find it more fun to use the standard <Tie::File> module, or the [DB\_File](db_file) module's `$DB_RECNO` bindings, which allow you to tie an array to a file so that accessing an element of the array actually accesses the corresponding line in the file.
If you want to load the entire file, you can use the <Path::Tiny> module to do it in one simple and efficient step:
```
use Path::Tiny;
my $all_of_it = path($filename)->slurp; # entire file in scalar
my @all_lines = path($filename)->lines; # one line per element
```
Or you can read the entire file contents into a scalar like this:
```
my $var;
{
local $/;
open my $fh, '<', $file or die "can't open $file: $!";
$var = <$fh>;
}
```
That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:
```
my $var = do { local $/; <$fh> };
```
You can also use a localized `@ARGV` to eliminate the `open`:
```
my $var = do { local( @ARGV, $/ ) = $file; <> };
```
###
How can I read in a file by paragraphs?
Use the `$/` variable (see <perlvar> for details). You can either set it to `""` to eliminate empty paragraphs (`"abc\n\n\n\ndef"`, for instance, gets treated as two paragraphs and not three), or `"\n\n"` to accept empty paragraphs.
Note that a blank line must have no blanks in it. Thus `"fred\n \nstuff\n\n"` is one paragraph, but `"fred\n\nstuff\n\n"` is two.
###
How can I read a single character from a file? From the keyboard?
You can use the builtin `getc()` function for most filehandles, but it won't (easily) work on a terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample code in ["getc" in perlfunc](perlfunc#getc).
If your system supports the portable operating system programming interface (POSIX), you can use the following code, which you'll note turns off echo processing as well.
```
#!/usr/bin/perl -w
use strict;
$| = 1;
for (1..4) {
print "gimme: ";
my $got = getone();
print "--> $got\n";
}
exit;
BEGIN {
use POSIX qw(:termios_h);
my ($term, $oterm, $echo, $noecho, $fd_stdin);
my $fd_stdin = fileno(STDIN);
$term = POSIX::Termios->new();
$term->getattr($fd_stdin);
$oterm = $term->getlflag();
$echo = ECHO | ECHOK | ICANON;
$noecho = $oterm & ~$echo;
sub cbreak {
$term->setlflag($noecho);
$term->setcc(VTIME, 1);
$term->setattr($fd_stdin, TCSANOW);
}
sub cooked {
$term->setlflag($oterm);
$term->setcc(VTIME, 0);
$term->setattr($fd_stdin, TCSANOW);
}
sub getone {
my $key = '';
cbreak();
sysread(STDIN, $key, 1);
cooked();
return $key;
}
}
END { cooked() }
```
The Term::ReadKey module from CPAN may be easier to use. Recent versions include also support for non-portable systems as well.
```
use Term::ReadKey;
open my $tty, '<', '/dev/tty';
print "Gimme a char: ";
ReadMode "raw";
my $key = ReadKey 0, $tty;
ReadMode "normal";
printf "\nYou said %s, char number %03d\n",
$key, ord $key;
```
###
How can I tell whether there's a character waiting on a filehandle?
The very first thing you should do is look into getting the Term::ReadKey extension from CPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not open systems, closed, proprietary, not POSIX, not Unix, etc.) systems.
You should also check out the Frequently Asked Questions list in comp.unix.\* for things like this: the answer is essentially the same. It's very system-dependent. Here's one solution that works on BSD systems:
```
sub key_ready {
my($rin, $nfd);
vec($rin, fileno(STDIN), 1) = 1;
return $nfd = select($rin,undef,undef,0);
}
```
If you want to find out how many characters are waiting, there's also the FIONREAD ioctl call to be looked at. The *h2ph* tool that comes with Perl tries to convert C include files to Perl code, which can be `require`d. FIONREAD ends up defined as a function in the *sys/ioctl.ph* file:
```
require './sys/ioctl.ph';
$size = pack("L", 0);
ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n";
$size = unpack("L", $size);
```
If *h2ph* wasn't installed or doesn't work for you, you can *grep* the include files by hand:
```
% grep FIONREAD /usr/include/*/*
/usr/include/asm/ioctls.h:#define FIONREAD 0x541B
```
Or write a small C program using the editor of champions:
```
% cat > fionread.c
#include <sys/ioctl.h>
main() {
printf("%#08x\n", FIONREAD);
}
^D
% cc -o fionread fionread.c
% ./fionread
0x4004667f
```
And then hard-code it, leaving porting as an exercise to your successor.
```
$FIONREAD = 0x4004667f; # XXX: opsys dependent
$size = pack("L", 0);
ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n";
$size = unpack("L", $size);
```
FIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty devices work, but *not* files.
###
How do I do a `tail -f` in perl?
First try
```
seek($gw_fh, 0, 1);
```
The statement `seek($gw_fh, 0, 1)` doesn't change the current position, but it does clear the end-of-file condition on the handle, so that the next `<$gw_fh>` makes Perl try again to read something.
If that doesn't work (it relies on features of your stdio implementation), then you need something more like this:
```
for (;;) {
for ($curpos = tell($gw_fh); <$gw_fh>; $curpos =tell($gw_fh)) {
# search for some stuff and put it into files
}
# sleep for a while
seek($gw_fh, $curpos, 0); # seek to where we had been
}
```
If this still doesn't work, look into the `clearerr` method from <IO::Handle>, which resets the error and end-of-file states on the handle.
There's also a <File::Tail> module from CPAN.
###
How do I dup() a filehandle in Perl?
If you check ["open" in perlfunc](perlfunc#open), you'll see that several of the ways to call open() should do the trick. For example:
```
open my $log, '>>', '/foo/logfile';
open STDERR, '>&', $log;
```
Or even with a literal numeric descriptor:
```
my $fd = $ENV{MHCONTEXTFD};
open $mhcontext, "<&=$fd"; # like fdopen(3S)
```
Note that "<&STDIN" makes a copy, but "<&=STDIN" makes an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one.
Error checking, as always, has been left as an exercise for the reader.
###
How do I close a file descriptor by number?
If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used `POSIX::open`), you can use the `close()` function from the [POSIX](posix) module:
```
use POSIX ();
POSIX::close( $fd );
```
This should rarely be necessary, as the Perl `close()` function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with `MHCONTEXT` above. But if you really have to, you may be able to do this:
```
require './sys/syscall.ph';
my $rc = syscall(SYS_close(), $fd + 0); # must force numeric
die "can't sysclose $fd: $!" unless $rc == -1;
```
Or, just use the fdopen(3S) feature of `open()`:
```
{
open my $fh, "<&=$fd" or die "Cannot reopen fd=$fd: $!";
close $fh;
}
```
###
Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings ("like\this"), the backslash is an escape character. The full list of these is in ["Quote and Quote-like Operators" in perlop](perlop#Quote-and-Quote-like-Operators). Unsurprisingly, you don't have a file called "c:(tab)emp(formfeed)oo" or "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.
Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated `/` and `\` the same in a path, you might as well use the one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too.
###
Why doesn't glob("\*.\*") get all the files?
Because even on non-Unix ports, Perl's glob function follows standard Unix globbing semantics. You'll need `glob("*")` to get all (non-hidden) files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details.
###
Why does Perl let me delete read-only files? Why does `-i` clobber protected files? Isn't this a bug in Perl?
This is elaborately and painstakingly described in the *file-dir-perms* article in the "Far More Than You Ever Wanted To Know" collection in <http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> .
The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. The permissions on a directory say what can happen to the list of files in that directory. If you delete a file, you're removing its name from the directory (so the operation depends on the permissions of the directory, not of the file). If you try to write to the file, the permissions of the file govern whether you're allowed to.
###
How do I select a random line from a file?
Short of loading the file into a database or pre-indexing the lines in the file, there are a couple of things that you can do.
Here's a reservoir-sampling algorithm from the Camel Book:
```
srand;
rand($.) < 1 && ($line = $_) while <>;
```
This has a significant advantage in space over reading the whole file in. You can find a proof of this method in *The Art of Computer Programming*, Volume 2, Section 3.4.2, by Donald E. Knuth.
You can use the <File::Random> module which provides a function for that algorithm:
```
use File::Random qw/random_line/;
my $line = random_line($filename);
```
Another way is to use the <Tie::File> module, which treats the entire file as an array. Simply access a random array element.
###
Why do I get weird spaces when I print an array of lines?
(contributed by brian d foy)
If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes:
```
my @animals = qw(camel llama alpaca vicuna);
print "animals are: @animals\n";
```
It's the double quotes, not the `print`, doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in `$"`, which is a space by default):
```
animals are: camel llama alpaca vicuna
```
This is different than printing the array without the interpolation:
```
my @animals = qw(camel llama alpaca vicuna);
print "animals are: ", @animals, "\n";
```
Now the output doesn't have the spaces between the elements because the elements of `@animals` simply become part of the list to `print`:
```
animals are: camelllamaalpacavicuna
```
You might notice this when each of the elements of `@array` end with a newline. You expect to print one element per line, but notice that every line after the first is indented:
```
this is a line
this is another line
this is the third line
```
That extra space comes from the interpolation of the array. If you don't want to put anything between your array elements, don't use the array in double quotes. You can send it to print without them:
```
print @lines;
```
###
How do I traverse a directory tree?
(contributed by brian d foy)
The <File::Find> module, which comes with Perl, does all of the hard work to traverse a directory structure. It comes with Perl. You simply call the `find` subroutine with a callback subroutine and the directories you want to traverse:
```
use File::Find;
find( \&wanted, @directories );
sub wanted {
# full path in $File::Find::name
# just filename in $_
... do whatever you want to do ...
}
```
The <File::Find::Closures>, which you can download from CPAN, provides many ready-to-use subroutines that you can use with <File::Find>.
The <File::Finder>, which you can download from CPAN, can help you create the callback subroutine using something closer to the syntax of the `find` command-line utility:
```
use File::Find;
use File::Finder;
my $deep_dirs = File::Finder->depth->type('d')->ls->exec('rmdir','{}');
find( $deep_dirs->as_options, @places );
```
The <File::Find::Rule> module, which you can download from CPAN, has a similar interface, but does the traversal for you too:
```
use File::Find::Rule;
my @files = File::Find::Rule->file()
->name( '*.pm' )
->in( @INC );
```
###
How do I delete a directory tree?
(contributed by brian d foy)
If you have an empty directory, you can use Perl's built-in `rmdir`. If the directory is not empty (so, with files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you.
The <File::Path> module, which comes with Perl, has a `remove_tree` which can take care of all of the hard work for you:
```
use File::Path qw(remove_tree);
remove_tree( @directories );
```
The <File::Path> module also has a legacy interface to the older `rmtree` subroutine.
###
How do I copy an entire directory?
(contributed by Shlomi Fish)
To do the equivalent of `cp -R` (i.e. copy an entire directory tree recursively) in portable Perl, you'll either need to write something yourself or find a good CPAN module such as <File::Copy::Recursive>.
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 Pod::Simple::Checker Pod::Simple::Checker
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Checker -- check the Pod syntax of a document
SYNOPSIS
--------
```
perl -MPod::Simple::Checker -e \
"exit Pod::Simple::Checker->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
This class is for checking the syntactic validity of Pod. It works by basically acting like a simple-minded version of <Pod::Simple::Text> that formats only the "Pod Errors" section (if Pod::Simple even generates one for the given document).
This is a subclass of <Pod::Simple> and inherits all its methods.
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::Text>, <Pod::Checker>
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 Getopt::Long Getopt::Long
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Command Line Options, an Introduction](#Command-Line-Options,-an-Introduction)
* [Getting Started with Getopt::Long](#Getting-Started-with-Getopt::Long)
+ [Simple options](#Simple-options)
+ [A little bit less simple options](#A-little-bit-less-simple-options)
+ [Mixing command line option with other arguments](#Mixing-command-line-option-with-other-arguments)
+ [Options with values](#Options-with-values)
+ [Options with multiple values](#Options-with-multiple-values)
+ [Options with hash values](#Options-with-hash-values)
+ [User-defined subroutines to handle options](#User-defined-subroutines-to-handle-options)
+ [Options with multiple names](#Options-with-multiple-names)
+ [Case and abbreviations](#Case-and-abbreviations)
+ [Summary of Option Specifications](#Summary-of-Option-Specifications)
* [Advanced Possibilities](#Advanced-Possibilities)
+ [Object oriented interface](#Object-oriented-interface)
+ [Callback object](#Callback-object)
+ [Thread Safety](#Thread-Safety)
+ [Documentation and help texts](#Documentation-and-help-texts)
+ [Parsing options from an arbitrary array](#Parsing-options-from-an-arbitrary-array)
+ [Parsing options from an arbitrary string](#Parsing-options-from-an-arbitrary-string)
+ [Storing options values in a hash](#Storing-options-values-in-a-hash)
+ [Bundling](#Bundling)
+ [The lonesome dash](#The-lonesome-dash)
+ [Argument callback](#Argument-callback)
* [Configuring Getopt::Long](#Configuring-Getopt::Long)
* [Exportable Methods](#Exportable-Methods)
* [Return values and Errors](#Return-values-and-Errors)
* [Legacy](#Legacy)
+ [Default destinations](#Default-destinations)
+ [Alternative option starters](#Alternative-option-starters)
+ [Configuration variables](#Configuration-variables)
* [Tips and Techniques](#Tips-and-Techniques)
+ [Pushing multiple values in a hash option](#Pushing-multiple-values-in-a-hash-option)
* [Troubleshooting](#Troubleshooting)
+ [GetOptions does not return a false result when an option is not supplied](#GetOptions-does-not-return-a-false-result-when-an-option-is-not-supplied)
+ [GetOptions does not split the command line correctly](#GetOptions-does-not-split-the-command-line-correctly)
+ [Undefined subroutine &main::GetOptions called](#Undefined-subroutine-&main::GetOptions-called)
+ [How do I put a "-?" option into a Getopt::Long?](#How-do-I-put-a-%22-?%22-option-into-a-Getopt::Long?)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND DISCLAIMER](#COPYRIGHT-AND-DISCLAIMER)
NAME
----
Getopt::Long - Extended processing of command line options
SYNOPSIS
--------
```
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose" => \$verbose) # flag
or die("Error in command line arguments\n");
```
DESCRIPTION
-----------
The Getopt::Long module implements an extended getopt function called GetOptions(). It parses the command line from `@ARGV`, recognizing and removing specified options and their possible values.
This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default.
Command Line Options, an Introduction
--------------------------------------
Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line *options* as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did.
Command line options come in several flavours. Historically, they are preceded by a single dash `-`, and consist of a single letter.
```
-l -a -c
```
Usually, these single-character options can be bundled:
```
-lac
```
Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not:
```
-s 24 -s24
```
Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic `-l` one could use the more descriptive `--long`. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Early implementations of long options used a plus `+` instead. Also, option values could be specified either like
```
--size=24
```
or
```
--size 24
```
The `+` form is now obsolete and strongly deprecated.
Getting Started with Getopt::Long
----------------------------------
Getopt::Long is the Perl5 successor of `newgetopt.pl`. This was the first Perl module that provided support for handling the new style of command line options, in particular long option names, hence the Perl5 name Getopt::Long. This module also supports single-character options and bundling.
To use Getopt::Long from a Perl program, you must include the following line in your Perl program:
```
use Getopt::Long;
```
This will load the core of the Getopt::Long module and prepare your program for using it. Most of the actual Getopt::Long code is not loaded until you really call one of its functions.
In the default configuration, options names may be abbreviated to uniqueness, case does not matter, and a single dash is sufficient, even for long option names. Also, options may be placed between non-option arguments. See ["Configuring Getopt::Long"](#Configuring-Getopt%3A%3ALong) for more details on how to configure Getopt::Long.
###
Simple options
The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are:
```
--all --verbose --quiet --debug
```
Handling simple options is straightforward:
```
my $verbose = ''; # option variable with default value (false)
my $all = ''; # option variable with default value (false)
GetOptions ('verbose' => \$verbose, 'all' => \$all);
```
The call to GetOptions() parses the command line arguments that are present in `@ARGV` and sets the option variable to the value `1` if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called *enabling* the option.
The option name as specified to the GetOptions() function is called the option *specification*. Later we'll see that this specification can contain more than just the option name. The reference to the variable is called the option *destination*.
GetOptions() will return a true value if the command line could be processed successfully. Otherwise, it will write error messages using die() and warn(), and return a false result.
###
A little bit less simple options
Getopt::Long supports two useful variants of simple options: *negatable* options and *incremental* options.
A negatable option is specified with an exclamation mark `!` after the option name:
```
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose!' => \$verbose);
```
Now, using `--verbose` on the command line will enable `$verbose`, as expected. But it is also allowed to use `--noverbose`, which will disable `$verbose` by setting its value to `0`. Using a suitable default value, the program can find out whether `$verbose` is false by default, or disabled by using `--noverbose`.
An incremental option is specified with a plus `+` after the option name:
```
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose+' => \$verbose);
```
Using `--verbose` on the command line will increment the value of `$verbose`. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of `--verbose` could increase the verbosity level of the program.
###
Mixing command line option with other arguments
Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash `--` on the command line:
```
--size 24 -- --all
```
In this example, `--all` will *not* be treated as an option, but passed to the program unharmed, in `@ARGV`.
###
Options with values
For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects.
Three kinds of values are supported: integer numbers, floating point numbers, and strings.
If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself.
```
my $tag = ''; # option variable with default value
GetOptions ('tag=s' => \$tag);
```
In the option specification, the option name is followed by an equals sign `=` and the letter `s`. The equals sign indicates that this option requires a value. The letter `s` indicates that this value is an arbitrary string. Other possible value types are `i` for integer values, and `f` for floating point values. Using a colon `:` instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string `''` assigned, while numeric options are set to `0`.
###
Options with multiple values
Options sometimes take several values. For example, a program could use multiple directories to search for library files:
```
--library lib/stdlib --library lib/extlib
```
To accomplish this behaviour, simply specify an array reference as the destination for the option:
```
GetOptions ("library=s" => \@libfiles);
```
Alternatively, you can specify that the option can have multiple values by adding a "@", and pass a reference to a scalar as the destination:
```
GetOptions ("library=s@" => \$libfiles);
```
Used with the example above, `@libfiles` c.q. `@$libfiles` would contain two strings upon completion: `"lib/stdlib"` and `"lib/extlib"`, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values.
Often it is useful to allow comma-separated lists of values as well as multiple occurrences of the options. This is easy using Perl's split() and join() operators:
```
GetOptions ("library=s" => \@libfiles);
@libfiles = split(/,/,join(',',@libfiles));
```
Of course, it is important to choose the right separator string for each purpose.
Warning: What follows is an experimental feature.
Options can take multiple values at once, for example
```
--coordinates 52.2 16.4 --rgbcolor 255 255 149
```
This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the `{...}` repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:
```
GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
```
The destination for the option must be an array or array reference.
It is also possible to specify the minimal and maximal number of arguments an option takes. `foo=s{2,4}` indicates an option that takes at least two and at most 4 arguments. `foo=s{1,}` indicates one or more values; `foo:s{,}` indicates zero or more option values.
###
Options with hash values
If the option destination is a reference to a hash, the option will take, as value, strings of the form *key*`=`*value*. The value will be stored with the specified key in the hash.
```
GetOptions ("define=s" => \%defines);
```
Alternatively you can use:
```
GetOptions ("define=s%" => \$defines);
```
When used with command line options:
```
--define os=linux --define vendor=redhat
```
the hash `%defines` (or `%$defines`) will contain two keys, `"os"` with value `"linux"` and `"vendor"` with value `"redhat"`. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings.
###
User-defined subroutines to handle options
Ultimate control over what should be done when (actually: each time) an option is encountered on the command line can be achieved by designating a reference to a subroutine (or an anonymous subroutine) as the option destination. When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option. (Actually, it is an object that stringifies to the name of the option.) For a scalar or array destination, the second argument is the value to be stored. For a hash destination, the second argument is the key to the hash, and the third argument the value to be stored. It is up to the subroutine to store the value, or do whatever it thinks is appropriate.
A trivial application of this mechanism is to implement options that are related to each other. For example:
```
my $verbose = ''; # option variable with default value (false)
GetOptions ('verbose' => \$verbose,
'quiet' => sub { $verbose = 0 });
```
Here `--verbose` and `--quiet` control the same variable `$verbose`, but with opposite values.
If the subroutine needs to signal an error, it should call die() with the desired error message as its argument. GetOptions() will catch the die(), issue the error message, and record that an error result must be returned upon completion.
If the text of the error message starts with an exclamation mark `!` it is interpreted specially by GetOptions(). There is currently one special command implemented: `die("!FINISH")` will cause GetOptions() to stop processing options, as if it encountered a double dash `--`.
Here is an example of how to access the option name and value from within a subroutine:
```
GetOptions ('opt=i' => \&handler);
sub handler {
my ($opt_name, $opt_value) = @_;
print("Option name is $opt_name and value is $opt_value\n");
}
```
###
Options with multiple names
Often it is user friendly to supply alternate mnemonic names for options. For example `--height` could be an alternate name for `--length`. Alternate names can be included in the option specification, separated by vertical bar `|` characters. To implement the above example:
```
GetOptions ('length|height=f' => \$length);
```
The first name is called the *primary* name, the other names are called *aliases*. When using a hash to store options, the key will always be the primary name.
Multiple alternate names are possible.
###
Case and abbreviations
Without additional configuration, GetOptions() will ignore the case of option names, and allow the options to be abbreviated to uniqueness.
```
GetOptions ('length|height=f' => \$length, "head" => \$head);
```
This call will allow `--l` and `--L` for the length option, but requires a least `--hea` and `--hei` for the head and height options.
###
Summary of Option Specifications
Each option specifier consists of two parts: the name specification and the argument specification.
The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters.
```
length option name is "length"
length|size|l name is "length", aliases are "size" and "l"
```
The argument specification is optional. If omitted, the option is considered boolean, a value of 1 will be assigned when the option is used on the command line.
The argument specification can be
! The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. `"foo!"` will allow `--foo` (a value of 1 will be assigned) as well as `--nofoo` and `--no-foo` (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well.
Using negation on a single letter option when bundling is in effect is pointless and will result in a warning.
+ The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. `"more+"`, when used with `--more --more --more`, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at first).
The `+` specifier is ignored if the option destination is not a scalar.
= *type* [ *desttype* ] [ *repeat* ] The option requires an argument of the given type. Supported types are:
s String. An arbitrary sequence of characters. It is valid for the argument to start with `-` or `--`.
i Integer. An optional leading plus or minus sign, followed by a sequence of digits.
o Extended integer, Perl style. This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (a zero, optionally followed by '0', '1', .. '7'), or a hexadecimal string (`0x` followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (`0b` followed by a series of '0' and '1').
f Real number. For example `3.14`, `-6.23E24` and so on.
The *desttype* can be `@` or `%` to specify that the option is list or a hash valued. This is only needed when the destination for the option value is not otherwise specified. It should be omitted when not needed.
The *repeat* specifies the number of values this option takes per occurrence on the command line. It has the format `{` [ *min* ] [ `,` [ *max* ] ] `}`.
*min* denotes the minimal number of arguments. It defaults to 1 for options with `=` and to 0 for options with `:`, see below. Note that *min* overrules the `=` / `:` semantics.
*max* denotes the maximum number of arguments. It must be at least *min*. If *max* is omitted, *but the comma is not*, there is no upper bound to the number of argument values taken.
: *type* [ *desttype* ] Like `=`, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options.
Note that if a string argument starts with `-` or `--`, it will be considered an option on itself.
: *number* [ *desttype* ] Like `:i`, but if the value is omitted, the *number* will be assigned.
: + [ *desttype* ] Like `:i`, but if the value is omitted, the current value for the option will be incremented.
Advanced Possibilities
-----------------------
###
Object oriented interface
Getopt::Long can be used in an object oriented way as well:
```
use Getopt::Long;
$p = Getopt::Long::Parser->new;
$p->configure(...configuration options...);
if ($p->getoptions(...options descriptions...)) ...
if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
```
Configuration options can be passed to the constructor:
```
$p = new Getopt::Long::Parser
config => [...configuration options...];
```
###
Callback object
In version 2.37 the first argument to the callback function was changed from string to object. This was done to make room for extensions and more detailed control. The object stringifies to the option name so this change should not introduce compatibility problems.
The callback object has the following methods:
name The name of the option, unabbreviated. For an option with multiple names it return the first (canonical) name.
given The name of the option as actually used, unabbreveated.
###
Thread Safety
Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is *not* thread safe when using the older (experimental and now obsolete) threads implementation that was added to Perl 5.005.
###
Documentation and help texts
Getopt::Long encourages the use of Pod::Usage to produce help messages. For example:
```
use Getopt::Long;
use Pod::Usage;
my $man = 0;
my $help = 0;
GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitval => 0, -verbose => 2) if $man;
__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 8
=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
```
See <Pod::Usage> for details.
###
Parsing options from an arbitrary array
By default, GetOptions parses the options that are present in the global array `@ARGV`. A special entry `GetOptionsFromArray` can be used to parse options from an arbitrary array.
```
use Getopt::Long qw(GetOptionsFromArray);
$ret = GetOptionsFromArray(\@myopts, ...);
```
When used like this, options and their possible values are removed from `@myopts`, the global `@ARGV` is not touched at all.
The following two calls behave identically:
```
$ret = GetOptions( ... );
$ret = GetOptionsFromArray(\@ARGV, ... );
```
This also means that a first argument hash reference now becomes the second argument:
```
$ret = GetOptions(\%opts, ... );
$ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
```
###
Parsing options from an arbitrary string
A special entry `GetOptionsFromString` can be used to parse options from an arbitrary string.
```
use Getopt::Long qw(GetOptionsFromString);
$ret = GetOptionsFromString($string, ...);
```
The contents of the string are split into arguments using a call to `Text::ParseWords::shellwords`. As with `GetOptionsFromArray`, the global `@ARGV` is not touched.
It is possible that, upon completion, not all arguments in the string have been processed. `GetOptionsFromString` will, when called in list context, return both the return status and an array reference to any remaining arguments:
```
($ret, $args) = GetOptionsFromString($string, ... );
```
If any arguments remain, and `GetOptionsFromString` was not called in list context, a message will be given and `GetOptionsFromString` will return failure.
As with GetOptionsFromArray, a first argument hash reference now becomes the second argument. See the next section.
###
Storing options values in a hash
Sometimes, for example when there are a lot of options, having a separate variable for each of them can be cumbersome. GetOptions() supports, as an alternative mechanism, storing options values in a hash.
To obtain this, a reference to a hash must be passed *as the first argument* to GetOptions(). For each option that is specified on the command line, the option value will be stored in the hash with the option name as key. Options that are not actually used on the command line will not be put in the hash, on other words, `exists($h{option})` (or defined()) can be used to test if an option was used. The drawback is that warnings will be issued if the program runs under `use strict` and uses `$h{option}` without testing with exists() or defined() first.
```
my %h = ();
GetOptions (\%h, 'length=i'); # will store in $h{length}
```
For options that take list or hash values, it is necessary to indicate this by appending an `@` or `%` sign after the type:
```
GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
```
To make things more complicated, the hash may contain references to the actual destinations, for example:
```
my $len = 0;
my %h = ('length' => \$len);
GetOptions (\%h, 'length=i'); # will store in $len
```
This example is fully equivalent with:
```
my $len = 0;
GetOptions ('length=i' => \$len); # will store in $len
```
Any mixture is possible. For example, the most frequently used options could be stored in variables while all other options get stored in the hash:
```
my $verbose = 0; # frequently referred
my $debug = 0; # frequently referred
my %h = ('verbose' => \$verbose, 'debug' => \$debug);
GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
if ( $verbose ) { ... }
if ( exists $h{filter} ) { ... option 'filter' was specified ... }
```
### Bundling
With bundling it is possible to set several single-character options at once. For example if `a`, `v` and `x` are all valid options,
```
-vax
```
will set all three.
Getopt::Long supports three styles of bundling. To enable bundling, a call to Getopt::Long::Configure is required.
The simplest style of bundling can be enabled with:
```
Getopt::Long::Configure ("bundling");
```
Configured this way, single-character options can be bundled but long options (and any of their auto-abbreviated shortened forms) **must** always start with a double dash `--` to avoid ambiguity. For example, when `vax`, `a`, `v` and `x` are all valid options,
```
-vax
```
will set `a`, `v` and `x`, but
```
--vax
```
will set `vax`.
The second style of bundling lifts this restriction. It can be enabled with:
```
Getopt::Long::Configure ("bundling_override");
```
Now, `-vax` will set the option `vax`.
In all of the above cases, option values may be inserted in the bundle. For example:
```
-h24w80
```
is equivalent to
```
-h 24 -w 80
```
A third style of bundling allows only values to be bundled with options. It can be enabled with:
```
Getopt::Long::Configure ("bundling_values");
```
Now, `-h24` will set the option `h` to `24`, but option bundles like `-vxa` and `-h24w80` are flagged as errors.
Enabling `bundling_values` will disable the other two styles of bundling.
When configured for bundling, single-character options are matched case sensitive while long options are matched case insensitive. To have the single-character options matched case insensitive as well, use:
```
Getopt::Long::Configure ("bundling", "ignorecase_always");
```
It goes without saying that bundling can be quite confusing.
###
The lonesome dash
Normally, a lone dash `-` on the command line will not be considered an option. Option processing will terminate (unless "permute" is configured) and the dash will be left in `@ARGV`.
It is possible to get special treatment for a lone dash. This can be achieved by adding an option specification with an empty name, for example:
```
GetOptions ('' => \$stdio);
```
A lone dash on the command line will now be a legal option, and using it will set variable `$stdio`.
###
Argument callback
A special option 'name' `<>` can be used to designate a subroutine to handle non-option arguments. When GetOptions() encounters an argument that does not look like an option, it will immediately call this subroutine and passes it one parameter: the argument name.
For example:
```
my $width = 80;
sub process { ... }
GetOptions ('width=i' => \$width, '<>' => \&process);
```
When applied to the following command line:
```
arg1 --width=72 arg2 --width=60 arg3
```
This will call `process("arg1")` while `$width` is `80`, `process("arg2")` while `$width` is `72`, and `process("arg3")` while `$width` is `60`.
This feature requires configuration option **permute**, see section ["Configuring Getopt::Long"](#Configuring-Getopt%3A%3ALong).
Configuring Getopt::Long
-------------------------
Getopt::Long can be configured by calling subroutine Getopt::Long::Configure(). This subroutine takes a list of quoted strings, each specifying a configuration option to be enabled, e.g. `ignore_case`. To disable, prefix with `no` or `no_`, e.g. `no_ignore_case`. Case does not matter. Multiple calls to Configure() are possible.
Alternatively, as of version 2.24, the configuration options may be passed together with the `use` statement:
```
use Getopt::Long qw(:config no_ignore_case bundling);
```
The following options are available:
default This option causes all configuration options to be reset to their default values.
posix\_default This option causes all configuration options to be reset to their default values as if the environment variable POSIXLY\_CORRECT had been set.
auto\_abbrev Allow option names to be abbreviated to uniqueness. Default is enabled unless environment variable POSIXLY\_CORRECT has been set, in which case `auto_abbrev` is disabled.
getopt\_compat Allow `+` to start options. Default is enabled unless environment variable POSIXLY\_CORRECT has been set, in which case `getopt_compat` is disabled.
gnu\_compat `gnu_compat` controls whether `--opt=` is allowed, and what it should do. Without `gnu_compat`, `--opt=` gives an error. With `gnu_compat`, `--opt=` will give option `opt` and empty value. This is the way GNU getopt\_long() does it.
Note that `--opt value` is still accepted, even though GNU getopt\_long() doesn't.
gnu\_getopt This is a short way of setting `gnu_compat` `bundling` `permute` `no_getopt_compat`. With `gnu_getopt`, command line handling should be reasonably compatible with GNU getopt\_long().
require\_order Whether command line arguments are allowed to be mixed with options. Default is disabled unless environment variable POSIXLY\_CORRECT has been set, in which case `require_order` is enabled.
See also `permute`, which is the opposite of `require_order`.
permute Whether command line arguments are allowed to be mixed with options. Default is enabled unless environment variable POSIXLY\_CORRECT has been set, in which case `permute` is disabled. Note that `permute` is the opposite of `require_order`.
If `permute` is enabled, this means that
```
--foo arg1 --bar arg2 arg3
```
is equivalent to
```
--foo --bar arg1 arg2 arg3
```
If an argument callback routine is specified, `@ARGV` will always be empty upon successful return of GetOptions() since all options have been processed. The only exception is when `--` is used:
```
--foo arg1 --bar arg2 -- arg3
```
This will call the callback routine for arg1 and arg2, and then terminate GetOptions() leaving `"arg3"` in `@ARGV`.
If `require_order` is enabled, options processing terminates when the first non-option is encountered.
```
--foo arg1 --bar arg2 arg3
```
is equivalent to
```
--foo -- arg1 --bar arg2 arg3
```
If `pass_through` is also enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first.
bundling (default: disabled) Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options (and any of their auto-abbreviated shortened forms) *must* be introduced with `--` and bundles with `-`.
Note that, if you have options `a`, `l` and `all`, and auto\_abbrev enabled, possible arguments and option settings are:
```
using argument sets option(s)
------------------------------------------
-a, --a a
-l, --l l
-al, -la, -ala, -all,... a, l
--al, --all all
```
The surprising part is that `--a` sets option `a` (due to auto completion), not `all`.
Note: disabling `bundling` also disables `bundling_override`.
bundling\_override (default: disabled) If `bundling_override` is enabled, bundling is enabled as with `bundling` but now long option names override option bundles.
Note: disabling `bundling_override` also disables `bundling`.
**Note:** Using option bundling can easily lead to unexpected results, especially when mixing long options and bundles. Caveat emptor.
ignore\_case (default: enabled) If enabled, case is ignored when matching option names. If, however, bundling is enabled as well, single character options will be treated case-sensitive.
With `ignore_case`, option specifications for options that only differ in case, e.g., `"foo"` and `"Foo"`, will be flagged as duplicates.
Note: disabling `ignore_case` also disables `ignore_case_always`.
ignore\_case\_always (default: disabled) When bundling is in effect, case is ignored on single-character options also.
Note: disabling `ignore_case_always` also disables `ignore_case`.
auto\_version (default:disabled) Automatically provide support for the **--version** option if the application did not specify a handler for this option itself.
Getopt::Long will provide a standard version message that includes the program name, its version (if $main::VERSION is defined), and the versions of Getopt::Long and Perl. The message will be written to standard output and processing will terminate.
`auto_version` will be enabled if the calling program explicitly specified a version number higher than 2.32 in the `use` or `require` statement.
auto\_help (default:disabled) Automatically provide support for the **--help** and **-?** options if the application did not specify a handler for this option itself.
Getopt::Long will provide a help message using module <Pod::Usage>. The message, derived from the SYNOPSIS POD section, will be written to standard output and processing will terminate.
`auto_help` will be enabled if the calling program explicitly specified a version number higher than 2.32 in the `use` or `require` statement.
pass\_through (default: disabled) With `pass_through` anything that is unknown, ambiguous or supplied with an invalid option will not be flagged as an error. Instead the unknown option(s) will be passed to the catchall `<>` if present, otherwise through to `@ARGV`. This makes it possible to write wrapper scripts that process only part of the user supplied command line arguments, and pass the remaining options to some other program.
If `require_order` is enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first and all remaining arguments are passed to `@ARGV` instead of the catchall `<>` if present. However, if `permute` is enabled instead, results can become confusing.
Note that the options terminator (default `--`), if present, will also be passed through in `@ARGV`.
prefix The string that starts options. If a constant string is not sufficient, see `prefix_pattern`.
prefix\_pattern A Perl pattern that identifies the strings that introduce options. Default is `--|-|\+` unless environment variable POSIXLY\_CORRECT has been set, in which case it is `--|-`.
long\_prefix\_pattern A Perl pattern that allows the disambiguation of long and short prefixes. Default is `--`.
Typically you only need to set this if you are using nonstandard prefixes and want some or all of them to have the same semantics as '--' does under normal circumstances.
For example, setting prefix\_pattern to `--|-|\+|\/` and long\_prefix\_pattern to `--|\/` would add Win32 style argument handling.
debug (default: disabled) Enable debugging output.
Exportable Methods
-------------------
VersionMessage This subroutine provides a standard version message. Its argument can be:
* A string containing the text of a message to print *before* printing the standard 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`
`-msg`
The text of a message to print immediately prior to printing the program's usage message.
`-exitval`
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.
`-output`
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`).
You cannot tie this routine directly to an option, e.g.:
```
GetOptions("version" => \&VersionMessage);
```
Use this instead:
```
GetOptions("version" => sub { VersionMessage() });
```
HelpMessage This subroutine produces a standard help message, derived from the program's POD section SYNOPSIS using <Pod::Usage>. It takes the same arguments as VersionMessage(). In particular, you cannot tie it directly to an option, e.g.:
```
GetOptions("help" => \&HelpMessage);
```
Use this instead:
```
GetOptions("help" => sub { HelpMessage() });
```
Return values and Errors
-------------------------
Configuration errors and errors in the option definitions are signalled using die() and will terminate the calling program unless the call to Getopt::Long::GetOptions() was embedded in `eval { ... }`, or die() was trapped using `$SIG{__DIE__}`.
GetOptions returns true to indicate success. It returns false when the function detected one or more errors during option parsing. These errors are signalled using warn() and can be trapped with `$SIG{__WARN__}`.
Legacy
------
The earliest development of `newgetopt.pl` started in 1990, with Perl version 4. As a result, its development, and the development of Getopt::Long, has gone through several stages. Since backward compatibility has always been extremely important, the current version of Getopt::Long still supports a lot of constructs that nowadays are no longer necessary or otherwise unwanted. This section describes briefly some of these 'features'.
###
Default destinations
When no destination is specified for an option, GetOptions will store the resultant value in a global variable named `opt_`*XXX*, where *XXX* is the primary name of this option. When a program executes under `use strict` (recommended), these variables must be pre-declared with our() or `use vars`.
```
our $opt_length = 0;
GetOptions ('length=i'); # will store in $opt_length
```
To yield a usable Perl variable, characters that are not part of the syntax for variables are translated to underscores. For example, `--fpp-struct-return` will set the variable `$opt_fpp_struct_return`. Note that this variable resides in the namespace of the calling program, not necessarily `main`. For example:
```
GetOptions ("size=i", "sizes=i@");
```
with command line "-size 10 -sizes 24 -sizes 48" will perform the equivalent of the assignments
```
$opt_size = 10;
@opt_sizes = (24, 48);
```
###
Alternative option starters
A string of alternative option starter characters may be passed as the first argument (or the first argument after a leading hash reference argument).
```
my $len = 0;
GetOptions ('/', 'length=i' => $len);
```
Now the command line may look like:
```
/length 24 -- arg
```
Note that to terminate options processing still requires a double dash `--`.
GetOptions() will not interpret a leading `"<>"` as option starters if the next argument is a reference. To force `"<"` and `">"` as option starters, use `"><"`. Confusing? Well, **using a starter argument is strongly deprecated** anyway.
###
Configuration variables
Previous versions of Getopt::Long used variables for the purpose of configuring. Although manipulating these variables still work, it is strongly encouraged to use the `Configure` routine that was introduced in version 2.17. Besides, it is much easier.
Tips and Techniques
--------------------
###
Pushing multiple values in a hash option
Sometimes you want to combine the best of hashes and arrays. For example, the command line:
```
--list add=first --list add=second --list add=third
```
where each successive 'list add' option will push the value of add into array ref $list->{'add'}. The result would be like
```
$list->{add} = [qw(first second third)];
```
This can be accomplished with a destination routine:
```
GetOptions('list=s%' =>
sub { push(@{$list{$_[1]}}, $_[2]) });
```
Troubleshooting
---------------
###
GetOptions does not return a false result when an option is not supplied
That's why they're called 'options'.
###
GetOptions does not split the command line correctly
The command line is not split by GetOptions, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (`'`) and double quotes (`"`) to group words together. The following alternatives are equivalent on Unix:
```
"two words"
'two words'
two\ words
```
In case of doubt, insert the following statement in front of your Perl program:
```
print STDERR (join("|",@ARGV),"\n");
```
to verify how your CLI passes the arguments to the program.
###
Undefined subroutine &main::GetOptions called
Are you running Windows, and did you write
```
use GetOpt::Long;
```
(note the capital 'O')?
###
How do I put a "-?" option into a Getopt::Long?
You can only obtain this using an alias, and Getopt::Long of at least version 2.13.
```
use Getopt::Long;
GetOptions ("help|?"); # -help and -? will both set $opt_help
```
Other characters that can't appear in Perl identifiers are also supported in aliases with Getopt::Long of at version 2.39. Note that the characters `!`, `|`, `+`, `=`, and `:` can only appear as the first (or only) character of an alias.
As of version 2.32 Getopt::Long provides auto-help, a quick and easy way to add the options --help and -? to your program, and handle them.
See `auto_help` in section ["Configuring Getopt::Long"](#Configuring-Getopt%3A%3ALong).
AUTHOR
------
Johan Vromans <[email protected]>
COPYRIGHT AND DISCLAIMER
-------------------------
This program is Copyright 1990,2015 by Johan Vromans. This program is free software; you can redistribute it and/or modify it under the terms of the Perl Artistic License or the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
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 the GNU General Public License for more details.
If you do not have a copy of the GNU General Public License write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
| programming_docs |
perl App::Prove::State App::Prove::State
=================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [result\_class](#result_class)
+ [extensions](#extensions)
+ [results](#results)
+ [commit](#commit)
+ [Instance Methods](#Instance-Methods)
- [apply\_switch](#apply_switch)
- [get\_tests](#get_tests)
- [observe\_test](#observe_test)
- [save](#save1)
- [load](#load)
NAME
----
App::Prove::State - State storage for the `prove` command.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
The `prove` command supports a `--state` option that instructs it to store persistent state across runs. This module implements that state and the operations that may be performed on it.
SYNOPSIS
--------
```
# Re-run failed tests
$ prove --state=failed,save -rbv
```
METHODS
-------
###
Class Methods
#### `new`
Accepts a hashref with the following key/value pairs:
* `store`
The filename of the data store holding the data that App::Prove::State reads.
* `extensions` (optional)
The test name extensions. Defaults to `.t`.
* `result_class` (optional)
The name of the `result_class`. Defaults to `App::Prove::State::Result`.
### `result_class`
Getter/setter for the name of the class used for tracking test results. This class should either subclass from `App::Prove::State::Result` or provide an identical interface.
### `extensions`
Get or set the list of extensions that files must have in order to be considered tests. Defaults to ['.t'].
### `results`
Get the results of the last test run. Returns a `result_class()` instance.
### `commit`
Save the test results. Should be called after all tests have run.
###
Instance Methods
#### `apply_switch`
```
$self->apply_switch('failed,save');
```
Apply a list of switch options to the state, updating the internal object state as a result. Nothing is returned.
Diagnostics: - "Illegal state option: %s"
`last` Run in the same order as last time
`failed` Run only the failed tests from last time
`passed` Run only the passed tests from last time
`all` Run all tests in normal order
`hot` Run the tests that most recently failed first
`todo` Run the tests ordered by number of todos.
`slow` Run the tests in slowest to fastest order.
`fast` Run test tests in fastest to slowest order.
`new` Run the tests in newest to oldest order.
`old` Run the tests in oldest to newest order.
`save` Save the state on exit.
#### `get_tests`
Given a list of args get the names of tests that should run
#### `observe_test`
Store the results of a test.
#### `save`
Write the state to a file.
#### `load`
Load the state from a file
perl Test2::Util::Facets2Legacy Test2::Util::Facets2Legacy
==========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
+ [AS METHODS](#AS-METHODS)
+ [AS FUNCTIONS](#AS-FUNCTIONS)
* [NOTE ON CYCLES](#NOTE-ON-CYCLES)
* [EXPORTS](#EXPORTS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Util::Facets2Legacy - Convert facet data to the legacy event API.
DESCRIPTION
-----------
This module exports several subroutines from the older event API (see <Test2::Event>). These subroutines can be used as methods on any object that provides a custom `facet_data()` method. These subroutines can also be used as functions that take a facet data hashref as arguments.
SYNOPSIS
--------
###
AS METHODS
```
package My::Event;
use Test2::Util::Facets2Legacy ':ALL';
sub facet_data { return { ... } }
```
Then to use it:
```
my $e = My::Event->new(...);
my $causes_fail = $e->causes_fail;
my $summary = $e->summary;
....
```
###
AS FUNCTIONS
```
use Test2::Util::Facets2Legacy ':ALL';
my $f = {
assert => { ... },
info => [{...}, ...],
control => {...},
...
};
my $causes_fail = causes_fail($f);
my $summary = summary($f);
```
NOTE ON CYCLES
---------------
When used as methods, all these subroutines call `$e->facet_data()`. The default `facet_data()` method in <Test2::Event> relies on the legacy methods this module emulates in order to work. As a result of this it is very easy to create infinite recursion bugs.
These methods have cycle detection and will throw an exception early if a cycle is detected. `uuid()` is currently the only subroutine in this library that has a fallback behavior when cycles are detected.
EXPORTS
-------
Nothing is exported by default. You must specify which methods to import, or use the ':ALL' tag.
$bool = $e->causes\_fail()
$bool = causes\_fail($f) Check if the event or facets result in a failing state.
$bool = $e->diagnostics()
$bool = diagnostics($f) Check if the event or facets contain any diagnostics information.
$bool = $e->global()
$bool = global($f) Check if the event or facets need to be globally processed.
$bool = $e->increments\_count()
$bool = increments\_count($f) Check if the event or facets make an assertion.
$bool = $e->no\_display()
$bool = no\_display($f) Check if the event or facets should be rendered or hidden.
($max, $directive, $reason) = $e->sets\_plan()
($max, $directive, $reason) = sets\_plan($f) Check if the event or facets set a plan, and return the plan details.
$id = $e->subtest\_id()
$id = subtest\_id($f) Get the subtest id, if any.
$string = $e->summary()
$string = summary($f) Get the summary of the event or facets hash, if any.
$undef\_or\_int = $e->terminate()
$undef\_or\_int = terminate($f) Check if the event or facets should result in process termination, if so the exit code is returned (which could be 0). undef is returned if no termination is requested.
$uuid = $e->uuid()
$uuid = uuid($f) Get the UUID of the facets or event.
**Note:** This will fall back to `$e->SUPER::uuid()` if a cycle is detected and an event is used as the argument.
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 perlsyn perlsyn
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Declarations](#Declarations)
+ [Comments](#Comments)
+ [Simple Statements](#Simple-Statements)
+ [Statement Modifiers](#Statement-Modifiers)
+ [Compound Statements](#Compound-Statements)
+ [Loop Control](#Loop-Control)
+ [For Loops](#For-Loops)
+ [Foreach Loops](#Foreach-Loops)
+ [Try Catch Exception Handling](#Try-Catch-Exception-Handling)
+ [Basic BLOCKs](#Basic-BLOCKs)
+ [defer blocks](#defer-blocks)
+ [Switch Statements](#Switch-Statements)
+ [Goto](#Goto)
+ [The Ellipsis Statement](#The-Ellipsis-Statement)
+ [PODs: Embedded Documentation](#PODs:-Embedded-Documentation)
+ [Plain Old Comments (Not!)](#Plain-Old-Comments-(Not!))
+ [Experimental Details on given and when](#Experimental-Details-on-given-and-when)
- [Breaking out](#Breaking-out)
- [Fall-through](#Fall-through)
- [Return value](#Return-value)
- [Switching in a loop](#Switching-in-a-loop)
- [Differences from Raku](#Differences-from-Raku)
NAME
----
perlsyn - Perl syntax
DESCRIPTION
-----------
A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code.
Perl is a **free-form** language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial.
Many of Perl's syntactic elements are **optional**. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as **Do What I Mean**, abbreviated **DWIM**. It allows programmers to be **lazy** and to code in a style with which they are comfortable.
Perl **borrows syntax** and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. Other languages have borrowed syntax from Perl, particularly its regular expression extensions. So if you have programmed in another language you will see familiar pieces in Perl. They often work the same, but see <perltrap> for information about how they differ.
### Declarations
The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines). A scalar variable holds the undefined value (`undef`) until it has been assigned a defined value, which is anything other than `undef`. When used as a number, `undef` is treated as `0`; when used as a string, it is treated as the empty string, `""`; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat `undef` as a string or a number. Well, usually. Boolean contexts, such as:
```
if ($a) {}
```
are exempt from warnings (because they care about truth rather than definedness). Operators such as `++`, `--`, `+=`, `-=`, and `.=`, that operate on undefined variables such as:
```
undef $a;
$a++;
```
are also always exempt from such warnings.
A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements: declarations all take effect at compile time. All declarations are typically put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with `my()`, `state()`, or `our()`, you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables.
Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying `sub name`, thus:
```
sub myname;
$me = myname $0 or die "can't get myname";
```
A bare declaration like that declares the function to be a list operator, not a unary operator, so you have to be careful to use parentheses (or `or` instead of `||`.) The `||` operator binds too tightly to use after list operators; it becomes part of the last element. You can always use parentheses around the list operators arguments to turn the list operator back into something that behaves more like a function call. Alternatively, you can use the prototype `($)` to turn the subroutine into a unary operator:
```
sub myname ($);
$me = myname $0 || die "can't get myname";
```
That now parses as you'd expect, but you still ought to get in the habit of using parentheses in that situation. For more on prototypes, see <perlsub>.
Subroutines declarations can also be loaded up with the `require` statement or both loaded and imported into your namespace with a `use` statement. See <perlmod> for details on this.
A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects.
### Comments
Text from a `"#"` character until the end of the line is a comment, and is ignored. Exceptions include `"#"` inside a string or regular expression.
###
Simple Statements
The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. Note that there are operators like `eval {}`, `sub {}`, and `do {}` that *look* like compound statements, but aren't--they're just TERMs in an expression--and thus need an explicit termination when used as the last item in a statement.
###
Statement Modifiers
Any simple statement may optionally be followed by a *SINGLE* modifier, just before the terminating semicolon (or block ending). The possible modifiers are:
```
if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR
```
The `EXPR` following the modifier is referred to as the "condition". Its truth or falsehood determines how the modifier will behave.
`if` executes the statement once *if* and only if the condition is true. `unless` is the opposite, it executes the statement *unless* the condition is true (that is, if the condition is false). See ["Scalar values" in perldata](perldata#Scalar-values) for definitions of true and false.
```
print "Basset hounds got long ears" if length $ear >= 10;
go_outside() and play() unless $is_raining;
```
The `for(each)` modifier is an iterator: it executes the statement once for each item in the LIST (with `$_` aliased to each item in turn). There is no syntax to specify a C-style for loop or a lexically scoped iteration variable in this form.
```
print "Hello $_!\n" for qw(world Dolly nurse);
```
`while` repeats the statement *while* the condition is true. Postfix `while` has the same magic treatment of some kinds of condition that prefix `while` has. `until` does the opposite, it repeats the statement *until* the condition is true (or while the condition is false):
```
# Both of these count from 0 to 10.
print $i++ while $i <= 10;
print $j++ until $j > 10;
```
The `while` and `until` modifiers have the usual "`while` loop" semantics (conditional evaluated first), except when applied to a `do`-BLOCK (or to the Perl4 `do`-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated.
This is so that you can write loops like:
```
do {
$line = <STDIN>;
...
} until !defined($line) || $line eq ".\n"
```
See ["do" in perlfunc](perlfunc#do). Note also that the loop control statements described later will *NOT* work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for `next`/`redo`) or around it (for `last`) to do that sort of thing.
For `next` or `redo`, just double the braces:
```
do {{
next if $x == $y;
# do something here
}} until $x++ > $z;
```
For `last`, you have to be more elaborate and put braces around it:
```
{
do {
last if $x == $y**2;
# do something here
} while $x++ <= $z;
}
```
If you need both `next` and `last`, you have to do both and also use a loop label:
```
LOOP: {
do {{
next if $x == $y;
last LOOP if $x == $y**2;
# do something here
}} until $x++ > $z;
}
```
**NOTE:** The behaviour of a `my`, `state`, or `our` modified with a statement modifier conditional or loop construct (for example, `my $x if ...`) is **undefined**. The value of the `my` variable may be `undef`, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.
The `when` modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a `use v5.14` declaration. (Technically, it requires only the `switch` feature, but that aspect of it was not available before 5.14.) Operative only from within a `foreach` loop or a `given` block, it executes the statement only if the smartmatch `$_ ~~ *EXPR*` is true. If the statement executes, it is followed by a `next` from inside a `foreach` and `break` from inside a `given`.
Under the current implementation, the `foreach` loop can be anywhere within the `when` modifier's dynamic scope, but must be within the `given` block's lexical scope. This restriction may be relaxed in a future release. See ["Switch Statements"](#Switch-Statements) below.
###
Compound Statements
In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval).
But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK. Because enclosing braces are also the syntax for hash reference constructor expressions (see <perlref>), you may occasionally need to disambiguate by placing a `;` immediately after an opening brace so that Perl realises the brace is the start of a block. You will more frequently need to disambiguate the other way, by placing a `+` immediately before an opening brace to force it to be interpreted as a hash reference constructor expression. It is considered good style to use these disambiguating mechanisms liberally, not only when Perl would otherwise guess incorrectly.
The following compound statements may be used to control flow:
```
if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
unless (EXPR) BLOCK
unless (EXPR) BLOCK else BLOCK
unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
given (EXPR) BLOCK
LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK
LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK
LABEL for (EXPR; EXPR; EXPR) BLOCK
LABEL for VAR (LIST) BLOCK
LABEL for VAR (LIST) BLOCK continue BLOCK
LABEL foreach (EXPR; EXPR; EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK
LABEL BLOCK
LABEL BLOCK continue BLOCK
PHASE BLOCK
```
As of Perl 5.36, you can iterate over multiple values at a time by specifying a list of lexicals within parentheses:
```
no warnings "experimental::for_list";
LABEL for my (VAR, VAR) (LIST) BLOCK
LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
LABEL foreach my (VAR, VAR) (LIST) BLOCK
LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK
```
If enabled by the experimental `try` feature, the following may also be used
```
try BLOCK catch (VAR) BLOCK
try BLOCK catch (VAR) BLOCK finally BLOCK
```
The experimental `given` statement is *not automatically enabled*; see ["Switch Statements"](#Switch-Statements) below for how to do so, and the attendant caveats.
Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements. This means that the curly brackets are *required*--no dangling statements allowed. If you want to write conditionals without curly brackets, there are several other ways to do it. The following all do the same thing:
```
if (!open(FOO)) { die "Can't open $FOO: $!" }
die "Can't open $FOO: $!" unless open(FOO);
open(FOO) || die "Can't open $FOO: $!";
open(FOO) ? () : die "Can't open $FOO: $!";
# a bit exotic, that last one
```
The `if` statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which `if` an `else` goes with. If you use `unless` in place of `if`, the sense of the test is reversed. Like `if`, `unless` can be followed by `else`. `unless` can even be followed by one or more `elsif` statements, though you may want to think twice before using that particular language construct, as everyone reading your code will have to think at least twice before they can understand what's going on.
The `while` statement executes the block as long as the expression is true. The `until` statement executes the block as long as the expression is false. The LABEL is optional, and if present, consists of an identifier followed by a colon. The LABEL identifies the loop for the loop control statements `next`, `last`, and `redo`. If the LABEL is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically searching through your call-stack at run time to find the LABEL. Such desperate behavior triggers a warning if you use the `use warnings` pragma or the **-w** flag.
If the condition expression of a `while` statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are [`readline`](perlfunc#readline-EXPR), the [`<FILEHANDLE>`](perlop#I%2FO-Operators) input operator, [`readdir`](perlfunc#readdir-DIRHANDLE), [`glob`](perlfunc#glob-EXPR), the [`<PATTERN>`](perlop#I%2FO-Operators) globbing operator, and [`each`](perlfunc#each-HASH). If the condition expression is one of these expression types, then the value yielded by the iterative operator will be implicitly assigned to `$_`. If the condition expression is one of these expression types or an explicit assignment of one of them to a scalar, then the condition actually tests for definedness of the expression's value, not for its regular truth value.
If there is a `continue` BLOCK, it is always executed just before the conditional is about to be evaluated again. Thus it can be used to increment a loop variable, even when the loop has been continued via the `next` statement.
When a block is preceded by a compilation phase keyword such as `BEGIN`, `END`, `INIT`, `CHECK`, or `UNITCHECK`, then the block will run only during the corresponding phase of execution. See <perlmod> for more details.
Extension modules can also hook into the Perl parser to define new kinds of compound statements. These are introduced by a keyword which the extension recognizes, and the syntax following the keyword is defined entirely by the extension. If you are an implementor, see ["PL\_keyword\_plugin" in perlapi](perlapi#PL_keyword_plugin) for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines.
###
Loop Control
The `next` command starts the next iteration of the loop:
```
LINE: while (<STDIN>) {
next LINE if /^#/; # discard comments
...
}
```
The `last` command immediately exits the loop in question. The `continue` block, if any, is not executed:
```
LINE: while (<STDIN>) {
last LINE if /^$/; # exit when done with header
...
}
```
The `redo` command restarts the loop block without evaluating the conditional again. The `continue` block, if any, is *not* executed. This command is normally used by programs that want to lie to themselves about what was just input.
For example, when processing a file like */etc/termcap*. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record.
```
while (<>) {
chomp;
if (s/\\$//) {
$_ .= <>;
redo unless eof();
}
# now process $_
}
```
which is Perl shorthand for the more explicitly written version:
```
LINE: while (defined($line = <ARGV>)) {
chomp($line);
if ($line =~ s/\\$//) {
$line .= <ARGV>;
redo LINE unless eof(); # not eof(ARGV)!
}
# now process $line
}
```
Note that if there were a `continue` block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or `m?pat?` one-time matches:
```
# inspired by :1,$g/fred/s//WILMA/
while (<>) {
m?(fred)? && s//WILMA $1 WILMA/;
m?(barney)? && s//BETTY $1 BETTY/;
m?(homer)? && s//MARGE $1 MARGE/;
} continue {
print "$ARGV $.: $_";
close ARGV if eof; # reset $.
reset if eof; # reset ?pat?
}
```
If the word `while` is replaced by the word `until`, the sense of the test is reversed, but the conditional is still tested before the first iteration.
Loop control statements don't work in an `if` or `unless`, since they aren't loops. You can double the braces to make them such, though.
```
if (/pattern/) {{
last if /fred/;
next if /barney/; # same effect as "last",
# but doesn't document as well
# do something here
}}
```
This is caused by the fact that a block by itself acts as a loop that executes once, see ["Basic BLOCKs"](#Basic-BLOCKs).
The form `while/if BLOCK BLOCK`, available in Perl 4, is no longer available. Replace any occurrence of `if BLOCK` by `if (do BLOCK)`.
###
For Loops
Perl's C-style `for` loop works like the corresponding `while` loop; that means that this:
```
for ($i = 1; $i < 10; $i++) {
...
}
```
is the same as this:
```
$i = 1;
while ($i < 10) {
...
} continue {
$i++;
}
```
There is one minor difference: if variables are declared with `my` in the initialization section of the `for`, the lexical scope of those variables is exactly the `for` loop (the body of the loop and the control sections). To illustrate:
```
my $i = 'samba';
for (my $i = 1; $i <= 4; $i++) {
print "$i\n";
}
print "$i\n";
```
when executed, gives:
```
1
2
3
4
samba
```
As a special case, if the test in the `for` loop (or the corresponding `while` loop) is empty, it is treated as true. That is, both
```
for (;;) {
...
}
```
and
```
while () {
...
}
```
are treated as infinite loops.
Besides the normal array index looping, `for` can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang.
```
$on_a_tty = -t STDIN && -t STDOUT;
sub prompt { print "yes? " if $on_a_tty }
for ( prompt(); <STDIN>; prompt() ) {
# do something
}
```
The condition expression of a `for` loop gets the same magic treatment of `readline` et al that the condition expression of a `while` loop gets.
###
Foreach Loops
The `foreach` loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword `my`, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with `my`, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs *only* for non C-style loops.
The `foreach` keyword is actually a synonym for the `for` keyword, so you can use either. If VAR is omitted, `$_` is set to each value.
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the `foreach` loop index variable is an implicit alias for each item in the list that you're looping over.
If any part of LIST is an array, `foreach` will get very confused if you add or remove elements within the loop body, for example with `splice`. So don't do that.
`foreach` probably won't do what you expect if VAR is a tied or other special variable. Don't do that either.
As of Perl 5.22, there is an experimental variant of this loop that accepts a variable preceded by a backslash for VAR, in which case the items in the LIST must be references. The backslashed variable will become an alias to each referenced item in the LIST, which must be of the correct type. The variable needn't be a scalar in this case, and the backslash may be followed by `my`. To use this form, you must enable the `refaliasing` feature via `use feature`. (See <feature>. See also ["Assigning to References" in perlref](perlref#Assigning-to-References).)
As of Perl 5.36, you can iterate over multiple values at a time. You can only iterate with lexical scalars as the iterator variables - unlike list assignment, it's not possible to use `undef` to signify a value that isn't wanted. This is a limitation of the current implementation, and might be changed in the future.
If the size of the LIST is not an exact multiple of the number of iterator variables, then on the last iteration the "excess" iterator variables are aliases to `undef`, as if the LIST had `, undef` appended as many times as needed for its length to become an exact multiple. This happens whether LIST is a literal LIST or an array - ie arrays are not extended if their size is not a multiple of the iteration size, consistent with iterating an array one-at-a-time. As these padding elements are not lvalues, attempting to modify them will fail, consistent with the behaviour when iterating a list with literal `undef`s. If this is not the behaviour you desire, then before the loop starts either explicitly extend your array to be an exact multiple, or explicitly throw an exception.
Examples:
```
for (@ary) { s/foo/bar/ }
for my $elem (@elements) {
$elem *= 2;
}
for $count (reverse(1..10), "BOOM") {
print $count, "\n";
sleep(1);
}
for (1..15) { print "Merry Christmas\n"; }
foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
print "Item: $item\n";
}
use feature "refaliasing";
no warnings "experimental::refaliasing";
foreach \my %hash (@array_of_hash_references) {
# do something with each %hash
}
foreach my ($foo, $bar, $baz) (@list) {
# do something three-at-a-time
}
foreach my ($key, $value) (%hash) {
# iterate over the hash
# The hash is immediately copied to a flat list before the loop
# starts. The list contains copies of keys but aliases of values.
# This is the same behaviour as for $var (%hash) {...}
}
```
Here's how a C programmer might code up a particular algorithm in Perl:
```
for (my $i = 0; $i < @ary1; $i++) {
for (my $j = 0; $j < @ary2; $j++) {
if ($ary1[$i] > $ary2[$j]) {
last; # can't go to outer :-(
}
$ary1[$i] += $ary2[$j];
}
# this is where that last takes me
}
```
Whereas here's how a Perl programmer more comfortable with the idiom might do it:
```
OUTER: for my $wid (@ary1) {
INNER: for my $jet (@ary2) {
next OUTER if $wid > $jet;
$wid += $jet;
}
}
```
See how much easier this is? It's cleaner, safer, and faster. It's cleaner because it's less noisy. It's safer because if code gets added between the inner and outer loops later on, the new code won't be accidentally executed. The `next` explicitly iterates the other loop rather than merely terminating the inner one. And it's faster because Perl executes a `foreach` statement more rapidly than it would the equivalent C-style `for` loop.
Perceptive Perl hackers may have noticed that a `for` loop has a return value, and that this value can be captured by wrapping the loop in a `do` block. The reward for this discovery is this cautionary advice: The return value of a `for` loop is unspecified and may change without notice. Do not rely on it.
###
Try Catch Exception Handling
The `try`/`catch` syntax provides control flow relating to exception handling. The `try` keyword introduces a block which will be executed when it is encountered, and the `catch` block provides code to handle any exception that may be thrown by the first.
```
try {
my $x = call_a_function();
$x < 100 or die "Too big";
send_output($x);
}
catch ($e) {
warn "Unable to output a value; $e";
}
print "Finished\n";
```
Here, the body of the `catch` block (i.e. the `warn` statement) will be executed if the initial block invokes the conditional `die`, or if either of the functions it invokes throws an uncaught exception. The `catch` block can inspect the `$e` lexical variable in this case to see what the exception was. If no exception was thrown then the `catch` block does not happen. In either case, execution will then continue from the following statement - in this example the `print`.
The `catch` keyword must be immediately followed by a variable declaration in parentheses, which introduces a new variable visible to the body of the subsequent block. Inside the block this variable will contain the exception value that was thrown by the code in the `try` block. It is not necessary to use the `my` keyword to declare this variable; this is implied (similar as it is for subroutine signatures).
Both the `try` and the `catch` blocks are permitted to contain control-flow expressions, such as `return`, `goto`, or `next`/`last`/`redo`. In all cases they behave as expected without warnings. In particular, a `return` expression inside the `try` block will make its entire containing function return - this is in contrast to its behaviour inside an `eval` block, where it would only make that block return.
Like other control-flow syntax, `try` and `catch` will yield the last evaluated value when placed as the final statement in a function or a `do` block. This permits the syntax to be used to create a value. In this case remember not to use the `return` expression, or that will cause the containing function to return.
```
my $value = do {
try {
get_thing(@args);
}
catch ($e) {
warn "Unable to get thing - $e";
$DEFAULT_THING;
}
};
```
As with other control-flow syntax, `try` blocks are not visible to `caller()` (just as for example, `while` or `foreach` loops are not). Successive levels of the `caller` result can see subroutine calls and `eval` blocks, because those affect the way that `return` would work. Since `try` blocks do not intercept `return`, they are not of interest to `caller`.
The `try` and `catch` blocks may optionally be followed by a third block introduced by the `finally` keyword. This third block is executed after the rest of the construct has finished.
```
try {
call_a_function();
}
catch ($e) {
warn "Unable to call; $e";
}
finally {
print "Finished\n";
}
```
The `finally` block is equivalent to using a `defer` block and will be invoked in the same situations; whether the `try` block completes successfully, throws an exception, or transfers control elsewhere by using `return`, a loop control, or `goto`.
Unlike the `try` and `catch` blocks, a `finally` block is not permitted to `return`, `goto` or use any loop controls. The final expression value is ignored, and does not affect the return value of the containing function even if it is placed last in the function.
This syntax is currently experimental and must be enabled with `use feature 'try'`. It emits a warning in the `experimental::try` category.
###
Basic BLOCKs
A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is *NOT* true in `eval{}`, `sub{}`, or contrary to popular belief `do{}` blocks, which do *NOT* count as loops.) The `continue` block is optional.
The BLOCK construct can be used to emulate case structures.
```
SWITCH: {
if (/^abc/) { $abc = 1; last SWITCH; }
if (/^def/) { $def = 1; last SWITCH; }
if (/^xyz/) { $xyz = 1; last SWITCH; }
$nothing = 1;
}
```
You'll also find that `foreach` loop used to create a topicalizer and a switch:
```
SWITCH:
for ($var) {
if (/^abc/) { $abc = 1; last SWITCH; }
if (/^def/) { $def = 1; last SWITCH; }
if (/^xyz/) { $xyz = 1; last SWITCH; }
$nothing = 1;
}
```
Such constructs are quite frequently used, both because older versions of Perl had no official `switch` statement, and also because the new version described immediately below remains experimental and can sometimes be confusing.
###
defer blocks
A block prefixed by the `defer` modifier provides a section of code which runs at a later time during scope exit.
A `defer` block can appear at any point where a regular block or other statement is permitted. If the flow of execution reaches this statement, the body of the block is stored for later, but not invoked immediately. When the flow of control leaves the containing block for any reason, this stored block is executed on the way past. It provides a means of deferring execution until a later time. This acts similarly to syntax provided by some other languages, often using keywords named `try / finally`.
This syntax is available if enabled by the `defer` named feature, and is currently experimental. If experimental warnings are enabled it will emit a warning when used.
```
use feature 'defer';
{
say "This happens first";
defer { say "This happens last"; }
say "And this happens inbetween";
}
```
If multiple `defer` blocks are contained in a single scope, they are executed in LIFO order; the last one reached is the first one executed.
The code stored by the `defer` block will be invoked when control leaves its containing block due to regular fallthrough, explicit `return`, exceptions thrown by `die` or propagated by functions called by it, `goto`, or any of the loop control statements `next`, `last` or `redo`.
If the flow of control does not reach the `defer` statement itself then its body is not stored for later execution. (This is in direct contrast to the code provided by an `END` phaser block, which is always enqueued by the compiler, regardless of whether execution ever reached the line it was given on.)
```
use feature 'defer';
{
defer { say "This will run"; }
return;
defer { say "This will not"; }
}
```
Exceptions thrown by code inside a `defer` block will propagate to the caller in the same way as any other exception thrown by normal code.
If the `defer` block is being executed due to a thrown exception and throws another one it is not specified what happens, beyond that the caller will definitely receive an exception.
Besides throwing an exception, a `defer` block is not permitted to otherwise alter the control flow of its surrounding code. In particular, it may not cause its containing function to `return`, nor may it `goto` a label, or control a containing loop using `next`, `last` or `redo`. These constructions are however, permitted entirely within the body of the `defer`.
```
use feature 'defer';
{
defer {
foreach ( 1 .. 5 ) {
last if $_ == 3; # this is permitted
}
}
}
{
foreach ( 6 .. 10 ) {
defer {
last if $_ == 8; # this is not
}
}
}
```
###
Switch Statements
Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can say
```
use feature "switch";
```
to enable an experimental switch feature. This is loosely based on an old version of a Raku proposal, but it no longer resembles the Raku construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl between 5.10 and 5.34. For example:
```
use v5.14;
```
Under the "switch" feature, Perl gains the experimental keywords `given`, `when`, `default`, `continue`, and `break`. Starting from Perl 5.16, one can prefix the switch keywords with `CORE::` to access the feature without a `use feature` statement. The keywords `given` and `when` are analogous to `switch` and `case` in other languages -- though `continue` is not -- so the code in the previous section could be rewritten as
```
use v5.10.1;
for ($var) {
when (/^abc/) { $abc = 1 }
when (/^def/) { $def = 1 }
when (/^xyz/) { $xyz = 1 }
default { $nothing = 1 }
}
```
The `foreach` is the non-experimental way to set a topicalizer. If you wish to use the highly experimental `given`, that could be written like this:
```
use v5.10.1;
given ($var) {
when (/^abc/) { $abc = 1 }
when (/^def/) { $def = 1 }
when (/^xyz/) { $xyz = 1 }
default { $nothing = 1 }
}
```
As of 5.14, that can also be written this way:
```
use v5.14;
for ($var) {
$abc = 1 when /^abc/;
$def = 1 when /^def/;
$xyz = 1 when /^xyz/;
default { $nothing = 1 }
}
```
Or if you don't care to play it safe, like this:
```
use v5.14;
given ($var) {
$abc = 1 when /^abc/;
$def = 1 when /^def/;
$xyz = 1 when /^xyz/;
default { $nothing = 1 }
}
```
The arguments to `given` and `when` are in scalar context, and `given` assigns the `$_` variable its topic value.
Exactly what the *EXPR* argument to `when` does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as `$_ ~~ *EXPR*`, and sometimes it is not. It also behaves differently when lexically enclosed by a `given` block than it does when dynamically enclosed by a `foreach` loop. The rules are far too difficult to understand to be described here. See ["Experimental Details on given and when"](#Experimental-Details-on-given-and-when) later on.
Due to an unfortunate bug in how `given` was implemented between Perl 5.10 and 5.16, under those implementations the version of `$_` governed by `given` is merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were a `foreach` or under both the original and the current Raku language specification. This bug was fixed in Perl 5.18 (and lexicalized `$_` itself was removed in Perl 5.24).
If your code still needs to run on older versions, stick to `foreach` for your topicalizer and you will be less unhappy.
### Goto
Although not for the faint of heart, Perl does support a `goto` statement. There are three forms: `goto`-LABEL, `goto`-EXPR, and `goto`-&NAME. A loop's LABEL is not actually a valid target for a `goto`; it's just the name of the loop.
The `goto`-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a `foreach` loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as `last` or `die`. The author of Perl has never felt the need to use this form of `goto` (in Perl, that is--C is another matter).
The `goto`-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed `goto`s per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:
```
goto(("FOO", "BAR", "GLARCH")[$i]);
```
The `goto`-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by `AUTOLOAD()` subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to `@_` in the current subroutine are propagated to the other subroutine.) After the `goto`, not even `caller()` will be able to tell that this routine was called first.
In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of `next`, `last`, or `redo` instead of resorting to a `goto`. For certain applications, the catch and throw pair of `eval{}` and die() for exception processing can also be a prudent approach.
###
The Ellipsis Statement
Beginning in Perl 5.12, Perl accepts an ellipsis, "`...`", as a placeholder for code that you haven't implemented yet. When Perl 5.12 or later encounters an ellipsis statement, it parses this without error, but if and when you should actually try to execute it, Perl throws an exception with the text `Unimplemented`:
```
use v5.12;
sub unimplemented { ... }
eval { unimplemented() };
if ($@ =~ /^Unimplemented at /) {
say "I found an ellipsis!";
}
```
You can only use the elliptical statement to stand in for a complete statement. Syntactically, "`...;`" is a complete statement, but, as with other kinds of semicolon-terminated statement, the semicolon may be omitted if "`...`" appears immediately before a closing brace. These examples show how the ellipsis works:
```
use v5.12;
{ ... }
sub foo { ... }
...;
eval { ... };
sub somemeth {
my $self = shift;
...;
}
$x = do {
my $n;
...;
say "Hurrah!";
$n;
};
```
The elliptical statement cannot stand in for an expression that is part of a larger statement. These examples of attempts to use an ellipsis are syntax errors:
```
use v5.12;
print ...;
open(my $fh, ">", "/dev/passwd") or ...;
if ($condition && ... ) { say "Howdy" };
... if $a > $b;
say "Cromulent" if ...;
$flub = 5 + ...;
```
There are some cases where Perl can't immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there's something in the braces to give Perl a hint. The ellipsis is a syntax error if Perl doesn't guess that the `{ ... }` is a block. Inside your block, you can use a `;` before the ellipsis to denote that the `{ ... }` is a block and not a hash reference constructor.
Note: Some folks colloquially refer to this bit of punctuation as a "yada-yada" or "triple-dot", but its true name is actually an ellipsis.
###
PODs: Embedded Documentation
Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this
```
=head1 Here There Be Pods!
```
Then that text and all remaining text up through and including a line beginning with `=cut` will be ignored. The format of the intervening text is described in <perlpod>.
This allows you to intermix your source code and your documentation text freely, as in
```
=item snazzle($)
The snazzle() function will behave in the most spectacular
form that you can possibly imagine, not even excepting
cybernetic pyrotechnics.
=cut back to the compiler, nuff of this pod stuff!
sub snazzle($) {
my $thingie = shift;
.........
}
```
Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators.
```
$a=3;
=secret stuff
warn "Neither POD nor CODE!?"
=cut back
print "got $a\n";
```
You probably shouldn't rely upon the `warn()` being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.
One may also use pod directives to quickly comment out a section of code.
###
Plain Old Comments (Not!)
Perl can process line directives, much like the C preprocessor. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with `eval()`). The syntax for this mechanism is almost the same as for most C preprocessors: it matches the regular expression
```
# example: '# line 42 "new_filename.plx"'
/^\# \s*
line \s+ (\d+) \s*
(?:\s("?)([^"]+)\g2)? \s*
$/x
```
with `$1` being the line number for the next line, and `$3` being the optional filename (specified with or without quotes). Note that no whitespace may precede the `#`, unlike modern C preprocessors.
There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later.
Here are some examples that you should be able to type into your command shell:
```
% perl
# line 200 "bzzzt"
# the '#' on the previous line must be the first char on line
die 'foo';
__END__
foo at bzzzt line 201.
% perl
# line 200 "bzzzt"
eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
__END__
foo at - line 2001.
% perl
eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
__END__
foo at foo bar line 200.
% perl
# line 345 "goop"
eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
print $@;
__END__
foo at goop line 345.
```
###
Experimental Details on given and when
As previously mentioned, the "switch" feature is considered highly experimental; it is subject to change with little notice. In particular, `when` has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. Before Perl 5.18, `given` also had tricky behaviours that you should still beware of if your code must run on older versions of Perl.
Here is a longer example of `given`:
```
use feature ":5.10";
given ($foo) {
when (undef) {
say '$foo is undefined';
}
when ("foo") {
say '$foo is the string "foo"';
}
when ([1,3,5,7,9]) {
say '$foo is an odd digit';
continue; # Fall through
}
when ($_ < 100) {
say '$foo is numerically less than 100';
}
when (\&complicated_check) {
say 'a complicated check for $foo is true';
}
default {
die q(I don't know what to do with $foo);
}
}
```
Before Perl 5.18, `given(EXPR)` assigned the value of *EXPR* to merely a lexically scoped ***copy*** (!) of `$_`, not a dynamically scoped alias the way `foreach` does. That made it similar to
```
do { my $_ = EXPR; ... }
```
except that the block was automatically broken out of by a successful `when` or an explicit `break`. Because it was only a copy, and because it was only lexically scoped, not dynamically scoped, you could not do the things with it that you are used to in a `foreach` loop. In particular, it did not work for arbitrary function calls if those functions might try to access $\_. Best stick to `foreach` for that.
Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, `when(EXPR)` is treated as an implicit smartmatch of `$_`, that is, `$_ ~~ EXPR`. (See ["Smartmatch Operator" in perlop](perlop#Smartmatch-Operator) for more information on smartmatching.) But when *EXPR* is one of the 10 exceptional cases (or things like them) listed below, it is used directly as a boolean.
1. A user-defined subroutine call or a method invocation.
2. A regular expression match in the form of `/REGEX/`, `$foo =~ /REGEX/`, or `$foo =~ EXPR`. Also, a negated regular expression match in the form `!/REGEX/`, `$foo !~ /REGEX/`, or `$foo !~ EXPR`.
3. A smart match that uses an explicit `~~` operator, such as `EXPR ~~ EXPR`.
**NOTE:** You will often have to use `$c ~~ $_` because the default case uses `$_ ~~ $c` , which is frequently the opposite of what you want.
4. A boolean comparison operator such as `$_ < 10` or `$x eq "abc"`. The relational operators that this applies to are the six numeric comparisons (`<`, `>`, `<=`, `>=`, `==`, and `!=`), and the six string comparisons (`lt`, `gt`, `le`, `ge`, `eq`, and `ne`).
5. At least the three builtin functions `defined(...)`, `exists(...)`, and `eof(...)`. We might someday add more of these later if we think of them.
6. A negated expression, whether `!(EXPR)` or `not(EXPR)`, or a logical exclusive-or, `(EXPR1) xor (EXPR2)`. The bitwise versions (`~` and `^`) are not included.
7. A filetest operator, with exactly 4 exceptions: `-s`, `-M`, `-A`, and `-C`, as these return numerical values, not boolean ones. The `-z` filetest operator is not included in the exception list.
8. The `..` and `...` flip-flop operators. Note that the `...` flip-flop operator is completely different from the `...` elliptical statement just described.
In those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching is done. You may think of `when` as a smartsmartmatch.
Furthermore, Perl inspects the operands of logical operators to decide whether to use smartmatching for each one by applying the above test to the operands:
9. If EXPR is `EXPR1 && EXPR2` or `EXPR1 and EXPR2`, the test is applied *recursively* to both EXPR1 and EXPR2. Only if *both* operands also pass the test, *recursively*, will the expression be treated as boolean. Otherwise, smartmatching is used.
10. If EXPR is `EXPR1 || EXPR2`, `EXPR1 // EXPR2`, or `EXPR1 or EXPR2`, the test is applied *recursively* to EXPR1 only (which might itself be a higher-precedence AND operator, for example, and thus subject to the previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to use smartmatching, then the second argument will not be either. This is quite different from the `&&` case just described, so be careful.
These rules are complicated, but the goal is for them to do what you want (even if you don't quite understand why they are doing it). For example:
```
when (/^\d+$/ && $_ < 75) { ... }
```
will be treated as a boolean match because the rules say both a regex match and an explicit test on `$_` will be treated as boolean.
Also:
```
when ([qw(foo bar)] && /baz/) { ... }
```
will use smartmatching because only *one* of the operands is a boolean: the other uses smartmatching, and that wins.
Further:
```
when ([qw(foo bar)] || /^baz/) { ... }
```
will use smart matching (only the first operand is considered), whereas
```
when (/^baz/ || [qw(foo bar)]) { ... }
```
will test only the regex, which causes both operands to be treated as boolean. Watch out for this one, then, because an arrayref is always a true value, which makes it effectively redundant. Not a good idea.
Tautologous boolean operators are still going to be optimized away. Don't be tempted to write
```
when ("foo" or "bar") { ... }
```
This will optimize down to `"foo"`, so `"bar"` will never be considered (even though the rules say to use a smartmatch on `"foo"`). For an alternation like this, an array ref will work, because this will instigate smartmatching:
```
when ([qw(foo bar)] { ... }
```
This is somewhat equivalent to the C-style switch statement's fallthrough functionality (not to be confused with *Perl's* fallthrough functionality--see below), wherein the same block is used for several `case` statements.
Another useful shortcut is that, if you use a literal array or hash as the argument to `given`, it is turned into a reference. So `given(@foo)` is the same as `given(\@foo)`, for example.
`default` behaves exactly like `when(1 == 1)`, which is to say that it always matches.
####
Breaking out
You can use the `break` keyword to break out of the enclosing `given` block. Every `when` block is implicitly ended with a `break`.
####
Fall-through
You can use the `continue` keyword to fall through from one case to the next immediate `when` or `default`:
```
given($foo) {
when (/x/) { say '$foo contains an x'; continue }
when (/y/) { say '$foo contains a y' }
default { say '$foo does not contain a y' }
}
```
####
Return value
When a `given` statement is also a valid expression (for example, when it's the last statement of a block), it evaluates to:
* An empty list as soon as an explicit `break` is encountered.
* The value of the last evaluated expression of the successful `when`/`default` clause, if there happens to be one.
* The value of the last evaluated expression of the `given` block if no condition is true.
In both last cases, the last expression is evaluated in the context that was applied to the `given` block.
Note that, unlike `if` and `unless`, failed `when` statements always evaluate to an empty list.
```
my $price = do {
given ($item) {
when (["pear", "apple"]) { 1 }
break when "vote"; # My vote cannot be bought
1e10 when /Mona Lisa/;
"unknown";
}
};
```
Currently, `given` blocks can't always be used as proper expressions. This may be addressed in a future version of Perl.
####
Switching in a loop
Instead of using `given()`, you can use a `foreach()` loop. For example, here's one way to count how many times a particular string occurs in an array:
```
use v5.10.1;
my $count = 0;
for (@array) {
when ("foo") { ++$count }
}
print "\@array contains $count copies of 'foo'\n";
```
Or in a more recent version:
```
use v5.14;
my $count = 0;
for (@array) {
++$count when "foo";
}
print "\@array contains $count copies of 'foo'\n";
```
At the end of all `when` blocks, there is an implicit `next`. You can override that with an explicit `last` if you're interested in only the first match alone.
This doesn't work if you explicitly specify a loop variable, as in `for $item (@array)`. You have to use the default variable `$_`.
####
Differences from Raku
The Perl 5 smartmatch and `given`/`when` constructs are not compatible with their Raku analogues. The most visible difference and least important difference is that, in Perl 5, parentheses are required around the argument to `given()` and `when()` (except when this last one is used as a statement modifier). Parentheses in Raku are always optional in a control construct such as `if()`, `while()`, or `when()`; they can't be made optional in Perl 5 without a great deal of potential confusion, because Perl 5 would parse the expression
```
given $foo {
...
}
```
as though the argument to `given` were an element of the hash `%foo`, interpreting the braces as hash-element syntax.
However, their are many, many other differences. For example, this works in Perl 5:
```
use v5.12;
my @primary = ("red", "blue", "green");
if (@primary ~~ "red") {
say "primary smartmatches red";
}
if ("red" ~~ @primary) {
say "red smartmatches primary";
}
say "that's all, folks!";
```
But it doesn't work at all in Raku. Instead, you should use the (parallelizable) `any` operator:
```
if any(@primary) eq "red" {
say "primary smartmatches red";
}
if "red" eq any(@primary) {
say "red smartmatches primary";
}
```
The table of smartmatches in ["Smartmatch Operator" in perlop](perlop#Smartmatch-Operator) is not identical to that proposed by the Raku specification, mainly due to differences between Raku's and Perl 5's data models, but also because the Raku spec has changed since Perl 5 rushed into early adoption.
In Raku, `when()` will always do an implicit smartmatch with its argument, while in Perl 5 it is convenient (albeit potentially confusing) to suppress this implicit smartmatch in various rather loosely-defined situations, as roughly outlined above. (The difference is largely because Perl 5 does not have, even internally, a boolean type.)
| programming_docs |
perl TAP::Formatter::Base TAP::Formatter::Base
====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [prepare](#prepare)
- [open\_test](#open_test)
- [summary](#summary)
NAME
----
TAP::Formatter::Base - Base class for harness output delegates
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides console orientated output formatting for TAP::Harness.
SYNOPSIS
--------
```
use TAP::Formatter::Console;
my $harness = TAP::Formatter::Console->new( \%args );
```
METHODS
-------
###
Class Methods
#### `new`
```
my %args = (
verbose => 1,
)
my $harness = TAP::Formatter::Console->new( \%args );
```
The constructor returns a new `TAP::Formatter::Console` object. If a <TAP::Harness> is created with no `formatter` a `TAP::Formatter::Console` is automatically created. If any of the following options were given to TAP::Harness->new they well be passed to this constructor which accepts an optional hashref whose allowed keys are:
* `verbosity`
Set the verbosity level.
* `verbose`
Printing individual test results to STDOUT.
* `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).
* `quiet`
Suppressing some test output (mostly failures while tests are running).
* `really_quiet`
Suppressing everything but the tests summary.
* `silent`
Suppressing all output.
* `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`, `failures`, or `comments`.
* `stdout`
A filehandle for catching standard output.
* `color`
If defined specifies whether color output is desired. If `color` is not defined it will default to color output if color support is available on the current platform and output is not being redirected.
* `jobs`
The number of concurrent jobs this formatter will handle.
* `show_count`
Boolean value. If false, disables the `X/Y` test count which shows up while tests are running.
Any keys for which the value is `undef` will be ignored.
#### `prepare`
Called by Test::Harness before any test output is generated.
This is an advisory and may not be called in the case where tests are being supplied to Test::Harness by an iterator.
#### `open_test`
Called to create a new test session. A test session looks like this:
```
my $session = $formatter->open_test( $test, $parser );
while ( defined( my $result = $parser->next ) ) {
$session->result($result);
exit 1 if $result->is_bailout;
}
$session->close_test;
```
#### `summary`
```
$harness->summary( $aggregate );
```
`summary` prints the summary report after all tests are run. The first argument is an aggregate to summarise. An optional second argument may be set to a true value to indicate that the summary is being output as a result of an interrupted test run.
perl warnings::register warnings::register
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
warnings::register - warnings import function
SYNOPSIS
--------
```
use warnings::register;
```
DESCRIPTION
-----------
Creates a warnings category with the same name as the current package.
See <warnings> for more information on this module's usage.
perl Locale::Maketext::GutsLoader Locale::Maketext::GutsLoader
============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Locale::Maketext::GutsLoader - Deprecated module to load Locale::Maketext utf8 code
SYNOPSIS
--------
```
# Do this instead please
use Locale::Maketext
```
DESCRIPTION
-----------
Previously Locale::Maketext::Guts performed some magic to load Locale::Maketext when utf8 was unavailable. The subs this module provided were merged back into Locale::Maketext.
perl IO::Select IO::Select
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [METHODS](#METHODS)
* [EXAMPLE](#EXAMPLE)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Select - OO interface to the select system call
SYNOPSIS
--------
```
use IO::Select;
$s = IO::Select->new();
$s->add(\*STDIN);
$s->add($some_handle);
@ready = $s->can_read($timeout);
@ready = IO::Select->new(@handles)->can_read(0);
```
DESCRIPTION
-----------
The `IO::Select` package implements an object approach to the system `select` function call. It allows the user to see what IO handles, see <IO::Handle>, are ready for reading, writing or have an exception pending.
CONSTRUCTOR
-----------
new ( [ HANDLES ] ) The constructor creates a new object and optionally initialises it with a set of handles.
METHODS
-------
add ( HANDLES ) Add the list of handles to the `IO::Select` object. It is these values that will be returned when an event occurs. `IO::Select` keeps these values in a cache which is indexed by the `fileno` of the handle, so if more than one handle with the same `fileno` is specified then only the last one is cached.
Each handle can be an `IO::Handle` object, an integer or an array reference where the first element is an `IO::Handle` or an integer.
remove ( HANDLES ) Remove all the given handles from the object. This method also works by the `fileno` of the handles. So the exact handles that were added need not be passed, just handles that have an equivalent `fileno`
exists ( HANDLE ) Returns a true value (actually the handle itself) if it is present. Returns undef otherwise.
handles Return an array of all registered handles.
can\_read ( [ TIMEOUT ] ) Return an array of handles that are ready for reading. `TIMEOUT` is the maximum amount of time to wait before returning an empty list (with `$!` unchanged), in seconds, possibly fractional. If `TIMEOUT` is not given and any handles are registered then the call will block indefinitely. Upon error, an empty list is returned, with `$!` set to indicate the error. To distinguish between timeout and error, set `$!` to zero before calling this method, and check it after an empty list is returned.
can\_write ( [ TIMEOUT ] ) Same as `can_read` except check for handles that can be written to.
has\_exception ( [ TIMEOUT ] ) Same as `can_read` except check for handles that have an exception condition, for example pending out-of-band data.
count () Returns the number of handles that the object will check for when one of the `can_` methods is called or the object is passed to the `select` static method.
bits() Return the bit string suitable as argument to the core select() call.
select ( READ, WRITE, EXCEPTION [, TIMEOUT ] ) `select` is a static method, that is you call it with the package name like `new`. `READ`, `WRITE` and `EXCEPTION` are either `undef` or `IO::Select` objects. `TIMEOUT` is optional and has the same effect as for the core select call.
If at least one handle is ready for the specified kind of operation, the result will be an array of 3 elements, each a reference to an array which will hold the handles that are ready for reading, writing and have exceptions respectively. Upon timeout, an empty list is returned, with `$!` unchanged. Upon error, an empty list is returned, with `$!` set to indicate the error. To distinguish between timeout and error, set `$!` to zero before calling this method, and check it after an empty list is returned.
EXAMPLE
-------
Here is a short example which shows how `IO::Select` could be used to write a server which communicates with several sockets while also listening for more connections on a listen socket
```
use IO::Select;
use IO::Socket;
$lsn = IO::Socket::INET->new(Listen => 1, LocalPort => 8080);
$sel = IO::Select->new( $lsn );
while(@ready = $sel->can_read) {
foreach $fh (@ready) {
if($fh == $lsn) {
# Create a new socket
$new = $lsn->accept;
$sel->add($new);
}
else {
# Process socket
# Maybe we have finished with the socket
$sel->remove($fh);
$fh->close;
}
}
}
```
AUTHOR
------
Graham Barr. Currently maintained by the Perl 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.
perl IO::Zlib IO::Zlib
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [OBJECT METHODS](#OBJECT-METHODS)
* [USING THE EXTERNAL GZIP](#USING-THE-EXTERNAL-GZIP)
* [CLASS METHODS](#CLASS-METHODS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Zlib - IO:: style interface to <Compress::Zlib>
SYNOPSIS
--------
With any version of Perl 5 you can use the basic OO interface:
```
use IO::Zlib;
$fh = new IO::Zlib;
if ($fh->open("file.gz", "rb")) {
print <$fh>;
$fh->close;
}
$fh = IO::Zlib->new("file.gz", "wb9");
if (defined $fh) {
print $fh "bar\n";
$fh->close;
}
$fh = IO::Zlib->new("file.gz", "rb");
if (defined $fh) {
print <$fh>;
undef $fh; # automatically closes the file
}
```
With Perl 5.004 you can also use the TIEHANDLE interface to access compressed files just like ordinary files:
```
use IO::Zlib;
tie *FILE, 'IO::Zlib', "file.gz", "wb";
print FILE "line 1\nline2\n";
tie *FILE, 'IO::Zlib', "file.gz", "rb";
while (<FILE>) { print "LINE: ", $_ };
```
DESCRIPTION
-----------
`IO::Zlib` provides an IO:: style interface to <Compress::Zlib> and hence to gzip/zlib compressed files. It provides many of the same methods as the <IO::Handle> interface.
Starting from IO::Zlib version 1.02, IO::Zlib can also use an external *gzip* command. The default behaviour is to try to use an external *gzip* if no `Compress::Zlib` can be loaded, unless explicitly disabled by
```
use IO::Zlib qw(:gzip_external 0);
```
If explicitly enabled by
```
use IO::Zlib qw(:gzip_external 1);
```
then the external *gzip* is used **instead** of `Compress::Zlib`.
CONSTRUCTOR
-----------
new ( [ARGS] ) Creates an `IO::Zlib` object. If it receives any parameters, they are passed to the method `open`; if the open fails, the object is destroyed. Otherwise, it is returned to the caller.
OBJECT METHODS
---------------
open ( FILENAME, MODE ) `open` takes two arguments. The first is the name of the file to open and the second is the open mode. The mode can be anything acceptable to <Compress::Zlib> and by extension anything acceptable to *zlib* (that basically means POSIX fopen() style mode strings plus an optional number to indicate the compression level).
opened Returns true if the object currently refers to a opened file.
close Close the file associated with the object and disassociate the file from the handle. Done automatically on destroy.
getc Return the next character from the file, or undef if none remain.
getline Return the next line from the file, or undef on end of string. Can safely be called in an array context. Currently ignores $/ ($INPUT\_RECORD\_SEPARATOR or $RS when [English](english) is in use) and treats lines as delimited by "\n".
getlines Get all remaining lines from the file. It will croak() if accidentally called in a scalar context.
print ( ARGS... ) Print ARGS to the file.
read ( BUF, NBYTES, [OFFSET] ) Read some bytes from the file. Returns the number of bytes actually read, 0 on end-of-file, undef on error.
eof Returns true if the handle is currently positioned at end of file?
seek ( OFFSET, WHENCE ) Seek to a given position in the stream. Not yet supported.
tell Return the current position in the stream, as a numeric offset. Not yet supported.
setpos ( POS ) Set the current position, using the opaque value returned by `getpos()`. Not yet supported.
getpos ( POS ) Return the current position in the string, as an opaque object. Not yet supported.
USING THE EXTERNAL GZIP
------------------------
If the external *gzip* is used, the following `open`s are used:
```
open(FH, "gzip -dc $filename |") # for read opens
open(FH, " | gzip > $filename") # for write opens
```
You can modify the 'commands' for example to hardwire an absolute path by e.g.
```
use IO::Zlib ':gzip_read_open' => '/some/where/gunzip -c %s |';
use IO::Zlib ':gzip_write_open' => '| /some/where/gzip.exe > %s';
```
The `%s` is expanded to be the filename (`sprintf` is used, so be careful to escape any other `%` signs). The 'commands' are checked for sanity - they must contain the `%s`, and the read open must end with the pipe sign, and the write open must begin with the pipe sign.
CLASS METHODS
--------------
has\_Compress\_Zlib Returns true if `Compress::Zlib` is available. Note that this does not mean that `Compress::Zlib` is being used: see ["gzip\_external"](#gzip_external) and <gzip_used>.
gzip\_external Undef if an external *gzip* **can** be used if `Compress::Zlib` is not available (see ["has\_Compress\_Zlib"](#has_Compress_Zlib)), true if an external *gzip* is explicitly used, false if an external *gzip* must not be used. See ["gzip\_used"](#gzip_used).
gzip\_used True if an external *gzip* is being used, false if not.
gzip\_read\_open Return the 'command' being used for opening a file for reading using an external *gzip*.
gzip\_write\_open Return the 'command' being used for opening a file for writing using an external *gzip*.
DIAGNOSTICS
-----------
IO::Zlib::getlines: must be called in list context If you want read lines, you must read in list context.
IO::Zlib::gzopen\_external: mode '...' is illegal Use only modes 'rb' or 'wb' or /wb[1-9]/.
IO::Zlib::import: '...' is illegal The known import symbols are the `:gzip_external`, `:gzip_read_open`, and `:gzip_write_open`. Anything else is not recognized.
IO::Zlib::import: ':gzip\_external' requires an argument The `:gzip_external` requires one boolean argument.
IO::Zlib::import: 'gzip\_read\_open' requires an argument The `:gzip_external` requires one string argument.
IO::Zlib::import: 'gzip\_read' '...' is illegal The `:gzip_read_open` argument must end with the pipe sign (|) and have the `%s` for the filename. See ["USING THE EXTERNAL GZIP"](#USING-THE-EXTERNAL-GZIP).
IO::Zlib::import: 'gzip\_write\_open' requires an argument The `:gzip_external` requires one string argument.
IO::Zlib::import: 'gzip\_write\_open' '...' is illegal The `:gzip_write_open` argument must begin with the pipe sign (|) and have the `%s` for the filename. An output redirect (>) is also often a good idea, depending on your operating system shell syntax. See ["USING THE EXTERNAL GZIP"](#USING-THE-EXTERNAL-GZIP).
IO::Zlib::import: no Compress::Zlib and no external gzip Given that we failed to load `Compress::Zlib` and that the use of an external *gzip* was disabled, IO::Zlib has not much chance of working.
IO::Zlib::open: needs a filename No filename, no open.
IO::Zlib::READ: NBYTES must be specified We must know how much to read.
IO::Zlib::WRITE: too long LENGTH The LENGTH must be less than or equal to the buffer size.
SEE ALSO
---------
<perlfunc>, ["I/O Operators" in perlop](perlop#I%2FO-Operators), <IO::Handle>, <Compress::Zlib>
HISTORY
-------
Created by Tom Hughes <*[email protected]*>.
Support for external gzip added by Jarkko Hietaniemi <*[email protected]*>.
COPYRIGHT
---------
Copyright (c) 1998-2004 Tom Hughes <*[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 I18N::LangTags::Detect I18N::LangTags::Detect
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
* [ENVIRONMENT](#ENVIRONMENT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
* [AUTHOR](#AUTHOR)
NAME
----
I18N::LangTags::Detect - detect the user's language preferences
SYNOPSIS
--------
```
use I18N::LangTags::Detect;
my @user_wants = I18N::LangTags::Detect::detect();
```
DESCRIPTION
-----------
It is a common problem to want to detect what language(s) the user would prefer output in.
FUNCTIONS
---------
This module defines one public function, `I18N::LangTags::Detect::detect()`. This function is not exported (nor is even exportable), and it takes no parameters.
In scalar context, the function returns the most preferred language tag (or undef if no preference was seen).
In list context (which is usually what you want), the function returns a (possibly empty) list of language tags representing (best first) what languages the user apparently would accept output in. You will probably want to pass the output of this through `I18N::LangTags::implicate_supers_tightly(...)` or `I18N::LangTags::implicate_supers(...)`, like so:
```
my @languages =
I18N::LangTags::implicate_supers_tightly(
I18N::LangTags::Detect::detect()
);
```
ENVIRONMENT
-----------
This module looks at several environment variables: REQUEST\_METHOD, HTTP\_ACCEPT\_LANGUAGE, LANGUAGE, LC\_ALL, LC\_MESSAGES, and LANG.
It will also use the <Win32::Locale> module, if it's installed and IGNORE\_WIN32\_LOCALE is not set to a true value in the environment.
SEE ALSO
---------
<I18N::LangTags>, <Win32::Locale>, <Locale::Maketext>.
(This module's core code started out as a routine in Locale::Maketext; but I moved it here once I realized it was more generally useful.)
COPYRIGHT
---------
Copyright (c) 1998-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.
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 Pod::Perldoc::ToANSI Pod::Perldoc::ToANSI
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToANSI - render Pod with ANSI color escapes
SYNOPSIS
--------
```
perldoc -o ansi 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 term -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::Text::Color>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2011 Mark Allen. 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]>`
| programming_docs |
perl threads::shared threads::shared
===============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORT](#EXPORT)
* [FUNCTIONS](#FUNCTIONS)
* [OBJECTS](#OBJECTS)
* [NOTES](#NOTES)
* [WARNINGS](#WARNINGS)
* [BUGS AND LIMITATIONS](#BUGS-AND-LIMITATIONS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
threads::shared - Perl extension for sharing data structures between threads
VERSION
-------
This document describes threads::shared version 1.64
SYNOPSIS
--------
```
use threads;
use threads::shared;
my $var :shared;
my %hsh :shared;
my @ary :shared;
my ($scalar, @array, %hash);
share($scalar);
share(@array);
share(%hash);
$var = $scalar_value;
$var = $shared_ref_value;
$var = shared_clone($non_shared_ref_value);
$var = shared_clone({'foo' => [qw/foo bar baz/]});
$hsh{'foo'} = $scalar_value;
$hsh{'bar'} = $shared_ref_value;
$hsh{'baz'} = shared_clone($non_shared_ref_value);
$hsh{'quz'} = shared_clone([1..3]);
$ary[0] = $scalar_value;
$ary[1] = $shared_ref_value;
$ary[2] = shared_clone($non_shared_ref_value);
$ary[3] = shared_clone([ {}, [] ]);
{ lock(%hash); ... }
cond_wait($scalar);
cond_timedwait($scalar, time() + 30);
cond_broadcast(@array);
cond_signal(%hash);
my $lockvar :shared;
# condition var != lock var
cond_wait($var, $lockvar);
cond_timedwait($var, time()+30, $lockvar);
```
DESCRIPTION
-----------
By default, variables are private to each thread, and each newly created thread gets a private copy of each existing variable. This module allows you to share variables across different threads (and pseudo-forks on Win32). It is used together with the <threads> module.
This module supports the sharing of the following data types only: scalars and scalar refs, arrays and array refs, and hashes and hash refs.
EXPORT
------
The following functions are exported by this module: `share`, `shared_clone`, `is_shared`, `cond_wait`, `cond_timedwait`, `cond_signal` and `cond_broadcast`
Note that if this module is imported when <threads> has not yet been loaded, then these functions all become no-ops. This makes it possible to write modules that will work in both threaded and non-threaded environments.
FUNCTIONS
---------
share VARIABLE `share` takes a variable and marks it as shared:
```
my ($scalar, @array, %hash);
share($scalar);
share(@array);
share(%hash);
```
`share` will return the shared rvalue, but always as a reference.
Variables can also be marked as shared at compile time by using the `:shared` attribute:
```
my ($var, %hash, @array) :shared;
```
Shared variables can only store scalars, refs of shared variables, or refs of shared data (discussed in next section):
```
my ($var, %hash, @array) :shared;
my $bork;
# Storing scalars
$var = 1;
$hash{'foo'} = 'bar';
$array[0] = 1.5;
# Storing shared refs
$var = \%hash;
$hash{'ary'} = \@array;
$array[1] = \$var;
# The following are errors:
# $var = \$bork; # ref of non-shared variable
# $hash{'bork'} = []; # non-shared array ref
# push(@array, { 'x' => 1 }); # non-shared hash ref
```
shared\_clone REF `shared_clone` takes a reference, and returns a shared version of its argument, performing a deep copy on any non-shared elements. Any shared elements in the argument are used as is (i.e., they are not cloned).
```
my $cpy = shared_clone({'foo' => [qw/foo bar baz/]});
```
Object status (i.e., the class an object is blessed into) is also cloned.
```
my $obj = {'foo' => [qw/foo bar baz/]};
bless($obj, 'Foo');
my $cpy = shared_clone($obj);
print(ref($cpy), "\n"); # Outputs 'Foo'
```
For cloning empty array or hash refs, the following may also be used:
```
$var = &share([]); # Same as $var = shared_clone([]);
$var = &share({}); # Same as $var = shared_clone({});
```
Not all Perl data types can be cloned (e.g., globs, code refs). By default, `shared_clone` will [croak](carp) if it encounters such items. To change this behaviour to a warning, then set the following:
```
$threads::shared::clone_warn = 1;
```
In this case, `undef` will be substituted for the item to be cloned. If set to zero:
```
$threads::shared::clone_warn = 0;
```
then the `undef` substitution will be performed silently.
is\_shared VARIABLE `is_shared` checks if the specified variable is shared or not. If shared, returns the variable's internal ID (similar to `refaddr()` (see <Scalar::Util>). Otherwise, returns `undef`.
```
if (is_shared($var)) {
print("\$var is shared\n");
} else {
print("\$var is not shared\n");
}
```
When used on an element of an array or hash, `is_shared` checks if the specified element belongs to a shared array or hash. (It does not check the contents of that element.)
```
my %hash :shared;
if (is_shared(%hash)) {
print("\%hash is shared\n");
}
$hash{'elem'} = 1;
if (is_shared($hash{'elem'})) {
print("\$hash{'elem'} is in a shared hash\n");
}
```
lock VARIABLE `lock` places a **advisory** lock on a variable until the lock goes out of scope. If the variable is locked by another thread, the `lock` call will block until it's available. Multiple calls to `lock` by the same thread from within dynamically nested scopes are safe -- the variable will remain locked until the outermost lock on the variable goes out of scope.
`lock` follows references exactly *one* level:
```
my %hash :shared;
my $ref = \%hash;
lock($ref); # This is equivalent to lock(%hash)
```
Note that you cannot explicitly unlock a variable; you can only wait for the lock to go out of scope. This is most easily accomplished by locking the variable inside a block.
```
my $var :shared;
{
lock($var);
# $var is locked from here to the end of the block
...
}
# $var is now unlocked
```
As locks are advisory, they do not prevent data access or modification by another thread that does not itself attempt to obtain a lock on the variable.
You cannot lock the individual elements of a container variable:
```
my %hash :shared;
$hash{'foo'} = 'bar';
#lock($hash{'foo'}); # Error
lock(%hash); # Works
```
If you need more fine-grained control over shared variable access, see <Thread::Semaphore>.
cond\_wait VARIABLE
cond\_wait CONDVAR, LOCKVAR The `cond_wait` function takes a **locked** variable as a parameter, unlocks the variable, and blocks until another thread does a `cond_signal` or `cond_broadcast` for that same locked variable. The variable that `cond_wait` blocked on is re-locked after the `cond_wait` is satisfied. If there are multiple threads `cond_wait`ing on the same variable, all but one will re-block waiting to reacquire the lock on the variable. (So if you're only using `cond_wait` for synchronization, give up the lock as soon as possible). The two actions of unlocking the variable and entering the blocked wait state are atomic, the two actions of exiting from the blocked wait state and re-locking the variable are not.
In its second form, `cond_wait` takes a shared, **unlocked** variable followed by a shared, **locked** variable. The second variable is unlocked and thread execution suspended until another thread signals the first variable.
It is important to note that the variable can be notified even if no thread `cond_signal` or `cond_broadcast` on the variable. It is therefore important to check the value of the variable and go back to waiting if the requirement is not fulfilled. For example, to pause until a shared counter drops to zero:
```
{ lock($counter); cond_wait($counter) until $counter == 0; }
```
cond\_timedwait VARIABLE, ABS\_TIMEOUT
cond\_timedwait CONDVAR, ABS\_TIMEOUT, LOCKVAR In its two-argument form, `cond_timedwait` takes a **locked** variable and an absolute timeout in *epoch* seconds (see [time() in perlfunc](perlfunc#time) for more) as parameters, unlocks the variable, and blocks until the timeout is reached or another thread signals the variable. A false value is returned if the timeout is reached, and a true value otherwise. In either case, the variable is re-locked upon return.
Like `cond_wait`, this function may take a shared, **locked** variable as an additional parameter; in this case the first parameter is an **unlocked** condition variable protected by a distinct lock variable.
Again like `cond_wait`, waking up and reacquiring the lock are not atomic, and you should always check your desired condition after this function returns. Since the timeout is an absolute value, however, it does not have to be recalculated with each pass:
```
lock($var);
my $abs = time() + 15;
until ($ok = desired_condition($var)) {
last if !cond_timedwait($var, $abs);
}
# we got it if $ok, otherwise we timed out!
```
cond\_signal VARIABLE The `cond_signal` function takes a **locked** variable as a parameter and unblocks one thread that's `cond_wait`ing on that variable. If more than one thread is blocked in a `cond_wait` on that variable, only one (and which one is indeterminate) will be unblocked.
If there are no threads blocked in a `cond_wait` on the variable, the signal is discarded. By always locking before signaling, you can (with care), avoid signaling before another thread has entered cond\_wait().
`cond_signal` will normally generate a warning if you attempt to use it on an unlocked variable. On the rare occasions where doing this may be sensible, you can suppress the warning with:
```
{ no warnings 'threads'; cond_signal($foo); }
```
cond\_broadcast VARIABLE The `cond_broadcast` function works similarly to `cond_signal`. `cond_broadcast`, though, will unblock **all** the threads that are blocked in a `cond_wait` on the locked variable, rather than only one.
OBJECTS
-------
<threads::shared> exports a version of [bless()](perlfunc#bless-REF) that works on shared objects such that *blessings* propagate across threads.
```
# Create a shared 'Foo' object
my $foo :shared = shared_clone({});
bless($foo, 'Foo');
# Create a shared 'Bar' object
my $bar :shared = shared_clone({});
bless($bar, 'Bar');
# Put 'bar' inside 'foo'
$foo->{'bar'} = $bar;
# Rebless the objects via a thread
threads->create(sub {
# Rebless the outer object
bless($foo, 'Yin');
# Cannot directly rebless the inner object
#bless($foo->{'bar'}, 'Yang');
# Retrieve and rebless the inner object
my $obj = $foo->{'bar'};
bless($obj, 'Yang');
$foo->{'bar'} = $obj;
})->join();
print(ref($foo), "\n"); # Prints 'Yin'
print(ref($foo->{'bar'}), "\n"); # Prints 'Yang'
print(ref($bar), "\n"); # Also prints 'Yang'
```
NOTES
-----
<threads::shared> is designed to disable itself silently if threads are not available. This allows you to write modules and packages that can be used in both threaded and non-threaded applications.
If you want access to threads, you must `use threads` before you `use threads::shared`. <threads> will emit a warning if you use it after <threads::shared>.
WARNINGS
--------
cond\_broadcast() called on unlocked variable
cond\_signal() called on unlocked variable See ["cond\_signal VARIABLE"](#cond_signal-VARIABLE), above.
BUGS AND LIMITATIONS
---------------------
When `share` is used on arrays, hashes, array refs or hash refs, any data they contain will be lost.
```
my @arr = qw(foo bar baz);
share(@arr);
# @arr is now empty (i.e., == ());
# Create a 'foo' object
my $foo = { 'data' => 99 };
bless($foo, 'foo');
# Share the object
share($foo); # Contents are now wiped out
print("ERROR: \$foo is empty\n")
if (! exists($foo->{'data'}));
```
Therefore, populate such variables **after** declaring them as shared. (Scalar and scalar refs are not affected by this problem.)
Blessing a shared item after it has been nested in another shared item does not propagate the blessing to the shared reference:
```
my $foo = &share({});
my $bar = &share({});
$bar->{foo} = $foo;
bless($foo, 'baz'); # $foo is now of class 'baz',
# but $bar->{foo} is unblessed.
```
Therefore, you should bless objects before sharing them.
It is often not wise to share an object unless the class itself has been written to support sharing. For example, a shared object's destructor may get called multiple times, once for each thread's scope exit, or may not get called at all if it is embedded inside another shared object. Another issue is that the contents of hash-based objects will be lost due to the above mentioned limitation. See *examples/class.pl* (in the CPAN distribution of this module) for how to create a class that supports object sharing.
Destructors may not be called on objects if those objects still exist at global destruction time. If the destructors must be called, make sure there are no circular references and that nothing is referencing the objects before the program ends.
Does not support `splice` on arrays. Does not support explicitly changing array lengths via $#array -- use `push` and `pop` instead.
Taking references to the elements of shared arrays and hashes does not autovivify the elements, and neither does slicing a shared array/hash over non-existent indices/keys autovivify the elements.
`share()` allows you to `share($hashref->{key})` and `share($arrayref->[idx])` without giving any error message. But the `$hashref->{key}` or `$arrayref->[idx]` is **not** shared, causing the error "lock can only be used on shared values" to occur when you attempt to `lock($hashref->{key})` or `lock($arrayref->[idx])` in another thread.
Using `refaddr()` is unreliable for testing whether or not two shared references are equivalent (e.g., when testing for circular references). Use [is\_shared()](#is_shared-VARIABLE), instead:
```
use threads;
use threads::shared;
use Scalar::Util qw(refaddr);
# If ref is shared, use threads::shared's internal ID.
# Otherwise, use refaddr().
my $addr1 = is_shared($ref1) || refaddr($ref1);
my $addr2 = is_shared($ref2) || refaddr($ref2);
if ($addr1 == $addr2) {
# The refs are equivalent
}
```
[each()](perlfunc#each-HASH) does not work properly on shared references embedded in shared structures. For example:
```
my %foo :shared;
$foo{'bar'} = shared_clone({'a'=>'x', 'b'=>'y', 'c'=>'z'});
while (my ($key, $val) = each(%{$foo{'bar'}})) {
...
}
```
Either of the following will work instead:
```
my $ref = $foo{'bar'};
while (my ($key, $val) = each(%{$ref})) {
...
}
foreach my $key (keys(%{$foo{'bar'}})) {
my $val = $foo{'bar'}{$key};
...
}
```
This module supports dual-valued variables created using `dualvar()` from <Scalar::Util>. However, while `$!` acts like a dualvar, it is implemented as a tied SV. To propagate its value, use the follow construct, if needed:
```
my $errno :shared = dualvar($!,$!);
```
View existing bug reports at, and submit any new bugs, problems, patches, etc. to: <http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
SEE ALSO
---------
threads::shared on MetaCPAN: <https://metacpan.org/release/threads-shared>
Code repository for CPAN distribution: <https://github.com/Dual-Life/threads-shared>
<threads>, <perlthrtut>
<http://www.perl.com/pub/a/2002/06/11/threads.html> and <http://www.perl.com/pub/a/2002/09/04/threads.html>
Perl threads mailing list: <http://lists.perl.org/list/ithreads.html>
Sample code in the *examples* directory of this distribution on CPAN.
AUTHOR
------
Artur Bergman <sky AT crucially DOT net>
Documentation borrowed from the old Thread.pm.
CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>.
LICENSE
-------
threads::shared is released under the same license as Perl.
perl ExtUtils::Embed ExtUtils::Embed
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [@EXPORT](#@EXPORT)
* [FUNCTIONS](#FUNCTIONS)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Embed - Utilities for embedding Perl in C/C++ applications
SYNOPSIS
--------
```
perl -MExtUtils::Embed -e xsinit
perl -MExtUtils::Embed -e ccopts
perl -MExtUtils::Embed -e ldopts
```
DESCRIPTION
-----------
`ExtUtils::Embed` provides utility functions for embedding a Perl interpreter and extensions in your C/C++ applications. Typically, an application *Makefile* will invoke `ExtUtils::Embed` functions while building your application.
@EXPORT
--------
`ExtUtils::Embed` exports the following functions:
xsinit(), ldopts(), ccopts(), perl\_inc(), ccflags(), ccdlflags(), xsi\_header(), xsi\_protos(), xsi\_body()
FUNCTIONS
---------
xsinit() Generate C/C++ code for the XS initializer function.
When invoked as ``perl -MExtUtils::Embed -e xsinit --`` the following options are recognized:
**-o** <output filename> (Defaults to **perlxsi.c**)
**-o STDOUT** will print to STDOUT.
**-std** (Write code for extensions that are linked with the current Perl.)
Any additional arguments are expected to be names of modules to generate code for.
When invoked with parameters the following are accepted and optional:
`xsinit($filename,$std,[@modules])`
Where,
**$filename** is equivalent to the **-o** option.
**$std** is boolean, equivalent to the **-std** option.
**[@modules]** is an array ref, same as additional arguments mentioned above.
Examples
```
perl -MExtUtils::Embed -e xsinit -- -o xsinit.c Socket
```
This will generate code with an `xs_init` function that glues the perl `Socket::bootstrap` function to the C `boot_Socket` function and writes it to a file named *xsinit.c*.
Note that [DynaLoader](dynaloader) is a special case where it must call `boot_DynaLoader` directly.
```
perl -MExtUtils::Embed -e xsinit
```
This will generate code for linking with `DynaLoader` and each static extension found in `$Config{static_ext}`. The code is written to the default file name *perlxsi.c*.
```
perl -MExtUtils::Embed -e xsinit -- -o xsinit.c \
-std DBI DBD::Oracle
```
Here, code is written for all the currently linked extensions along with code for `DBI` and `DBD::Oracle`.
If you have a working `DynaLoader` then there is rarely any need to statically link in any other extensions.
ldopts() Output arguments for linking the Perl library and extensions to your application.
When invoked as ``perl -MExtUtils::Embed -e ldopts --`` the following options are recognized:
**-std**
Output arguments for linking the Perl library and any extensions linked with the current Perl.
**-I** <path1:path2>
Search path for ModuleName.a archives. Default path is `@INC`. Library archives are expected to be found as */some/path/auto/ModuleName/ModuleName.a* For example, when looking for *Socket.a* relative to a search path, we should find *auto/Socket/Socket.a*
When looking for `DBD::Oracle` relative to a search path, we should find *auto/DBD/Oracle/Oracle.a*
Keep in mind that you can always supply */my/own/path/ModuleName.a* as an additional linker argument.
**--** <list of linker args>
Additional linker arguments to be considered.
Any additional arguments found before the **--** token are expected to be names of modules to generate code for.
When invoked with parameters the following are accepted and optional:
`ldopts($std,[@modules],[@link_args],$path)`
Where:
**$std** is boolean, equivalent to the **-std** option.
**[@modules]** is equivalent to additional arguments found before the **--** token.
**[@link\_args]** is equivalent to arguments found after the **--** token.
**$path** is equivalent to the **-I** option.
In addition, when ldopts is called with parameters, it will return the argument string rather than print it to STDOUT.
Examples
```
perl -MExtUtils::Embed -e ldopts
```
This will print arguments for linking with `libperl` and extensions found in `$Config{static_ext}`. This includes libraries found in `$Config{libs}` and the first ModuleName.a library for each extension that is found by searching `@INC` or the path specified by the **-I** option. In addition, when ModuleName.a is found, additional linker arguments are picked up from the *extralibs.ld* file in the same directory.
```
perl -MExtUtils::Embed -e ldopts -- -std Socket
```
This will do the same as the above example, along with printing additional arguments for linking with the `Socket` extension.
```
perl -MExtUtils::Embed -e ldopts -- -std Msql -- \
-L/usr/msql/lib -lmsql
```
Any arguments after the second '--' token are additional linker arguments that will be examined for potential conflict. If there is no conflict, the additional arguments will be part of the output.
perl\_inc() For including perl header files this function simply prints:
```
-I$Config{archlibexp}/CORE
```
So, rather than having to say:
```
perl -MConfig -e 'print "-I$Config{archlibexp}/CORE"'
```
Just say:
```
perl -MExtUtils::Embed -e perl_inc
```
ccflags(), ccdlflags() These functions simply print $Config{ccflags} and $Config{ccdlflags}
ccopts() This function combines `perl_inc()`, `ccflags()` and `ccdlflags()` into one.
xsi\_header() This function simply returns a string defining the same `EXTERN_C` macro as *perlmain.c* along with #including *perl.h* and *EXTERN.h*.
xsi\_protos(@modules) This function returns a string of `boot_$ModuleName` prototypes for each @modules.
xsi\_body(@modules) This function returns a string of calls to `newXS()` that glue the module *bootstrap* function to *boot\_ModuleName* for each @modules.
`xsinit()` uses the xsi\_\* functions to generate most of its code.
EXAMPLES
--------
For examples on how to use `ExtUtils::Embed` for building C/C++ applications with embedded perl, see <perlembed>.
SEE ALSO
---------
<perlembed>
AUTHOR
------
Doug MacEachern <`[email protected]`>
Based on ideas from Tim Bunce <`[email protected]`> and *minimod.pl* by Andreas Koenig <`[email protected]`> and Tim Bunce.
| programming_docs |
perl File::Compare File::Compare
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [RETURN](#RETURN)
* [AUTHOR](#AUTHOR)
NAME
----
File::Compare - Compare files or filehandles
SYNOPSIS
--------
```
use File::Compare;
if (compare("file1","file2") == 0) {
print "They're equal\n";
}
```
DESCRIPTION
-----------
The File::Compare::compare function compares the contents of two sources, each of which can be a file or a file handle. It is exported from File::Compare by default.
File::Compare::cmp is a synonym for File::Compare::compare. It is exported from File::Compare only by request.
File::Compare::compare\_text does a line by line comparison of the two files. It stops as soon as a difference is detected. compare\_text() accepts an optional third argument: This must be a CODE reference to a line comparison function, which returns 0 when both lines are considered equal. For example:
```
compare_text($file1, $file2)
```
is basically equivalent to
```
compare_text($file1, $file2, sub {$_[0] ne $_[1]} )
```
RETURN
------
File::Compare::compare and its sibling functions return 0 if the files are equal, 1 if the files are unequal, or -1 if an error was encountered.
AUTHOR
------
File::Compare was written by Nick Ing-Simmons. Its original documentation was written by Chip Salzenberg.
perl Sys::Syslog Sys::Syslog
===========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTS](#EXPORTS)
* [FUNCTIONS](#FUNCTIONS)
* [THE RULES OF SYS::SYSLOG](#THE-RULES-OF-SYS::SYSLOG)
* [EXAMPLES](#EXAMPLES)
* [CONSTANTS](#CONSTANTS)
+ [Facilities](#Facilities)
+ [Levels](#Levels)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
+ [Other modules](#Other-modules)
+ [Manual Pages](#Manual-Pages)
+ [RFCs](#RFCs)
+ [Articles](#Articles)
+ [Event Log](#Event-Log)
* [AUTHORS & ACKNOWLEDGEMENTS](#AUTHORS-&-ACKNOWLEDGEMENTS)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT](#COPYRIGHT)
* [LICENSE](#LICENSE)
NAME
----
Sys::Syslog - Perl interface to the UNIX syslog(3) calls
VERSION
-------
This is the documentation of version 0.36
SYNOPSIS
--------
```
use Sys::Syslog; # all except setlogsock()
use Sys::Syslog qw(:standard :macros); # standard functions & macros
openlog($ident, $logopt, $facility); # don't forget this
syslog($priority, $format, @args);
$oldmask = setlogmask($mask_priority);
closelog();
```
DESCRIPTION
-----------
`Sys::Syslog` is an interface to the UNIX `syslog(3)` program. Call `syslog()` with a string priority and a list of `printf()` args just like `syslog(3)`.
EXPORTS
-------
`Sys::Syslog` exports the following `Exporter` tags:
* `:standard` exports the standard `syslog(3)` functions:
```
openlog closelog setlogmask syslog
```
* `:extended` exports the Perl specific functions for `syslog(3)`:
```
setlogsock
```
* `:macros` exports the symbols corresponding to most of your `syslog(3)` macros and the `LOG_UPTO()` and `LOG_MASK()` functions. See ["CONSTANTS"](#CONSTANTS) for the supported constants and their meaning.
By default, `Sys::Syslog` exports the symbols from the `:standard` tag.
FUNCTIONS
---------
**openlog($ident, $logopt, $facility)**
Opens the syslog. `$ident` is prepended to every message. `$logopt` contains zero or more of the options detailed below. `$facility` specifies the part of the system to report about, for example `LOG_USER` or `LOG_LOCAL0`: see ["Facilities"](#Facilities) for a list of well-known facilities, and your `syslog(3)` documentation for the facilities available in your system. Check ["SEE ALSO"](#SEE-ALSO) for useful links. Facility can be given as a string or a numeric macro.
This function will croak if it can't connect to the syslog daemon.
Note that `openlog()` now takes three arguments, just like `openlog(3)`.
**You should use `openlog()` before calling `syslog()`.**
**Options**
* `cons` - This option is ignored, since the failover mechanism will drop down to the console automatically if all other media fail.
* `ndelay` - Open the connection immediately (normally, the connection is opened when the first message is logged).
* `noeol` - When set to true, no end of line character (`\n`) will be appended to the message. This can be useful for some syslog daemons. Added in `Sys::Syslog` 0.29.
* `nofatal` - When set to true, `openlog()` and `syslog()` will only emit warnings instead of dying if the connection to the syslog can't be established. Added in `Sys::Syslog` 0.15.
* `nonul` - When set to true, no `NUL` character (`\0`) will be appended to the message. This can be useful for some syslog daemons. Added in `Sys::Syslog` 0.29.
* `nowait` - Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)
* `perror` - Write the message to standard error output as well to the system log. Added in `Sys::Syslog` 0.22.
* `pid` - Include PID with each message.
**Examples**
Open the syslog with options `ndelay` and `pid`, and with facility `LOCAL0`:
```
openlog($name, "ndelay,pid", "local0");
```
Same thing, but this time using the macro corresponding to `LOCAL0`:
```
openlog($name, "ndelay,pid", LOG_LOCAL0);
```
**syslog($priority, $message)**
**syslog($priority, $format, @args)**
If `$priority` permits, logs `$message` or `sprintf($format, @args)` with the addition that `%m` in $message or `$format` is replaced with `"$!"` (the latest error message).
`$priority` can specify a level, or a level and a facility. Levels and facilities can be given as strings or as macros. When using the `eventlog` mechanism, priorities `DEBUG` and `INFO` are mapped to event type `informational`, `NOTICE` and `WARNING` to `warning` and `ERR` to `EMERG` to `error`.
If you didn't use `openlog()` before using `syslog()`, `syslog()` will try to guess the `$ident` by extracting the shortest prefix of `$format` that ends in a `":"`.
**Examples**
```
# informational level
syslog("info", $message);
syslog(LOG_INFO, $message);
# information level, Local0 facility
syslog("info|local0", $message);
syslog(LOG_INFO|LOG_LOCAL0, $message);
```
**Note** `Sys::Syslog` version v0.07 and older passed the `$message` as the formatting string to `sprintf()` even when no formatting arguments were provided. If the code calling `syslog()` might execute with older versions of this module, make sure to call the function as `syslog($priority, "%s", $message)` instead of `syslog($priority, $message)`. This protects against hostile formatting sequences that might show up if $message contains tainted data.
**setlogmask($mask\_priority)**
Sets the log mask for the current process to `$mask_priority` and returns the old mask. If the mask argument is 0, the current log mask is not modified. See ["Levels"](#Levels) for the list of available levels. You can use the `LOG_UPTO()` function to allow all levels up to a given priority (but it only accept the numeric macros as arguments).
**Examples**
Only log errors:
```
setlogmask( LOG_MASK(LOG_ERR) );
```
Log everything except informational messages:
```
setlogmask( ~(LOG_MASK(LOG_INFO)) );
```
Log critical messages, errors and warnings:
```
setlogmask( LOG_MASK(LOG_CRIT)
| LOG_MASK(LOG_ERR)
| LOG_MASK(LOG_WARNING) );
```
Log all messages up to debug:
```
setlogmask( LOG_UPTO(LOG_DEBUG) );
```
**setlogsock()**
Sets the socket type and options to be used for the next call to `openlog()` or `syslog()`. Returns true on success, `undef` on failure.
Being Perl-specific, this function has evolved along time. It can currently be called as follow:
* `setlogsock($sock_type)`
* `setlogsock($sock_type, $stream_location)` (added in Perl 5.004\_02)
* `setlogsock($sock_type, $stream_location, $sock_timeout)` (added in `Sys::Syslog` 0.25)
* `setlogsock(\%options)` (added in `Sys::Syslog` 0.28)
The available options are:
* `type` - equivalent to `$sock_type`, selects the socket type (or "mechanism"). An array reference can be passed to specify several mechanisms to try, in the given order.
* `path` - equivalent to `$stream_location`, sets the stream location. Defaults to standard Unix location, or `_PATH_LOG`.
* `timeout` - equivalent to `$sock_timeout`, sets the socket timeout in seconds. Defaults to 0 on all systems except Mac OS X where it is set to 0.25 sec.
* `host` - sets the hostname to send the messages to. Defaults to the local host.
* `port` - sets the TCP or UDP port to connect to. Defaults to the first standard syslog port available on the system.
The available mechanisms are:
* `"native"` - use the native C functions from your `syslog(3)` library (added in `Sys::Syslog` 0.15).
* `"eventlog"` - send messages to the Win32 events logger (Win32 only; added in `Sys::Syslog` 0.19).
* `"tcp"` - connect to a TCP socket, on the `syslog/tcp` or `syslogng/tcp` service. See also the `host`, `port` and `timeout` options.
* `"udp"` - connect to a UDP socket, on the `syslog/udp` service. See also the `host`, `port` and `timeout` options.
* `"inet"` - connect to an INET socket, either TCP or UDP, tried in that order. See also the `host`, `port` and `timeout` options.
* `"unix"` - connect to a UNIX domain socket (in some systems a character special device). The name of that socket is given by the `path` option or, if omitted, the value returned by the `_PATH_LOG` macro (if your system defines it), */dev/log* or */dev/conslog*, whichever is writable.
* `"stream"` - connect to the stream indicated by the `path` option, or, if omitted, the value returned by the `_PATH_LOG` macro (if your system defines it), */dev/log* or */dev/conslog*, whichever is writable. For example Solaris and IRIX system may prefer `"stream"` instead of `"unix"`.
* `"pipe"` - connect to the named pipe indicated by the `path` option, or, if omitted, to the value returned by the `_PATH_LOG` macro (if your system defines it), or */dev/log* (added in `Sys::Syslog` 0.21). HP-UX is a system which uses such a named pipe.
* `"console"` - send messages directly to the console, as for the `"cons"` option of `openlog()`.
The default is to try `native`, `tcp`, `udp`, `unix`, `pipe`, `stream`, `console`. Under systems with the Win32 API, `eventlog` will be added as the first mechanism to try if `Win32::EventLog` is available.
Giving an invalid value for `$sock_type` will `croak`.
**Examples**
Select the UDP socket mechanism:
```
setlogsock("udp");
```
Send messages using the TCP socket mechanism on a custom port:
```
setlogsock({ type => "tcp", port => 2486 });
```
Send messages to a remote host using the TCP socket mechanism:
```
setlogsock({ type => "tcp", host => $loghost });
```
Try the native, UDP socket then UNIX domain socket mechanisms:
```
setlogsock(["native", "udp", "unix"]);
```
**Note** Now that the "native" mechanism is supported by `Sys::Syslog` and selected by default, the use of the `setlogsock()` function is discouraged because other mechanisms are less portable across operating systems. Authors of modules and programs that use this function, especially its cargo-cult form `setlogsock("unix")`, are advised to remove any occurrence of it unless they specifically want to use a given mechanism (like TCP or UDP to connect to a remote host).
**closelog()**
Closes the log file and returns true on success.
THE RULES OF SYS::SYSLOG
-------------------------
*The First Rule of Sys::Syslog is:* You do not call `setlogsock`.
*The Second Rule of Sys::Syslog is:* You **do not** call `setlogsock`.
*The Third Rule of Sys::Syslog is:* The program crashes, `die`s, calls `closelog`, the log is over.
*The Fourth Rule of Sys::Syslog is:* One facility, one priority.
*The Fifth Rule of Sys::Syslog is:* One log at a time.
*The Sixth Rule of Sys::Syslog is:* No `syslog` before `openlog`.
*The Seventh Rule of Sys::Syslog is:* Logs will go on as long as they have to.
*The Eighth, and Final Rule of Sys::Syslog is:* If this is your first use of Sys::Syslog, you must read the doc.
EXAMPLES
--------
An example:
```
openlog($program, 'cons,pid', 'user');
syslog('info', '%s', 'this is another test');
syslog('mail|warning', 'this is a better test: %d', time);
closelog();
syslog('debug', 'this is the last test');
```
Another example:
```
openlog("$program $$", 'ndelay', 'user');
syslog('notice', 'fooprogram: this is really done');
```
Example of use of `%m`:
```
$! = 55;
syslog('info', 'problem was %m'); # %m == $! in syslog(3)
```
Log to UDP port on `$remotehost` instead of logging locally:
```
setlogsock("udp", $remotehost);
openlog($program, 'ndelay', 'user');
syslog('info', 'something happened over here');
```
CONSTANTS
---------
### Facilities
* `LOG_AUDIT` - audit daemon (IRIX); falls back to `LOG_AUTH`
* `LOG_AUTH` - security/authorization messages
* `LOG_AUTHPRIV` - security/authorization messages (private)
* `LOG_CONSOLE` - `/dev/console` output (FreeBSD); falls back to `LOG_USER`
* `LOG_CRON` - clock daemons (**cron** and **at**)
* `LOG_DAEMON` - system daemons without separate facility value
* `LOG_FTP` - FTP daemon
* `LOG_KERN` - kernel messages
* `LOG_INSTALL` - installer subsystem (Mac OS X); falls back to `LOG_USER`
* `LOG_LAUNCHD` - launchd - general bootstrap daemon (Mac OS X); falls back to `LOG_DAEMON`
* `LOG_LFMT` - logalert facility; falls back to `LOG_USER`
* `LOG_LOCAL0` through `LOG_LOCAL7` - reserved for local use
* `LOG_LPR` - line printer subsystem
* `LOG_MAIL` - mail subsystem
* `LOG_NETINFO` - NetInfo subsystem (Mac OS X); falls back to `LOG_DAEMON`
* `LOG_NEWS` - USENET news subsystem
* `LOG_NTP` - NTP subsystem (FreeBSD, NetBSD); falls back to `LOG_DAEMON`
* `LOG_RAS` - Remote Access Service (VPN / PPP) (Mac OS X); falls back to `LOG_AUTH`
* `LOG_REMOTEAUTH` - remote authentication/authorization (Mac OS X); falls back to `LOG_AUTH`
* `LOG_SECURITY` - security subsystems (firewalling, etc.) (FreeBSD); falls back to `LOG_AUTH`
* `LOG_SYSLOG` - messages generated internally by **syslogd**
* `LOG_USER` (default) - generic user-level messages
* `LOG_UUCP` - UUCP subsystem
### Levels
* `LOG_EMERG` - system is unusable
* `LOG_ALERT` - action must be taken immediately
* `LOG_CRIT` - critical conditions
* `LOG_ERR` - error conditions
* `LOG_WARNING` - warning conditions
* `LOG_NOTICE` - normal, but significant, condition
* `LOG_INFO` - informational message
* `LOG_DEBUG` - debug-level message
DIAGNOSTICS
-----------
`Invalid argument passed to setlogsock`
**(F)** You gave `setlogsock()` an invalid value for `$sock_type`.
`eventlog passed to setlogsock, but no Win32 API available`
**(W)** You asked `setlogsock()` to use the Win32 event logger but the operating system running the program isn't Win32 or does not provides Win32 compatible facilities.
`no connection to syslog available`
**(F)** `syslog()` failed to connect to the specified socket.
`stream passed to setlogsock, but %s is not writable`
**(W)** You asked `setlogsock()` to use a stream socket, but the given path is not writable.
`stream passed to setlogsock, but could not find any device`
**(W)** You asked `setlogsock()` to use a stream socket, but didn't provide a path, and `Sys::Syslog` was unable to find an appropriate one.
`tcp passed to setlogsock, but tcp service unavailable`
**(W)** You asked `setlogsock()` to use a TCP socket, but the service is not available on the system.
`syslog: expecting argument %s`
**(F)** You forgot to give `syslog()` the indicated argument.
`syslog: invalid level/facility: %s`
**(F)** You specified an invalid level or facility.
`syslog: too many levels given: %s`
**(F)** You specified too many levels.
`syslog: too many facilities given: %s`
**(F)** You specified too many facilities.
`syslog: level must be given`
**(F)** You forgot to specify a level.
`udp passed to setlogsock, but udp service unavailable`
**(W)** You asked `setlogsock()` to use a UDP socket, but the service is not available on the system.
`unix passed to setlogsock, but path not available`
**(W)** You asked `setlogsock()` to use a UNIX socket, but `Sys::Syslog` was unable to find an appropriate an appropriate device.
HISTORY
-------
`Sys::Syslog` is a core module, part of the standard Perl distribution since 1990. At this time, modules as we know them didn't exist, the Perl library was a collection of *.pl* files, and the one for sending syslog messages with was simply *lib/syslog.pl*, included with Perl 3.0. It was converted as a module with Perl 5.0, but had a version number only starting with Perl 5.6. Here is a small table with the matching Perl and `Sys::Syslog` versions.
```
Sys::Syslog Perl
----------- ----
undef 5.0.0 ~ 5.5.4
0.01 5.6.*
0.03 5.8.0
0.04 5.8.1, 5.8.2, 5.8.3
0.05 5.8.4, 5.8.5, 5.8.6
0.06 5.8.7
0.13 5.8.8
0.22 5.10.0
0.27 5.8.9, 5.10.1 ~ 5.14.*
0.29 5.16.*
0.32 5.18.*
0.33 5.20.*
0.33 5.22.*
```
SEE ALSO
---------
###
Other modules
<Log::Log4perl> - Perl implementation of the Log4j API
<Log::Dispatch> - Dispatches messages to one or more outputs
<Log::Report> - Report a problem, with exceptions and language support
###
Manual Pages
[syslog(3)](http://man.he.net/man3/syslog)
SUSv3 issue 6, IEEE Std 1003.1, 2004 edition, <http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
GNU C Library documentation on syslog, <http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
FreeBSD documentation on syslog, <https://www.freebsd.org/cgi/man.cgi?query=syslog>
Solaris 11 documentation on syslog, <https://docs.oracle.com/cd/E53394_01/html/E54766/syslog-3c.html>
Mac OS X documentation on syslog, <http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
IRIX documentation on syslog, <http://nixdoc.net/man-pages/IRIX/man3/syslog.3c.html>
AIX 5L 5.3 documentation on syslog, <http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
HP-UX 11i documentation on syslog, <http://docs.hp.com/en/B2355-60130/syslog.3C.html>
Tru64 documentation on syslog, <http://nixdoc.net/man-pages/Tru64/man3/syslog.3.html>
Stratus VOS 15.1, <http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
### RFCs
*RFC 3164 - The BSD syslog Protocol*, <http://www.faqs.org/rfcs/rfc3164.html> -- Please note that this is an informational RFC, and therefore does not specify a standard of any kind.
*RFC 3195 - Reliable Delivery for syslog*, <http://www.faqs.org/rfcs/rfc3195.html>
### Articles
*Syslogging with Perl*, <http://lexington.pm.org/meetings/022001.html>
###
Event Log
Windows Event Log, <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
AUTHORS & ACKNOWLEDGEMENTS
---------------------------
Tom Christiansen <*tchrist (at) perl.com*> and Larry Wall <*larry (at) wall.org*>.
UNIX domain sockets added by Sean Robinson <*robinson\_s (at) sc.maricopa.edu*> with support from Tim Bunce <*Tim.Bunce (at) ig.co.uk*> and the `perl5-porters` mailing list.
Dependency on *syslog.ph* replaced with XS code by Tom Hughes <*tom (at) compton.nu*>.
Code for `constant()`s regenerated by Nicholas Clark <*nick (at) ccl4.org*>.
Failover to different communication modes by Nick Williams <*Nick.Williams (at) morganstanley.com*>.
Extracted from core distribution for publishing on the CPAN by Sรฉbastien Aperghis-Tramoni <sebastien (at) aperghis.net>.
XS code for using native C functions borrowed from `<Unix::Syslog>`, written by Marcus Harnisch <*marcus.harnisch (at) gmx.net*>.
Yves Orton suggested and helped for making `Sys::Syslog` use the native event logger under Win32 systems.
Jerry D. Hedden and Reini Urban provided greatly appreciated help to debug and polish `Sys::Syslog` under Cygwin.
BUGS
----
Please report any bugs or feature requests to `bug-sys-syslog (at) rt.cpan.org`, or through the web interface at <http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>. I 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 Sys::Syslog
```
You can also look for information at:
* Perl Documentation
<http://perldoc.perl.org/Sys/Syslog.html>
* MetaCPAN
<https://metacpan.org/module/Sys::Syslog>
* Search CPAN
<http://search.cpan.org/dist/Sys-Syslog/>
* AnnoCPAN: Annotated CPAN documentation
<http://annocpan.org/dist/Sys-Syslog>
* CPAN Ratings
<http://cpanratings.perl.org/d/Sys-Syslog>
* RT: CPAN's request tracker
<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
The source code is available on Git Hub: <https://github.com/maddingue/Sys-Syslog/>
COPYRIGHT
---------
Copyright (C) 1990-2012 by Larry Wall and others.
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Pod::Simple::SimpleTree Pod::Simple::SimpleTree
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [Tree Contents](#Tree-Contents)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::SimpleTree -- parse Pod into a simple parse tree
SYNOPSIS
--------
```
% cat ptest.pod
=head1 PIE
I like B<pie>!
% perl -MPod::Simple::SimpleTree -MData::Dumper -e \
"print Dumper(Pod::Simple::SimpleTree->new->parse_file(shift)->root)" \
ptest.pod
$VAR1 = [
'Document',
{ 'start_line' => 1 },
[
'head1',
{ 'start_line' => 1 },
'PIE'
],
[
'Para',
{ 'start_line' => 3 },
'I like ',
[
'B',
{},
'pie'
],
'!'
]
];
```
DESCRIPTION
-----------
This class is of interest to people writing a Pod processor/formatter.
This class takes Pod and parses it, returning a parse tree made just of arrayrefs, and hashrefs, and strings.
This is a subclass of <Pod::Simple> and inherits all its methods.
This class is inspired by XML::Parser's "Tree" parsing-style, although it doesn't use exactly the same LoL format.
METHODS
-------
At the end of the parse, call `$parser->root` to get the tree's top node.
Tree Contents
--------------
Every element node in the parse tree is represented by an arrayref of the form: `[ *elementname*, \%attributes, *...subnodes...* ]`. See the example tree dump in the Synopsis, above.
Every text node in the tree is represented by a simple (non-ref) string scalar. So you can test `ref($node)` to see whether you have an element node or just a text node.
The top node in the tree is `[ 'Document', \%attributes, *...subnodes...* ]`
SEE ALSO
---------
<Pod::Simple>
<perllol>
[The "Tree" subsubsection in XML::Parser](XML::Parser#Tree)
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 Test2::Event::Ok Test2::Event::Ok
================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [ACCESSORS](#ACCESSORS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Ok - Ok event type
DESCRIPTION
-----------
Ok events are generated whenever you run a test that produces a result. Examples are `ok()`, and `is()`.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Ok;
my $ctx = context();
my $event = $ctx->ok($bool, $name, \@diag);
```
or:
```
my $ctx = context();
my $event = $ctx->send_event(
'Ok',
pass => $bool,
name => $name,
);
```
ACCESSORS
---------
$rb = $e->pass The original true/false value of whatever was passed into the event (but reduced down to 1 or 0).
$name = $e->name Name of the test.
$b = $e->effective\_pass This is the true/false value of the test after TODO and similar modifiers are taken into account.
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 perlvar perlvar
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [The Syntax of Variable Names](#The-Syntax-of-Variable-Names)
* [SPECIAL VARIABLES](#SPECIAL-VARIABLES)
+ [General Variables](#General-Variables)
+ [Variables related to regular expressions](#Variables-related-to-regular-expressions)
- [Performance issues](#Performance-issues)
+ [Variables related to filehandles](#Variables-related-to-filehandles)
- [Variables related to formats](#Variables-related-to-formats)
+ [Error Variables](#Error-Variables)
+ [Variables related to the interpreter state](#Variables-related-to-the-interpreter-state)
+ [Deprecated and removed variables](#Deprecated-and-removed-variables)
NAME
----
perlvar - Perl predefined variables
DESCRIPTION
-----------
###
The Syntax of Variable Names
Variable names in Perl can have several formats. Usually, they must begin with a letter or underscore, in which case they can be arbitrarily long (up to an internal limit of 251 characters) and may contain letters, digits, underscores, or the special sequence `::` or `'`. In this case, the part before the last `::` or `'` is taken to be a *package qualifier*; see <perlmod>. A Unicode letter that is not ASCII is not considered to be a letter unless `"use utf8"` is in effect, and somewhat more complicated rules apply; see ["Identifier parsing" in perldata](perldata#Identifier-parsing) for details.
Perl variable names may also be a sequence of digits, a single punctuation character, or the two-character sequence: `^` (caret or CIRCUMFLEX ACCENT) followed by any one of the characters `[][A-Z^_?\]`. These names are all reserved for special uses by Perl; for example, the all-digits names are used to hold data captured by backreferences after a regular expression match.
Since Perl v5.6.0, Perl variable names may also be alphanumeric strings preceded by a caret. These must all be written using the demarcated variable form using curly braces such as `${^Foo}`; the braces are **not** optional. `${^Foo}` denotes the scalar variable whose name is considered to be a control-`F` followed by two `o`'s. (See ["Demarcated variable names using braces" in perldata](perldata#Demarcated-variable-names-using-braces) for more information on this form of spelling a variable name or specifying access to an element of an array or a hash). These variables are reserved for future special uses by Perl, except for the ones that begin with `^_` (caret-underscore). No name that begins with `^_` will acquire a special meaning in any future version of Perl; such names may therefore be used safely in programs. `$^_` itself, however, *is* reserved.
Note that you also **must** use the demarcated form to access subscripts of variables of this type when interpolating, for instance to access the first element of the `@{^CAPTURE}` variable inside of a double quoted string you would write `"${^CAPTURE[0]}"` and NOT `"${^CAPTURE}[0]"` which would mean to reference a scalar variable named `${^CAPTURE}` and not index 0 of the magic `@{^CAPTURE}` array which is populated by the regex engine.
Perl identifiers that begin with digits or punctuation characters are exempt from the effects of the `package` declaration and are always forced to be in package `main`; they are also exempt from `strict 'vars'` errors. A few other names are also exempt in these ways:
```
ENV STDIN
INC STDOUT
ARGV STDERR
ARGVOUT
SIG
```
In particular, the special `${^_XYZ}` variables are always taken to be in package `main`, regardless of any `package` declarations presently in scope.
SPECIAL VARIABLES
------------------
The following names have special meaning to Perl. Most punctuation names have reasonable mnemonics, or analogs in the shells. Nevertheless, if you wish to use long variable names, you need only say:
```
use English;
```
at the top of your program. This aliases all the short names to the long names in the current package. Some even have medium names, generally borrowed from **awk**. For more info, please see [English](english).
Before you continue, note the sort order for variables. In general, we first list the variables in case-insensitive, almost-lexigraphical order (ignoring the `{` or `^` preceding words, as in `${^UNICODE}` or `$^T`), although `$_` and `@_` move up to the top of the pile. For variables with the same identifier, we list it in order of scalar, array, hash, and bareword.
###
General Variables
$ARG
$\_ The default input and pattern-searching space. The following pairs are equivalent:
```
while (<>) {...} # equivalent only in while!
while (defined($_ = <>)) {...}
/^Subject:/
$_ =~ /^Subject:/
tr/a-z/A-Z/
$_ =~ tr/a-z/A-Z/
chomp
chomp($_)
```
Here are the places where Perl will assume `$_` even if you don't use it:
* The following functions use `$_` as a default argument:
abs, alarm, chomp, chop, chr, chroot, cos, defined, eval, evalbytes, exp, fc, glob, hex, int, lc, lcfirst, length, log, lstat, mkdir, oct, ord, pos, print, printf, quotemeta, readlink, readpipe, ref, require, reverse (in scalar context only), rmdir, say, sin, split (for its second argument), sqrt, stat, study, uc, ucfirst, unlink, unpack.
* All file tests (`-f`, `-d`) except for `-t`, which defaults to STDIN. See ["-X" in perlfunc](perlfunc#-X)
* The pattern matching operations `m//`, `s///` and `tr///` (aka `y///`) when used without an `=~` operator.
* The default iterator variable in a `foreach` loop if no other variable is supplied.
* The implicit iterator variable in the `grep()` and `map()` functions.
* The implicit variable of `given()`.
* The default place to put the next value or input record when a `<FH>`, `readline`, `readdir` or `each` operation's result is tested by itself as the sole criterion of a `while` test. Outside a `while` test, this will not happen.
`$_` is a global variable.
However, between perl v5.10.0 and v5.24.0, it could be used lexically by writing `my $_`. Making `$_` refer to the global `$_` in the same scope was then possible with `our $_`. This experimental feature was removed and is now a fatal error, but you may encounter it in older code.
Mnemonic: underline is understood in certain operations.
@ARG
@\_ Within a subroutine the array `@_` contains the parameters passed to that subroutine. Inside a subroutine, `@_` is the default array for the array operators `pop` and `shift`.
See <perlsub>.
$LIST\_SEPARATOR
$" When an array or an array slice is interpolated into a double-quoted string or a similar context such as `/.../`, its elements are separated by this value. Default is a space. For example, this:
```
print "The array is: @array\n";
```
is equivalent to this:
```
print "The array is: " . join($", @array) . "\n";
```
Mnemonic: works in double-quoted context.
$PROCESS\_ID
$PID
$$ The process number of the Perl running this script. Though you *can* set this variable, doing so is generally discouraged, although it can be invaluable for some testing purposes. It will be reset automatically across `fork()` calls.
Note for Linux and Debian GNU/kFreeBSD users: Before Perl v5.16.0 perl would emulate POSIX semantics on Linux systems using LinuxThreads, a partial implementation of POSIX Threads that has since been superseded by the Native POSIX Thread Library (NPTL).
LinuxThreads is now obsolete on Linux, and caching `getpid()` like this made embedding perl unnecessarily complex (since you'd have to manually update the value of $$), so now `$$` and `getppid()` will always return the same values as the underlying C library.
Debian GNU/kFreeBSD systems also used LinuxThreads up until and including the 6.0 release, but after that moved to FreeBSD thread semantics, which are POSIX-like.
To see if your system is affected by this discrepancy check if `getconf GNU_LIBPTHREAD_VERSION | grep -q NPTL` returns a false value. NTPL threads preserve the POSIX semantics.
Mnemonic: same as shells.
$PROGRAM\_NAME
$0 Contains the name of the program being executed.
On some (but not all) operating systems assigning to `$0` modifies the argument area that the `ps` program sees. On some platforms you may have to use special `ps` options or a different `ps` to see the changes. Modifying the `$0` is more useful as a way of indicating the current program state than it is for hiding the program you're running.
Note that there are platform-specific limitations on the maximum length of `$0`. In the most extreme case it may be limited to the space occupied by the original `$0`.
In some platforms there may be arbitrary amount of padding, for example space characters, after the modified name as shown by `ps`. In some platforms this padding may extend all the way to the original length of the argument area, no matter what you do (this is the case for example with Linux 2.2).
Note for BSD users: setting `$0` does not completely remove "perl" from the ps(1) output. For example, setting `$0` to `"foobar"` may result in `"perl: foobar (perl)"` (whether both the `"perl: "` prefix and the " (perl)" suffix are shown depends on your exact BSD variant and version). This is an operating system feature, Perl cannot help it.
In multithreaded scripts Perl coordinates the threads so that any thread may modify its copy of the `$0` and the change becomes visible to ps(1) (assuming the operating system plays along). Note that the view of `$0` the other threads have will not change since they have their own copies of it.
If the program has been given to perl via the switches `-e` or `-E`, `$0` will contain the string `"-e"`.
On Linux as of perl v5.14.0 the legacy process name will be set with `prctl(2)`, in addition to altering the POSIX name via `argv[0]` as perl has done since version 4.000. Now system utilities that read the legacy process name such as ps, top and killall will recognize the name you set when assigning to `$0`. The string you supply will be cut off at 16 bytes, this is a limitation imposed by Linux.
Wide characters are invalid in `$0` values. For historical reasons, though, Perl accepts them and encodes them to UTF-8. When this happens a wide-character warning is triggered.
Mnemonic: same as **sh** and **ksh**.
$REAL\_GROUP\_ID
$GID
$( The real gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by `getgid()`, and the subsequent ones by `getgroups()`, one of which may be the same as the first number.
However, a value assigned to `$(` must be a single number used to set the real gid. So the value given by `$(` should *not* be assigned back to `$(` without being forced numeric, such as by adding zero. Note that this is different to the effective gid (`$)`) which does take a list.
You can change both the real gid and the effective gid at the same time by using `POSIX::setgid()`. Changes to `$(` require a check to `$!` to detect any possible errors after an attempted change.
Mnemonic: parentheses are used to *group* things. The real gid is the group you *left*, if you're running setgid.
$EFFECTIVE\_GROUP\_ID
$EGID
$) The effective gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by `getegid()`, and the subsequent ones by `getgroups()`, one of which may be the same as the first number.
Similarly, a value assigned to `$)` must also be a space-separated list of numbers. The first number sets the effective gid, and the rest (if any) are passed to `setgroups()`. To get the effect of an empty list for `setgroups()`, just repeat the new effective gid; that is, to force an effective gid of 5 and an effectively empty `setgroups()` list, say `$) = "5 5"` .
You can change both the effective gid and the real gid at the same time by using `POSIX::setgid()` (use only a single numeric argument). Changes to `$)` require a check to `$!` to detect any possible errors after an attempted change.
`$<`, `$>`, `$(` and `$)` can be set only on machines that support the corresponding *set[re][ug]id()* routine. `$(` and `$)` can be swapped only on machines supporting `setregid()`.
Mnemonic: parentheses are used to *group* things. The effective gid is the group that's *right* for you, if you're running setgid.
$REAL\_USER\_ID
$UID
$< The real uid of this process. You can change both the real uid and the effective uid at the same time by using `POSIX::setuid()`. Since changes to `$<` require a system call, check `$!` after a change attempt to detect any possible errors.
Mnemonic: it's the uid you came *from*, if you're running setuid.
$EFFECTIVE\_USER\_ID
$EUID
$> The effective uid of this process. For example:
```
$< = $>; # set real to effective uid
($<,$>) = ($>,$<); # swap real and effective uids
```
You can change both the effective uid and the real uid at the same time by using `POSIX::setuid()`. Changes to `$>` require a check to `$!` to detect any possible errors after an attempted change.
`$<` and `$>` can be swapped only on machines supporting `setreuid()`.
Mnemonic: it's the uid you went *to*, if you're running setuid.
$SUBSCRIPT\_SEPARATOR
$SUBSEP
$; The subscript separator for multidimensional array emulation. If you refer to a hash element as
```
$foo{$x,$y,$z}
```
it really means
```
$foo{join($;, $x, $y, $z)}
```
But don't put
```
@foo{$x,$y,$z} # a slice--note the @
```
which means
```
($foo{$x},$foo{$y},$foo{$z})
```
Default is "\034", the same as SUBSEP in **awk**. If your keys contain binary data there might not be any safe value for `$;`.
Consider using "real" multidimensional arrays as described in <perllol>.
Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon.
$a
$b Special package variables when using `sort()`, see ["sort" in perlfunc](perlfunc#sort). Because of this specialness `$a` and `$b` don't need to be declared (using `use vars`, or `our()`) even when using the `strict 'vars'` pragma. Don't lexicalize them with `my $a` or `my $b` if you want to be able to use them in the `sort()` comparison block or function.
%ENV The hash `%ENV` contains your current environment. Setting a value in `ENV` changes the environment for any child processes you subsequently `fork()` off.
As of v5.18.0, both keys and values stored in `%ENV` are stringified.
```
my $foo = 1;
$ENV{'bar'} = \$foo;
if( ref $ENV{'bar'} ) {
say "Pre 5.18.0 Behaviour";
} else {
say "Post 5.18.0 Behaviour";
}
```
Previously, only child processes received stringified values:
```
my $foo = 1;
$ENV{'bar'} = \$foo;
# Always printed 'non ref'
system($^X, '-e',
q/print ( ref $ENV{'bar'} ? 'ref' : 'non ref' ) /);
```
This happens because you can't really share arbitrary data structures with foreign processes.
$OLD\_PERL\_VERSION
$] The revision, version, and subversion of the Perl interpreter, represented as a decimal of the form 5.XXXYYY, where XXX is the version / 1e3 and YYY is the subversion / 1e6. For example, Perl v5.10.1 would be "5.010001".
This variable can be used to determine whether the Perl interpreter executing a script is in the right range of versions:
```
warn "No PerlIO!\n" if "$]" < 5.008;
```
When comparing `$]`, numeric comparison operators should be used, but the variable should be stringified first to avoid issues where its original numeric value is inaccurate.
See also the documentation of [`use VERSION`](perlfunc#use-VERSION) and `require VERSION` for a convenient way to fail if the running Perl interpreter is too old.
See ["$^V"](#%24%5EV) for a representation of the Perl version as a <version> object, which allows more flexible string comparisons.
The main advantage of `$]` over `$^V` is that it works the same on any version of Perl. The disadvantages are that it can't easily be compared to versions in other formats (e.g. literal v-strings, "v1.2.3" or version objects) and numeric comparisons are subject to the binary floating point representation; it's good for numeric literal version checks and bad for comparing to a variable that hasn't been sanity-checked.
The `$OLD_PERL_VERSION` form was added in Perl v5.20.0 for historical reasons but its use is discouraged. (If your reason to use `$]` is to run code on old perls then referring to it as `$OLD_PERL_VERSION` would be self-defeating.)
Mnemonic: Is this version of perl in the right bracket?
$SYSTEM\_FD\_MAX
$^F The maximum system file descriptor, ordinarily 2. System file descriptors are passed to `exec()`ed processes, while higher file descriptors are not. Also, during an `open()`, system file descriptors are preserved even if the `open()` fails (ordinary file descriptors are closed before the `open()` is attempted). The close-on-exec status of a file descriptor will be decided according to the value of `$^F` when the corresponding file, pipe, or socket was opened, not the time of the `exec()`.
@F The array `@F` contains the fields of each line read in when autosplit mode is turned on. See [perlrun](perlrun#-a) for the **-a** switch. This array is package-specific, and must be declared or given a full package name if not in package main when running under `strict 'vars'`.
@INC The array `@INC` contains the list of places that the `do EXPR`, `require`, or `use` constructs look for their library files. It initially consists of the arguments to any **-I** command-line switches, followed by the default Perl library, probably */usr/local/lib/perl*. Prior to Perl 5.26, `.` -which represents the current directory, was included in `@INC`; it has been removed. This change in behavior is documented in [`PERL_USE_UNSAFE_INC`](perlrun#PERL_USE_UNSAFE_INC) and it is not recommended that `.` be re-added to `@INC`. If you need to modify `@INC` at runtime, you should use the `use lib` pragma to get the machine-dependent library properly loaded as well:
```
use lib '/mypath/libdir/';
use SomeMod;
```
You can also insert hooks into the file inclusion system by putting Perl code directly into `@INC`. Those hooks may be subroutine references, array references or blessed objects. See ["require" in perlfunc](perlfunc#require) for details.
%INC The hash `%INC` contains entries for each filename included via the `do`, `require`, or `use` operators. The key is the filename you specified (with module names converted to pathnames), and the value is the location of the file found. The `require` operator uses this hash to determine whether a particular file has already been included.
If the file was loaded via a hook (e.g. a subroutine reference, see ["require" in perlfunc](perlfunc#require) for a description of these hooks), this hook is by default inserted into `%INC` in place of a filename. Note, however, that the hook may have set the `%INC` entry by itself to provide some more specific info.
$INPLACE\_EDIT
$^I The current value of the inplace-edit extension. Use `undef` to disable inplace editing.
Mnemonic: value of **-i** switch.
@ISA Each package contains a special array called `@ISA` which contains a list of that class's parent classes, if any. This array is simply a list of scalars, each of which is a string that corresponds to a package name. The array is examined when Perl does method resolution, which is covered in <perlobj>.
To load packages while adding them to `@ISA`, see the <parent> pragma. The discouraged <base> pragma does this as well, but should not be used except when compatibility with the discouraged <fields> pragma is required.
$^M By default, running out of memory is an untrappable, fatal error. However, if suitably built, Perl can use the contents of `$^M` as an emergency memory pool after `die()`ing. Suppose that your Perl were compiled with `-DPERL_EMERGENCY_SBRK` and used Perl's malloc. Then
```
$^M = 'a' x (1 << 16);
```
would allocate a 64K buffer for use in an emergency. See the *INSTALL* file in the Perl distribution for information on how to add custom C compilation flags when compiling perl. To discourage casual use of this advanced feature, there is no [English](english) long name for this variable.
This variable was added in Perl 5.004.
$OSNAME
$^O The name of the operating system under which this copy of Perl was built, as determined during the configuration process. For examples see ["PLATFORMS" in perlport](perlport#PLATFORMS).
The value is identical to `$Config{'osname'}`. See also [Config](config) and the **-V** command-line switch documented in [perlrun](perlrun#-V).
In Windows platforms, `$^O` is not very helpful: since it is always `MSWin32`, it doesn't tell the difference between 95/98/ME/NT/2000/XP/CE/.NET. Use `Win32::GetOSName()` or Win32::GetOSVersion() (see [Win32](win32) and <perlport>) to distinguish between the variants.
This variable was added in Perl 5.003.
%SIG The hash `%SIG` contains signal handlers for signals. For example:
```
sub handler { # 1st argument is signal name
my($sig) = @_;
print "Caught a SIG$sig--shutting down\n";
close(LOG);
exit(0);
}
$SIG{'INT'} = \&handler;
$SIG{'QUIT'} = \&handler;
...
$SIG{'INT'} = 'DEFAULT'; # restore default action
$SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT
```
Using a value of `'IGNORE'` usually has the effect of ignoring the signal, except for the `CHLD` signal. See <perlipc> for more about this special case. Using an empty string or `undef` as the value has the same effect as `'DEFAULT'`.
Here are some other examples:
```
$SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not
# recommended)
$SIG{"PIPE"} = \&Plumber; # just fine; assume current
# Plumber
$SIG{"PIPE"} = *Plumber; # somewhat esoteric
$SIG{"PIPE"} = Plumber(); # oops, what did Plumber()
# return??
```
Be sure not to use a bareword as the name of a signal handler, lest you inadvertently call it.
Using a string that doesn't correspond to any existing function or a glob that doesn't contain a code slot is equivalent to `'IGNORE'`, but a warning is emitted when the handler is being called (the warning is not emitted for the internal hooks described below).
If your system has the `sigaction()` function then signal handlers are installed using it. This means you get reliable signal handling.
The default delivery policy of signals changed in Perl v5.8.0 from immediate (also known as "unsafe") to deferred, also known as "safe signals". See <perlipc> for more information.
Certain internal hooks can be also set using the `%SIG` hash. The routine indicated by `$SIG{__WARN__}` is called when a warning message is about to be printed. The warning message is passed as the first argument. The presence of a `__WARN__` hook causes the ordinary printing of warnings to `STDERR` to be suppressed. You can use this to save warnings in a variable, or turn warnings into fatal errors, like this:
```
local $SIG{__WARN__} = sub { die $_[0] };
eval $proggie;
```
As the `'IGNORE'` hook is not supported by `__WARN__`, its effect is the same as using `'DEFAULT'`. You can disable warnings using the empty subroutine:
```
local $SIG{__WARN__} = sub {};
```
The routine indicated by `$SIG{__DIE__}` is called when a fatal exception is about to be thrown. The error message is passed as the first argument. When a `__DIE__` hook routine returns, the exception processing continues as it would have in the absence of the hook, unless the hook routine itself exits via a `goto &sub`, a loop exit, or a `die()`. The `__DIE__` handler is explicitly disabled during the call, so that you can die from a `__DIE__` handler. Similarly for `__WARN__`.
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.
The `$SIG{__DIE__}` doesn't support `'IGNORE'`; it has the same effect as `'DEFAULT'`.
`__DIE__`/`__WARN__` handlers are very special in one respect: they may be called to report (probable) errors found by the parser. In such a case the parser may be in inconsistent state, so any attempt to evaluate Perl code from such a handler will probably result in a segfault. This means that warnings or errors that result from parsing Perl should be used with extreme caution, like this:
```
require Carp if defined $^S;
Carp::confess("Something wrong") if defined &Carp::confess;
die "Something wrong, but could not load Carp to give "
. "backtrace...\n\t"
. "To see backtrace try starting Perl with -MCarp switch";
```
Here the first line will load `Carp` *unless* it is the parser who called the handler. The second line will print backtrace and die if `Carp` was available. The third line will be executed only if `Carp` was not available.
Having to even think about the `$^S` variable in your exception handlers is simply wrong. `$SIG{__DIE__}` as currently implemented invites grievous and difficult to track down errors. Avoid it and use an `END{}` or CORE::GLOBAL::die override instead.
See ["die" in perlfunc](perlfunc#die), ["warn" in perlfunc](perlfunc#warn), ["eval" in perlfunc](perlfunc#eval), and <warnings> for additional information.
$BASETIME
$^T The time at which the program began running, in seconds since the epoch (beginning of 1970). The values returned by the **-M**, **-A**, and **-C** filetests are based on this value.
$PERL\_VERSION
$^V The revision, version, and subversion of the Perl interpreter, represented as a <version> object.
This variable first appeared in perl v5.6.0; earlier versions of perl will see an undefined value. Before perl v5.10.0 `$^V` was represented as a v-string rather than a <version> object.
`$^V` can be used to determine whether the Perl interpreter executing a script is in the right range of versions. For example:
```
warn "Hashes not randomized!\n" if !$^V or $^V lt v5.8.1
```
While version objects overload stringification, to portably convert `$^V` into its string representation, use `sprintf()`'s `"%vd"` conversion, which works for both v-strings or version objects:
```
printf "version is v%vd\n", $^V; # Perl's version
```
See the documentation of `use VERSION` and `require VERSION` for a convenient way to fail if the running Perl interpreter is too old.
See also `["$]"](#%24%5D)` for a decimal representation of the Perl version.
The main advantage of `$^V` over `$]` is that, for Perl v5.10.0 or later, it overloads operators, allowing easy comparison against other version representations (e.g. decimal, literal v-string, "v1.2.3", or objects). The disadvantage is that prior to v5.10.0, it was only a literal v-string, which can't be easily printed or compared, whereas the behavior of `$]` is unchanged on all versions of Perl.
Mnemonic: use ^V for a version object.
$EXECUTABLE\_NAME
$^X The name used to execute the current copy of Perl, from C's `argv[0]` or (where supported) */proc/self/exe*.
Depending on the host operating system, the value of `$^X` may be a relative or absolute pathname of the perl program file, or may be the string used to invoke perl but not the pathname of the perl program file. Also, most operating systems permit invoking programs that are not in the PATH environment variable, so there is no guarantee that the value of `$^X` is in PATH. For VMS, the value may or may not include a version number.
You usually can use the value of `$^X` to re-invoke an independent copy of the same perl that is currently running, e.g.,
```
@first_run = `$^X -le "print int rand 100 for 1..100"`;
```
But recall that not all operating systems support forking or capturing of the output of commands, so this complex statement may not be portable.
It is not safe to use the value of `$^X` as a path name of a file, as some operating systems that have a mandatory suffix on executable files do not require use of the suffix when invoking a command. To convert the value of `$^X` to a path name, use the following statements:
```
# Build up a set of file names (not command names).
use Config;
my $this_perl = $^X;
if ($^O ne 'VMS') {
$this_perl .= $Config{_exe}
unless $this_perl =~ m/$Config{_exe}$/i;
}
```
Because many operating systems permit anyone with read access to the Perl program file to make a copy of it, patch the copy, and then execute the copy, the security-conscious Perl programmer should take care to invoke the installed copy of perl, not the copy referenced by `$^X`. The following statements accomplish this goal, and produce a pathname that can be invoked as a command or referenced as a file.
```
use Config;
my $secure_perl_path = $Config{perlpath};
if ($^O ne 'VMS') {
$secure_perl_path .= $Config{_exe}
unless $secure_perl_path =~ m/$Config{_exe}$/i;
}
```
###
Variables related to regular expressions
Most of the special variables related to regular expressions are side effects. Perl sets these variables when it has a successful match, so you should check the match result before using them. For instance:
```
if( /P(A)TT(ER)N/ ) {
print "I found $1 and $2\n";
}
```
These variables are read-only and dynamically-scoped, unless we note otherwise.
The dynamic nature of the regular expression variables means that their value is limited to the block that they are in, as demonstrated by this bit of code:
```
my $outer = 'Wallace and Grommit';
my $inner = 'Mutt and Jeff';
my $pattern = qr/(\S+) and (\S+)/;
sub show_n { print "\$1 is $1; \$2 is $2\n" }
{
OUTER:
show_n() if $outer =~ m/$pattern/;
INNER: {
show_n() if $inner =~ m/$pattern/;
}
show_n();
}
```
The output shows that while in the `OUTER` block, the values of `$1` and `$2` are from the match against `$outer`. Inside the `INNER` block, the values of `$1` and `$2` are from the match against `$inner`, but only until the end of the block (i.e. the dynamic scope). After the `INNER` block completes, the values of `$1` and `$2` return to the values for the match against `$outer` even though we have not made another match:
```
$1 is Wallace; $2 is Grommit
$1 is Mutt; $2 is Jeff
$1 is Wallace; $2 is Grommit
```
####
Performance issues
Traditionally in Perl, any use of any of the three variables `$``, `$&` or `$'` (or their `use English` equivalents) anywhere in the code, caused all subsequent successful pattern matches to make a copy of the matched string, in case the code might subsequently access one of those variables. This imposed a considerable performance penalty across the whole program, so generally the use of these variables has been discouraged.
In Perl 5.6.0 the `@-` and `@+` dynamic arrays were introduced that supply the indices of successful matches. So you could for example do this:
```
$str =~ /pattern/;
print $`, $&, $'; # bad: performance hit
print # good: no performance hit
substr($str, 0, $-[0]),
substr($str, $-[0], $+[0]-$-[0]),
substr($str, $+[0]);
```
In Perl 5.10.0 the `/p` match operator flag and the `${^PREMATCH}`, `${^MATCH}`, and `${^POSTMATCH}` variables were introduced, that allowed you to suffer the penalties only on patterns marked with `/p`.
In Perl 5.18.0 onwards, perl started noting the presence of each of the three variables separately, and only copied that part of the string required; so in
```
$`; $&; "abcdefgh" =~ /d/
```
perl would only copy the "abcd" part of the string. That could make a big difference in something like
```
$str = 'x' x 1_000_000;
$&; # whoops
$str =~ /x/g # one char copied a million times, not a million chars
```
In Perl 5.20.0 a new copy-on-write system was enabled by default, which finally fixes all performance issues with these three variables, and makes them safe to use anywhere.
The `Devel::NYTProf` and `Devel::FindAmpersand` modules can help you find uses of these problematic match variables in your code.
$<*digits*> ($1, $2, ...) Contains the subpattern from the corresponding set of capturing parentheses from the last successful pattern match, not counting patterns matched in nested blocks that have been exited already.
Note there is a distinction between a capture buffer which matches the empty string a capture buffer which is optional. Eg, `(x?)` and `(x)?` The latter may be undef, the former not.
These variables are read-only and dynamically-scoped.
Mnemonic: like \digits.
@{^CAPTURE} An array which exposes the contents of the capture buffers, if any, of the last successful pattern match, not counting patterns matched in nested blocks that have been exited already.
Note that the 0 index of @{^CAPTURE} is equivalent to $1, the 1 index is equivalent to $2, etc.
```
if ("foal"=~/(.)(.)(.)(.)/) {
print join "-", @{^CAPTURE};
}
```
should output "f-o-a-l".
See also ["$<*digits*> ($1, $2, ...)"](#%24-%28%241%2C-%242%2C-...%29), ["%{^CAPTURE}"](#%25%7B%5ECAPTURE%7D) and ["%{^CAPTURE\_ALL}"](#%25%7B%5ECAPTURE_ALL%7D).
Note that unlike most other regex magic variables there is no single letter equivalent to `@{^CAPTURE}`. Also be aware that when interpolating subscripts of this array you **must** use the demarcated variable form, for instance
```
print "${^CAPTURE[0]}"
```
see ["Demarcated variable names using braces" in perldata](perldata#Demarcated-variable-names-using-braces) for more information on this form and its uses.
This variable was added in 5.25.7
$MATCH
$& The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or `eval()` enclosed by the current BLOCK).
See ["Performance issues"](#Performance-issues) above for the serious performance implications of using this variable (even once) in your code.
This variable is read-only and dynamically-scoped.
Mnemonic: like `&` in some editors.
${^MATCH} This is similar to `$&` (`$MATCH`) except that it does not incur the performance penalty associated with that variable.
See ["Performance issues"](#Performance-issues) above.
In Perl v5.18 and earlier, it is only guaranteed to return a defined value when the pattern was compiled or executed with the `/p` modifier. In Perl v5.20, the `/p` modifier does nothing, so `${^MATCH}` does the same thing as `$MATCH`.
This variable was added in Perl v5.10.0.
This variable is read-only and dynamically-scoped.
$PREMATCH
$` The string preceding whatever was matched by the last successful pattern match, not counting any matches hidden within a BLOCK or `eval` enclosed by the current BLOCK.
See ["Performance issues"](#Performance-issues) above for the serious performance implications of using this variable (even once) in your code.
This variable is read-only and dynamically-scoped.
Mnemonic: ``` often precedes a quoted string.
${^PREMATCH} This is similar to `$`` ($PREMATCH) except that it does not incur the performance penalty associated with that variable.
See ["Performance issues"](#Performance-issues) above.
In Perl v5.18 and earlier, it is only guaranteed to return a defined value when the pattern was compiled or executed with the `/p` modifier. In Perl v5.20, the `/p` modifier does nothing, so `${^PREMATCH}` does the same thing as `$PREMATCH`.
This variable was added in Perl v5.10.0.
This variable is read-only and dynamically-scoped.
$POSTMATCH
$' The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or `eval()` enclosed by the current BLOCK). Example:
```
local $_ = 'abcdefghi';
/def/;
print "$`:$&:$'\n"; # prints abc:def:ghi
```
See ["Performance issues"](#Performance-issues) above for the serious performance implications of using this variable (even once) in your code.
This variable is read-only and dynamically-scoped.
Mnemonic: `'` often follows a quoted string.
${^POSTMATCH} This is similar to `$'` (`$POSTMATCH`) except that it does not incur the performance penalty associated with that variable.
See ["Performance issues"](#Performance-issues) above.
In Perl v5.18 and earlier, it is only guaranteed to return a defined value when the pattern was compiled or executed with the `/p` modifier. In Perl v5.20, the `/p` modifier does nothing, so `${^POSTMATCH}` does the same thing as `$POSTMATCH`.
This variable was added in Perl v5.10.0.
This variable is read-only and dynamically-scoped.
$LAST\_PAREN\_MATCH
$+ The text matched by the highest used capture group of the last successful search pattern. It is logically equivalent to the highest numbered capture variable (`$1`, `$2`, ...) which has a defined value.
This is useful if you don't know which one of a set of alternative patterns matched. For example:
```
/Version: (.*)|Revision: (.*)/ && ($rev = $+);
```
This variable is read-only and dynamically-scoped.
Mnemonic: be positive and forward looking.
$LAST\_SUBMATCH\_RESULT
$^N The text matched by the used group most-recently closed (i.e. the group with the rightmost closing parenthesis) of the last successful search pattern. This is subtly different from `$+`. For example in
```
"ab" =~ /^((.)(.))$/
```
we have
```
$1,$^N have the value "ab"
$2 has the value "a"
$3,$+ have the value "b"
```
This is primarily used inside `(?{...})` blocks for examining text recently matched. For example, to effectively capture text to a variable (in addition to `$1`, `$2`, etc.), replace `(...)` with
```
(?:(...)(?{ $var = $^N }))
```
By setting and then using `$var` in this way relieves you from having to worry about exactly which numbered set of parentheses they are.
This variable was added in Perl v5.8.0.
Mnemonic: the (possibly) Nested parenthesis that most recently closed.
@LAST\_MATCH\_END
@+ This array holds the offsets of the ends of the last successful submatches in the currently active dynamic scope. `$+[0]` is the offset into the string of the end of the entire match. This is the same value as what the `pos` function returns when called on the variable that was matched against. The *n*th element of this array holds the offset of the *n*th submatch, so `$+[1]` is the offset past where `$1` ends, `$+[2]` the offset past where `$2` ends, and so on. You can use `$#+` to determine how many subgroups were in the last successful match. See the examples given for the `@-` variable.
This variable was added in Perl v5.6.0.
%{^CAPTURE}
%LAST\_PAREN\_MATCH
%+ Similar to `@+`, the `%+` hash allows access to the named capture buffers, should they exist, in the last successful match in the currently active dynamic scope.
For example, `$+{foo}` is equivalent to `$1` after the following match:
```
'foo' =~ /(?<foo>foo)/;
```
The keys of the `%+` hash list only the names of buffers that have captured (and that are thus associated to defined values).
If multiple distinct capture groups have the same name, then `$+{NAME}` will refer to the leftmost defined group in the match.
The underlying behaviour of `%+` is provided by the <Tie::Hash::NamedCapture> module.
**Note:** `%-` and `%+` are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via `each` may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising.
This variable was added in Perl v5.10.0. The `%{^CAPTURE}` alias was added in 5.25.7.
This variable is read-only and dynamically-scoped.
@LAST\_MATCH\_START
@- `$-[0]` is the offset of the start of the last successful match. `$-[*n*]` is the offset of the start of the substring matched by *n*-th subpattern, or undef if the subpattern did not match.
Thus, after a match against `$_`, `$&` coincides with `substr $_, $-[0], $+[0] - $-[0]`. Similarly, $*n* coincides with `substr $_, $-[n], $+[n] - $-[n]` if `$-[n]` is defined, and $+ coincides with `substr $_, $-[$#-], $+[$#-] - $-[$#-]`. One can use `$#-` to find the last matched subgroup in the last successful match. Contrast with `$#+`, the number of subgroups in the regular expression. Compare with `@+`.
This array holds the offsets of the beginnings of the last successful submatches in the currently active dynamic scope. `$-[0]` is the offset into the string of the beginning of the entire match. The *n*th element of this array holds the offset of the *n*th submatch, so `$-[1]` is the offset where `$1` begins, `$-[2]` the offset where `$2` begins, and so on.
After a match against some variable `$var`:
`$`` is the same as `substr($var, 0, $-[0])`
`$&` is the same as `substr($var, $-[0], $+[0] - $-[0])`
`$'` is the same as `substr($var, $+[0])`
`$1` is the same as `substr($var, $-[1], $+[1] - $-[1])`
`$2` is the same as `substr($var, $-[2], $+[2] - $-[2])`
`$3` is the same as `substr($var, $-[3], $+[3] - $-[3])`
This variable was added in Perl v5.6.0.
%{^CAPTURE\_ALL}
%- Similar to `%+`, this variable allows access to the named capture groups in the last successful match in the currently active dynamic scope. To each capture group name found in the regular expression, it associates a reference to an array containing the list of values captured by all buffers with that name (should there be several of them), in the order where they appear.
Here's an example:
```
if ('1234' =~ /(?<A>1)(?<B>2)(?<A>3)(?<B>4)/) {
foreach my $bufname (sort keys %-) {
my $ary = $-{$bufname};
foreach my $idx (0..$#$ary) {
print "\$-{$bufname}[$idx] : ",
(defined($ary->[$idx])
? "'$ary->[$idx]'"
: "undef"),
"\n";
}
}
}
```
would print out:
```
$-{A}[0] : '1'
$-{A}[1] : '3'
$-{B}[0] : '2'
$-{B}[1] : '4'
```
The keys of the `%-` hash correspond to all buffer names found in the regular expression.
The behaviour of `%-` is implemented via the <Tie::Hash::NamedCapture> module.
**Note:** `%-` and `%+` are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via `each` may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising.
This variable was added in Perl v5.10.0. The `%{^CAPTURE_ALL}` alias was added in 5.25.7.
This variable is read-only and dynamically-scoped.
$LAST\_REGEXP\_CODE\_RESULT
$^R The result of evaluation of the last successful `(?{ code })` regular expression assertion (see <perlre>). May be written to.
This variable was added in Perl 5.005.
${^RE\_COMPILE\_RECURSION\_LIMIT} The current value giving the maximum number of open but unclosed parenthetical groups there may be at any point during a regular expression compilation. The default is currently 1000 nested groups. You may adjust it depending on your needs and the amount of memory available.
This variable was added in Perl v5.30.0.
${^RE\_DEBUG\_FLAGS} The current value of the regex debugging flags. Set to 0 for no debug output even when the `re 'debug'` module is loaded. See <re> for details.
This variable was added in Perl v5.10.0.
${^RE\_TRIE\_MAXBUF} Controls how certain regex optimisations are applied and how much memory they utilize. This value by default is 65536 which corresponds to a 512kB temporary cache. Set this to a higher value to trade memory for speed when matching large alternations. Set it to a lower value if you want the optimisations to be as conservative of memory as possible but still occur, and set it to a negative value to prevent the optimisation and conserve the most memory. Under normal situations this variable should be of no interest to you.
This variable was added in Perl v5.10.0.
###
Variables related to filehandles
Variables that depend on the currently selected filehandle may be set by calling an appropriate object method on the `IO::Handle` object, although this is less efficient than using the regular built-in variables. (Summary lines below for this contain the word HANDLE.) First you must say
```
use IO::Handle;
```
after which you may use either
```
method HANDLE EXPR
```
or more safely,
```
HANDLE->method(EXPR)
```
Each method returns the old value of the `IO::Handle` attribute. The methods each take an optional EXPR, which, if supplied, specifies the new value for the `IO::Handle` attribute in question. If not supplied, most methods do nothing to the current value--except for `autoflush()`, which will assume a 1 for you, just to be different.
Because loading in the `IO::Handle` class is an expensive operation, you should learn how to use the regular built-in variables.
A few of these variables are considered "read-only". This means that if you try to assign to this variable, either directly or indirectly through a reference, you'll raise a run-time exception.
You should be very careful when modifying the default values of most special variables described in this document. In most cases you want to localize these variables before changing them, since if you don't, the change may affect other modules which rely on the default values of the special variables that you have changed. This is one of the correct ways to read the whole file at once:
```
open my $fh, "<", "foo" or die $!;
local $/; # enable localized slurp mode
my $content = <$fh>;
close $fh;
```
But the following code is quite bad:
```
open my $fh, "<", "foo" or die $!;
undef $/; # enable slurp mode
my $content = <$fh>;
close $fh;
```
since some other module, may want to read data from some file in the default "line mode", so if the code we have just presented has been executed, the global value of `$/` is now changed for any other code running inside the same Perl interpreter.
Usually when a variable is localized you want to make sure that this change affects the shortest scope possible. So unless you are already inside some short `{}` block, you should create one yourself. For example:
```
my $content = '';
open my $fh, "<", "foo" or die $!;
{
local $/;
$content = <$fh>;
}
close $fh;
```
Here is an example of how your own code can go broken:
```
for ( 1..3 ){
$\ = "\r\n";
nasty_break();
print "$_";
}
sub nasty_break {
$\ = "\f";
# do something with $_
}
```
You probably expect this code to print the equivalent of
```
"1\r\n2\r\n3\r\n"
```
but instead you get:
```
"1\f2\f3\f"
```
Why? Because `nasty_break()` modifies `$\` without localizing it first. The value you set in `nasty_break()` is still there when you return. The fix is to add `local()` so the value doesn't leak out of `nasty_break()`:
```
local $\ = "\f";
```
It's easy to notice the problem in such a short example, but in more complicated code you are looking for trouble if you don't localize changes to the special variables.
$ARGV Contains the name of the current file when reading from `<>`.
@ARGV The array `@ARGV` contains the command-line arguments intended for the script. `$#ARGV` is generally the number of arguments minus one, because `$ARGV[0]` is the first argument, *not* the program's command name itself. See ["$0"](#%240) for the command name.
ARGV The special filehandle that iterates over command-line filenames in `@ARGV`. Usually written as the null filehandle in the angle operator `<>`. Note that currently `ARGV` only has its magical effect within the `<>` operator; elsewhere it is just a plain filehandle corresponding to the last file opened by `<>`. In particular, passing `\*ARGV` as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in `@ARGV`.
ARGVOUT The special filehandle that points to the currently open output file when doing edit-in-place processing with **-i**. Useful when you have to do a lot of inserting and don't want to keep modifying `$_`. See [perlrun](perlrun#-i%5Bextension%5D) for the **-i** switch.
IO::Handle->output\_field\_separator( EXPR )
$OUTPUT\_FIELD\_SEPARATOR
$OFS
$, The output field separator for the print operator. If defined, this value is printed between each of print's arguments. Default is `undef`.
You cannot call `output_field_separator()` on a handle, only as a static method. See <IO::Handle>.
Mnemonic: what is printed when there is a "," in your print statement.
HANDLE->input\_line\_number( EXPR )
$INPUT\_LINE\_NUMBER
$NR
$. Current line number for the last filehandle accessed.
Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of `$/`, Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via `readline()` or `<>`), or when `tell()` or `seek()` is called on it, `$.` becomes an alias to the line counter for that filehandle.
You can adjust the counter by assigning to `$.`, but this will not actually move the seek pointer. *Localizing `$.` will not localize the filehandle's line count*. Instead, it will localize perl's notion of which filehandle `$.` is currently aliased to.
`$.` is reset when the filehandle is closed, but **not** when an open filehandle is reopened without an intervening `close()`. For more details, see ["I/O Operators" in perlop](perlop#I%2FO-Operators). Because `<>` never does an explicit close, line numbers increase across `ARGV` files (but see examples in ["eof" in perlfunc](perlfunc#eof)).
You can also use `HANDLE->input_line_number(EXPR)` to access the line counter for a given filehandle without having to worry about which handle you last accessed.
Mnemonic: many programs use "." to mean the current line number.
IO::Handle->input\_record\_separator( EXPR )
$INPUT\_RECORD\_SEPARATOR
$RS
$/ The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like **awk**'s RS variable, including treating empty lines as a terminator if set to the null string (an empty line cannot contain any spaces or tabs). You may set it to a multi-character string to match a multi-character terminator, or to `undef` to read through the end of file. Setting it to `"\n\n"` means something slightly different than setting to `""`, if the file contains consecutive empty lines. Setting to `""` will treat two or more consecutive empty lines as a single empty line. Setting to `"\n\n"` will blindly assume that the next input character belongs to the next paragraph, even if it's a newline.
```
local $/; # enable "slurp" mode
local $_ = <FH>; # whole file now here
s/\n[ \t]+/ /g;
```
Remember: the value of `$/` is a string, not a regex. **awk** has to be better for something. :-)
Setting `$/` to an empty string -- the so-called *paragraph mode* -- merits special attention. When `$/` is set to `""` and the entire file is read in with that setting, any sequence of one or more consecutive newlines at the beginning of the file is discarded. With the exception of the final record in the file, each sequence of characters ending in two or more newlines is treated as one record and is read in to end in exactly two newlines. If the last record in the file ends in zero or one consecutive newlines, that record is read in with that number of newlines. If the last record ends in two or more consecutive newlines, it is read in with two newlines like all preceding records.
Suppose we wrote the following string to a file:
```
my $string = "\n\n\n";
$string .= "alpha beta\ngamma delta\n\n\n";
$string .= "epsilon zeta eta\n\n";
$string .= "theta\n";
my $file = 'simple_file.txt';
open my $OUT, '>', $file or die;
print $OUT $string;
close $OUT or die;
```
Now we read that file in paragraph mode:
```
local $/ = ""; # paragraph mode
open my $IN, '<', $file or die;
my @records = <$IN>;
close $IN or die;
```
`@records` will consist of these 3 strings:
```
(
"alpha beta\ngamma delta\n\n",
"epsilon zeta eta\n\n",
"theta\n",
)
```
Setting `$/` to a reference to an integer, scalar containing an integer, or scalar that's convertible to an integer will attempt to read records instead of lines, with the maximum record size being the referenced integer number of characters. So this:
```
local $/ = \32768; # or \"32768", or \$var_containing_32768
open my $fh, "<", $myfile or die $!;
local $_ = <$fh>;
```
will read a record of no more than 32768 characters from $fh. If you're not reading from a record-oriented file (or your OS doesn't have record-oriented files), then you'll likely get a full chunk of data with every read. If a record is larger than the record size you've set, you'll get the record back in pieces. Trying to set the record size to zero or less is deprecated and will cause $/ to have the value of "undef", which will cause reading in the (rest of the) whole file.
As of 5.19.9 setting `$/` to any other form of reference will throw a fatal exception. This is in preparation for supporting new ways to set `$/` in the future.
On VMS only, record reads bypass PerlIO layers and any associated buffering, so you must not mix record and non-record reads on the same filehandle. Record mode mixes with line mode only when the same buffering layer is in use for both modes.
You cannot call `input_record_separator()` on a handle, only as a static method. See <IO::Handle>.
See also ["Newlines" in perlport](perlport#Newlines). Also see ["$."](#%24.).
Mnemonic: / delimits line boundaries when quoting poetry.
IO::Handle->output\_record\_separator( EXPR )
$OUTPUT\_RECORD\_SEPARATOR
$ORS
$\ The output record separator for the print operator. If defined, this value is printed after the last of print's arguments. Default is `undef`.
You cannot call `output_record_separator()` on a handle, only as a static method. See <IO::Handle>.
Mnemonic: you set `$\` instead of adding "\n" at the end of the print. Also, it's just like `$/`, but it's what you get "back" from Perl.
HANDLE->autoflush( EXPR )
$OUTPUT\_AUTOFLUSH
$| If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; `$|` tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under **rsh** and want to see the output as it's happening. This has no effect on input buffering. See ["getc" in perlfunc](perlfunc#getc) for that. See ["select" in perlfunc](perlfunc#select) on how to select the output channel. See also <IO::Handle>.
Mnemonic: when you want your pipes to be piping hot.
${^LAST\_FH} This read-only variable contains a reference to the last-read filehandle. This is set by `<HANDLE>`, `readline`, `tell`, `eof` and `seek`. This is the same handle that `$.` and `tell` and `eof` without arguments use. It is also the handle used when Perl appends ", <STDIN> line 1" to an error or warning message.
This variable was added in Perl v5.18.0.
####
Variables related to formats
The special variables for formats are a subset of those for filehandles. See <perlform> for more information about Perl's formats.
$ACCUMULATOR
$^A The current value of the `write()` accumulator for `format()` lines. A format contains `formline()` calls that put their result into `$^A`. After calling its format, `write()` prints out the contents of `$^A` and empties. So you never really see the contents of `$^A` unless you call `formline()` yourself and then look at it. See <perlform> and ["formline PICTURE,LIST" in perlfunc](perlfunc#formline-PICTURE%2CLIST).
IO::Handle->format\_formfeed(EXPR)
$FORMAT\_FORMFEED
$^L What formats output as a form feed. The default is `\f`.
You cannot call `format_formfeed()` on a handle, only as a static method. See <IO::Handle>.
HANDLE->format\_page\_number(EXPR)
$FORMAT\_PAGE\_NUMBER
$% The current page number of the currently selected output channel.
Mnemonic: `%` is page number in **nroff**.
HANDLE->format\_lines\_left(EXPR)
$FORMAT\_LINES\_LEFT
$- The number of lines left on the page of the currently selected output channel.
Mnemonic: lines\_on\_page - lines\_printed.
IO::Handle->format\_line\_break\_characters EXPR
$FORMAT\_LINE\_BREAK\_CHARACTERS
$: The current set of characters after which a string may be broken to fill continuation fields (starting with `^`) in a format. The default is " \n-", to break on a space, newline, or a hyphen.
You cannot call `format_line_break_characters()` on a handle, only as a static method. See <IO::Handle>.
Mnemonic: a "colon" in poetry is a part of a line.
HANDLE->format\_lines\_per\_page(EXPR)
$FORMAT\_LINES\_PER\_PAGE
$= The current page length (printable lines) of the currently selected output channel. The default is 60.
Mnemonic: = has horizontal lines.
HANDLE->format\_top\_name(EXPR)
$FORMAT\_TOP\_NAME
$^ The name of the current top-of-page format for the currently selected output channel. The default is the name of the filehandle with `_TOP` appended. For example, the default format top name for the `STDOUT` filehandle is `STDOUT_TOP`.
Mnemonic: points to top of page.
HANDLE->format\_name(EXPR)
$FORMAT\_NAME
$~ The name of the current report format for the currently selected output channel. The default format name is the same as the filehandle name. For example, the default format name for the `STDOUT` filehandle is just `STDOUT`.
Mnemonic: brother to `$^`.
###
Error Variables
The variables `$@`, `$!`, `$^E`, and `$?` contain information about different types of error conditions that may appear during execution of a Perl program. The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process. They correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively.
To illustrate the differences between these variables, consider the following Perl expression, which uses a single-quoted string. After execution of this statement, perl may have set all four special error variables:
```
eval q{
open my $pipe, "/cdrom/install |" or die $!;
my @res = <$pipe>;
close $pipe or die "bad pipe: $?, $!";
};
```
When perl executes the `eval()` expression, it translates the `open()`, `<PIPE>`, and `close` calls in the C run-time library and thence to the operating system kernel. perl sets `$!` to the C library's `errno` if one of these calls fails.
`$@` is set if the string to be `eval`-ed did not compile (this may happen if `open` or `close` were imported with bad prototypes), or if Perl code executed during evaluation `die()`d. In these cases the value of `$@` is the compile error, or the argument to `die` (which will interpolate `$!` and `$?`). (See also [Fatal](fatal), though.)
Under a few operating systems, `$^E` may contain a more verbose error indicator, such as in this case, "CDROM tray not closed." Systems that do not support extended error messages leave `$^E` the same as `$!`.
Finally, `$?` may be set to a non-0 value if the external program */cdrom/install* fails. The upper eight bits reflect specific error conditions encountered by the program (the program's `exit()` value). The lower eight bits reflect mode of failure, like signal death and core dump information. See [wait(2)](http://man.he.net/man2/wait) for details. In contrast to `$!` and `$^E`, which are set only if an error condition is detected, the variable `$?` is set on each `wait` or pipe `close`, overwriting the old value. This is more like `$@`, which on every `eval()` is always set on failure and cleared on success.
For more details, see the individual descriptions at `$@`, `$!`, `$^E`, and `$?`.
${^CHILD\_ERROR\_NATIVE} The native status returned by the last pipe close, backtick (````) command, successful call to `wait()` or `waitpid()`, or from the `system()` operator. On POSIX-like systems this value can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, and WSTOPSIG functions provided by the [POSIX](posix) module.
Under VMS this reflects the actual VMS exit status; i.e. it is the same as `$?` when the pragma `use vmsish 'status'` is in effect.
This variable was added in Perl v5.10.0.
$EXTENDED\_OS\_ERROR
$^E Error information specific to the current operating system. At the moment, this differs from `["$!"](#%24%21)` under only VMS, OS/2, and Win32 (and for MacPerl). On all other platforms, `$^E` is always just the same as `$!`.
Under VMS, `$^E` provides the VMS status value from the last system error. This is more specific information about the last system error than that provided by `$!`. This is particularly important when `$!` is set to **EVMSERR**.
Under OS/2, `$^E` is set to the error code of the last call to OS/2 API either via CRT, or directly from perl.
Under Win32, `$^E` always returns the last error information reported by the Win32 call `GetLastError()` which describes the last error from within the Win32 API. Most Win32-specific code will report errors via `$^E`. ANSI C and Unix-like calls set `errno` and so most portable Perl code will report errors via `$!`.
Caveats mentioned in the description of `["$!"](#%24%21)` generally apply to `$^E`, also.
This variable was added in Perl 5.003.
Mnemonic: Extra error explanation.
$EXCEPTIONS\_BEING\_CAUGHT
$^S Current state of the interpreter.
```
$^S State
--------- -------------------------------------
undef Parsing module, eval, or main program
true (1) Executing an eval or try block
false (0) Otherwise
```
The first state may happen in `$SIG{__DIE__}` and `$SIG{__WARN__}` handlers.
The English name $EXCEPTIONS\_BEING\_CAUGHT is slightly misleading, because the `undef` value does not indicate whether exceptions are being caught, since compilation of the main program does not catch exceptions.
This variable was added in Perl 5.004.
$WARNING
$^W The current value of the warning switch, initially true if **-w** was used, false otherwise, but directly modifiable.
See also <warnings>.
Mnemonic: related to the **-w** switch.
${^WARNING\_BITS} The current set of warning checks enabled by the `use warnings` pragma. It has the same scoping as the `$^H` and `%^H` variables. The exact values are considered internal to the <warnings> pragma and may change between versions of Perl.
Each time a statement completes being compiled, the current value of `${^WARNING_BITS}` is stored with that statement, and can later be retrieved via `(caller($level))[9]`.
This variable was added in Perl v5.6.0.
$OS\_ERROR
$ERRNO
$! When referenced, `$!` retrieves the current value of the C `errno` integer variable. If `$!` is assigned a numerical value, that value is stored in `errno`. When referenced as a string, `$!` yields the system error string corresponding to `errno`.
Many system or library calls set `errno` if they fail, to indicate the cause of failure. They usually do **not** set `errno` to zero if they succeed and may set `errno` to a non-zero value on success. This means `errno`, hence `$!`, is meaningful only *immediately* after a **failure**:
```
if (open my $fh, "<", $filename) {
# Here $! is meaningless.
...
}
else {
# ONLY here is $! meaningful.
...
# Already here $! might be meaningless.
}
# Since here we might have either success or failure,
# $! is meaningless.
```
Here, *meaningless* means that `$!` may be unrelated to the outcome of the `open()` operator. Assignment to `$!` is similarly ephemeral. It can be used immediately before invoking the `die()` operator, to set the exit value, or to inspect the system error string corresponding to error *n*, or to restore `$!` to a meaningful state.
Perl itself may set `errno` to a non-zero on failure even if no system call is performed.
Mnemonic: What just went bang?
%OS\_ERROR
%ERRNO
%! Each element of `%!` has a true value only if `$!` is set to that value. For example, `$!{ENOENT}` is true if and only if the current value of `$!` is `ENOENT`; that is, if the most recent error was "No such file or directory" (or its moral equivalent: not all operating systems give that exact error, and certainly not all languages). The specific true value is not guaranteed, but in the past has generally been the numeric value of `$!`. To check if a particular key is meaningful on your system, use `exists $!{the_key}`; for a list of legal keys, use `keys %!`. See [Errno](errno) for more information, and also see ["$!"](#%24%21).
This variable was added in Perl 5.005.
$CHILD\_ERROR
$? The status returned by the last pipe close, backtick (````) command, successful call to `wait()` or `waitpid()`, or from the `system()` operator. This is just the 16-bit status word returned by the traditional Unix `wait()` system call (or else is made up to look like it). Thus, the exit value of the subprocess is really (`$? >> 8`), and `$? & 127` gives which signal, if any, the process died from, and `$? & 128` reports whether there was a core dump.
Additionally, if the `h_errno` variable is supported in C, its value is returned via `$?` if any `gethost*()` function fails.
If you have installed a signal handler for `SIGCHLD`, the value of `$?` will usually be wrong outside that handler.
Inside an `END` subroutine `$?` contains the value that is going to be given to `exit()`. You can modify `$?` in an `END` subroutine to change the exit status of your program. For example:
```
END {
$? = 1 if $? == 255; # die would make it 255
}
```
Under VMS, the pragma `use vmsish 'status'` makes `$?` reflect the actual VMS exit status, instead of the default emulation of POSIX status; see ["$?" in perlvms](perlvms#%24%3F) for details.
Mnemonic: similar to **sh** and **ksh**.
$EVAL\_ERROR
$@ The Perl error from the last `eval` operator, i.e. the last exception that was caught. For `eval BLOCK`, this is either a runtime error message or the string or reference `die` was called with. The `eval STRING` form also catches syntax errors and other compile time exceptions.
If no error occurs, `eval` sets `$@` to the empty string.
Warning messages are not collected in this variable. You can, however, set up a routine to process warnings by setting `$SIG{__WARN__}` as described in ["%SIG"](#%25SIG).
Mnemonic: Where was the error "at"?
###
Variables related to the interpreter state
These variables provide information about the current interpreter state.
$COMPILING
$^C The current value of the flag associated with the **-c** switch. Mainly of use with **-MO=...** to allow code to alter its behavior when being compiled, such as for example to `AUTOLOAD` at compile time rather than normal, deferred loading. Setting `$^C = 1` is similar to calling `B::minus_c`.
This variable was added in Perl v5.6.0.
$DEBUGGING
$^D The current value of the debugging flags. May be read or set. Like its [command-line equivalent](perlrun#-Dletters), you can use numeric or symbolic values, e.g. `$^D = 10` or `$^D = "st"`. See ["**-D***number*" in perlrun](perlrun#-Dnumber). The contents of this variable also affects the debugger operation. See ["Debugger Internals" in perldebguts](perldebguts#Debugger-Internals).
Mnemonic: value of **-D** switch.
${^GLOBAL\_PHASE} The current phase of the perl interpreter.
Possible values are:
CONSTRUCT The `PerlInterpreter*` is being constructed via `perl_construct`. This value is mostly there for completeness and for use via the underlying C variable `PL_phase`. It's not really possible for Perl code to be executed unless construction of the interpreter is finished.
START This is the global compile-time. That includes, basically, every `BEGIN` block executed directly or indirectly from during the compile-time of the top-level program.
This phase is not called "BEGIN" to avoid confusion with `BEGIN`-blocks, as those are executed during compile-time of any compilation unit, not just the top-level program. A new, localised compile-time entered at run-time, for example by constructs as `eval "use SomeModule"` are not global interpreter phases, and therefore aren't reflected by `${^GLOBAL_PHASE}`.
CHECK Execution of any `CHECK` blocks.
INIT Similar to "CHECK", but for `INIT`-blocks, not `CHECK` blocks.
RUN The main run-time, i.e. the execution of `PL_main_root`.
END Execution of any `END` blocks.
DESTRUCT Global destruction.
Also note that there's no value for UNITCHECK-blocks. That's because those are run for each compilation unit individually, and therefore is not a global interpreter phase.
Not every program has to go through each of the possible phases, but transition from one phase to another can only happen in the order described in the above list.
An example of all of the phases Perl code can see:
```
BEGIN { print "compile-time: ${^GLOBAL_PHASE}\n" }
INIT { print "init-time: ${^GLOBAL_PHASE}\n" }
CHECK { print "check-time: ${^GLOBAL_PHASE}\n" }
{
package Print::Phase;
sub new {
my ($class, $time) = @_;
return bless \$time, $class;
}
sub DESTROY {
my $self = shift;
print "$$self: ${^GLOBAL_PHASE}\n";
}
}
print "run-time: ${^GLOBAL_PHASE}\n";
my $runtime = Print::Phase->new(
"lexical variables are garbage collected before END"
);
END { print "end-time: ${^GLOBAL_PHASE}\n" }
our $destruct = Print::Phase->new(
"package variables are garbage collected after END"
);
```
This will print out
```
compile-time: START
check-time: CHECK
init-time: INIT
run-time: RUN
lexical variables are garbage collected before END: RUN
end-time: END
package variables are garbage collected after END: DESTRUCT
```
This variable was added in Perl 5.14.0.
$^H WARNING: This variable is strictly for internal use only. Its availability, behavior, and contents are subject to change without notice.
This variable contains compile-time hints for the Perl interpreter. At the end of compilation of a BLOCK the value of this variable is restored to the value when the interpreter started to compile the BLOCK.
Each time a statement completes being compiled, the current value of `$^H` is stored with that statement, and can later be retrieved via `(caller($level))[8]`.
When perl begins to parse any block construct that provides a lexical scope (e.g., eval body, required file, subroutine body, loop body, or conditional block), the existing value of `$^H` is saved, but its value is left unchanged. When the compilation of the block is completed, it regains the saved value. Between the points where its value is saved and restored, code that executes within BEGIN blocks is free to change the value of `$^H`.
This behavior provides the semantic of lexical scoping, and is used in, for instance, the `use strict` pragma.
The contents should be an integer; different bits of it are used for different pragmatic flags. Here's an example:
```
sub add_100 { $^H |= 0x100 }
sub foo {
BEGIN { add_100() }
bar->baz($boon);
}
```
Consider what happens during execution of the BEGIN block. At this point the BEGIN block has already been compiled, but the body of `foo()` is still being compiled. The new value of `$^H` will therefore be visible only while the body of `foo()` is being compiled.
Substitution of `BEGIN { add_100() }` block with:
```
BEGIN { require strict; strict->import('vars') }
```
demonstrates how `use strict 'vars'` is implemented. Here's a conditional version of the same lexical pragma:
```
BEGIN {
require strict; strict->import('vars') if $condition
}
```
This variable was added in Perl 5.003.
%^H The `%^H` hash provides the same scoping semantic as `$^H`. This makes it useful for implementation of lexically scoped pragmas. See <perlpragma>. All the entries are stringified when accessed at runtime, so only simple values can be accommodated. This means no pointers to objects, for example.
Each time a statement completes being compiled, the current value of `%^H` is stored with that statement, and can later be retrieved via `(caller($level))[10]`.
When putting items into `%^H`, in order to avoid conflicting with other users of the hash there is a convention regarding which keys to use. A module should use only keys that begin with the module's name (the name of its main package) and a "/" character. For example, a module `Foo::Bar` should use keys such as `Foo::Bar/baz`.
This variable was added in Perl v5.6.0.
${^OPEN} An internal variable used by [PerlIO](perlio). A string in two parts, separated by a `\0` byte, the first part describes the input layers, the second part describes the output layers.
This is the mechanism that applies the lexical effects of the <open> pragma, and the main program scope effects of the `io` or `D` options for the [-C command-line switch](perlrun#-C-%5Bnumber%2Flist%5D) and [PERL\_UNICODE environment variable](perlrun#PERL_UNICODE).
The functions `accept()`, `open()`, `pipe()`, `readpipe()` (as well as the related `qx` and ``STRING`` operators), `socket()`, `socketpair()`, and `sysopen()` are affected by the lexical value of this variable. The implicit ["ARGV"](#ARGV) handle opened by `readline()` (or the related `<>` and `<<>>` operators) on passed filenames is also affected (but not if it opens `STDIN`). If this variable is not set, these functions will set the default layers as described in ["Defaults and how to override them" in PerlIO](perlio#Defaults-and-how-to-override-them).
`open()` ignores this variable (and the default layers) when called with 3 arguments and explicit layers are specified. Indirect calls to these functions via modules like <IO::Handle> are not affected as they occur in a different lexical scope. Directory handles such as opened by `opendir()` are not currently affected.
This variable was added in Perl v5.8.0.
$PERLDB
$^P The internal variable for debugging support. The meanings of the various bits are subject to change, but currently indicate:
0x01 Debug subroutine enter/exit.
0x02 Line-by-line debugging. Causes `DB::DB()` subroutine to be called for each statement executed. Also causes saving source code lines (like 0x400).
0x04 Switch off optimizations.
0x08 Preserve more data for future interactive inspections.
0x10 Keep info about source lines on which a subroutine is defined.
0x20 Start with single-step on.
0x40 Use subroutine address instead of name when reporting.
0x80 Report `goto &subroutine` as well.
0x100 Provide informative "file" names for evals based on the place they were compiled.
0x200 Provide informative names to anonymous subroutines based on the place they were compiled.
0x400 Save source code lines into `@{"_<$filename"}`.
0x800 When saving source, include evals that generate no subroutines.
0x1000 When saving source, include source that did not compile.
Some bits may be relevant at compile-time only, some at run-time only. This is a new mechanism and the details may change. See also <perldebguts>.
${^TAINT} Reflects if taint mode is on or off. 1 for on (the program was run with **-T**), 0 for off, -1 when only taint warnings are enabled (i.e. with **-t** or **-TU**).
Note: if your perl was built without taint support (see <perlsec>), then `${^TAINT}` will always be 0, even if the program was run with **-T**).
This variable is read-only.
This variable was added in Perl v5.8.0.
${^SAFE\_LOCALES} Reflects if safe locale operations are available to this perl (when the value is 1) or not (the value is 0). This variable is always 1 if the perl has been compiled without threads. It is also 1 if this perl is using thread-safe locale operations. Note that an individual thread may choose to use the global locale (generally unsafe) by calling ["switch\_to\_global\_locale" in perlapi](perlapi#switch_to_global_locale). This variable currently is still set to 1 in such threads.
This variable is read-only.
This variable was added in Perl v5.28.0.
${^UNICODE} Reflects certain Unicode settings of Perl. See [perlrun](perlrun#-C-%5Bnumber%2Flist%5D) documentation for the `-C` switch for more information about the possible values.
This variable is set during Perl startup and is thereafter read-only.
This variable was added in Perl v5.8.2.
${^UTF8CACHE} This variable controls the state of the internal UTF-8 offset caching code. 1 for on (the default), 0 for off, -1 to debug the caching code by checking all its results against linear scans, and panicking on any discrepancy.
This variable was added in Perl v5.8.9. It is subject to change or removal without notice, but is currently used to avoid recalculating the boundaries of multi-byte UTF-8-encoded characters.
${^UTF8LOCALE} This variable indicates whether a UTF-8 locale was detected by perl at startup. This information is used by perl when it's in adjust-utf8ness-to-locale mode (as when run with the `-CL` command-line switch); see [perlrun](perlrun#-C-%5Bnumber%2Flist%5D) for more info on this.
This variable was added in Perl v5.8.8.
###
Deprecated and removed variables
Deprecating a variable announces the intent of the perl maintainers to eventually remove the variable from the language. It may still be available despite its status. Using a deprecated variable triggers a warning.
Once a variable is removed, its use triggers an error telling you the variable is unsupported.
See <perldiag> for details about error messages.
$# `$#` was a variable that could be used to format printed numbers. After a deprecation cycle, its magic was removed in Perl v5.10.0 and using it now triggers a warning: `$# is no longer supported`.
This is not the sigil you use in front of an array name to get the last index, like `$#array`. That's still how you get the last index of an array in Perl. The two have nothing to do with each other.
Deprecated in Perl 5.
Removed in Perl v5.10.0.
$\* `$*` was a variable that you could use to enable multiline matching. After a deprecation cycle, its magic was removed in Perl v5.10.0. Using it now triggers a warning: `$* is no longer supported`. You should use the `/s` and `/m` regexp modifiers instead.
Deprecated in Perl 5.
Removed in Perl v5.10.0.
$[ This variable stores the index of the first element in an array, and of the first character in a substring. The default is 0, but you could theoretically set it to 1 to make Perl behave more like **awk** (or Fortran) when subscripting and when evaluating the index() and substr() functions.
As of release 5 of Perl, assignment to `$[` is treated as a compiler directive, and cannot influence the behavior of any other file. (That's why you can only assign compile-time constants to it.) Its use is highly discouraged.
Prior to Perl v5.10.0, assignment to `$[` could be seen from outer lexical scopes in the same file, unlike other compile-time directives (such as <strict>). Using local() on it would bind its value strictly to a lexical block. Now it is always lexically scoped.
As of Perl v5.16.0, it is implemented by the <arybase> module.
As of Perl v5.30.0, or under `use v5.16`, or `no feature "array_base"`, `$[` no longer has any effect, and always contains 0. Assigning 0 to it is permitted, but any other value will produce an error.
Mnemonic: [ begins subscripts.
Deprecated in Perl v5.12.0.
${^ENCODING} This variable is no longer supported.
It used to hold the *object reference* to the `Encode` object that was used to convert the source code to Unicode.
Its purpose was to allow your non-ASCII Perl scripts not to have to be written in UTF-8; this was useful before editors that worked on UTF-8 encoded text were common, but that was long ago. It caused problems, such as affecting the operation of other modules that weren't expecting it, causing general mayhem.
If you need something like this functionality, it is recommended that use you a simple source filter, such as <Filter::Encoding>.
If you are coming here because code of yours is being adversely affected by someone's use of this variable, you can usually work around it by doing this:
```
local ${^ENCODING};
```
near the beginning of the functions that are getting broken. This undefines the variable during the scope of execution of the including function.
This variable was added in Perl 5.8.2 and removed in 5.26.0. Setting it to anything other than `undef` was made fatal in Perl 5.28.0.
${^WIN32\_SLOPPY\_STAT} This variable no longer has any function.
This variable was added in Perl v5.10.0 and removed in Perl v5.34.0.
| programming_docs |
perl Net::libnetFAQ Net::libnetFAQ
==============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Where to get this document](#Where-to-get-this-document)
+ [How to contribute to this document](#How-to-contribute-to-this-document)
* [Author and Copyright Information](#Author-and-Copyright-Information)
+ [Disclaimer](#Disclaimer)
* [Obtaining and installing libnet](#Obtaining-and-installing-libnet)
+ [What is libnet ?](#What-is-libnet-?)
+ [Which version of perl do I need ?](#Which-version-of-perl-do-I-need-?)
+ [What other modules do I need ?](#What-other-modules-do-I-need-?)
+ [What machines support libnet ?](#What-machines-support-libnet-?)
+ [Where can I get the latest libnet release](#Where-can-I-get-the-latest-libnet-release)
* [Using Net::FTP](#Using-Net::FTP)
+ [How do I download files from an FTP server ?](#How-do-I-download-files-from-an-FTP-server-?)
+ [How do I transfer files in binary mode ?](#How-do-I-transfer-files-in-binary-mode-?)
+ [How can I get the size of a file on a remote FTP server ?](#How-can-I-get-the-size-of-a-file-on-a-remote-FTP-server-?)
+ [How can I get the modification time of a file on a remote FTP server ?](#How-can-I-get-the-modification-time-of-a-file-on-a-remote-FTP-server-?)
+ [How can I change the permissions of a file on a remote server ?](#How-can-I-change-the-permissions-of-a-file-on-a-remote-server-?)
+ [Can I do a reget operation like the ftp command ?](#Can-I-do-a-reget-operation-like-the-ftp-command-?)
+ [How do I get a directory listing from an FTP server ?](#How-do-I-get-a-directory-listing-from-an-FTP-server-?)
+ [Changing directory to "" does not fail ?](#Changing-directory-to-%22%22-does-not-fail-?)
+ [I am behind a SOCKS firewall, but the Firewall option does not work ?](#I-am-behind-a-SOCKS-firewall,-but-the-Firewall-option-does-not-work-?)
+ [I am behind an FTP proxy firewall, but cannot access machines outside ?](#I-am-behind-an-FTP-proxy-firewall,-but-cannot-access-machines-outside-?)
+ [My ftp proxy firewall does not listen on port 21](#My-ftp-proxy-firewall-does-not-listen-on-port-21)
+ [Is it possible to change the file permissions of a file on an FTP server ?](#Is-it-possible-to-change-the-file-permissions-of-a-file-on-an-FTP-server-?)
+ [I have seen scripts call a method message, but cannot find it documented ?](#I-have-seen-scripts-call-a-method-message,-but-cannot-find-it-documented-?)
+ [Why does Net::FTP not implement mput and mget methods](#Why-does-Net::FTP-not-implement-mput-and-mget-methods)
* [Using Net::SMTP](#Using-Net::SMTP)
+ [Why can't the part of an Email address after the @ be used as the hostname ?](#Why-can't-the-part-of-an-Email-address-after-the-@-be-used-as-the-hostname-?)
+ [Why does Net::SMTP not do DNS MX lookups ?](#Why-does-Net::SMTP-not-do-DNS-MX-lookups-?)
+ [The verify method always returns true ?](#The-verify-method-always-returns-true-?)
* [Debugging scripts](#Debugging-scripts)
+ [How can I debug my scripts that use Net::\* modules ?](#How-can-I-debug-my-scripts-that-use-Net::*-modules-?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
libnetFAQ - libnet Frequently Asked Questions
DESCRIPTION
-----------
###
Where to get this document
This document is distributed with the libnet distribution, and is also available on the libnet web page at
<https://metacpan.org/release/libnet>
###
How to contribute to this document
You may report corrections, additions, and suggestions on the CPAN Request Tracker at
<https://rt.cpan.org/Public/Bug/Report.html?Queue=libnet>
Author and Copyright Information
---------------------------------
Copyright (C) 1997-1998 Graham Barr. All rights reserved. This document is free; 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.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
### Disclaimer
This information is offered in good faith and in the hope that it may be of use, but is not guaranteed to be correct, up to date, or suitable for any particular purpose whatsoever. The authors accept no liability in respect of this information or its use.
Obtaining and installing libnet
--------------------------------
###
What is libnet ?
libnet is a collection of perl5 modules which all related to network programming. The majority of the modules available provided the client side of popular server-client protocols that are used in the internet community.
###
Which version of perl do I need ?
This version of libnet requires Perl 5.8.1 or higher.
###
What other modules do I need ?
No non-core modules are required for normal use, except on os390, which requires Convert::EBCDIC.
Authen::SASL is required for AUTH support.
IO::Socket::SSL version 2.007 or higher is required for SSL support.
IO::Socket::IP version 0.25 or IO::Socket::INET6 version 2.62 is required for IPv6 support.
###
What machines support libnet ?
libnet itself is an entirely perl-code distribution so it should work on any machine that perl runs on.
###
Where can I get the latest libnet release
The latest libnet release is always on CPAN, you will find it in
<https://metacpan.org/release/libnet>
Using Net::FTP
---------------
###
How do I download files from an FTP server ?
An example taken from an article posted to comp.lang.perl.misc
```
#!/your/path/to/perl
# a module making life easier
use Net::FTP;
# for debugging: $ftp = Net::FTP->new('site','Debug',10);
# open a connection and log in!
$ftp = Net::FTP->new('target_site.somewhere.xxx');
$ftp->login('username','password');
# set transfer mode to binary
$ftp->binary();
# change the directory on the ftp site
$ftp->cwd('/some/path/to/somewhere/');
foreach $name ('file1', 'file2', 'file3') {
# get's arguments are in the following order:
# ftp server's filename
# filename to save the transfer to on the local machine
# can be simply used as get($name) if you want the same name
$ftp->get($name,$name);
}
# ftp done!
$ftp->quit;
```
###
How do I transfer files in binary mode ?
To transfer files without <LF><CR> translation Net::FTP provides the `binary` method
```
$ftp->binary;
```
###
How can I get the size of a file on a remote FTP server ?
###
How can I get the modification time of a file on a remote FTP server ?
###
How can I change the permissions of a file on a remote server ?
The FTP protocol does not have a command for changing the permissions of a file on the remote server. But some ftp servers may allow a chmod command to be issued via a SITE command, eg
```
$ftp->quot('site chmod 0777',$filename);
```
But this is not guaranteed to work.
###
Can I do a reget operation like the ftp command ?
###
How do I get a directory listing from an FTP server ?
###
Changing directory to "" does not fail ?
Passing an argument of "" to ->cwd() has the same affect of calling ->cwd() without any arguments. Turn on Debug (*See below*) and you will see what is happening
```
$ftp = Net::FTP->new($host, Debug => 1);
$ftp->login;
$ftp->cwd("");
```
gives
```
Net::FTP=GLOB(0x82196d8)>>> CWD /
Net::FTP=GLOB(0x82196d8)<<< 250 CWD command successful.
```
###
I am behind a SOCKS firewall, but the Firewall option does not work ?
The Firewall option is only for support of one type of firewall. The type supported is an ftp proxy.
To use Net::FTP, or any other module in the libnet distribution, through a SOCKS firewall you must create a socks-ified perl executable by compiling perl with the socks library.
###
I am behind an FTP proxy firewall, but cannot access machines outside ?
Net::FTP implements the most popular ftp proxy firewall approach. The scheme implemented is that where you log in to the firewall with `user@hostname`
I have heard of one other type of firewall which requires a login to the firewall with an account, then a second login with `user@hostname`. You can still use Net::FTP to traverse these firewalls, but a more manual approach must be taken, eg
```
$ftp = Net::FTP->new($firewall) or die $@;
$ftp->login($firewall_user, $firewall_passwd) or die $ftp->message;
$ftp->login($ext_user . '@' . $ext_host, $ext_passwd) or die $ftp->message.
```
###
My ftp proxy firewall does not listen on port 21
FTP servers usually listen on the same port number, port 21, as any other FTP server. But there is no reason why this has to be the case.
If you pass a port number to Net::FTP then it assumes this is the port number of the final destination. By default Net::FTP will always try to connect to the firewall on port 21.
Net::FTP uses IO::Socket to open the connection and IO::Socket allows the port number to be specified as part of the hostname. So this problem can be resolved by either passing a Firewall option like `"hostname:1234"` or by setting the `ftp_firewall` option in Net::Config to be a string in the same form.
###
Is it possible to change the file permissions of a file on an FTP server ?
The answer to this is "maybe". The FTP protocol does not specify a command to change file permissions on a remote host. However many servers do allow you to run the chmod command via the `SITE` command. This can be done with
```
$ftp->site('chmod','0775',$file);
```
###
I have seen scripts call a method message, but cannot find it documented ?
Net::FTP, like several other packages in libnet, inherits from Net::Cmd, so all the methods described in Net::Cmd are also available on Net::FTP objects.
###
Why does Net::FTP not implement mput and mget methods
The quick answer is because they are easy to implement yourself. The long answer is that to write these in such a way that multiple platforms are supported correctly would just require too much code. Below are some examples how you can implement these yourself.
sub mput { my($ftp,$pattern) = @\_; foreach my $file (glob($pattern)) { $ftp->put($file) or warn $ftp->message; } }
sub mget { my($ftp,$pattern) = @\_; foreach my $file ($ftp->ls($pattern)) { $ftp->get($file) or warn $ftp->message; } }
Using Net::SMTP
----------------
###
Why can't the part of an Email address after the @ be used as the hostname ?
The part of an Email address which follows the @ is not necessarily a hostname, it is a mail domain. To find the name of a host to connect for a mail domain you need to do a DNS MX lookup
###
Why does Net::SMTP not do DNS MX lookups ?
Net::SMTP implements the SMTP protocol. The DNS MX lookup is not part of this protocol.
###
The verify method always returns true ?
Well it may seem that way, but it does not. The verify method returns true if the command succeeded. If you pass verify an address which the server would normally have to forward to another machine, the command will succeed with something like
```
252 Couldn't verify <someone@there> but will attempt delivery anyway
```
This command will fail only if you pass it an address in a domain the server directly delivers for, and that address does not exist.
Debugging scripts
------------------
###
How can I debug my scripts that use Net::\* modules ?
Most of the libnet client classes allow options to be passed to the constructor, in most cases one option is called `Debug`. Passing this option with a non-zero value will turn on a protocol trace, which will be sent to STDERR. This trace can be useful to see what commands are being sent to the remote server and what responses are being received back.
```
#!/your/path/to/perl
use Net::FTP;
my $ftp = new Net::FTP($host, Debug => 1);
$ftp->login('gbarr','password');
$ftp->quit;
```
this script would output something like
```
Net::FTP: Net::FTP(2.22)
Net::FTP: Exporter
Net::FTP: Net::Cmd(2.0801)
Net::FTP: IO::Socket::INET
Net::FTP: IO::Socket(1.1603)
Net::FTP: IO::Handle(1.1504)
Net::FTP=GLOB(0x8152974)<<< 220 imagine FTP server (Version wu-2.4(5) Tue Jul 29 11:17:18 CDT 1997) ready.
Net::FTP=GLOB(0x8152974)>>> user gbarr
Net::FTP=GLOB(0x8152974)<<< 331 Password required for gbarr.
Net::FTP=GLOB(0x8152974)>>> PASS ....
Net::FTP=GLOB(0x8152974)<<< 230 User gbarr logged in. Access restrictions apply.
Net::FTP=GLOB(0x8152974)>>> QUIT
Net::FTP=GLOB(0x8152974)<<< 221 Goodbye.
```
The first few lines tell you the modules that Net::FTP uses and their versions, this is useful data to me when a user reports a bug. The last seven lines show the communication with the server. Each line has three parts. The first part is the object itself, this is useful for separating the output if you are using multiple objects. The second part is either `<<<<` to show data coming from the server or `>>>>` to show data going to the server. The remainder of the line is the command being sent or response being received.
AUTHOR AND COPYRIGHT
---------------------
Copyright (C) 1997-1998 Graham Barr. All rights reserved.
perl Tie::Handle Tie::Handle
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [MORE INFORMATION](#MORE-INFORMATION)
* [COMPATIBILITY](#COMPATIBILITY)
NAME
----
Tie::Handle - 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
-----------
This module provides some skeletal methods for handle-tying classes. See <perltie> for a list of the functions required in tying a handle to a package. The basic **Tie::Handle** package provides a `new` method, as well as methods `TIEHANDLE`, `PRINT`, `PRINTF` and `GETC`.
For developers wishing to write their own tied-handle classes, the methods are summarized below. The <perltie> section not only documents these, but has sample code as well:
TIEHANDLE classname, LIST The method invoked by the command `tie *glob, classname`. Associates a new glob 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.
WRITE this, scalar, length, offset Write *length* bytes of data from *scalar* starting at *offset*.
PRINT this, LIST Print the values in *LIST*
PRINTF this, format, LIST Print the values in *LIST* using *format*
READ this, scalar, length, offset Read *length* bytes of data into *scalar* starting at *offset*.
READLINE this Read a single line
GETC this Get a single character
CLOSE this Close the handle
OPEN this, filename (Re-)open the handle
BINMODE this Specify content is binary
EOF this Test for end of file.
TELL this Return position in the file.
SEEK this, offset, whence Position the file.
Test for end of file.
DESTROY this Free the storage associated with the tied handle 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.
MORE INFORMATION
-----------------
The <perltie> section contains an example of tying handles.
COMPATIBILITY
-------------
This version of Tie::Handle is neither related to nor compatible with the Tie::Handle (3.0) module available on CPAN. It was due to an accident that two modules with the same name appeared. The namespace clash has been cleared in favor of this module that comes with the perl core in September 2000 and accordingly the version number has been bumped up to 4.0.
perl version version
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [TYPES OF VERSION OBJECTS](#TYPES-OF-VERSION-OBJECTS)
* [DECLARING VERSIONS](#DECLARING-VERSIONS)
+ [How to convert a module from decimal to dotted-decimal](#How-to-convert-a-module-from-decimal-to-dotted-decimal)
+ [How to declare() a dotted-decimal version](#How-to-declare()-a-dotted-decimal-version)
* [PARSING AND COMPARING VERSIONS](#PARSING-AND-COMPARING-VERSIONS)
+ [How to parse() a version](#How-to-parse()-a-version)
+ [How to check for a legal version string](#How-to-check-for-a-legal-version-string)
+ [How to compare version objects](#How-to-compare-version-objects)
* [OBJECT METHODS](#OBJECT-METHODS)
+ [is\_alpha()](#is_alpha())
+ [is\_qv()](#is_qv())
+ [normal()](#normal())
+ [numify()](#numify())
+ [stringify()](#stringify())
* [EXPORTED FUNCTIONS](#EXPORTED-FUNCTIONS)
+ [qv()](#qv())
+ [is\_lax()](#is_lax()1)
+ [is\_strict()](#is_strict()1)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
version - Perl extension for Version Objects
SYNOPSIS
--------
```
# Parsing version strings (decimal or dotted-decimal)
use version 0.77; # get latest bug-fixes and API
$ver = version->parse($string)
# Declaring a dotted-decimal $VERSION (keep on one line!)
use version; our $VERSION = version->declare("v1.2.3"); # formal
use version; our $VERSION = qv("v1.2.3"); # deprecated
use version; our $VERSION = qv("v1.2_3"); # deprecated
# Declaring an old-style decimal $VERSION (use quotes!)
our $VERSION = "1.0203"; # recommended
use version; our $VERSION = version->parse("1.0203"); # formal
use version; our $VERSION = version->parse("1.02_03"); # alpha
# Comparing mixed version styles (decimals, dotted-decimals, objects)
if ( version->parse($v1) == version->parse($v2) ) {
# do stuff
}
# Sorting mixed version styles
@ordered = sort { version->parse($a) <=> version->parse($b) } @list;
```
DESCRIPTION
-----------
Version objects were added to Perl in 5.10. This module implements version objects for older version of Perl and provides the version object API for all versions of Perl. All previous releases before 0.74 are deprecated and should not be used due to incompatible API changes. Version 0.77 introduces the new 'parse' and 'declare' methods to standardize usage. You are strongly urged to set 0.77 as a minimum in your code, e.g.
```
use version 0.77; # even for Perl v.5.10.0
```
TYPES OF VERSION OBJECTS
-------------------------
There are two different types of version objects, corresponding to the two different styles of versions in use:
Decimal Versions The classic floating-point number $VERSION. The advantage to this style is that you don't need to do anything special, just type a number into your source file. Quoting is recommended, as it ensures that trailing zeroes ("1.50") are preserved in any warnings or other output.
Dotted Decimal Versions The more modern form of version assignment, with 3 (or potentially more) integers separated by decimal points (e.g. v1.2.3). This is the form that Perl itself has used since 5.6.0 was released. The leading 'v' is now strongly recommended for clarity, and will throw a warning in a future release if omitted. A leading 'v' character is required to pass the ["is\_strict()"](#is_strict%28%29) test.
DECLARING VERSIONS
-------------------
If you have a module that uses a decimal $VERSION (floating point), and you do not intend to ever change that, this module is not for you. There is nothing that version.pm gains you over a simple $VERSION assignment:
```
our $VERSION = "1.02";
```
Since Perl v5.10.0 includes the version.pm comparison logic anyways, you don't need to do anything at all.
###
How to convert a module from decimal to dotted-decimal
If you have used a decimal $VERSION in the past and wish to switch to a dotted-decimal $VERSION, then you need to make a one-time conversion to the new format.
**Important Note**: you must ensure that your new $VERSION is numerically greater than your current decimal $VERSION; this is not always obvious. First, convert your old decimal version (e.g. 1.02) to a normalized dotted-decimal form:
```
$ perl -Mversion -e 'print version->parse("1.02")->normal'
v1.20.0
```
Then increment any of the dotted-decimal components (v1.20.1 or v1.21.0).
###
How to `declare()` a dotted-decimal version
```
use version; our $VERSION = version->declare("v1.2.3");
```
The `declare()` method always creates dotted-decimal version objects. When used in a module, you **must** put it on the same line as "use version" to ensure that $VERSION is read correctly by PAUSE and installer tools. You should also add 'version' to the 'configure\_requires' section of your module metadata file. See instructions in <ExtUtils::MakeMaker> or <Module::Build> for details.
**Important Note**: Even if you pass in what looks like a decimal number ("1.2"), a dotted-decimal will be created ("v1.200.0"). To avoid confusion or unintentional errors on older Perls, follow these guidelines:
* Always use a dotted-decimal with (at least) three components
* Always use a leading-v
* Always quote the version
If you really insist on using version.pm with an ordinary decimal version, use `parse()` instead of declare. See the ["PARSING AND COMPARING VERSIONS"](#PARSING-AND-COMPARING-VERSIONS) for details.
See also <version::Internals> for more on version number conversion, quoting, calculated version numbers and declaring developer or "alpha" version numbers.
PARSING AND COMPARING VERSIONS
-------------------------------
If you need to compare version numbers, but can't be sure whether they are expressed as numbers, strings, v-strings or version objects, then you should use version.pm to parse them all into objects for comparison.
###
How to `parse()` a version
The `parse()` method takes in anything that might be a version and returns a corresponding version object, doing any necessary conversion along the way.
* Dotted-decimal: bare v-strings (v1.2.3) and strings with more than one decimal point and a leading 'v' ("v1.2.3"); NOTE you can technically use a v-string or strings with a leading-v and only one decimal point (v1.2 or "v1.2"), but you will confuse both yourself and others.
* Decimal: regular decimal numbers (literal or in a string)
Some examples:
```
$variable version->parse($variable)
--------- -------------------------
1.23 v1.230.0
"1.23" v1.230.0
v1.23 v1.23.0
"v1.23" v1.23.0
"1.2.3" v1.2.3
"v1.2.3" v1.2.3
```
See <version::Internals> for more on version number conversion.
###
How to check for a legal version string
If you do not want to actually create a full blown version object, but would still like to verify that a given string meets the criteria to be parsed as a version, there are two helper functions that can be employed directly:
`is_lax()`
The lax criteria corresponds to what is currently allowed by the version parser. All of the following formats are acceptable for dotted-decimal formats strings:
```
v1.2
1.2345.6
v1.23_4
1.2345
1.2345_01
```
`is_strict()`
If you want to limit yourself to a much more narrow definition of what a version string constitutes, `is_strict()` is limited to version strings like the following list:
```
v1.234.5
2.3456
```
See <version::Internals> for details of the regular expressions that define the legal version string forms, as well as how to use those regular expressions in your own code if `is_lax()` and `is_strict()` are not sufficient for your needs.
###
How to compare version objects
Version objects overload the `cmp` and `<=>` operators. Perl automatically generates all of the other comparison operators based on those two so all the normal logical comparisons will work.
```
if ( version->parse($v1) == version->parse($v2) ) {
# do stuff
}
```
If a version object is compared against a non-version object, the non-object term will be converted to a version object using `parse()`. This may give surprising results:
```
$v1 = version->parse("v0.95.0");
$bool = $v1 < 0.94; # TRUE since 0.94 is v0.940.0
```
Always comparing to a version object will help avoid surprises:
```
$bool = $v1 < version->parse("v0.94.0"); # FALSE
```
Note that "alpha" version objects (where the version string contains a trailing underscore segment) compare as less than the equivalent version without an underscore:
```
$bool = version->parse("1.23_45") < version->parse("1.2345"); # TRUE
```
See <version::Internals> for more details on "alpha" versions.
OBJECT METHODS
---------------
###
is\_alpha()
True if and only if the version object was created with a underscore, e.g.
```
version->parse('1.002_03')->is_alpha; # TRUE
version->declare('1.2.3_4')->is_alpha; # TRUE
```
###
is\_qv()
True only if the version object is a dotted-decimal version, e.g.
```
version->parse('v1.2.0')->is_qv; # TRUE
version->declare('v1.2')->is_qv; # TRUE
qv('1.2')->is_qv; # TRUE
version->parse('1.2')->is_qv; # FALSE
```
###
normal()
Returns a string with a standard 'normalized' dotted-decimal form with a leading-v and at least 3 components.
```
version->declare('v1.2')->normal; # v1.2.0
version->parse('1.2')->normal; # v1.200.0
```
###
numify()
Returns a value representing the object in a pure decimal.
```
version->declare('v1.2')->numify; # 1.002000
version->parse('1.2')->numify; # 1.200
```
###
stringify()
Returns a string that is as close to the original representation as possible. If the original representation was a numeric literal, it will be returned the way perl would normally represent it in a string. This method is used whenever a version object is interpolated into a string.
```
version->declare('v1.2')->stringify; # v1.2
version->parse('1.200')->stringify; # 1.2
version->parse(1.02_30)->stringify; # 1.023
```
EXPORTED FUNCTIONS
-------------------
###
qv()
This function is no longer recommended for use, but is maintained for compatibility with existing code. If you do not want to have it exported to your namespace, use this form:
```
use version 0.77 ();
```
###
is\_lax()
(Not exported by default)
This function takes a scalar argument and returns a boolean value indicating whether the argument meets the "lax" rules for a version number. Leading and trailing spaces are not allowed.
###
is\_strict()
(Not exported by default)
This function takes a scalar argument and returns a boolean value indicating whether the argument meets the "strict" rules for a version number. Leading and trailing spaces are not allowed.
AUTHOR
------
John Peacock <[email protected]>
SEE ALSO
---------
<version::Internals>.
<perl>.
| programming_docs |
perl ExtUtils::MM_Any ExtUtils::MM\_Any
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Cross-platform helper methods](#Cross-platform-helper-methods)
- [os\_flavor Abstract](#os_flavor-Abstract)
- [os\_flavor\_is](#os_flavor_is)
- [can\_load\_xs](#can_load_xs)
- [can\_run](#can_run)
- [can\_redirect\_error](#can_redirect_error)
- [is\_make\_type](#is_make_type)
- [can\_dep\_space](#can_dep_space)
- [quote\_dep](#quote_dep)
- [split\_command](#split_command)
- [make\_type](#make_type)
- [stashmeta](#stashmeta)
- [echo](#echo)
- [wraplist](#wraplist)
- [maketext\_filter](#maketext_filter)
- [cd Abstract](#cd-Abstract)
- [oneliner Abstract](#oneliner-Abstract)
- [quote\_literal Abstract](#quote_literal-Abstract)
- [escape\_dollarsigns](#escape_dollarsigns)
- [escape\_all\_dollarsigns](#escape_all_dollarsigns)
- [escape\_newlines Abstract](#escape_newlines-Abstract)
- [max\_exec\_len Abstract](#max_exec_len-Abstract)
- [make](#make)
+ [Targets](#Targets)
- [all\_target](#all_target)
- [blibdirs\_target](#blibdirs_target)
- [clean (o)](#clean-(o))
- [clean\_subdirs\_target](#clean_subdirs_target)
- [dir\_target](#dir_target)
- [distdir](#distdir)
- [dist\_test](#dist_test)
- [xs\_dlsyms\_arg](#xs_dlsyms_arg)
- [xs\_dlsyms\_ext](#xs_dlsyms_ext)
- [xs\_dlsyms\_extra](#xs_dlsyms_extra)
- [xs\_dlsyms\_iterator](#xs_dlsyms_iterator)
- [xs\_make\_dlsyms](#xs_make_dlsyms)
- [dynamic (o)](#dynamic-(o))
- [makemakerdflt\_target](#makemakerdflt_target)
- [manifypods\_target](#manifypods_target)
- [metafile\_target](#metafile_target)
- [metafile\_data](#metafile_data)
- [metafile\_file](#metafile_file)
- [distmeta\_target](#distmeta_target)
- [mymeta](#mymeta)
- [write\_mymeta](#write_mymeta)
- [realclean (o)](#realclean-(o))
- [realclean\_subdirs\_target](#realclean_subdirs_target)
- [signature\_target](#signature_target)
- [distsignature\_target](#distsignature_target)
- [special\_targets](#special_targets)
+ [Init methods](#Init-methods)
- [init\_ABSTRACT](#init_ABSTRACT)
- [init\_INST](#init_INST)
- [init\_INSTALL](#init_INSTALL)
- [init\_INSTALL\_from\_PREFIX](#init_INSTALL_from_PREFIX)
- [init\_from\_INSTALL\_BASE](#init_from_INSTALL_BASE)
- [init\_VERSION Abstract](#init_VERSION-Abstract)
- [init\_tools](#init_tools)
- [init\_others](#init_others)
- [tools\_other](#tools_other)
- [init\_DIRFILESEP Abstract](#init_DIRFILESEP-Abstract)
- [init\_linker Abstract](#init_linker-Abstract)
- [init\_platform](#init_platform)
- [init\_MAKE](#init_MAKE)
+ [Tools](#Tools)
- [manifypods](#manifypods)
- [POD2MAN\_macro](#POD2MAN_macro)
- [test\_via\_harness](#test_via_harness)
- [test\_via\_script](#test_via_script)
- [tool\_autosplit](#tool_autosplit)
- [arch\_check](#arch_check)
+ [File::Spec wrappers](#File::Spec-wrappers)
- [catfile](#catfile)
+ [Misc](#Misc)
- [find\_tests](#find_tests)
- [find\_tests\_recursive](#find_tests_recursive)
- [find\_tests\_recursive\_in](#find_tests_recursive_in)
- [extra\_clean\_files](#extra_clean_files)
- [installvars](#installvars)
- [libscan](#libscan)
- [platform\_constants](#platform_constants)
- [post\_constants (o)](#post_constants-(o))
- [post\_initialize (o)](#post_initialize-(o))
- [postamble (o)](#postamble-(o))
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::MM\_Any - Platform-agnostic MM methods
SYNOPSIS
--------
```
FOR INTERNAL USE ONLY!
package ExtUtils::MM_SomeOS;
# Temporarily, you have to subclass both. Put MM_Any first.
require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
@ISA = qw(ExtUtils::MM_Any ExtUtils::Unix);
```
DESCRIPTION
-----------
**FOR INTERNAL USE ONLY!**
ExtUtils::MM\_Any is a superclass for the ExtUtils::MM\_\* set of modules. It contains methods which are either inherently cross-platform or are written in a cross-platform manner.
Subclass off of ExtUtils::MM\_Any *and* <ExtUtils::MM_Unix>. This is a temporary solution.
**THIS MAY BE TEMPORARY!**
METHODS
-------
Any methods marked *Abstract* must be implemented by subclasses.
###
Cross-platform helper methods
These are methods which help writing cross-platform code.
####
os\_flavor *Abstract*
```
my @os_flavor = $mm->os_flavor;
```
@os\_flavor is the style of operating system this is, usually corresponding to the MM\_\*.pm file we're using.
The first element of @os\_flavor is the major family (ie. Unix, Windows, VMS, OS/2, etc...) and the rest are sub families.
Some examples:
```
Cygwin98 ('Unix', 'Cygwin', 'Cygwin9x')
Windows ('Win32')
Win98 ('Win32', 'Win9x')
Linux ('Unix', 'Linux')
MacOS X ('Unix', 'Darwin', 'MacOS', 'MacOS X')
OS/2 ('OS/2')
```
This is used to write code for styles of operating system. See os\_flavor\_is() for use.
#### os\_flavor\_is
```
my $is_this_flavor = $mm->os_flavor_is($this_flavor);
my $is_this_flavor = $mm->os_flavor_is(@one_of_these_flavors);
```
Checks to see if the current operating system is one of the given flavors.
This is useful for code like:
```
if( $mm->os_flavor_is('Unix') ) {
$out = `foo 2>&1`;
}
else {
$out = `foo`;
}
```
#### can\_load\_xs
```
my $can_load_xs = $self->can_load_xs;
```
Returns true if we have the ability to load XS.
This is important because miniperl, used to build XS modules in the core, can not load XS.
#### can\_run
```
use ExtUtils::MM;
my $runnable = MM->can_run($Config{make});
```
If called in a scalar context it will return the full path to the binary you asked for if it was found, or `undef` if it was not.
If called in a list context, it will return a list of the full paths to instances of the binary where found in `PATH`, or an empty list if it was not found.
Copied from [IPC::Cmd](IPC::Cmd#%24path-%3D-can_run%28-PROGRAM-%29%3B), but modified into a method (and removed `$INSTANCES` capability).
#### can\_redirect\_error
```
$useredirect = MM->can_redirect_error;
```
True if on an OS where qx operator (or backticks) can redirect `STDERR` onto `STDOUT`.
#### is\_make\_type
```
my $is_dmake = $self->is_make_type('dmake');
```
Returns true if `$self->make` is the given type; possibilities are:
```
gmake GNU make
dmake
nmake
bsdmake BSD pmake-derived
```
#### can\_dep\_space
```
my $can_dep_space = $self->can_dep_space;
```
Returns true if `make` can handle (probably by quoting) dependencies that contain a space. Currently known true for GNU make, false for BSD pmake derivative.
#### quote\_dep
```
$text = $mm->quote_dep($text);
```
Method that protects Makefile single-value constants (mainly filenames), so that make will still treat them as single values even if they inconveniently have spaces in. If the make program being used cannot achieve such protection and the given text would need it, throws an exception.
#### split\_command
```
my @cmds = $MM->split_command($cmd, @args);
```
Most OS have a maximum command length they can execute at once. Large modules can easily generate commands well past that limit. Its necessary to split long commands up into a series of shorter commands.
`split_command` will return a series of @cmds each processing part of the args. Collectively they will process all the arguments. Each individual line in @cmds will not be longer than the $self->max\_exec\_len being careful to take into account macro expansion.
$cmd should include any switches and repeated initial arguments.
If no @args are given, no @cmds will be returned.
Pairs of arguments will always be preserved in a single command, this is a heuristic for things like pm\_to\_blib and pod2man which work on pairs of arguments. This makes things like this safe:
```
$self->split_command($cmd, %pod2man);
```
#### make\_type
Returns a suitable string describing the type of makefile being written.
#### stashmeta
```
my @recipelines = $MM->stashmeta($text, $file);
```
Generates a set of `@recipelines` which will result in the literal `$text` ending up in literal `$file` when the recipe is executed. Call it once, with all the text you want in `$file`. Make macros will not be expanded, so the locations will be fixed at configure-time, not at build-time.
#### echo
```
my @commands = $MM->echo($text);
my @commands = $MM->echo($text, $file);
my @commands = $MM->echo($text, $file, \%opts);
```
Generates a set of @commands which print the $text to a $file.
If $file is not given, output goes to STDOUT.
If $opts{append} is true the $file will be appended to rather than overwritten. Default is to overwrite.
If $opts{allow\_variables} is true, make variables of the form `$(...)` will not be escaped. Other `$` will. Default is to escape all `$`.
Example of use:
```
my $make = join '', map "\t$_\n", $MM->echo($text, $file);
```
#### wraplist
```
my $args = $mm->wraplist(@list);
```
Takes an array of items and turns them into a well-formatted list of arguments. In most cases this is simply something like:
```
FOO \
BAR \
BAZ
```
#### maketext\_filter
```
my $filter_make_text = $mm->maketext_filter($make_text);
```
The text of the Makefile is run through this method before writing to disk. It allows systems a chance to make portability fixes to the Makefile.
By default it does nothing.
This method is protected and not intended to be called outside of MakeMaker.
####
cd *Abstract*
```
my $subdir_cmd = $MM->cd($subdir, @cmds);
```
This will generate a make fragment which runs the @cmds in the given $dir. The rough equivalent to this, except cross platform.
```
cd $subdir && $cmd
```
Currently $dir can only go down one level. "foo" is fine. "foo/bar" is not. "../foo" is right out.
The resulting $subdir\_cmd has no leading tab nor trailing newline. This makes it easier to embed in a make string. For example.
```
my $make = sprintf <<'CODE', $subdir_cmd;
foo :
$(ECHO) what
%s
$(ECHO) mouche
CODE
```
####
oneliner *Abstract*
```
my $oneliner = $MM->oneliner($perl_code);
my $oneliner = $MM->oneliner($perl_code, \@switches);
```
This will generate a perl one-liner safe for the particular platform you're on based on the given $perl\_code and @switches (a -e is assumed) suitable for using in a make target. It will use the proper shell quoting and escapes.
$(PERLRUN) will be used as perl.
Any newlines in $perl\_code will be escaped. Leading and trailing newlines will be stripped. Makes this idiom much easier:
```
my $code = $MM->oneliner(<<'CODE', [...switches...]);
some code here
another line here
CODE
```
Usage might be something like:
```
# an echo emulation
$oneliner = $MM->oneliner('print "Foo\n"');
$make = '$oneliner > somefile';
```
Dollar signs in the $perl\_code will be protected from make using the `quote_literal` method, unless they are recognised as being a make variable, `$(varname)`, in which case they will be left for make to expand. Remember to quote make macros else it might be used as a bareword. For example:
```
# Assign the value of the $(VERSION_FROM) make macro to $vf.
$oneliner = $MM->oneliner('$vf = "$(VERSION_FROM)"');
```
Its currently very simple and may be expanded sometime in the figure to include more flexible code and switches.
####
quote\_literal *Abstract*
```
my $safe_text = $MM->quote_literal($text);
my $safe_text = $MM->quote_literal($text, \%options);
```
This will quote $text so it is interpreted literally in the shell.
For example, on Unix this would escape any single-quotes in $text and put single-quotes around the whole thing.
If $options{allow\_variables} is true it will leave `'$(FOO)'` make variables untouched. If false they will be escaped like any other `$`. Defaults to true.
#### escape\_dollarsigns
```
my $escaped_text = $MM->escape_dollarsigns($text);
```
Escapes stray `$` so they are not interpreted as make variables.
It lets by `$(...)`.
#### escape\_all\_dollarsigns
```
my $escaped_text = $MM->escape_all_dollarsigns($text);
```
Escapes all `$` so they are not interpreted as make variables.
####
escape\_newlines *Abstract*
```
my $escaped_text = $MM->escape_newlines($text);
```
Shell escapes newlines in $text.
####
max\_exec\_len *Abstract*
```
my $max_exec_len = $MM->max_exec_len;
```
Calculates the maximum command size the OS can exec. Effectively, this is the max size of a shell command line.
#### make
```
my $make = $MM->make;
```
Returns the make variant we're generating the Makefile for. This attempts to do some normalization on the information from %Config or the user.
### Targets
These are methods which produce make targets.
#### all\_target
Generate the default target 'all'.
#### blibdirs\_target
```
my $make_frag = $mm->blibdirs_target;
```
Creates the blibdirs target which creates all the directories we use in blib/.
The blibdirs.ts target is deprecated. Depend on blibdirs instead.
####
clean (o)
Defines the clean target.
#### clean\_subdirs\_target
```
my $make_frag = $MM->clean_subdirs_target;
```
Returns the clean\_subdirs target. This is used by the clean target to call clean on any subdirectories which contain Makefiles.
#### dir\_target
```
my $make_frag = $mm->dir_target(@directories);
```
Generates targets to create the specified directories and set its permission to PERM\_DIR.
Because depending on a directory to just ensure it exists doesn't work too well (the modified time changes too often) dir\_target() creates a .exists file in the created directory. It is this you should depend on. For portability purposes you should use the $(DIRFILESEP) macro rather than a '/' to separate the directory from the file.
```
yourdirectory$(DIRFILESEP).exists
```
#### distdir
Defines the scratch directory target that will hold the distribution before tar-ing (or shar-ing).
#### dist\_test
Defines a target that produces the distribution in the scratch directory, and runs 'perl Makefile.PL; make ;make test' in that subdirectory.
#### xs\_dlsyms\_arg
Returns command-line arg(s) to linker for file listing dlsyms to export. Defaults to returning empty string, can be overridden by e.g. AIX.
#### xs\_dlsyms\_ext
Returns file-extension for `xs_make_dlsyms` method's output file, including any "." character.
#### xs\_dlsyms\_extra
Returns any extra text to be prepended to the `$extra` argument of `xs_make_dlsyms`.
#### xs\_dlsyms\_iterator
Iterates over necessary shared objects, calling `xs_make_dlsyms` method for each with appropriate arguments.
#### xs\_make\_dlsyms
```
$self->xs_make_dlsyms(
\%attribs, # hashref from %attribs in caller
"$self->{BASEEXT}.def", # output file for Makefile target
'Makefile.PL', # dependency
$self->{NAME}, # shared object's "name"
$self->{DLBASE}, # last ::-separated part of name
$attribs{DL_FUNCS} || $self->{DL_FUNCS} || {}, # various params
$attribs{FUNCLIST} || $self->{FUNCLIST} || [],
$attribs{IMPORTS} || $self->{IMPORTS} || {},
$attribs{DL_VARS} || $self->{DL_VARS} || [],
# optional extra param that will be added as param to Mksymlists
);
```
Utility method that returns Makefile snippet to call `Mksymlists`.
####
dynamic (o)
Defines the dynamic target.
#### makemakerdflt\_target
```
my $make_frag = $mm->makemakerdflt_target
```
Returns a make fragment with the makemakerdeflt\_target specified. This target is the first target in the Makefile, is the default target and simply points off to 'all' just in case any make variant gets confused or something gets snuck in before the real 'all' target.
#### manifypods\_target
```
my $manifypods_target = $self->manifypods_target;
```
Generates the manifypods target. This target generates man pages from all POD files in MAN1PODS and MAN3PODS.
#### metafile\_target
```
my $target = $mm->metafile_target;
```
Generate the metafile target.
Writes the file META.yml (YAML encoded meta-data) and META.json (JSON encoded meta-data) about the module in the distdir. The format follows Module::Build's as closely as possible.
#### metafile\_data
```
my $metadata_hashref = $mm->metafile_data(\%meta_add, \%meta_merge);
```
Returns the data which MakeMaker turns into the META.yml file and the META.json file. It is always in version 2.0 of the format.
Values of %meta\_add will overwrite any existing metadata in those keys. %meta\_merge will be merged with them.
#### metafile\_file
```
my $meta_yml = $mm->metafile_file(@metadata_pairs);
```
Turns the @metadata\_pairs into YAML.
This method does not implement a complete YAML dumper, being limited to dump a hash with values which are strings, undef's or nested hashes and arrays of strings. No quoting/escaping is done.
#### distmeta\_target
```
my $make_frag = $mm->distmeta_target;
```
Generates the distmeta target to add META.yml and META.json to the MANIFEST in the distdir.
#### mymeta
```
my $mymeta = $mm->mymeta;
```
Generate MYMETA information as a hash either from an existing CPAN Meta file (META.json or META.yml) or from internal data.
#### write\_mymeta
```
$self->write_mymeta( $mymeta );
```
Write MYMETA information to MYMETA.json and MYMETA.yml.
####
realclean (o)
Defines the realclean target.
#### realclean\_subdirs\_target
```
my $make_frag = $MM->realclean_subdirs_target;
```
Returns the realclean\_subdirs target. This is used by the realclean target to call realclean on any subdirectories which contain Makefiles.
#### signature\_target
```
my $target = $mm->signature_target;
```
Generate the signature target.
Writes the file SIGNATURE with "cpansign -s".
#### distsignature\_target
```
my $make_frag = $mm->distsignature_target;
```
Generates the distsignature target to add SIGNATURE to the MANIFEST in the distdir.
#### special\_targets
```
my $make_frag = $mm->special_targets
```
Returns a make fragment containing any targets which have special meaning to make. For example, .SUFFIXES and .PHONY.
###
Init methods
Methods which help initialize the MakeMaker object and macros.
#### init\_ABSTRACT
```
$mm->init_ABSTRACT
```
#### init\_INST
```
$mm->init_INST;
```
Called by init\_main. Sets up all INST\_\* variables except those related to XS code. Those are handled in init\_xs.
#### init\_INSTALL
```
$mm->init_INSTALL;
```
Called by init\_main. Sets up all INSTALL\_\* variables (except INSTALLDIRS) and \*PREFIX.
#### init\_INSTALL\_from\_PREFIX
```
$mm->init_INSTALL_from_PREFIX;
```
#### init\_from\_INSTALL\_BASE
```
$mm->init_from_INSTALL_BASE
```
####
init\_VERSION *Abstract*
```
$mm->init_VERSION
```
Initialize macros representing versions of MakeMaker and other tools
MAKEMAKER: path to the MakeMaker module.
MM\_VERSION: ExtUtils::MakeMaker Version
MM\_REVISION: ExtUtils::MakeMaker version control revision (for backwards compat)
VERSION: version of your module
VERSION\_MACRO: which macro represents the version (usually 'VERSION')
VERSION\_SYM: like version but safe for use as an RCS revision number
DEFINE\_VERSION: -D line to set the module version when compiling
XS\_VERSION: version in your .xs file. Defaults to $(VERSION)
XS\_VERSION\_MACRO: which macro represents the XS version.
XS\_DEFINE\_VERSION: -D line to set the xs version when compiling.
Called by init\_main.
#### init\_tools
```
$MM->init_tools();
```
Initializes the simple macro definitions used by tools\_other() and places them in the $MM object. These use conservative cross platform versions and should be overridden with platform specific versions for performance.
Defines at least these macros.
```
Macro Description
NOOP Do nothing
NOECHO Tell make not to display the command itself
SHELL Program used to run shell commands
ECHO Print text adding a newline on the end
RM_F Remove a file
RM_RF Remove a directory
TOUCH Update a file's timestamp
TEST_F Test for a file's existence
TEST_S Test the size of a file
CP Copy a file
CP_NONEMPTY Copy a file if it is not empty
MV Move a file
CHMOD Change permissions on a file
FALSE Exit with non-zero
TRUE Exit with zero
UMASK_NULL Nullify umask
DEV_NULL Suppress all command output
```
#### init\_others
```
$MM->init_others();
```
Initializes the macro definitions having to do with compiling and linking used by tools\_other() and places them in the $MM object.
If there is no description, its the same as the parameter to WriteMakefile() documented in <ExtUtils::MakeMaker>.
#### tools\_other
```
my $make_frag = $MM->tools_other;
```
Returns a make fragment containing definitions for the macros init\_others() initializes.
####
init\_DIRFILESEP *Abstract*
```
$MM->init_DIRFILESEP;
my $dirfilesep = $MM->{DIRFILESEP};
```
Initializes the DIRFILESEP macro which is the separator between the directory and filename in a filepath. ie. / on Unix, \ on Win32 and nothing on VMS.
For example:
```
# instead of $(INST_ARCHAUTODIR)/extralibs.ld
$(INST_ARCHAUTODIR)$(DIRFILESEP)extralibs.ld
```
Something of a hack but it prevents a lot of code duplication between MM\_\* variants.
Do not use this as a separator between directories. Some operating systems use different separators between subdirectories as between directories and filenames (for example: VOLUME:[dir1.dir2]file on VMS).
####
init\_linker *Abstract*
```
$mm->init_linker;
```
Initialize macros which have to do with linking.
PERL\_ARCHIVE: path to libperl.a equivalent to be linked to dynamic extensions.
PERL\_ARCHIVE\_AFTER: path to a library which should be put on the linker command line *after* the external libraries to be linked to dynamic extensions. This may be needed if the linker is one-pass, and Perl includes some overrides for C RTL functions, such as malloc().
EXPORT\_LIST: name of a file that is passed to linker to define symbols to be exported.
Some OSes do not need these in which case leave it blank.
#### init\_platform
```
$mm->init_platform
```
Initialize any macros which are for platform specific use only.
A typical one is the version number of your OS specific module. (ie. MM\_Unix\_VERSION or MM\_VMS\_VERSION).
#### init\_MAKE
```
$mm->init_MAKE
```
Initialize MAKE from either a MAKE environment variable or $Config{make}.
### Tools
A grab bag of methods to generate specific macros and commands.
#### manifypods
Defines targets and routines to translate the pods into manpages and put them into the INST\_\* directories.
#### POD2MAN\_macro
```
my $pod2man_macro = $self->POD2MAN_macro
```
Returns a definition for the POD2MAN macro. This is a program which emulates the pod2man utility. You can add more switches to the command by simply appending them on the macro.
Typical usage:
```
$(POD2MAN) --section=3 --perm_rw=$(PERM_RW) podfile1 man_page1 ...
```
#### test\_via\_harness
```
my $command = $mm->test_via_harness($perl, $tests);
```
Returns a $command line which runs the given set of $tests with Test::Harness and the given $perl.
Used on the t/\*.t files.
#### test\_via\_script
```
my $command = $mm->test_via_script($perl, $script);
```
Returns a $command line which just runs a single test without Test::Harness. No checks are done on the results, they're just printed.
Used for test.pl, since they don't always follow Test::Harness formatting.
#### tool\_autosplit
Defines a simple perl call that runs autosplit. May be deprecated by pm\_to\_blib soon.
#### arch\_check
```
my $arch_ok = $mm->arch_check(
$INC{"Config.pm"},
File::Spec->catfile($Config{archlibexp}, "Config.pm")
);
```
A sanity check that what Perl thinks the architecture is and what Config thinks the architecture is are the same. If they're not it will return false and show a diagnostic message.
When building Perl it will always return true, as nothing is installed yet.
The interface is a bit odd because this is the result of a quick refactoring. Don't rely on it.
###
File::Spec wrappers
ExtUtils::MM\_Any is a subclass of <File::Spec>. The methods noted here override File::Spec.
#### catfile
File::Spec <= 0.83 has a bug where the file part of catfile is not canonicalized. This override fixes that bug.
### Misc
Methods I can't really figure out where they should go yet.
#### find\_tests
```
my $test = $mm->find_tests;
```
Returns a string suitable for feeding to the shell to return all tests in t/\*.t.
#### find\_tests\_recursive
```
my $tests = $mm->find_tests_recursive;
```
Returns a string suitable for feeding to the shell to return all tests in t/ but recursively. Equivalent to
```
my $tests = $mm->find_tests_recursive_in('t');
```
#### find\_tests\_recursive\_in
```
my $tests = $mm->find_tests_recursive_in($dir);
```
Returns a string suitable for feeding to the shell to return all tests in $dir recursively.
#### extra\_clean\_files
```
my @files_to_clean = $MM->extra_clean_files;
```
Returns a list of OS specific files to be removed in the clean target in addition to the usual set.
#### installvars
```
my @installvars = $mm->installvars;
```
A list of all the INSTALL\* variables without the INSTALL prefix. Useful for iteration or building related variable sets.
#### libscan
```
my $wanted = $self->libscan($path);
```
Takes a path to a file or dir and returns an empty string if we don't want to include this file in the library. Otherwise it returns the the $path unchanged.
Mainly used to exclude version control administrative directories and base-level *README.pod* from installation.
#### platform\_constants
```
my $make_frag = $mm->platform_constants
```
Returns a make fragment defining all the macros initialized in init\_platform() rather than put them in constants().
####
post\_constants (o)
Returns an empty string per default. Dedicated to overrides from within Makefile.PL after all constants have been defined.
####
post\_initialize (o)
Returns an empty string per default. Used in Makefile.PLs to add some chunk of text to the Makefile after the object is initialized.
####
postamble (o)
Returns an empty string. Can be used in Makefile.PLs to write some text to the Makefile at the end.
AUTHOR
------
Michael G Schwern <[email protected]> and the denizens of [email protected] with code from ExtUtils::MM\_Unix and ExtUtils::MM\_Win32.
| programming_docs |
perl Encode::Unicode Encode::Unicode
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [Size, Endianness, and BOM](#Size,-Endianness,-and-BOM)
+ [by size](#by-size)
+ [by endianness](#by-endianness)
* [Surrogate Pairs](#Surrogate-Pairs)
* [Error Checking](#Error-Checking)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::Unicode -- Various Unicode Transformation Formats
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$ucs2 = encode("UCS-2BE", $utf8);
$utf8 = decode("UCS-2BE", $ucs2);
```
ABSTRACT
--------
This module implements all Character Encoding Schemes of Unicode that are officially documented by Unicode Consortium (except, of course, for UTF-8, which is a native format in perl).
<http://www.unicode.org/glossary/> says: *Character Encoding Scheme* A character encoding form plus byte serialization. There are Seven character encoding schemes in Unicode: UTF-8, UTF-16, UTF-16BE, UTF-16LE, UTF-32 (UCS-4), UTF-32BE (UCS-4BE) and UTF-32LE (UCS-4LE), and UTF-7.
Since UTF-7 is a 7-bit (re)encoded version of UTF-16BE, It is not part of Unicode's Character Encoding Scheme. It is separately implemented in Encode::Unicode::UTF7. For details see <Encode::Unicode::UTF7>.
Quick Reference
```
Decodes from ord(N) Encodes chr(N) to...
octet/char BOM S.P d800-dfff ord > 0xffff \x{1abcd} ==
---------------+-----------------+------------------------------
UCS-2BE 2 N N is bogus Not Available
UCS-2LE 2 N N bogus Not Available
UTF-16 2/4 Y Y is S.P S.P BE/LE
UTF-16BE 2/4 N Y S.P S.P 0xd82a,0xdfcd
UTF-16LE 2/4 N Y S.P S.P 0x2ad8,0xcddf
UTF-32 4 Y - is bogus As is BE/LE
UTF-32BE 4 N - bogus As is 0x0001abcd
UTF-32LE 4 N - bogus As is 0xcdab0100
UTF-8 1-4 - - bogus >= 4 octets \xf0\x9a\af\8d
---------------+-----------------+------------------------------
```
Size, Endianness, and BOM
--------------------------
You can categorize these CES by 3 criteria: size of each character, endianness, and Byte Order Mark.
###
by size
UCS-2 is a fixed-length encoding with each character taking 16 bits. It **does not** support *surrogate pairs*. When a surrogate pair is encountered during decode(), its place is filled with \x{FFFD} if *CHECK* is 0, or the routine croaks if *CHECK* is 1. When a character whose ord value is larger than 0xFFFF is encountered, its place is filled with \x{FFFD} if *CHECK* is 0, or the routine croaks if *CHECK* is 1.
UTF-16 is almost the same as UCS-2 but it supports *surrogate pairs*. When it encounters a high surrogate (0xD800-0xDBFF), it fetches the following low surrogate (0xDC00-0xDFFF) and `desurrogate`s them to form a character. Bogus surrogates result in death. When \x{10000} or above is encountered during encode(), it `ensurrogate`s them and pushes the surrogate pair to the output stream.
UTF-32 (UCS-4) is a fixed-length encoding with each character taking 32 bits. Since it is 32-bit, there is no need for *surrogate pairs*.
###
by endianness
The first (and now failed) goal of Unicode was to map all character repertoires into a fixed-length integer so that programmers are happy. Since each character is either a *short* or *long* in C, you have to pay attention to the endianness of each platform when you pass data to one another.
Anything marked as BE is Big Endian (or network byte order) and LE is Little Endian (aka VAX byte order). For anything not marked either BE or LE, a character called Byte Order Mark (BOM) indicating the endianness is prepended to the string.
CAVEAT: Though BOM in utf8 (\xEF\xBB\xBF) is valid, it is meaningless and as of this writing Encode suite just leave it as is (\x{FeFF}).
BOM as integer when fetched in network byte order
```
16 32 bits/char
-------------------------
BE 0xFeFF 0x0000FeFF
LE 0xFFFe 0xFFFe0000
-------------------------
```
This modules handles the BOM as follows.
* When BE or LE is explicitly stated as the name of encoding, BOM is simply treated as a normal character (ZERO WIDTH NO-BREAK SPACE).
* When BE or LE is omitted during decode(), it checks if BOM is at the beginning of the string; if one is found, the endianness is set to what the BOM says.
* Default Byte Order
When no BOM is found, Encode 2.76 and blow croaked. Since Encode 2.77, it falls back to BE accordingly to RFC2781 and the Unicode Standard version 8.0
* When BE or LE is omitted during encode(), it returns a BE-encoded string with BOM prepended. So when you want to encode a whole text file, make sure you encode() the whole text at once, not line by line or each line, not file, will have a BOM prepended.
* `UCS-2` is an exception. Unlike others, this is an alias of UCS-2BE. UCS-2 is already registered by IANA and others that way.
Surrogate Pairs
----------------
To say the least, surrogate pairs were the biggest mistake of the Unicode Consortium. But according to the late Douglas Adams in *The Hitchhiker's Guide to the Galaxy* Trilogy, `In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move`. Their mistake was not of this magnitude so let's forgive them.
(I don't dare make any comparison with Unicode Consortium and the Vogons here ;) Or, comparing Encode to Babel Fish is completely appropriate -- if you can only stick this into your ear :)
Surrogate pairs were born when the Unicode Consortium finally admitted that 16 bits were not big enough to hold all the world's character repertoires. But they already made UCS-2 16-bit. What do we do?
Back then, the range 0xD800-0xDFFF was not allocated. Let's split that range in half and use the first half to represent the `upper half of a character` and the second half to represent the `lower half of a character`. That way, you can represent 1024 \* 1024 = 1048576 more characters. Now we can store character ranges up to \x{10ffff} even with 16-bit encodings. This pair of half-character is now called a *surrogate pair* and UTF-16 is the name of the encoding that embraces them.
Here is a formula to ensurrogate a Unicode character \x{10000} and above;
```
$hi = ($uni - 0x10000) / 0x400 + 0xD800;
$lo = ($uni - 0x10000) % 0x400 + 0xDC00;
```
And to desurrogate;
```
$uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
```
Note this move has made \x{D800}-\x{DFFF} into a forbidden zone but perl does not prohibit the use of characters within this range. To perl, every one of \x{0000\_0000} up to \x{ffff\_ffff} (\*) is *a character*.
```
(*) or \x{ffff_ffff_ffff_ffff} if your perl is compiled with 64-bit
integer support!
```
Error Checking
---------------
Unlike most encodings which accept various ways to handle errors, Unicode encodings simply croaks.
```
% perl -MEncode -e'$_ = "\xfe\xff\xd8\xd9\xda\xdb\0\n"' \
-e'Encode::from_to($_, "utf16","shift_jis", 0); print'
UTF-16:Malformed LO surrogate d8d9 at /path/to/Encode.pm line 184.
% perl -MEncode -e'$a = "BOM missing"' \
-e' Encode::from_to($a, "utf16", "shift_jis", 0); print'
UTF-16:Unrecognised BOM 424f at /path/to/Encode.pm line 184.
```
Unlike other encodings where mappings are not one-to-one against Unicode, UTFs are supposed to map 100% against one another. So Encode is more strict on UTFs.
Consider that "division by zero" of Encode :)
SEE ALSO
---------
[Encode](encode), <Encode::Unicode::UTF7>, <https://www.unicode.org/glossary/>, <https://www.unicode.org/faq/utf_bom.html>,
RFC 2781 <http://www.ietf.org/rfc/rfc2781.txt>,
The whole Unicode standard <https://www.unicode.org/standard/standard.html>
Ch. 6 pp. 275 of `Programming Perl (3rd Edition)` by Tom Christiansen, brian d foy & Larry Wall; O'Reilly & Associates; ISBN 978-0-596-00492-7
perl ok ok
==
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CC0 1.0 Universal](#CC0-1.0-Universal)
NAME
----
ok - Alternative to Test::More::use\_ok
SYNOPSIS
--------
```
use ok 'Some::Module';
```
DESCRIPTION
-----------
With this module, simply change all `use_ok` in test scripts to `use ok`, and they will be executed at `BEGIN` time.
Please see <Test::use::ok> for the full description.
CC0 1.0 Universal
------------------
To the extent possible under law, ๅ้ณณ has waived all copyright and related or neighboring rights to [Test-use-ok](test-use-ok).
This work is published from Taiwan.
<http://creativecommons.org/publicdomain/zero/1.0>
perl Compress::Raw::Zlib Compress::Raw::Zlib
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Compress::Raw::Zlib::Deflate](#Compress::Raw::Zlib::Deflate)
+ [($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] )](#(%24d,-%24status)-=-new-Compress::Raw::Zlib::Deflate(-%5BOPT%5D-))
+ [$status = $d->deflate($input, $output)](#%24status-=-%24d-%3Edeflate(%24input,-%24output))
+ [$status = $d->flush($output [, $flush\_type])](#%24status-=-%24d-%3Eflush(%24output-%5B,-%24flush_type%5D))
+ [$status = $d->deflateReset()](#%24status-=-%24d-%3EdeflateReset())
+ [$status = $d->deflateParams([OPT])](#%24status-=-%24d-%3EdeflateParams(%5BOPT%5D))
+ [$status = $d->deflateTune($good\_length, $max\_lazy, $nice\_length, $max\_chain)](#%24status-=-%24d-%3EdeflateTune(%24good_length,-%24max_lazy,-%24nice_length,-%24max_chain))
+ [$d->dict\_adler()](#%24d-%3Edict_adler())
+ [$d->crc32()](#%24d-%3Ecrc32())
+ [$d->adler32()](#%24d-%3Eadler32())
+ [$d->msg()](#%24d-%3Emsg())
+ [$d->total\_in()](#%24d-%3Etotal_in())
+ [$d->total\_out()](#%24d-%3Etotal_out())
+ [$d->get\_Strategy()](#%24d-%3Eget_Strategy())
+ [$d->get\_Level()](#%24d-%3Eget_Level())
+ [$d->get\_BufSize()](#%24d-%3Eget_BufSize())
+ [Example](#Example)
* [Compress::Raw::Zlib::Inflate](#Compress::Raw::Zlib::Inflate)
+ [($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] )](#(%24i,-%24status)-=-new-Compress::Raw::Zlib::Inflate(-%5BOPT%5D-))
+ [$status = $i->inflate($input, $output [,$eof])](#%24status-=-%24i-%3Einflate(%24input,-%24output-%5B,%24eof%5D))
+ [$status = $i->inflateSync($input)](#%24status-=-%24i-%3EinflateSync(%24input))
+ [$status = $i->inflateReset()](#%24status-=-%24i-%3EinflateReset())
+ [$i->dict\_adler()](#%24i-%3Edict_adler())
+ [$i->crc32()](#%24i-%3Ecrc32())
+ [$i->adler32()](#%24i-%3Eadler32())
+ [$i->msg()](#%24i-%3Emsg())
+ [$i->total\_in()](#%24i-%3Etotal_in())
+ [$i->total\_out()](#%24i-%3Etotal_out())
+ [$d->get\_BufSize()](#%24d-%3Eget_BufSize()1)
+ [Examples](#Examples)
* [CHECKSUM FUNCTIONS](#CHECKSUM-FUNCTIONS)
* [Misc](#Misc)
+ [my $version = Compress::Raw::Zlib::zlib\_version();](#my-%24version-=-Compress::Raw::Zlib::zlib_version();)
+ [my $flags = Compress::Raw::Zlib::zlibCompileFlags();](#my-%24flags-=-Compress::Raw::Zlib::zlibCompileFlags();)
* [The LimitOutput option.](#The-LimitOutput-option.)
* [ACCESSING ZIP FILES](#ACCESSING-ZIP-FILES)
* [FAQ](#FAQ)
+ [Compatibility with Unix compress/uncompress.](#Compatibility-with-Unix-compress/uncompress.)
+ [Accessing .tar.Z files](#Accessing-.tar.Z-files)
+ [Zlib Library Version Support](#Zlib-Library-Version-Support)
* [CONSTANTS](#CONSTANTS)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Compress::Raw::Zlib - Low-Level Interface to zlib compression library
SYNOPSIS
--------
```
use Compress::Raw::Zlib ;
($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) ;
$status = $d->deflate($input, $output) ;
$status = $d->flush($output [, $flush_type]) ;
$d->deflateReset() ;
$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) = new Compress::Raw::Zlib::Inflate( [OPT] ) ;
$status = $i->inflate($input, $output [, $eof]) ;
$status = $i->inflateSync($input) ;
$i->inflateReset() ;
$i->dict_adler() ;
$d->crc32() ;
$d->adler32() ;
$i->total_in() ;
$i->total_out() ;
$i->msg() ;
$d->get_BufSize();
$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();
my $flags = Compress::Raw::Zlib::zlibCompileFlags();
```
DESCRIPTION
-----------
The *Compress::Raw::Zlib* module provides a Perl interface to the *zlib* compression library (see ["SEE ALSO"](#SEE-ALSO) for details about where to get *zlib*).
Compress::Raw::Zlib::Deflate
-----------------------------
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) = new Compress::Raw::Zlib::Deflate( [OPT] )**
Initialises a deflation object.
If you are familiar with the *zlib* library, it combines the features of the *zlib* functions `deflateInit`, `deflateInit2` and `deflateSetDictionary`.
If successful, it will return the initialised deflation object, `$d` and a `$status` of `Z_OK` in a list context. In scalar context it returns the deflation object, `$d`, only.
If not successful, the returned deflation object, `$d`, will be *undef* and `$status` will hold the a *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.
Below 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 compress an RFC 1950 data stream, set `WindowBits` to a positive number between 8 and 15.
To compress an RFC 1951 data stream, set `WindowBits` to `-MAX_WBITS`.
To compress an RFC 1952 data stream (i.e. gzip), set `WindowBits` to `WANT_GZIP`.
For a 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`, `Z_RLE`, `Z_FIXED` and `Z_HUFFMAN_ONLY`.
The default is `Z_DEFAULT_STRATEGY`.
**-Dictionary**
When a dictionary is specified *Compress::Raw::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 output buffer used by the `$d->deflate` and `$d->flush` methods. If the buffer has to be reallocated to increase the size, it will grow in increments of `Bufsize`.
The default buffer size is 4096.
**-AppendOutput**
This option controls how data is written to the output buffer by the `$d->deflate` and `$d->flush` methods.
If the `AppendOutput` option is set to false, the output buffers in the `$d->deflate` and `$d->flush` methods will be truncated before uncompressed data is written to them.
If the option is set to true, uncompressed data will be appended to the output buffer in the `$d->deflate` and `$d->flush` methods.
This option defaults to false.
**-CRC32**
If set to true, a crc32 checksum of the uncompressed data will be calculated. Use the `$d->crc32` method to retrieve this value.
This option defaults to false.
**-ADLER32**
If set to true, an adler32 checksum of the uncompressed data will be calculated. Use the `$d->adler32` method to retrieve this value.
This option defaults to false.
Here is an example of using the `Compress::Raw::Zlib::Deflate` optional parameter list to override the default buffer size and compression level. All other options will take their default values.
```
my $d = new Compress::Raw::Zlib::Deflate ( -Bufsize => 300,
-Level => Z_BEST_SPEED ) ;
```
###
**$status = $d->deflate($input, $output)**
Deflates the contents of `$input` and writes the compressed data to `$output`.
The `$input` and `$output` parameters can be either scalars or scalar references.
When finished, `$input` will be completely processed (assuming there were no errors). If the deflation was successful it writes the deflated data to `$output` and returns a status value of `Z_OK`.
On error, it returns a *zlib* error code.
If the `AppendOutput` option is set to true in the constructor for the `$d` object, the compressed data will be appended to `$output`. If it is false, `$output` will be truncated before any compressed data is written to it.
**Note**: This method will not necessarily write compressed data to `$output` every time it is called. So do not assume that there has been an error if the contents of `$output` is empty on returning from this method. As long as the return code from the method is `Z_OK`, the deflate has succeeded.
###
**$status = $d->flush($output [, $flush\_type])**
Typically used to finish the deflation. Any pending output will be written to `$output`.
Returns `Z_OK` if successful.
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.
If the `AppendOutput` option is set to true in the constructor for the `$d` object, the compressed data will be appended to `$output`. If it is false, `$output` will be truncated before any compressed data is written to it.
###
**$status = $d->deflateReset()**
This method will reset the deflation object `$d`. It can be used when you are compressing multiple data streams and want to use the same object to compress each of them. It should only be used once the previous data stream has been flushed successfully, i.e. a call to `$d->flush(Z_FINISH)` has returned `Z_OK`.
Returns `Z_OK` if successful.
###
**$status = $d->deflateParams([OPT])**
Change settings for the deflate object `$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`.
**-BufSize**
Sets the initial size for the output buffer used by the `$d->deflate` and `$d->flush` methods. If the buffer has to be reallocated to increase the size, it will grow in increments of `Bufsize`.
###
**$status = $d->deflateTune($good\_length, $max\_lazy, $nice\_length, $max\_chain)**
Tune the internal settings for the deflate object `$d`. This option is only available if you are running zlib 1.2.2.3 or better.
Refer to the documentation in zlib.h for instructions on how to fly `deflateTune`.
###
**$d->dict\_adler()**
Returns the adler32 value for the dictionary.
###
**$d->crc32()**
Returns the crc32 value for the uncompressed data to date.
If the `CRC32` option is not enabled in the constructor for this object, this method will always return 0;
###
**$d->adler32()**
Returns the adler32 value for the uncompressed data to date.
###
**$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.
###
**$d->get\_Strategy()**
Returns the deflation strategy currently used. Valid values are `Z_DEFAULT_STRATEGY`, `Z_FILTERED` and `Z_HUFFMAN_ONLY`.
###
**$d->get\_Level()**
Returns the compression level being used.
###
**$d->get\_BufSize()**
Returns the buffer size used to carry out the compression.
### 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::Raw::Zlib ;
binmode STDIN;
binmode STDOUT;
my $x = new Compress::Raw::Zlib::Deflate
or die "Cannot create a deflation stream\n" ;
my ($output, $status) ;
while (<>)
{
$status = $x->deflate($_, $output) ;
$status == Z_OK
or die "deflation failed\n" ;
print $output ;
}
$status = $x->flush($output) ;
$status == Z_OK
or die "deflation failed\n" ;
print $output ;
```
Compress::Raw::Zlib::Inflate
-----------------------------
This section defines an interface that allows in-memory uncompression using the *inflate* interface provided by zlib.
Here is a definition of the interface:
###
**($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] )**
Initialises an inflation object.
In a list context it returns the inflation object, `$i`, and the *zlib* status code (`$status`). In a scalar context it returns the inflation object only.
If successful, `$i` will hold the inflation object 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.
Here is a list of the valid options:
**-WindowBits**
To uncompress an RFC 1950 data stream, set `WindowBits` to a positive number between 8 and 15.
To uncompress an RFC 1951 data stream, set `WindowBits` to `-MAX_WBITS`.
To uncompress an RFC 1952 data stream (i.e. gzip), set `WindowBits` to `WANT_GZIP`.
To auto-detect and uncompress an RFC 1950 or RFC 1952 data stream (i.e. gzip), set `WindowBits` to `WANT_GZIP_OR_ZLIB`.
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 output buffer used by the `$i->inflate` method. If the output buffer in this method has to be reallocated to increase the size, it will grow in increments of `Bufsize`.
Default is 4096.
**-Dictionary**
The default is no dictionary.
**-AppendOutput**
This option controls how data is written to the output buffer by the `$i->inflate` method.
If the option is set to false, the output buffer in the `$i->inflate` method will be truncated before uncompressed data is written to it.
If the option is set to true, uncompressed data will be appended to the output buffer by the `$i->inflate` method.
This option defaults to false.
**-CRC32**
If set to true, a crc32 checksum of the uncompressed data will be calculated. Use the `$i->crc32` method to retrieve this value.
This option defaults to false.
**-ADLER32**
If set to true, an adler32 checksum of the uncompressed data will be calculated. Use the `$i->adler32` method to retrieve this value.
This option defaults to false.
**-ConsumeInput**
If set to true, this option will remove compressed data from the input buffer of the `$i->inflate` method as the inflate progresses.
This option can be useful when you are processing compressed data that is embedded in another file/buffer. In this case the data that immediately follows the compressed stream will be left in the input buffer.
This option defaults to true.
**-LimitOutput**
The `LimitOutput` option changes the behavior of the `$i->inflate` 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 value of the `Bufsize` option 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->inflate` 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.
See ["The LimitOutput option"](#The-LimitOutput-option) for a discussion on why `LimitOutput` is needed and how to use it.
Here is an example of using an optional parameter to override the default buffer size.
```
my ($i, $status) = new Compress::Raw::Zlib::Inflate( -Bufsize => 300 ) ;
```
###
**$status = $i->inflate($input, $output [,$eof])**
Inflates the complete contents of `$input` and writes the uncompressed data to `$output`. The `$input` and `$output` parameters can either be scalars or scalar references.
Returns `Z_OK` if successful and `Z_STREAM_END` if the end of the compressed data has been successfully reached.
If not successful `$status` will hold the *zlib* error code.
If the `ConsumeInput` option has been set to true when the `Compress::Raw::Zlib::Inflate` object is created, the `$input` parameter is modified by `inflate`. On completion it will contain what remains of the input buffer after inflation. In practice, this means that when the return status is `Z_OK` the `$input` parameter will contain an empty string, and when the return status is `Z_STREAM_END` the `$input` 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) and there is useful data immediately after the deflation stream.
If the `AppendOutput` option is set to true in the constructor for this object, the uncompressed data will be appended to `$output`. If it is false, `$output` will be truncated before any uncompressed data is written to it.
The `$eof` parameter needs a bit of explanation.
Prior to version 1.2.0, zlib assumed that there was at least one trailing byte immediately after the compressed data stream when it was carrying out decompression. This normally isn't a problem because the majority of zlib applications guarantee that there will be data directly after the compressed data stream. For example, both gzip (RFC 1950) and zip both define trailing data that follows the compressed data stream.
The `$eof` parameter only needs to be used if **all** of the following conditions apply
1. You are either using a copy of zlib that is older than version 1.2.0 or you want your application code to be able to run with as many different versions of zlib as possible.
2. You have set the `WindowBits` parameter to `-MAX_WBITS` in the constructor for this object, i.e. you are uncompressing a raw deflated data stream (RFC 1951).
3. There is no data immediately after the compressed data stream.
If **all** of these are the case, then you need to set the `$eof` parameter to true on the final call (and only the final call) to `$i->inflate`.
If you have built this module with zlib >= 1.2.0, the `$eof` parameter is ignored. You can still set it if you want, but it won't be used behind the scenes.
###
**$status = $i->inflateSync($input)**
This method can be used to attempt to recover good data from a compressed data stream that is partially corrupt. It scans `$input` 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 `$input` will be have all data up to the flush point removed. This data can then be passed to the `$i->inflate` method to be uncompressed.
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.
Note *full flush points* are not present by default in compressed data streams. They must have been added explicitly when the data stream was created by calling `Compress::Deflate::flush` with `Z_FULL_FLUSH`.
###
**$status = $i->inflateReset()**
This method will reset the inflation object `$i`. It can be used when you are uncompressing multiple data streams and want to use the same object to uncompress each of them.
Returns `Z_OK` if successful.
###
**$i->dict\_adler()**
Returns the adler32 value for the dictionary.
###
**$i->crc32()**
Returns the crc32 value for the uncompressed data to date.
If the `CRC32` option is not enabled in the constructor for this object, this method will always return 0;
###
**$i->adler32()**
Returns the adler32 value for the uncompressed data to date.
If the `ADLER32` option is not enabled in the constructor for this object, this method will always return 0;
###
**$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.
###
**$d->get\_BufSize()**
Returns the buffer size used to carry out the decompression.
### Examples
Here is an example of using `inflate`.
```
use strict ;
use warnings ;
use Compress::Raw::Zlib;
my $x = new Compress::Raw::Zlib::Inflate()
or die "Cannot create a inflation stream\n" ;
my $input = '' ;
binmode STDIN;
binmode STDOUT;
my ($output, $status) ;
while (read(STDIN, $input, 4096))
{
$status = $x->inflate($input, $output) ;
print $output ;
last if $status != Z_OK ;
}
die "inflation failed\n"
unless $status == Z_STREAM_END ;
```
The next example show how to use the `LimitOutput` option. Notice the use of two nested loops in this case. The outer loop reads the data from the input source - STDIN and the inner loop repeatedly calls `inflate` until `$input` is exhausted, we get an error, or the end of the stream is reached. One point worth remembering is by using the `LimitOutput` option you also get `ConsumeInput` set as well - this makes the code below much simpler.
```
use strict ;
use warnings ;
use Compress::Raw::Zlib;
my $x = new Compress::Raw::Zlib::Inflate(LimitOutput => 1)
or die "Cannot create a inflation stream\n" ;
my $input = '' ;
binmode STDIN;
binmode STDOUT;
my ($output, $status) ;
OUTER:
while (read(STDIN, $input, 4096))
{
do
{
$status = $x->inflate($input, $output) ;
print $output ;
last OUTER
unless $status == Z_OK || $status == Z_BUF_ERROR ;
}
while ($status == Z_OK && length $input);
}
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::Raw::Zlib::zlib\_version();
Returns the version of the zlib library.
###
my $flags = Compress::Raw::Zlib::zlibCompileFlags();
Returns the flags indicating compile-time options that were used to build the zlib library. See the zlib documentation for a description of the flags returned by `zlibCompileFlags`.
Note that when the zlib sources are built along with this module the `sprintf` flags (bits 24, 25 and 26) should be ignored.
If you are using zlib 1.2.0 or older, `zlibCompileFlags` will return 0.
The LimitOutput option.
------------------------
By default `$i->inflate($input, $output)` will uncompress *all* data in `$input` and write *all* of the uncompressed data it has generated to `$output`. This makes the interface to `inflate` much simpler - if the method has uncompressed `$input` successfully *all* compressed data in `$input` will have been dealt with. So if you are reading from an input source and uncompressing as you go the code will look something like this
```
use strict ;
use warnings ;
use Compress::Raw::Zlib;
my $x = new Compress::Raw::Zlib::Inflate()
or die "Cannot create a inflation stream\n" ;
my $input = '' ;
my ($output, $status) ;
while (read(STDIN, $input, 4096))
{
$status = $x->inflate($input, $output) ;
print $output ;
last if $status != Z_OK ;
}
die "inflation failed\n"
unless $status == Z_STREAM_END ;
```
The points to note are
* The main processing loop in the code handles reading of compressed data from STDIN.
* The status code returned from `inflate` will only trigger termination of the main processing loop if it isn't `Z_OK`. When `LimitOutput` has not been used the `Z_OK` status means that the end of the compressed data stream has been reached or there has been an error in uncompression.
* After the call to `inflate` *all* of the uncompressed data in `$input` will have been processed. This means the subsequent call to `read` can overwrite it's contents without any problem.
For most use-cases the behavior described above is acceptable (this module and it's predecessor, `Compress::Zlib`, have used it for over 10 years without an issue), but in a few very specific use-cases the amount of memory required for `$output` can prohibitively large. For example, if the compressed data stream contains the same pattern repeated thousands of times, a relatively small compressed data stream can uncompress into hundreds of megabytes. Remember `inflate` will keep allocating memory until *all* the uncompressed data has been written to the output buffer - the size of `$output` is unbounded.
The `LimitOutput` option is designed to help with this use-case.
The main difference in your code when using `LimitOutput` is having to deal with cases where the `$input` parameter still contains some uncompressed data that `inflate` hasn't processed yet. The status code returned from `inflate` will be `Z_OK` if uncompression took place and `Z_BUF_ERROR` if the output buffer is full.
Below is typical code that shows how to use `LimitOutput`.
```
use strict ;
use warnings ;
use Compress::Raw::Zlib;
my $x = new Compress::Raw::Zlib::Inflate(LimitOutput => 1)
or die "Cannot create a inflation stream\n" ;
my $input = '' ;
binmode STDIN;
binmode STDOUT;
my ($output, $status) ;
OUTER:
while (read(STDIN, $input, 4096))
{
do
{
$status = $x->inflate($input, $output) ;
print $output ;
last OUTER
unless $status == Z_OK || $status == Z_BUF_ERROR ;
}
while ($status == Z_OK && length $input);
}
die "inflation failed\n"
unless $status == Z_STREAM_END ;
```
Points to note this time:
* There are now two nested loops in the code: the outer loop for reading the compressed data from STDIN, as before; and the inner loop to carry out the uncompression.
* There are two exit points from the inner uncompression loop.
Firstly when `inflate` has returned a status other than `Z_OK` or `Z_BUF_ERROR`. This means that either the end of the compressed data stream has been reached (`Z_STREAM_END`) or there is an error in the compressed data. In either of these cases there is no point in continuing with reading the compressed data, so both loops are terminated.
The second exit point tests if there is any data left in the input buffer, `$input` - remember that the `ConsumeInput` option is automatically enabled when `LimitOutput` is used. When the input buffer has been exhausted, the outer loop can run again and overwrite a now empty `$input`.
ACCESSING ZIP FILES
--------------------
Although it is possible (with some effort on your part) to use this module to access .zip files, there are other perl modules available that will do all the hard work for you. Check out `Archive::Zip`, `Archive::Zip::SimpleZip`, `IO::Compress::Zip` and `IO::Uncompress::Unzip`.
FAQ
---
###
Compatibility with Unix compress/uncompress.
This 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
See previous FAQ item.
If the `Archive::Tar` module is installed and either the `uncompress` or `gunzip` programs are available, you can use one of these workarounds to read `.tar.Z` files.
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 = new IO::File "| compress -c >$filename";
my $tar = Archive::Tar->new();
...
$tar->write($fh);
$fh->close ;
```
###
Zlib Library Version Support
By default `Compress::Raw::Zlib` will build with a private copy of version 1.2.5 of the zlib library. (See the *README* file for details of how to override this behaviour)
If you decide to use a different version of the zlib library, you need to be aware of the following issues
* First off, you must have zlib 1.0.5 or better.
* You need to have zlib 1.2.1 or better if you want to use the `-Merge` option with `IO::Compress::Gzip`, `IO::Compress::Deflate` and `IO::Compress::RawDeflate`.
CONSTANTS
---------
All the *zlib* constants are automatically imported when you make use of *Compress::Raw::Zlib*.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/Compress-Raw-Zlib/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=Compress-Raw-Zlib>.
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 perldbmfilter perldbmfilter
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [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.)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perldbmfilter - Perl DBM Filters
SYNOPSIS
--------
```
$db = tie %hash, 'DBM', ...
$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 { ... } );
```
DESCRIPTION
-----------
The four `filter_*` methods shown above are available in all the DBM modules that ship with Perl, namely DB\_File, GDBM\_File, NDBM\_File, ODBM\_File and SDBM\_File.
Each of the methods works identically, and is used to install (or uninstall) a single DBM Filter. 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` if 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.
DBM Filters are useful for a class of problems where you *always* want to make the same transformation to all keys, all values or both.
For example, 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 v5.36;
use SDBM_File;
use Fcntl;
my %hash;
my $filename = "filt";
unlink $filename;
my $db = tie(%hash, 'SDBM_File', $filename, O_RDWR|O_CREAT, 0640)
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 { no warnings 'uninitialized'; s/\0$// } );
$db->filter_store_value( sub { $_ .= "\0" } );
$hash{"abc"} = "def";
my $a = $hash{"ABC"};
# ...
undef $db;
untie %hash;
```
The code above uses SDBM\_File, but it will work with any of the DBM modules.
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 v5.36;
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;
```
The code above uses DB\_File, but again it will work with any of the DBM modules.
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.
SEE ALSO
---------
[DB\_File](db_file), [GDBM\_File](gdbm_file), [NDBM\_File](ndbm_file), [ODBM\_File](odbm_file) and [SDBM\_File](sdbm_file).
AUTHOR
------
Paul Marquess
perl perlhacktips perlhacktips
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [COMMON PROBLEMS](#COMMON-PROBLEMS)
+ [Perl environment problems](#Perl-environment-problems)
+ [C99](#C99)
+ [Portability problems](#Portability-problems)
+ [Problematic System Interfaces](#Problematic-System-Interfaces)
+ [Security problems](#Security-problems)
* [DEBUGGING](#DEBUGGING)
+ [Poking at Perl](#Poking-at-Perl)
+ [Using a source-level debugger](#Using-a-source-level-debugger)
+ [gdb macro support](#gdb-macro-support)
+ [Dumping Perl Data Structures](#Dumping-Perl-Data-Structures)
+ [Using gdb to look at specific parts of a program](#Using-gdb-to-look-at-specific-parts-of-a-program)
+ [Using gdb to look at what the parser/lexer are doing](#Using-gdb-to-look-at-what-the-parser/lexer-are-doing)
* [SOURCE CODE STATIC ANALYSIS](#SOURCE-CODE-STATIC-ANALYSIS)
+ [lint](#lint)
+ [Coverity](#Coverity)
+ [HP-UX cadvise (Code Advisor)](#HP-UX-cadvise-(Code-Advisor))
+ [cpd (cut-and-paste detector)](#cpd-(cut-and-paste-detector))
+ [gcc warnings](#gcc-warnings)
+ [Warnings of other C compilers](#Warnings-of-other-C-compilers)
* [MEMORY DEBUGGERS](#MEMORY-DEBUGGERS)
+ [valgrind](#valgrind)
+ [AddressSanitizer](#AddressSanitizer)
* [PROFILING](#PROFILING)
+ [Gprof Profiling](#Gprof-Profiling)
+ [GCC gcov Profiling](#GCC-gcov-Profiling)
+ [callgrind profiling](#callgrind-profiling)
* [MISCELLANEOUS TRICKS](#MISCELLANEOUS-TRICKS)
+ [PERL\_DESTRUCT\_LEVEL](#PERL_DESTRUCT_LEVEL)
+ [PERL\_MEM\_LOG](#PERL_MEM_LOG)
+ [DDD over gdb](#DDD-over-gdb)
+ [C backtrace](#C-backtrace)
+ [Poison](#Poison)
+ [Read-only optrees](#Read-only-optrees)
+ [When is a bool not a bool?](#When-is-a-bool-not-a-bool?)
+ [Finding unsafe truncations](#Finding-unsafe-truncations)
+ [The .i Targets](#The-.i-Targets)
* [AUTHOR](#AUTHOR)
NAME
----
perlhacktips - Tips for Perl core C code hacking
DESCRIPTION
-----------
This document will help you learn the best way to go about hacking on the Perl core C code. It covers common problems, debugging, profiling, and more.
If you haven't read <perlhack> and <perlhacktut> yet, you might want to do that first.
COMMON PROBLEMS
----------------
Perl source now permits some specific C99 features which we know are supported by all platforms, but mostly plays by ANSI C89 rules. You don't care about some particular platform having broken Perl? I hear there is still a strong demand for J2EE programmers.
###
Perl environment problems
* Not compiling with threading
Compiling with threading (-Duseithreads) completely rewrites the function prototypes of Perl. You better try your changes with that. Related to this is the difference between "Perl\_-less" and "Perl\_-ly" APIs, for example:
```
Perl_sv_setiv(aTHX_ ...);
sv_setiv(...);
```
The first one explicitly passes in the context, which is needed for e.g. threaded builds. The second one does that implicitly; do not get them mixed. If you are not passing in a aTHX\_, you will need to do a dTHX as the first thing in the function.
See ["How multiple interpreters and concurrency are supported" in perlguts](perlguts#How-multiple-interpreters-and-concurrency-are-supported) for further discussion about context.
* Not compiling with -DDEBUGGING
The DEBUGGING define exposes more code to the compiler, therefore more ways for things to go wrong. You should try it.
* Introducing (non-read-only) globals
Do not introduce any modifiable globals, truly global or file static. They are bad form and complicate multithreading and other forms of concurrency. The right way is to introduce them as new interpreter variables, see *intrpvar.h* (at the very end for binary compatibility).
Introducing read-only (const) globals is okay, as long as you verify with e.g. `nm libperl.a|egrep -v ' [TURtr] '` (if your `nm` has BSD-style output) that the data you added really is read-only. (If it is, it shouldn't show up in the output of that command.)
If you want to have static strings, make them constant:
```
static const char etc[] = "...";
```
If you want to have arrays of constant strings, note carefully the right combination of `const`s:
```
static const char * const yippee[] =
{"hi", "ho", "silver"};
```
* Not exporting your new function
Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any function that is part of the public API (the shared Perl library) to be explicitly marked as exported. See the discussion about *embed.pl* in <perlguts>.
* Exporting your new function
The new shiny result of either genuine new functionality or your arduous refactoring is now ready and correctly exported. So what could possibly go wrong?
Maybe simply that your function did not need to be exported in the first place. Perl has a long and not so glorious history of exporting functions that it should not have.
If the function is used only inside one source code file, make it static. See the discussion about *embed.pl* in <perlguts>.
If the function is used across several files, but intended only for Perl's internal use (and this should be the common case), do not export it to the public API. See the discussion about *embed.pl* in <perlguts>.
### C99
Starting from 5.35.5 we now permit some C99 features in the core C source. However, code in dual life extensions still needs to be C89 only, because it needs to compile against earlier version of Perl running on older platforms. Also note that our headers need to also be valid as C++, because XS extensions written in C++ need to include them, hence *member structure initialisers* can't be used in headers.
C99 support is still far from complete on all platforms we currently support. As a baseline we can only assume C89 semantics with the specific C99 features described below, which we've verified work everywhere. It's fine to probe for additional C99 features and use them where available, providing there is also a fallback for compilers that don't support the feature. For example, we use C11 thread local storage when available, but fall back to POSIX thread specific APIs otherwise, and we use `char` for booleans if `<stdbool.h>` isn't available.
Code can use (and rely on) the following C99 features being present
* mixed declarations and code
* 64 bit integer types
For consistency with the existing source code, use the typedefs `I64` and `U64`, instead of using `long long` and `unsigned long long` directly.
* variadic macros
```
void greet(char *file, unsigned int line, char *format, ...);
#define logged_greet(...) greet(__FILE__, __LINE__, __VA_ARGS__);
```
Note that `__VA_OPT__` is a gcc extension not yet in any published standard.
* declarations in for loops
```
for (const char *p = message; *p; ++p) {
putchar(*p);
}
```
* member structure initialisers
But not in headers, as support was only added to C++ relatively recently.
Hence this is fine in C and XS code, but not headers:
```
struct message {
char *action;
char *target;
};
struct message mcguffin = {
.target = "member structure initialisers",
.action = "Built"
};
```
* flexible array members
This is standards conformant:
```
struct greeting {
unsigned int len;
char message[];
};
```
However, the source code already uses the "unwarranted chumminess with the compiler" hack in many places:
```
struct greeting {
unsigned int len;
char message[1];
};
```
Strictly it **is** undefined behaviour accessing beyond `message[0]`, but this has been a commonly used hack since K&R times, and using it hasn't been a practical issue anywhere (in the perl source or any other common C code). Hence it's unclear what we would gain from actively changing to the C99 approach.
* `//` comments
All compilers we tested support their use. Not all humans we tested support their use.
Code explicitly should not use any other C99 features. For example
* variable length arrays
Not supported by **any** MSVC, and this is not going to change.
Even "variable" length arrays where the variable is a constant expression are syntax errors under MSVC.
* C99 types in `<stdint.h>`
Use `PERL_INT_FAST8_T` etc as defined in *handy.h*
* C99 format strings in `<inttypes.h>`
`snprintf` in the VMS libc only added support for `PRIdN` etc very recently, meaning that there are live supported installations without this, or formats such as `%zu`.
(perl's `sv_catpvf` etc use parser code code in `sv.c`, which supports the `z` modifier, along with perl-specific formats such as `SVf`.)
If you want to use a C99 feature not listed above then you need to do one of
* Probe for it in *Configure*, set a variable in *config.sh*, and add fallback logic in the headers for platforms which don't have it.
* Write test code and verify that it works on platforms we need to support, before relying on it unconditionally.
Likely you want to repeat the same plan as we used to get the current C99 feature set. See the message at https://markmail.org/thread/odr4fjrn72u2fkpz for the C99 probes we used before. Note that the two most "fussy" compilers appear to be MSVC and the vendor compiler on VMS. To date all the \*nix compilers have been far more flexible in what they support.
On \*nix platforms, *Configure* attempts to set compiler flags appropriately. All vendor compilers that we tested defaulted to C99 (or C11) support. However, older versions of gcc default to C89, or permit *most* C99 (with warnings), but forbid *declarations in for loops* unless `-std=gnu99` is added. The alternative `-std=c99` **might** seem better, but using it on some platforms can prevent `<unistd.h>` declaring some prototypes being declared, which breaks the build. gcc's `-ansi` flag implies `-std=c89` so we can no longer set that, hence the Configure option `-gccansipedantic` now only adds `-pedantic`.
The Perl core source code files (the ones at the top level of the source code distribution) are automatically compiled with as many as possible of the `-std=gnu99`, `-pedantic`, and a selection of `-W` flags (see cflags.SH). Files in *ext/* *dist/* *cpan/* etc are compiled with the same flags as the installed perl would use to compile XS extensions.
Basically, it's safe to assume that *Configure* and *cflags.SH* have picked the best combination of flags for the version of gcc on the platform, and attempting to add more flags related to enforcing a C dialect will cause problems either locally, or on other systems that the code is shipped to.
We believe that the C99 support in gcc 3.1 is good enough for us, but we don't have a 19 year old gcc handy to check this :-) If you have ancient vendor compilers that don't default to C99, the flags you might want to try are
AIX `-qlanglvl=stdc99`
HP/UX `-AC99`
Solaris `-xc99`
###
Portability problems
The following are common causes of compilation and/or execution failures, not common to Perl as such. The C FAQ is good bedtime reading. Please test your changes with as many C compilers and platforms as possible; we will, anyway, and it's nice to save oneself from public embarrassment.
Also study <perlport> carefully to avoid any bad assumptions about the operating system, filesystems, character set, and so forth.
Do not assume an operating system indicates a certain compiler.
* Casting pointers to integers or casting integers to pointers
```
void castaway(U8* p)
{
IV i = p;
```
or
```
void castaway(U8* p)
{
IV i = (IV)p;
```
Both are bad, and broken, and unportable. Use the PTR2IV() macro that does it right. (Likewise, there are PTR2UV(), PTR2NV(), INT2PTR(), and NUM2PTR().)
* Casting between function pointers and data pointers
Technically speaking casting between function pointers and data pointers is unportable and undefined, but practically speaking it seems to work, but you should use the FPTR2DPTR() and DPTR2FPTR() macros. Sometimes you can also play games with unions.
* Assuming sizeof(int) == sizeof(long)
There are platforms where longs are 64 bits, and platforms where ints are 64 bits, and while we are out to shock you, even platforms where shorts are 64 bits. This is all legal according to the C standard. (In other words, "long long" is not a portable way to specify 64 bits, and "long long" is not even guaranteed to be any wider than "long".)
Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth. Avoid things like I32 because they are **not** guaranteed to be *exactly* 32 bits, they are *at least* 32 bits, nor are they guaranteed to be **int** or **long**. If you explicitly need 64-bit variables, use I64 and U64.
* Assuming one can dereference any type of pointer for any type of data
```
char *p = ...;
long pony = *(long *)p; /* BAD */
```
Many platforms, quite rightly so, will give you a core dump instead of a pony if the p happens not to be correctly aligned.
* Lvalue casts
```
(int)*p = ...; /* BAD */
```
Simply not portable. Get your lvalue to be of the right type, or maybe use temporary variables, or dirty tricks with unions.
* Assume **anything** about structs (especially the ones you don't control, like the ones coming from the system headers)
+ That a certain field exists in a struct
+ That no other fields exist besides the ones you know of
+ That a field is of certain signedness, sizeof, or type
+ That the fields are in a certain order
- While C guarantees the ordering specified in the struct definition, between different platforms the definitions might differ
+ That the sizeof(struct) or the alignments are the same everywhere
- There might be padding bytes between the fields to align the fields - the bytes can be anything
- Structs are required to be aligned to the maximum alignment required by the fields - which for native types is for usually equivalent to sizeof() of the field
* Assuming the character set is ASCIIish
Perl can compile and run under EBCDIC platforms. See <perlebcdic>. This is transparent for the most part, but because the character sets differ, you shouldn't use numeric (decimal, octal, nor hex) constants to refer to characters. You can safely say `'A'`, but not `0x41`. You can safely say `'\n'`, but not `\012`. However, you can use macros defined in *utf8.h* to specify any code point portably. `LATIN1_TO_NATIVE(0xDF)` is going to be the code point that means LATIN SMALL LETTER SHARP S on whatever platform you are running on (on ASCII platforms it compiles without adding any extra code, so there is zero performance hit on those). The acceptable inputs to `LATIN1_TO_NATIVE` are from `0x00` through `0xFF`. If your input isn't guaranteed to be in that range, use `UNICODE_TO_NATIVE` instead. `NATIVE_TO_LATIN1` and `NATIVE_TO_UNICODE` translate the opposite direction.
If you need the string representation of a character that doesn't have a mnemonic name in C, you should add it to the list in *regen/unicode\_constants.pl*, and have Perl create `#define`'s for you, based on the current platform.
Note that the `is*FOO*` and `to*FOO*` macros in *handy.h* work properly on native code points and strings.
Also, the range 'A' - 'Z' in ASCII is an unbroken sequence of 26 upper case alphabetic characters. That is not true in EBCDIC. Nor for 'a' to 'z'. But '0' - '9' is an unbroken range in both systems. Don't assume anything about other ranges. (Note that special handling of ranges in regular expression patterns and transliterations makes it appear to Perl code that the aforementioned ranges are all unbroken.)
Many of the comments in the existing code ignore the possibility of EBCDIC, and may be wrong therefore, even if the code works. This is actually a tribute to the successful transparent insertion of being able to handle EBCDIC without having to change pre-existing code.
UTF-8 and UTF-EBCDIC are two different encodings used to represent Unicode code points as sequences of bytes. Macros with the same names (but different definitions) in *utf8.h* and *utfebcdic.h* are used to allow the calling code to think that there is only one such encoding. This is almost always referred to as `utf8`, but it means the EBCDIC version as well. Again, comments in the code may well be wrong even if the code itself is right. For example, the concept of UTF-8 `invariant characters` differs between ASCII and EBCDIC. On ASCII platforms, only characters that do not have the high-order bit set (i.e. whose ordinals are strict ASCII, 0 - 127) are invariant, and the documentation and comments in the code may assume that, often referring to something like, say, `hibit`. The situation differs and is not so simple on EBCDIC machines, but as long as the code itself uses the `NATIVE_IS_INVARIANT()` macro appropriately, it works, even if the comments are wrong.
As noted in ["TESTING" in perlhack](perlhack#TESTING), when writing test scripts, the file *t/charset\_tools.pl* contains some helpful functions for writing tests valid on both ASCII and EBCDIC platforms. Sometimes, though, a test can't use a function and it's inconvenient to have different test versions depending on the platform. There are 20 code points that are the same in all 4 character sets currently recognized by Perl (the 3 EBCDIC code pages plus ISO 8859-1 (ASCII/Latin1)). These can be used in such tests, though there is a small possibility that Perl will become available in yet another character set, breaking your test. All but one of these code points are C0 control characters. The most significant controls that are the same are `\0`, `\r`, and `\N{VT}` (also specifiable as `\cK`, `\x0B`, `\N{U+0B}`, or `\013`). The single non-control is U+00B6 PILCROW SIGN. The controls that are the same have the same bit pattern in all 4 character sets, regardless of the UTF8ness of the string containing them. The bit pattern for U+B6 is the same in all 4 for non-UTF8 strings, but differs in each when its containing string is UTF-8 encoded. The only other code points that have some sort of sameness across all 4 character sets are the pair 0xDC and 0xFC. Together these represent upper- and lowercase LATIN LETTER U WITH DIAERESIS, but which is upper and which is lower may be reversed: 0xDC is the capital in Latin1 and 0xFC is the small letter, while 0xFC is the capital in EBCDIC and 0xDC is the small one. This factoid may be exploited in writing case insensitive tests that are the same across all 4 character sets.
* Assuming the character set is just ASCII
ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128 extra characters have different meanings depending on the locale. Absent a locale, currently these extra characters are generally considered to be unassigned, and this has presented some problems. This has being changed starting in 5.12 so that these characters can be considered to be Latin-1 (ISO-8859-1).
* Mixing #define and #ifdef
```
#define BURGLE(x) ... \
#ifdef BURGLE_OLD_STYLE /* BAD */
... do it the old way ... \
#else
... do it the new way ... \
#endif
```
You cannot portably "stack" cpp directives. For example in the above you need two separate BURGLE() #defines, one for each #ifdef branch.
* Adding non-comment stuff after #endif or #else
```
#ifdef SNOSH
...
#else !SNOSH /* BAD */
...
#endif SNOSH /* BAD */
```
The #endif and #else cannot portably have anything non-comment after them. If you want to document what is going (which is a good idea especially if the branches are long), use (C) comments:
```
#ifdef SNOSH
...
#else /* !SNOSH */
...
#endif /* SNOSH */
```
The gcc option `-Wendif-labels` warns about the bad variant (by default on starting from Perl 5.9.4).
* Having a comma after the last element of an enum list
```
enum color {
CERULEAN,
CHARTREUSE,
CINNABAR, /* BAD */
};
```
is not portable. Leave out the last comma.
Also note that whether enums are implicitly morphable to ints varies between compilers, you might need to (int).
* Mixing signed char pointers with unsigned char pointers
```
int foo(char *s) { ... }
...
unsigned char *t = ...; /* Or U8* t = ... */
foo(t); /* BAD */
```
While this is legal practice, it is certainly dubious, and downright fatal in at least one platform: for example VMS cc considers this a fatal error. One cause for people often making this mistake is that a "naked char" and therefore dereferencing a "naked char pointer" have an undefined signedness: it depends on the compiler and the flags of the compiler and the underlying platform whether the result is signed or unsigned. For this very same reason using a 'char' as an array index is bad.
* Macros that have string constants and their arguments as substrings of the string constants
```
#define FOO(n) printf("number = %d\n", n) /* BAD */
FOO(10);
```
Pre-ANSI semantics for that was equivalent to
```
printf("10umber = %d\10");
```
which is probably not what you were expecting. Unfortunately at least one reasonably common and modern C compiler does "real backward compatibility" here, in AIX that is what still happens even though the rest of the AIX compiler is very happily C89.
* Using printf formats for non-basic C types
```
IV i = ...;
printf("i = %d\n", i); /* BAD */
```
While this might by accident work in some platform (where IV happens to be an `int`), in general it cannot. IV might be something larger. Even worse the situation is with more specific types (defined by Perl's configuration step in *config.h*):
```
Uid_t who = ...;
printf("who = %d\n", who); /* BAD */
```
The problem here is that Uid\_t might be not only not `int`-wide but it might also be unsigned, in which case large uids would be printed as negative values.
There is no simple solution to this because of printf()'s limited intelligence, but for many types the right format is available as with either 'f' or '\_f' suffix, for example:
```
IVdf /* IV in decimal */
UVxf /* UV is hexadecimal */
printf("i = %"IVdf"\n", i); /* The IVdf is a string constant. */
Uid_t_f /* Uid_t in decimal */
printf("who = %"Uid_t_f"\n", who);
```
Or you can try casting to a "wide enough" type:
```
printf("i = %"IVdf"\n", (IV)something_very_small_and_signed);
```
See ["Formatted Printing of Size\_t and SSize\_t" in perlguts](perlguts#Formatted-Printing-of-Size_t-and-SSize_t) for how to print those.
Also remember that the `%p` format really does require a void pointer:
```
U8* p = ...;
printf("p = %p\n", (void*)p);
```
The gcc option `-Wformat` scans for such problems.
* Blindly passing va\_list
Not all platforms support passing va\_list to further varargs (stdarg) functions. The right thing to do is to copy the va\_list using the Perl\_va\_copy() if the NEED\_VA\_COPY is defined.
* Using gcc statement expressions
```
val = ({...;...;...}); /* BAD */
```
While a nice extension, it's not portable. Historically, Perl used them in macros if available to gain some extra speed (essentially as a funky form of inlining), but we now support (or emulate) C99 `static inline` functions, so use them instead. Declare functions as `PERL_STATIC_INLINE` to transparently fall back to emulation where needed.
* Binding together several statements in a macro
Use the macros STMT\_START and STMT\_END.
```
STMT_START {
...
} STMT_END
```
* Testing for operating systems or versions when should be testing for features
```
#ifdef __FOONIX__ /* BAD */
foo = quux();
#endif
```
Unless you know with 100% certainty that quux() is only ever available for the "Foonix" operating system **and** that is available **and** correctly working for **all** past, present, **and** future versions of "Foonix", the above is very wrong. This is more correct (though still not perfect, because the below is a compile-time check):
```
#ifdef HAS_QUUX
foo = quux();
#endif
```
How does the HAS\_QUUX become defined where it needs to be? Well, if Foonix happens to be Unixy enough to be able to run the Configure script, and Configure has been taught about detecting and testing quux(), the HAS\_QUUX will be correctly defined. In other platforms, the corresponding configuration step will hopefully do the same.
In a pinch, if you cannot wait for Configure to be educated, or if you have a good hunch of where quux() might be available, you can temporarily try the following:
```
#if (defined(__FOONIX__) || defined(__BARNIX__))
# define HAS_QUUX
#endif
...
#ifdef HAS_QUUX
foo = quux();
#endif
```
But in any case, try to keep the features and operating systems separate.
A good resource on the predefined macros for various operating systems, compilers, and so forth is <http://sourceforge.net/p/predef/wiki/Home/>
* Assuming the contents of static memory pointed to by the return values of Perl wrappers for C library functions doesn't change. Many C library functions return pointers to static storage that can be overwritten by subsequent calls to the same or related functions. Perl has wrappers for some of these functions. Originally many of those wrappers returned those volatile pointers. But over time almost all of them have evolved to return stable copies. To cope with the remaining ones, do a ["savepv" in perlapi](perlapi#savepv) to make a copy, thus avoiding these problems. You will have to free the copy when you're done to avoid memory leaks. If you don't have control over when it gets freed, you'll need to make the copy in a mortal scalar, like so
```
SvPVX(sv_2mortal(newSVpv(volatile_string, 0)))
```
###
Problematic System Interfaces
* Perl strings are NOT the same as C strings: They may contain `NUL` characters, whereas a C string is terminated by the first `NUL`. That is why Perl API functions that deal with strings generally take a pointer to the first byte and either a length or a pointer to the byte just beyond the final one.
And this is the reason that many of the C library string handling functions should not be used. They don't cope with the full generality of Perl strings. It may be that your test cases don't have embedded `NUL`s, and so the tests pass, whereas there may well eventually arise real-world cases where they fail. A lesson here is to include `NUL`s in your tests. Now it's fairly rare in most real world cases to get `NUL`s, so your code may seem to work, until one day a `NUL` comes along.
Here's an example. It used to be a common paradigm, for decades, in the perl core to use `strchr("list", c)` to see if the character `c` is any of the ones given in `"list"`, a double-quote-enclosed string of the set of characters that we are seeing if `c` is one of. As long as `c` isn't a `NUL`, it works. But when `c` is a `NUL`, `strchr` returns a pointer to the terminating `NUL` in `"list"`. This likely will result in a segfault or a security issue when the caller uses that end pointer as the starting point to read from.
A solution to this and many similar issues is to use the `mem`*-foo* C library functions instead. In this case `memchr` can be used to see if `c` is in `"list"` and works even if `c` is `NUL`. These functions need an additional parameter to give the string length. In the case of literal string parameters, perl has defined macros that calculate the length for you. See ["String Handling" in perlapi](perlapi#String-Handling).
* malloc(0), realloc(0), calloc(0, 0) are non-portable. To be portable allocate at least one byte. (In general you should rarely need to work at this low level, but instead use the various malloc wrappers.)
* snprintf() - the return type is unportable. Use my\_snprintf() instead.
###
Security problems
Last but not least, here are various tips for safer coding. See also <perlclib> for libc/stdio replacements one should use.
* Do not use gets()
Or we will publicly ridicule you. Seriously.
* Do not use tmpfile()
Use mkstemp() instead.
* Do not use strcpy() or strcat() or strncpy() or strncat()
Use my\_strlcpy() and my\_strlcat() instead: they either use the native implementation, or Perl's own implementation (borrowed from the public domain implementation of INN).
* Do not use sprintf() or vsprintf()
If you really want just plain byte strings, use my\_snprintf() and my\_vsnprintf() instead, which will try to use snprintf() and vsnprintf() if those safer APIs are available. If you want something fancier than a plain byte string, use [`Perl_form`()](perlapi#form) or SVs and [`Perl_sv_catpvf()`](perlapi#sv_catpvf).
Note that glibc `printf()`, `sprintf()`, etc. are buggy before glibc version 2.17. They won't allow a `%.s` format with a precision to create a string that isn't valid UTF-8 if the current underlying locale of the program is UTF-8. What happens is that the `%s` and its operand are simply skipped without any notice. <https://sourceware.org/bugzilla/show_bug.cgi?id=6530>.
* Do not use atoi()
Use grok\_atoUV() instead. atoi() has ill-defined behavior on overflows, and cannot be used for incremental parsing. It is also affected by locale, which is bad.
* Do not use strtol() or strtoul()
Use grok\_atoUV() instead. strtol() or strtoul() (or their IV/UV-friendly macro disguises, Strtol() and Strtoul(), or Atol() and Atoul() are affected by locale, which is bad.
DEBUGGING
---------
You can compile a special debugging version of Perl, which allows you to use the `-D` option of Perl to tell more about what Perl is doing. But sometimes there is no alternative than to dive in with a debugger, either to see the stack trace of a core dump (very useful in a bug report), or trying to figure out what went wrong before the core dump happened, or how did we end up having wrong or unexpected results.
###
Poking at Perl
To really poke around with Perl, you'll probably want to build Perl for debugging, like this:
```
./Configure -d -DDEBUGGING
make
```
`-DDEBUGGING` turns on the C compiler's `-g` flag to have it produce debugging information which will allow us to step through a running program, and to see in which C function we are at (without the debugging information we might see only the numerical addresses of the functions, which is not very helpful). It will also turn on the `DEBUGGING` compilation symbol which enables all the internal debugging code in Perl. There are a whole bunch of things you can debug with this: [perlrun](perlrun#-Dletters) lists them all, and the best way to find out about them is to play about with them. The most useful options are probably
```
l Context (loop) stack processing
s Stack snapshots (with v, displays all stacks)
t Trace execution
o Method and overloading resolution
c String/numeric conversions
```
For example
```
$ perl -Dst -e '$a + 1'
....
(-e:1) gvsv(main::a)
=> UNDEF
(-e:1) const(IV(1))
=> UNDEF IV(1)
(-e:1) add
=> NV(1)
```
Some of the functionality of the debugging code can be achieved with a non-debugging perl by using XS modules:
```
-Dr => use re 'debug'
-Dx => use O 'Debug'
```
###
Using a source-level debugger
If the debugging output of `-D` doesn't help you, it's time to step through perl's execution with a source-level debugger.
* We'll use `gdb` for our examples here; the principles will apply to any debugger (many vendors call their debugger `dbx`), but check the manual of the one you're using.
To fire up the debugger, type
```
gdb ./perl
```
Or if you have a core dump:
```
gdb ./perl core
```
You'll want to do that in your Perl source tree so the debugger can read the source code. You should see the copyright message, followed by the prompt.
```
(gdb)
```
`help` will get you into the documentation, but here are the most useful commands:
* run [args]
Run the program with the given arguments.
* break function\_name
* break source.c:xxx
Tells the debugger that we'll want to pause execution when we reach either the named function (but see ["Internal Functions" in perlguts](perlguts#Internal-Functions)!) or the given line in the named source file.
* step
Steps through the program a line at a time.
* next
Steps through the program a line at a time, without descending into functions.
* continue
Run until the next breakpoint.
* finish
Run until the end of the current function, then stop again.
* 'enter'
Just pressing Enter will do the most recent operation again - it's a blessing when stepping through miles of source code.
* ptype
Prints the C definition of the argument given.
```
(gdb) ptype PL_op
type = struct op {
OP *op_next;
OP *op_sibparent;
OP *(*op_ppaddr)(void);
PADOFFSET op_targ;
unsigned int op_type : 9;
unsigned int op_opt : 1;
unsigned int op_slabbed : 1;
unsigned int op_savefree : 1;
unsigned int op_static : 1;
unsigned int op_folded : 1;
unsigned int op_spare : 2;
U8 op_flags;
U8 op_private;
} *
```
* print
Execute the given C code and print its results. **WARNING**: Perl makes heavy use of macros, and *gdb* does not necessarily support macros (see later ["gdb macro support"](#gdb-macro-support)). You'll have to substitute them yourself, or to invoke cpp on the source code files (see ["The .i Targets"](#The-.i-Targets)) So, for instance, you can't say
```
print SvPV_nolen(sv)
```
but you have to say
```
print Perl_sv_2pv_nolen(sv)
```
You may find it helpful to have a "macro dictionary", which you can produce by saying `cpp -dM perl.c | sort`. Even then, *cpp* won't recursively apply those macros for you.
###
gdb macro support
Recent versions of *gdb* have fairly good macro support, but in order to use it you'll need to compile perl with macro definitions included in the debugging information. Using *gcc* version 3.1, this means configuring with `-Doptimize=-g3`. Other compilers might use a different switch (if they support debugging macros at all).
###
Dumping Perl Data Structures
One way to get around this macro hell is to use the dumping functions in *dump.c*; these work a little like an internal <Devel::Peek>, but they also cover OPs and other structures that you can't get at from Perl. Let's take an example. We'll use the `$a = $b + $c` we used before, but give it a bit of context: `$b = "6XXXX"; $c = 2.3;`. Where's a good place to stop and poke around?
What about `pp_add`, the function we examined earlier to implement the `+` operator:
```
(gdb) break Perl_pp_add
Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.
```
Notice we use `Perl_pp_add` and not `pp_add` - see ["Internal Functions" in perlguts](perlguts#Internal-Functions). With the breakpoint in place, we can run our program:
```
(gdb) run -e '$b = "6XXXX"; $c = 2.3; $a = $b + $c'
```
Lots of junk will go past as gdb reads in the relevant source files and libraries, and then:
```
Breakpoint 1, Perl_pp_add () at pp_hot.c:309
1396 dSP; dATARGET; bool useleft; SV *svl, *svr;
(gdb) step
311 dPOPTOPnnrl_ul;
(gdb)
```
We looked at this bit of code before, and we said that `dPOPTOPnnrl_ul` arranges for two `NV`s to be placed into `left` and `right` - let's slightly expand it:
```
#define dPOPTOPnnrl_ul NV right = POPn; \
SV *leftsv = TOPs; \
NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0
```
`POPn` takes the SV from the top of the stack and obtains its NV either directly (if `SvNOK` is set) or by calling the `sv_2nv` function. `TOPs` takes the next SV from the top of the stack - yes, `POPn` uses `TOPs` - but doesn't remove it. We then use `SvNV` to get the NV from `leftsv` in the same way as before - yes, `POPn` uses `SvNV`.
Since we don't have an NV for `$b`, we'll have to use `sv_2nv` to convert it. If we step again, we'll find ourselves there:
```
(gdb) step
Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
1669 if (!sv)
(gdb)
```
We can now use `Perl_sv_dump` to investigate the SV:
```
(gdb) print Perl_sv_dump(sv)
SV = PV(0xa057cc0) at 0xa0675d0
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0xa06a510 "6XXXX"\0
CUR = 5
LEN = 6
$1 = void
```
We know we're going to get `6` from this, so let's finish the subroutine:
```
(gdb) finish
Run till exit from #0 Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
0x462669 in Perl_pp_add () at pp_hot.c:311
311 dPOPTOPnnrl_ul;
```
We can also dump out this op: the current op is always stored in `PL_op`, and we can dump it with `Perl_op_dump`. This'll give us similar output to CPAN module B::Debug.
```
(gdb) print Perl_op_dump(PL_op)
{
13 TYPE = add ===> 14
TARG = 1
FLAGS = (SCALAR,KIDS)
{
TYPE = null ===> (12)
(was rv2sv)
FLAGS = (SCALAR,KIDS)
{
11 TYPE = gvsv ===> 12
FLAGS = (SCALAR)
GV = main::b
}
}
```
# finish this later #
###
Using gdb to look at specific parts of a program
With the example above, you knew to look for `Perl_pp_add`, but what if there were multiple calls to it all over the place, or you didn't know what the op was you were looking for?
One way to do this is to inject a rare call somewhere near what you're looking for. For example, you could add `study` before your method:
```
study;
```
And in gdb do:
```
(gdb) break Perl_pp_study
```
And then step until you hit what you're looking for. This works well in a loop if you want to only break at certain iterations:
```
for my $c (1..100) {
study if $c == 50;
}
```
###
Using gdb to look at what the parser/lexer are doing
If you want to see what perl is doing when parsing/lexing your code, you can use `BEGIN {}`:
```
print "Before\n";
BEGIN { study; }
print "After\n";
```
And in gdb:
```
(gdb) break Perl_pp_study
```
If you want to see what the parser/lexer is doing inside of `if` blocks and the like you need to be a little trickier:
```
if ($a && $b && do { BEGIN { study } 1 } && $c) { ... }
```
SOURCE CODE STATIC ANALYSIS
----------------------------
Various tools exist for analysing C source code **statically**, as opposed to **dynamically**, that is, without executing the code. It is possible to detect resource leaks, undefined behaviour, type mismatches, portability problems, code paths that would cause illegal memory accesses, and other similar problems by just parsing the C code and looking at the resulting graph, what does it tell about the execution and data flows. As a matter of fact, this is exactly how C compilers know to give warnings about dubious code.
### lint
The good old C code quality inspector, `lint`, is available in several platforms, but please be aware that there are several different implementations of it by different vendors, which means that the flags are not identical across different platforms.
There is a `lint` target in Makefile, but you may have to diddle with the flags (see above).
### Coverity
Coverity (<http://www.coverity.com/>) is a product similar to lint and as a testbed for their product they periodically check several open source projects, and they give out accounts to open source developers to the defect databases.
There is Coverity setup for the perl5 project: <https://scan.coverity.com/projects/perl5>
###
HP-UX cadvise (Code Advisor)
HP has a C/C++ static analyzer product for HP-UX caller Code Advisor. (Link not given here because the URL is horribly long and seems horribly unstable; use the search engine of your choice to find it.) The use of the `cadvise_cc` recipe with `Configure ... -Dcc=./cadvise_cc` (see cadvise "User Guide") is recommended; as is the use of `+wall`.
###
cpd (cut-and-paste detector)
The cpd tool detects cut-and-paste coding. If one instance of the cut-and-pasted code changes, all the other spots should probably be changed, too. Therefore such code should probably be turned into a subroutine or a macro.
cpd (<https://pmd.github.io/latest/pmd_userdocs_cpd.html>) is part of the pmd project (<https://pmd.github.io/>). pmd was originally written for static analysis of Java code, but later the cpd part of it was extended to parse also C and C++.
Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the pmd-X.Y.jar from it, and then run that on source code thusly:
```
java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD \
--minimum-tokens 100 --files /some/where/src --language c > cpd.txt
```
You may run into memory limits, in which case you should use the -Xmx option:
```
java -Xmx512M ...
```
###
gcc warnings
Though much can be written about the inconsistency and coverage problems of gcc warnings (like `-Wall` not meaning "all the warnings", or some common portability problems not being covered by `-Wall`, or `-ansi` and `-pedantic` both being a poorly defined collection of warnings, and so forth), gcc is still a useful tool in keeping our coding nose clean.
The `-Wall` is by default on.
It would be nice for `-pedantic`) to be on always, but unfortunately it is not safe on all platforms - for example fatal conflicts with the system headers (Solaris being a prime example). If Configure `-Dgccansipedantic` is used, the `cflags` frontend selects `-pedantic` for the platforms where it is known to be safe.
The following extra flags are added:
* `-Wendif-labels`
* `-Wextra`
* `-Wc++-compat`
* `-Wwrite-strings`
* `-Werror=pointer-arith`
* `-Werror=vla`
The following flags would be nice to have but they would first need their own Augean stablemaster:
* `-Wshadow`
* `-Wstrict-prototypes`
The `-Wtraditional` is another example of the annoying tendency of gcc to bundle a lot of warnings under one switch (it would be impossible to deploy in practice because it would complain a lot) but it does contain some warnings that would be beneficial to have available on their own, such as the warning about string constants inside macros containing the macro arguments: this behaved differently pre-ANSI than it does in ANSI, and some C compilers are still in transition, AIX being an example.
###
Warnings of other C compilers
Other C compilers (yes, there **are** other C compilers than gcc) often have their "strict ANSI" or "strict ANSI with some portability extensions" modes on, like for example the Sun Workshop has its `-Xa` mode on (though implicitly), or the DEC (these days, HP...) has its `-std1` mode on.
MEMORY DEBUGGERS
-----------------
**NOTE 1**: Running under older memory debuggers such as Purify, valgrind or Third Degree greatly slows down the execution: seconds become minutes, minutes become hours. For example as of Perl 5.8.1, the ext/Encode/t/Unicode.t takes extraordinarily long to complete under e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more than six hours, even on a snappy computer. The said test must be doing something that is quite unfriendly for memory debuggers. If you don't feel like waiting, that you can simply kill away the perl process. Roughly valgrind slows down execution by factor 10, AddressSanitizer by factor 2.
**NOTE 2**: To minimize the number of memory leak false alarms (see ["PERL\_DESTRUCT\_LEVEL"](#PERL_DESTRUCT_LEVEL) for more information), you have to set the environment variable PERL\_DESTRUCT\_LEVEL to 2. For example, like this:
```
env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ...
```
**NOTE 3**: There are known memory leaks when there are compile-time errors within eval or require, seeing `S_doeval` in the call stack is a good sign of these. Fixing these leaks is non-trivial, unfortunately, but they must be fixed eventually.
**NOTE 4**: [DynaLoader](dynaloader) will not clean up after itself completely unless Perl is built with the Configure option `-Accflags=-DDL_UNLOAD_ALL_AT_EXIT`.
### valgrind
The valgrind tool can be used to find out both memory leaks and illegal heap memory accesses. As of version 3.3.0, Valgrind only supports Linux on x86, x86-64 and PowerPC and Darwin (OS X) on x86 and x86-64. The special "test.valgrind" target can be used to run the tests under valgrind. Found errors and memory leaks are logged in files named *testfile.valgrind* and by default output is displayed inline.
Example usage:
```
make test.valgrind
```
Since valgrind adds significant overhead, tests will take much longer to run. The valgrind tests support being run in parallel to help with this:
```
TEST_JOBS=9 make test.valgrind
```
Note that the above two invocations will be very verbose as reachable memory and leak-checking is enabled by default. If you want to just see pure errors, try:
```
VG_OPTS='-q --leak-check=no --show-reachable=no' TEST_JOBS=9 \
make test.valgrind
```
Valgrind also provides a cachegrind tool, invoked on perl as:
```
VG_OPTS=--tool=cachegrind make test.valgrind
```
As system libraries (most notably glibc) are also triggering errors, valgrind allows to suppress such errors using suppression files. The default suppression file that comes with valgrind already catches a lot of them. Some additional suppressions are defined in *t/perl.supp*.
To get valgrind and for more information see
```
http://valgrind.org/
```
### AddressSanitizer
AddressSanitizer ("ASan") consists of a compiler instrumentation module and a run-time `malloc` library. ASan is available for a variety of architectures, operating systems, and compilers (see project link below). It checks for unsafe memory usage, such as use after free and buffer overflow conditions, and is fast enough that you can easily compile your debugging or optimized perl with it. Modern versions of ASan check for memory leaks by default on most platforms, otherwise (e.g. x86\_64 OS X) this feature can be enabled via `ASAN_OPTIONS=detect_leaks=1`.
To build perl with AddressSanitizer, your Configure invocation should look like:
```
sh Configure -des -Dcc=clang \
-Accflags=-fsanitize=address -Aldflags=-fsanitize=address \
-Alddlflags=-shared\ -fsanitize=address \
-fsanitize-blacklist=`pwd`/asan_ignore
```
where these arguments mean:
* -Dcc=clang
This should be replaced by the full path to your clang executable if it is not in your path.
* -Accflags=-fsanitize=address
Compile perl and extensions sources with AddressSanitizer.
* -Aldflags=-fsanitize=address
Link the perl executable with AddressSanitizer.
* -Alddlflags=-shared\ -fsanitize=address
Link dynamic extensions with AddressSanitizer. You must manually specify `-shared` because using `-Alddlflags=-shared` will prevent Configure from setting a default value for `lddlflags`, which usually contains `-shared` (at least on Linux).
* -fsanitize-blacklist=`pwd`/asan\_ignore
AddressSanitizer will ignore functions listed in the `asan_ignore` file. (This file should contain a short explanation of why each of the functions is listed.)
See also <https://github.com/google/sanitizers/wiki/AddressSanitizer>.
PROFILING
---------
Depending on your platform there are various ways of profiling Perl.
There are two commonly used techniques of profiling executables: *statistical time-sampling* and *basic-block counting*.
The first method takes periodically samples of the CPU program counter, and since the program counter can be correlated with the code generated for functions, we get a statistical view of in which functions the program is spending its time. The caveats are that very small/fast functions have lower probability of showing up in the profile, and that periodically interrupting the program (this is usually done rather frequently, in the scale of milliseconds) imposes an additional overhead that may skew the results. The first problem can be alleviated by running the code for longer (in general this is a good idea for profiling), the second problem is usually kept in guard by the profiling tools themselves.
The second method divides up the generated code into *basic blocks*. Basic blocks are sections of code that are entered only in the beginning and exited only at the end. For example, a conditional jump starts a basic block. Basic block profiling usually works by *instrumenting* the code by adding *enter basic block #nnnn* book-keeping code to the generated code. During the execution of the code the basic block counters are then updated appropriately. The caveat is that the added extra code can skew the results: again, the profiling tools usually try to factor their own effects out of the results.
###
Gprof Profiling
*gprof* is a profiling tool available in many Unix platforms which uses *statistical time-sampling*. You can build a profiled version of *perl* by compiling using gcc with the flag `-pg`. Either edit *config.sh* or re-run *Configure*. Running the profiled version of Perl will create an output file called *gmon.out* which contains the profiling data collected during the execution.
quick hint:
```
$ sh Configure -des -Dusedevel -Accflags='-pg' \
-Aldflags='-pg' -Alddlflags='-pg -shared' \
&& make perl
$ ./perl ... # creates gmon.out in current directory
$ gprof ./perl > out
$ less out
```
(you probably need to add `-shared` to the <-Alddlflags> line until RT #118199 is resolved)
The *gprof* tool can then display the collected data in various ways. Usually *gprof* understands the following options:
* -a
Suppress statically defined functions from the profile.
* -b
Suppress the verbose descriptions in the profile.
* -e routine
Exclude the given routine and its descendants from the profile.
* -f routine
Display only the given routine and its descendants in the profile.
* -s
Generate a summary file called *gmon.sum* which then may be given to subsequent gprof runs to accumulate data over several runs.
* -z
Display routines that have zero usage.
For more detailed explanation of the available commands and output formats, see your own local documentation of *gprof*.
###
GCC gcov Profiling
*basic block profiling* is officially available in gcc 3.0 and later. You can build a profiled version of *perl* by compiling using gcc with the flags `-fprofile-arcs -ftest-coverage`. Either edit *config.sh* or re-run *Configure*.
quick hint:
```
$ sh Configure -des -Dusedevel -Doptimize='-g' \
-Accflags='-fprofile-arcs -ftest-coverage' \
-Aldflags='-fprofile-arcs -ftest-coverage' \
-Alddlflags='-fprofile-arcs -ftest-coverage -shared' \
&& make perl
$ rm -f regexec.c.gcov regexec.gcda
$ ./perl ...
$ gcov regexec.c
$ less regexec.c.gcov
```
(you probably need to add `-shared` to the <-Alddlflags> line until RT #118199 is resolved)
Running the profiled version of Perl will cause profile output to be generated. For each source file an accompanying *.gcda* file will be created.
To display the results you use the *gcov* utility (which should be installed if you have gcc 3.0 or newer installed). *gcov* is run on source code files, like this
```
gcov sv.c
```
which will cause *sv.c.gcov* to be created. The *.gcov* files contain the source code annotated with relative frequencies of execution indicated by "#" markers. If you want to generate *.gcov* files for all profiled object files, you can run something like this:
```
for file in `find . -name \*.gcno`
do sh -c "cd `dirname $file` && gcov `basename $file .gcno`"
done
```
Useful options of *gcov* include `-b` which will summarise the basic block, branch, and function call coverage, and `-c` which instead of relative frequencies will use the actual counts. For more information on the use of *gcov* and basic block profiling with gcc, see the latest GNU CC manual. As of gcc 4.8, this is at <http://gcc.gnu.org/onlinedocs/gcc/Gcov-Intro.html#Gcov-Intro>
###
callgrind profiling
callgrind is a valgrind tool for profiling source code. Paired with kcachegrind (a Qt based UI), it gives you an overview of where code is taking up time, as well as the ability to examine callers, call trees, and more. One of its benefits is you can use it on perl and XS modules that have not been compiled with debugging symbols.
If perl is compiled with debugging symbols (`-g`), you can view the annotated source and click around, much like Devel::NYTProf's HTML output.
For basic usage:
```
valgrind --tool=callgrind ./perl ...
```
By default it will write output to *callgrind.out.PID*, but you can change that with `--callgrind-out-file=...`
To view the data, do:
```
kcachegrind callgrind.out.PID
```
If you'd prefer to view the data in a terminal, you can use *callgrind\_annotate*. In it's basic form:
```
callgrind_annotate callgrind.out.PID | less
```
Some useful options are:
* --threshold
Percentage of counts (of primary sort event) we are interested in. The default is 99%, 100% might show things that seem to be missing.
* --auto
Annotate all source files containing functions that helped reach the event count threshold.
MISCELLANEOUS TRICKS
---------------------
### PERL\_DESTRUCT\_LEVEL
If you want to run any of the tests yourself manually using e.g. valgrind, please note that by default perl **does not** explicitly cleanup all the memory it has allocated (such as global memory arenas) but instead lets the exit() of the whole program "take care" of such allocations, also known as "global destruction of objects".
There is a way to tell perl to do complete cleanup: set the environment variable PERL\_DESTRUCT\_LEVEL to a non-zero value. The t/TEST wrapper does set this to 2, and this is what you need to do too, if you don't want to see the "global leaks": For example, for running under valgrind
```
env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib t/foo/bar.t
```
(Note: the mod\_perl apache module uses also this environment variable for its own purposes and extended its semantics. Refer to the mod\_perl documentation for more information. Also, spawned threads do the equivalent of setting this variable to the value 1.)
If, at the end of a run you get the message *N scalars leaked*, you can recompile with `-DDEBUG_LEAKING_SCALARS`, (`Configure -Accflags=-DDEBUG_LEAKING_SCALARS`), which will cause the addresses of all those leaked SVs to be dumped along with details as to where each SV was originally allocated. This information is also displayed by Devel::Peek. Note that the extra details recorded with each SV increases memory usage, so it shouldn't be used in production environments. It also converts `new_SV()` from a macro into a real function, so you can use your favourite debugger to discover where those pesky SVs were allocated.
If you see that you're leaking memory at runtime, but neither valgrind nor `-DDEBUG_LEAKING_SCALARS` will find anything, you're probably leaking SVs that are still reachable and will be properly cleaned up during destruction of the interpreter. In such cases, using the `-Dm` switch can point you to the source of the leak. If the executable was built with `-DDEBUG_LEAKING_SCALARS`, `-Dm` will output SV allocations in addition to memory allocations. Each SV allocation has a distinct serial number that will be written on creation and destruction of the SV. So if you're executing the leaking code in a loop, you need to look for SVs that are created, but never destroyed between each cycle. If such an SV is found, set a conditional breakpoint within `new_SV()` and make it break only when `PL_sv_serial` is equal to the serial number of the leaking SV. Then you will catch the interpreter in exactly the state where the leaking SV is allocated, which is sufficient in many cases to find the source of the leak.
As `-Dm` is using the PerlIO layer for output, it will by itself allocate quite a bunch of SVs, which are hidden to avoid recursion. You can bypass the PerlIO layer if you use the SV logging provided by `-DPERL_MEM_LOG` instead.
### PERL\_MEM\_LOG
If compiled with `-DPERL_MEM_LOG` (`-Accflags=-DPERL_MEM_LOG`), both memory and SV allocations go through logging functions, which is handy for breakpoint setting.
Unless `-DPERL_MEM_LOG_NOIMPL` (`-Accflags=-DPERL_MEM_LOG_NOIMPL`) is also compiled, the logging functions read $ENV{PERL\_MEM\_LOG} to determine whether to log the event, and if so how:
```
$ENV{PERL_MEM_LOG} =~ /m/ Log all memory ops
$ENV{PERL_MEM_LOG} =~ /s/ Log all SV ops
$ENV{PERL_MEM_LOG} =~ /t/ include timestamp in Log
$ENV{PERL_MEM_LOG} =~ /^(\d+)/ write to FD given (default is 2)
```
Memory logging is somewhat similar to `-Dm` but is independent of `-DDEBUGGING`, and at a higher level; all uses of Newx(), Renew(), and Safefree() are logged with the caller's source code file and line number (and C function name, if supported by the C compiler). In contrast, `-Dm` is directly at the point of `malloc()`. SV logging is similar.
Since the logging doesn't use PerlIO, all SV allocations are logged and no extra SV allocations are introduced by enabling the logging. If compiled with `-DDEBUG_LEAKING_SCALARS`, the serial number for each SV allocation is also logged.
###
DDD over gdb
Those debugging perl with the DDD frontend over gdb may find the following useful:
You can extend the data conversion shortcuts menu, so for example you can display an SV's IV value with one click, without doing any typing. To do that simply edit ~/.ddd/init file and add after:
```
! Display shortcuts.
Ddd*gdbDisplayShortcuts: \
/t () // Convert to Bin\n\
/d () // Convert to Dec\n\
/x () // Convert to Hex\n\
/o () // Convert to Oct(\n\
```
the following two lines:
```
((XPV*) (())->sv_any )->xpv_pv // 2pvx\n\
((XPVIV*) (())->sv_any )->xiv_iv // 2ivx
```
so now you can do ivx and pvx lookups or you can plug there the sv\_peek "conversion":
```
Perl_sv_peek(my_perl, (SV*)()) // sv_peek
```
(The my\_perl is for threaded builds.) Just remember that every line, but the last one, should end with \n\
Alternatively edit the init file interactively via: 3rd mouse button -> New Display -> Edit Menu
Note: you can define up to 20 conversion shortcuts in the gdb section.
###
C backtrace
On some platforms Perl supports retrieving the C level backtrace (similar to what symbolic debuggers like gdb do).
The backtrace returns the stack trace of the C call frames, with the symbol names (function names), the object names (like "perl"), and if it can, also the source code locations (file:line).
The supported platforms are Linux, and OS X (some \*BSD might work at least partly, but they have not yet been tested).
This feature hasn't been tested with multiple threads, but it will only show the backtrace of the thread doing the backtracing.
The feature needs to be enabled with `Configure -Dusecbacktrace`.
The `-Dusecbacktrace` also enables keeping the debug information when compiling/linking (often: `-g`). Many compilers/linkers do support having both optimization and keeping the debug information. The debug information is needed for the symbol names and the source locations.
Static functions might not be visible for the backtrace.
Source code locations, even if available, can often be missing or misleading if the compiler has e.g. inlined code. Optimizer can make matching the source code and the object code quite challenging.
Linux You **must** have the BFD (-lbfd) library installed, otherwise `perl` will fail to link. The BFD is usually distributed as part of the GNU binutils.
Summary: `Configure ... -Dusecbacktrace` and you need `-lbfd`.
OS X The source code locations are supported **only** if you have the Developer Tools installed. (BFD is **not** needed.)
Summary: `Configure ... -Dusecbacktrace` and installing the Developer Tools would be good.
Optionally, for trying out the feature, you may want to enable automatic dumping of the backtrace just before a warning or croak (die) message is emitted, by adding `-Accflags=-DUSE_C_BACKTRACE_ON_ERROR` for Configure.
Unless the above additional feature is enabled, nothing about the backtrace functionality is visible, except for the Perl/XS level.
Furthermore, even if you have enabled this feature to be compiled, you need to enable it in runtime with an environment variable: `PERL_C_BACKTRACE_ON_ERROR=10`. It must be an integer higher than zero, telling the desired frame count.
Retrieving the backtrace from Perl level (using for example an XS extension) would be much less exciting than one would hope: normally you would see `runops`, `entersub`, and not much else. This API is intended to be called **from within** the Perl implementation, not from Perl level execution.
The C API for the backtrace is as follows:
get\_c\_backtrace free\_c\_backtrace get\_c\_backtrace\_dump dump\_c\_backtrace ### Poison
If you see in a debugger a memory area mysteriously full of 0xABABABAB or 0xEFEFEFEF, you may be seeing the effect of the Poison() macros, see <perlclib>.
###
Read-only optrees
Under ithreads the optree is read only. If you want to enforce this, to check for write accesses from buggy code, compile with `-Accflags=-DPERL_DEBUG_READONLY_OPS` to enable code that allocates op memory via `mmap`, and sets it read-only when it is attached to a subroutine. Any write access to an op results in a `SIGBUS` and abort.
This code is intended for development only, and may not be portable even to all Unix variants. Also, it is an 80% solution, in that it isn't able to make all ops read only. Specifically it does not apply to op slabs belonging to `BEGIN` blocks.
However, as an 80% solution it is still effective, as it has caught bugs in the past.
###
When is a bool not a bool?
There wasn't necessarily a standard `bool` type on compilers prior to C99, and so some workarounds were created. The `TRUE` and `FALSE` macros are still available as alternatives for `true` and `false`. And the `cBOOL` macro was created to correctly cast to a true/false value in all circumstances, but should no longer be necessary. Using `(bool)` *expr*> should now always work.
There are no plans to remove any of `TRUE`, `FALSE`, nor `cBOOL`.
###
Finding unsafe truncations
You may wish to run `Configure` with something like
```
-Accflags='-Wconversion -Wno-sign-conversion -Wno-shorten-64-to-32'
```
or your compiler's equivalent to make it easier to spot any unsafe truncations that show up.
###
The .i Targets
You can expand the macros in a *foo.c* file by saying
```
make foo.i
```
which will expand the macros using cpp. Don't be scared by the results.
AUTHOR
------
This document was originally written by Nathan Torkington, and is maintained by the perl5-porters mailing list.
| programming_docs |
perl B::Showlex B::Showlex
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
+ [OPTIONS](#OPTIONS)
* [SEE ALSO](#SEE-ALSO)
* [TODO](#TODO)
* [AUTHOR](#AUTHOR)
NAME
----
B::Showlex - Show lexical variables used in functions or files
SYNOPSIS
--------
```
perl -MO=Showlex[,-OPTIONS][,SUBROUTINE] foo.pl
```
DESCRIPTION
-----------
When a comma-separated list of subroutine names is given as options, Showlex prints the lexical variables used in those subroutines. Otherwise, it prints the file-scope lexicals in the file.
EXAMPLES
--------
Traditional form:
```
$ perl -MO=Showlex -e 'my ($i,$j,$k)=(1,"foo")'
Pad of lexical names for comppadlist has 4 entries
0: (0x8caea4) undef
1: (0x9db0fb0) $i
2: (0x9db0f38) $j
3: (0x9db0f50) $k
Pad of lexical values for comppadlist has 5 entries
0: SPECIAL #1 &PL_sv_undef
1: NULL (0x9da4234)
2: NULL (0x9db0f2c)
3: NULL (0x9db0f44)
4: NULL (0x9da4264)
-e syntax OK
```
New-style form:
```
$ perl -MO=Showlex,-newlex -e 'my ($i,$j,$k)=(1,"foo")'
main Pad has 4 entries
0: (0x8caea4) undef
1: (0xa0c4fb8) "$i" = NULL (0xa0b8234)
2: (0xa0c4f40) "$j" = NULL (0xa0c4f34)
3: (0xa0c4f58) "$k" = NULL (0xa0c4f4c)
-e syntax OK
```
New form, no specials, outside O framework:
```
$ perl -MB::Showlex -e \
'my ($i,$j,$k)=(1,"foo"); B::Showlex::compile(-newlex,-nosp)->()'
main Pad has 4 entries
1: (0x998ffb0) "$i" = IV (0x9983234) 1
2: (0x998ff68) "$j" = PV (0x998ff5c) "foo"
3: (0x998ff80) "$k" = NULL (0x998ff74)
```
Note that this example shows the values of the lexicals, whereas the other examples did not (as they're compile-time only).
### OPTIONS
The `-newlex` option produces a more readable `name => value` format, and is shown in the second example above.
The `-nosp` option eliminates reporting of SPECIALs, such as `0: SPECIAL #1 &PL_sv_undef` above. Reporting of SPECIALs can sometimes overwhelm your declared lexicals.
SEE ALSO
---------
<B::Showlex> can also be used outside of the O framework, as in the third example. See <B::Concise> for a fuller explanation of reasons.
TODO
----
Some of the reported info, such as hex addresses, is not particularly valuable. Other information would be more useful for the typical programmer, such as line-numbers, pad-slot reuses, etc.. Given this, -newlex is not a particularly good flag-name.
AUTHOR
------
Malcolm Beattie, `[email protected]`
perl perlriscos perlriscos
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [BUILD](#BUILD)
* [AUTHOR](#AUTHOR)
NAME
----
perlriscos - Perl version 5 for RISC OS
DESCRIPTION
-----------
This document gives instructions for building Perl for RISC OS. It is complicated by the need to cross compile. There is a binary version of perl available from <http://www.cp15.org/perl/> which you may wish to use instead of trying to compile it yourself.
BUILD
-----
You need an installed and working gccsdk cross compiler <http://gccsdk.riscos.info/> and REXEN <http://www.cp15.org/programming/>
Firstly, copy the source and build a native copy of perl for your host system. Then, in the source to be cross compiled:
1. ```
$ ./Configure
```
2. Select the riscos hint file. The default answers for the rest of the questions are usually sufficient.
Note that, if you wish to run Configure non-interactively (see the INSTALL document for details), to have it select the correct hint file, you'll need to provide the argument -Dhintfile=riscos on the Configure command-line.
3. ```
$ make miniperl
```
4. This should build miniperl and then fail when it tries to run it.
5. Copy the miniperl executable from the native build done earlier to replace the cross compiled miniperl.
6. ```
$ make
```
7. This will use miniperl to complete the rest of the build.
AUTHOR
------
Alex Waugh <[email protected]>
perl Pod::Simple::TextContent Pod::Simple::TextContent
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::TextContent -- get the text content of Pod
SYNOPSIS
--------
```
TODO
perl -MPod::Simple::TextContent -e \
"exit Pod::Simple::TextContent->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
This class is that parses Pod and dumps just the text content. It is mainly meant for use by the Pod::Simple test suite, but you may find some other use for it.
This is a subclass of <Pod::Simple> and inherits all its methods.
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 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 Filter::Simple Filter::Simple
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The Problem](#The-Problem)
+ [A Solution](#A-Solution)
+ [Disabling or changing <no> behaviour](#Disabling-or-changing-%3Cno%3E-behaviour)
+ [All-in-one interface](#All-in-one-interface)
+ [Filtering only specific components of source code](#Filtering-only-specific-components-of-source-code)
+ [Filtering only the code parts of source code](#Filtering-only-the-code-parts-of-source-code)
+ [Using Filter::Simple with an explicit import subroutine](#Using-Filter::Simple-with-an-explicit-import-subroutine)
+ [Using Filter::Simple and Exporter together](#Using-Filter::Simple-and-Exporter-together)
+ [How it works](#How-it-works)
* [AUTHOR](#AUTHOR)
* [CONTACT](#CONTACT)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Filter::Simple - Simplified source filtering
SYNOPSIS
--------
```
# in MyFilter.pm:
package MyFilter;
use Filter::Simple;
FILTER { ... };
# or just:
#
# use Filter::Simple sub { ... };
# in user's code:
use MyFilter;
# this code is filtered
no MyFilter;
# this code is not
```
DESCRIPTION
-----------
###
The Problem
Source filtering is an immensely powerful feature of recent versions of Perl. It allows one to extend the language itself (e.g. the Switch module), to simplify the language (e.g. Language::Pythonesque), or to completely recast the language (e.g. Lingua::Romana::Perligata). Effectively, it allows one to use the full power of Perl as its own, recursively applied, macro language.
The excellent Filter::Util::Call module (by Paul Marquess) provides a usable Perl interface to source filtering, but it is often too powerful and not nearly as simple as it could be.
To use the module it is necessary to do the following:
1. Download, build, and install the Filter::Util::Call module. (If you have Perl 5.7.1 or later, this is already done for you.)
2. Set up a module that does a `use Filter::Util::Call`.
3. Within that module, create an `import` subroutine.
4. Within the `import` subroutine do a call to `filter_add`, passing it either a subroutine reference.
5. Within the subroutine reference, call `filter_read` or `filter_read_exact` to "prime" $\_ with source code data from the source file that will `use` your module. Check the status value returned to see if any source code was actually read in.
6. Process the contents of $\_ to change the source code in the desired manner.
7. Return the status value.
8. If the act of unimporting your module (via a `no`) should cause source code filtering to cease, create an `unimport` subroutine, and have it call `filter_del`. Make sure that the call to `filter_read` or `filter_read_exact` in step 5 will not accidentally read past the `no`. Effectively this limits source code filters to line-by-line operation, unless the `import` subroutine does some fancy pre-pre-parsing of the source code it's filtering.
For example, here is a minimal source code filter in a module named BANG.pm. It simply converts every occurrence of the sequence `BANG\s+BANG` to the sequence `die 'BANG' if $BANG` in any piece of code following a `use BANG;` statement (until the next `no BANG;` statement, if any):
```
package BANG;
use Filter::Util::Call ;
sub import {
filter_add( sub {
my $caller = caller;
my ($status, $no_seen, $data);
while ($status = filter_read()) {
if (/^\s*no\s+$caller\s*;\s*?$/) {
$no_seen=1;
last;
}
$data .= $_;
$_ = "";
}
$_ = $data;
s/BANG\s+BANG/die 'BANG' if \$BANG/g
unless $status < 0;
$_ .= "no $class;\n" if $no_seen;
return 1;
})
}
sub unimport {
filter_del();
}
1 ;
```
This level of sophistication puts filtering out of the reach of many programmers.
###
A Solution
The Filter::Simple module provides a simplified interface to Filter::Util::Call; one that is sufficient for most common cases.
Instead of the above process, with Filter::Simple the task of setting up a source code filter is reduced to:
1. Download and install the Filter::Simple module. (If you have Perl 5.7.1 or later, this is already done for you.)
2. Set up a module that does a `use Filter::Simple` and then calls `FILTER { ... }`.
3. Within the anonymous subroutine or block that is passed to `FILTER`, process the contents of $\_ to change the source code in the desired manner.
In other words, the previous example, would become:
```
package BANG;
use Filter::Simple;
FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
};
1 ;
```
Note that the source code is passed as a single string, so any regex that uses `^` or `$` to detect line boundaries will need the `/m` flag.
###
Disabling or changing <no> behaviour
By default, the installed filter only filters up to a line consisting of one of the three standard source "terminators":
```
no ModuleName; # optional comment
```
or:
```
__END__
```
or:
```
__DATA__
```
but this can be altered by passing a second argument to `use Filter::Simple` or `FILTER` (just remember: there's *no* comma after the initial block when you use `FILTER`).
That second argument may be either a `qr`'d regular expression (which is then used to match the terminator line), or a defined false value (which indicates that no terminator line should be looked for), or a reference to a hash (in which case the terminator is the value associated with the key `'terminator'`.
For example, to cause the previous filter to filter only up to a line of the form:
```
GNAB esu;
```
you would write:
```
package BANG;
use Filter::Simple;
FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
}
qr/^\s*GNAB\s+esu\s*;\s*?$/;
```
or:
```
FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
}
{ terminator => qr/^\s*GNAB\s+esu\s*;\s*?$/ };
```
and to prevent the filter's being turned off in any way:
```
package BANG;
use Filter::Simple;
FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
}
""; # or: 0
```
or:
```
FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
}
{ terminator => "" };
```
**Note that, no matter what you set the terminator pattern to, the actual terminator itself *must* be contained on a single source line.**
###
All-in-one interface
Separating the loading of Filter::Simple:
```
use Filter::Simple;
```
from the setting up of the filtering:
```
FILTER { ... };
```
is useful because it allows other code (typically parser support code or caching variables) to be defined before the filter is invoked. However, there is often no need for such a separation.
In those cases, it is easier to just append the filtering subroutine and any terminator specification directly to the `use` statement that loads Filter::Simple, like so:
```
use Filter::Simple sub {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
};
```
This is exactly the same as:
```
use Filter::Simple;
BEGIN {
Filter::Simple::FILTER {
s/BANG\s+BANG/die 'BANG' if \$BANG/g;
};
}
```
except that the `FILTER` subroutine is not exported by Filter::Simple.
###
Filtering only specific components of source code
One of the problems with a filter like:
```
use Filter::Simple;
FILTER { s/BANG\s+BANG/die 'BANG' if \$BANG/g };
```
is that it indiscriminately applies the specified transformation to the entire text of your source program. So something like:
```
warn 'BANG BANG, YOU'RE DEAD';
BANG BANG;
```
will become:
```
warn 'die 'BANG' if $BANG, YOU'RE DEAD';
die 'BANG' if $BANG;
```
It is very common when filtering source to only want to apply the filter to the non-character-string parts of the code, or alternatively to *only* the character strings.
Filter::Simple supports this type of filtering by automatically exporting the `FILTER_ONLY` subroutine.
`FILTER_ONLY` takes a sequence of specifiers that install separate (and possibly multiple) filters that act on only parts of the source code. For example:
```
use Filter::Simple;
FILTER_ONLY
code => sub { s/BANG\s+BANG/die 'BANG' if \$BANG/g },
quotelike => sub { s/BANG\s+BANG/CHITTY CHITTY/g };
```
The `"code"` subroutine will only be used to filter parts of the source code that are not quotelikes, POD, or `__DATA__`. The `quotelike` subroutine only filters Perl quotelikes (including here documents).
The full list of alternatives is:
`"code"`
Filters only those sections of the source code that are not quotelikes, POD, or `__DATA__`.
`"code_no_comments"`
Filters only those sections of the source code that are not quotelikes, POD, comments, or `__DATA__`.
`"executable"`
Filters only those sections of the source code that are not POD or `__DATA__`.
`"executable_no_comments"`
Filters only those sections of the source code that are not POD, comments, or `__DATA__`.
`"quotelike"`
Filters only Perl quotelikes (as interpreted by `&Text::Balanced::extract_quotelike`).
`"string"`
Filters only the string literal parts of a Perl quotelike (i.e. the contents of a string literal, either half of a `tr///`, the second half of an `s///`).
`"regex"`
Filters only the pattern literal parts of a Perl quotelike (i.e. the contents of a `qr//` or an `m//`, the first half of an `s///`).
`"all"`
Filters everything. Identical in effect to `FILTER`.
Except for `FILTER_ONLY code => sub {...}`, each of the component filters is called repeatedly, once for each component found in the source code.
Note that you can also apply two or more of the same type of filter in a single `FILTER_ONLY`. For example, here's a simple macro-preprocessor that is only applied within regexes, with a final debugging pass that prints the resulting source code:
```
use Regexp::Common;
FILTER_ONLY
regex => sub { s/!\[/[^/g },
regex => sub { s/%d/$RE{num}{int}/g },
regex => sub { s/%f/$RE{num}{real}/g },
all => sub { print if $::DEBUG };
```
###
Filtering only the code parts of source code
Most source code ceases to be grammatically correct when it is broken up into the pieces between string literals and regexes. So the `'code'` and `'code_no_comments'` component filter behave slightly differently from the other partial filters described in the previous section.
Rather than calling the specified processor on each individual piece of code (i.e. on the bits between quotelikes), the `'code...'` partial filters operate on the entire source code, but with the quotelike bits (and, in the case of `'code_no_comments'`, the comments) "blanked out".
That is, a `'code...'` filter *replaces* each quoted string, quotelike, regex, POD, and \_\_DATA\_\_ section with a placeholder. The delimiters of this placeholder are the contents of the `$;` variable at the time the filter is applied (normally `"\034"`). The remaining four bytes are a unique identifier for the component being replaced.
This approach makes it comparatively easy to write code preprocessors without worrying about the form or contents of strings, regexes, etc.
For convenience, during a `'code...'` filtering operation, Filter::Simple provides a package variable (`$Filter::Simple::placeholder`) that contains a pre-compiled regex that matches any placeholder...and captures the identifier within the placeholder. Placeholders can be moved and re-ordered within the source code as needed.
In addition, a second package variable (`@Filter::Simple::components`) contains a list of the various pieces of `$_`, as they were originally split up to allow placeholders to be inserted.
Once the filtering has been applied, the original strings, regexes, POD, etc. are re-inserted into the code, by replacing each placeholder with the corresponding original component (from `@components`). Note that this means that the `@components` variable must be treated with extreme care within the filter. The `@components` array stores the "back- translations" of each placeholder inserted into `$_`, as well as the interstitial source code between placeholders. If the placeholder backtranslations are altered in `@components`, they will be similarly changed when the placeholders are removed from `$_` after the filter is complete.
For example, the following filter detects concatenated pairs of strings/quotelikes and reverses the order in which they are concatenated:
```
package DemoRevCat;
use Filter::Simple;
FILTER_ONLY code => sub {
my $ph = $Filter::Simple::placeholder;
s{ ($ph) \s* [.] \s* ($ph) }{ $2.$1 }gx
};
```
Thus, the following code:
```
use DemoRevCat;
my $str = "abc" . q(def);
print "$str\n";
```
would become:
```
my $str = q(def)."abc";
print "$str\n";
```
and hence print:
```
defabc
```
###
Using Filter::Simple with an explicit `import` subroutine
Filter::Simple generates a special `import` subroutine for your module (see ["How it works"](#How-it-works)) which would normally replace any `import` subroutine you might have explicitly declared.
However, Filter::Simple is smart enough to notice your existing `import` and Do The Right Thing with it. That is, if you explicitly define an `import` subroutine in a package that's using Filter::Simple, that `import` subroutine will still be invoked immediately after any filter you install.
The only thing you have to remember is that the `import` subroutine *must* be declared *before* the filter is installed. If you use `FILTER` to install the filter:
```
package Filter::TurnItUpTo11;
use Filter::Simple;
FILTER { s/(\w+)/\U$1/ };
```
that will almost never be a problem, but if you install a filtering subroutine by passing it directly to the `use Filter::Simple` statement:
```
package Filter::TurnItUpTo11;
use Filter::Simple sub{ s/(\w+)/\U$1/ };
```
then you must make sure that your `import` subroutine appears before that `use` statement.
###
Using Filter::Simple and Exporter together
Likewise, Filter::Simple is also smart enough to Do The Right Thing if you use Exporter:
```
package Switch;
use base Exporter;
use Filter::Simple;
@EXPORT = qw(switch case);
@EXPORT_OK = qw(given when);
FILTER { $_ = magic_Perl_filter($_) }
```
Immediately after the filter has been applied to the source, Filter::Simple will pass control to Exporter, so it can do its magic too.
Of course, here too, Filter::Simple has to know you're using Exporter before it applies the filter. That's almost never a problem, but if you're nervous about it, you can guarantee that things will work correctly by ensuring that your `use base Exporter` always precedes your `use Filter::Simple`.
###
How it works
The Filter::Simple module exports into the package that calls `FILTER` (or `use`s it directly) -- such as package "BANG" in the above example -- two automagically constructed subroutines -- `import` and `unimport` -- which take care of all the nasty details.
In addition, the generated `import` subroutine passes its own argument list to the filtering subroutine, so the BANG.pm filter could easily be made parametric:
```
package BANG;
use Filter::Simple;
FILTER {
my ($die_msg, $var_name) = @_;
s/BANG\s+BANG/die '$die_msg' if \${$var_name}/g;
};
# and in some user code:
use BANG "BOOM", "BAM"; # "BANG BANG" becomes: die 'BOOM' if $BAM
```
The specified filtering subroutine is called every time a `use BANG` is encountered, and passed all the source code following that call, up to either the next `no BANG;` (or whatever terminator you've set) or the end of the source file, whichever occurs first. By default, any `no BANG;` call must appear by itself on a separate line, or it is ignored.
AUTHOR
------
Damian Conway
CONTACT
-------
Filter::Simple is now maintained by the Perl5-Porters. Please submit bug via the `perlbug` tool that comes with your perl. For usage instructions, read `perldoc perlbug` or possibly `man perlbug`. For mostly anything else, please contact <[email protected]>.
Maintainer of the CPAN release is Steffen Mueller <[email protected]>. Contact him with technical difficulties with respect to the packaging of the CPAN module.
Praise of the module, flowers, and presents still go to the author, Damian Conway <[email protected]>.
COPYRIGHT AND LICENSE
----------------------
```
Copyright (c) 2000-2014, Damian Conway. All Rights Reserved.
This module is free software. It may be used, redistributed
and/or modified under the same terms as Perl itself.
```
| programming_docs |
perl Exporter::Heavy Exporter::Heavy
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Exporter::Heavy - Exporter guts
SYNOPSIS
--------
(internal use only)
DESCRIPTION
-----------
No user-serviceable parts inside.
perl CPAN::Kwalify CPAN::Kwalify
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
CPAN::Kwalify - Interface between CPAN.pm and Kwalify.pm
SYNOPSIS
--------
```
use CPAN::Kwalify;
validate($schema_name, $data, $file, $doc);
```
DESCRIPTION
-----------
\_validate($schema\_name, $data, $file, $doc) $schema\_name is the name of a supported schema. Currently only `distroprefs` is supported. $data is the data to be validated. $file is the absolute path to the file the data are coming from. $doc is the index of the document within $doc that is to be validated. The last two arguments are only there for better error reporting.
Relies on being called from within CPAN.pm.
Dies if something fails. Does not return anything useful.
yaml($schema\_name) Returns the YAML text of that schema. Dies if something fails.
AUTHOR
------
Andreas Koenig `<[email protected]>`
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>
perl Module::CoreList::Utils Module::CoreList::Utils
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS API](#FUNCTIONS-API)
* [DATA STRUCTURES](#DATA-STRUCTURES)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Module::CoreList::Utils - what utilities shipped with versions of perl
SYNOPSIS
--------
```
use Module::CoreList::Utils;
print $Module::CoreList::Utils::utilities{5.009003}{ptar}; # prints 1
print Module::CoreList::Utils->first_release('corelist');
# prints 5.008009
print Module::CoreList::Utils->first_release_by_date('corelist');
# prints 5.009002
```
DESCRIPTION
-----------
Module::CoreList::Utils provides information on which core and dual-life utilities shipped with each version of <perl>.
It provides a number of mechanisms for querying this information.
There is a functional programming API available for programmers to query information.
Programmers may also query the contained hash structure 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::Utils::first_release('corelist'); # as a function
Module::CoreList::Utils->first_release('corelist'); # class method
```
`utilities` Requires a perl version as an argument, returns a list of utilities that shipped with that version of perl, or undef/empty list if that perl doesn't exist.
`first_release( UTILITY )`
Requires a UTILITY name as an argument, returns the perl version when that utility first appeared in core as ordered by perl version number or undef ( in scalar context ) or an empty list ( in list context ) if that utility is not in core.
`first_release_by_date( UTILITY )`
Requires a UTILITY name as an argument, returns the perl version when that utility first appeared in core as ordered by release date or undef ( in scalar context ) or an empty list ( in list context ) if that utility is not in core.
`removed_from( UTILITY )`
Takes a UTILITY name as an argument, returns the first perl version where that utility was removed from core. Returns undef if the given utility was never in core or remains in core.
`removed_from_by_date( UTILITY )`
Takes a UTILITY name as an argument, returns the first perl version by release date where that utility was removed from core. Returns undef if the given utility was never in core or remains in core.
DATA STRUCTURES
----------------
These are the hash data structures that are available:
`%Module::CoreList::Utils::utilities`
A hash of hashes that is keyed on perl version as indicated in $]. The second level hash is utility / defined pairs.
AUTHOR
------
Chris `BinGOs` Williams <[email protected]>
Currently maintained by the perl 5 porters <[email protected]>.
This module is the result of archaeology undertaken during QA Hackathon in Lancaster, April 2013.
LICENSE
-------
Copyright (C) 2013 Chris Williams. 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::CoreList>, <perl>, <http://perlpunks.de/corelist>
perl enc2xs enc2xs
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Quick Guide](#Quick-Guide)
* [The Unicode Character Map](#The-Unicode-Character-Map)
+ [Coping with duplicate mappings](#Coping-with-duplicate-mappings)
* [Bookmarks](#Bookmarks)
* [SEE ALSO](#SEE-ALSO)
NAME
----
enc2xs -- Perl Encode Module Generator
SYNOPSIS
--------
```
enc2xs -[options]
enc2xs -M ModName mapfiles...
enc2xs -C
```
DESCRIPTION
-----------
*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.
Quick Guide
------------
If you want to know as little about Perl as possible but need to add a new encoding, just read this chapter and forget the rest.
0. Have a .ucm file ready. You can get it from somewhere or you can write your own from scratch or you can grab one from the Encode distribution and customize it. For the UCM format, see the next Chapter. In the example below, I'll call my theoretical encoding myascii, defined in *my.ucm*. `$` is a shell prompt.
```
$ ls -F
my.ucm
```
1. Issue a command as follows;
```
$ enc2xs -M My my.ucm
generating Makefile.PL
generating My.pm
generating README
generating Changes
```
Now take a look at your current directory. It should look like this.
```
$ ls -F
Makefile.PL My.pm my.ucm t/
```
The following files were created.
```
Makefile.PL - MakeMaker script
My.pm - Encode submodule
t/My.t - test file
```
1.1. If you want \*.ucm installed together with the modules, do as follows;
```
$ mkdir Encode
$ mv *.ucm Encode
$ enc2xs -M My Encode/*ucm
```
2. Edit the files generated. You don't have to if you have no time AND no intention to give it to someone else. But it is a good idea to edit the pod and to add more tests.
3. Now issue a command all Perl Mongers love:
```
$ perl Makefile.PL
Writing Makefile for Encode::My
```
4. Now all you have to do is make.
```
$ make
cp My.pm blib/lib/Encode/My.pm
/usr/local/bin/perl /usr/local/bin/enc2xs -Q -O \
-o encode_t.c -f encode_t.fnm
Reading myascii (myascii)
Writing compiled form
128 bytes in string tables
384 bytes (75%) saved spotting duplicates
1 bytes (0.775%) saved using substrings
....
chmod 644 blib/arch/auto/Encode/My/My.bs
$
```
The time it takes varies depending on how fast your machine is and how large your encoding is. Unless you are working on something big like euc-tw, it won't take too long.
5. You can "make install" already but you should test first.
```
$ make test
PERL_DL_NONLAZY=1 /usr/local/bin/perl -Iblib/arch -Iblib/lib \
-e 'use Test::Harness qw(&runtests $verbose); \
$verbose=0; runtests @ARGV;' t/*.t
t/My....ok
All tests successful.
Files=1, Tests=2, 0 wallclock secs
( 0.09 cusr + 0.01 csys = 0.09 CPU)
```
6. If you are content with the test result, just "make install"
7. If you want to add your encoding to Encode's demand-loading list (so you don't have to "use Encode::YourEncoding"), run
```
enc2xs -C
```
to update Encode::ConfigLocal, a module that controls local settings. After that, "use Encode;" is enough to load your encodings on demand.
The Unicode Character Map
--------------------------
Encode uses the Unicode Character Map (UCM) format for source character mappings. This format is used by IBM's ICU package and was adopted by Nick Ing-Simmons for use with the Encode module. Since UCM is more flexible than Tcl's Encoding Map and far more user-friendly, this is the recommended format for Encode now.
A UCM file looks like this.
```
#
# Comments
#
<code_set_name> "US-ascii" # Required
<code_set_alias> "ascii" # Optional
<mb_cur_min> 1 # Required; usually 1
<mb_cur_max> 1 # Max. # of bytes/char
<subchar> \x3F # Substitution char
#
CHARMAP
<U0000> \x00 |0 # <control>
<U0001> \x01 |0 # <control>
<U0002> \x02 |0 # <control>
....
<U007C> \x7C |0 # VERTICAL LINE
<U007D> \x7D |0 # RIGHT CURLY BRACKET
<U007E> \x7E |0 # TILDE
<U007F> \x7F |0 # <control>
END CHARMAP
```
* Anything that follows `#` is treated as a comment.
* The header section continues until a line containing the word CHARMAP. This section has a form of *<keyword> value*, one pair per line. Strings used as values must be quoted. Barewords are treated as numbers. *\xXX* represents a byte.
Most of the keywords are self-explanatory. *subchar* means substitution character, not subcharacter. When you decode a Unicode sequence to this encoding but no matching character is found, the byte sequence defined here will be used. For most cases, the value here is \x3F; in ASCII, this is a question mark.
* CHARMAP starts the character map section. Each line has a form as follows:
```
<UXXXX> \xXX.. |0 # comment
^ ^ ^
| | +- Fallback flag
| +-------- Encoded byte sequence
+-------------- Unicode Character ID in hex
```
The format is roughly the same as a header section except for the fallback flag: | followed by 0..3. The meaning of the possible values is as follows:
|0 Round trip safe. A character decoded to Unicode encodes back to the same byte sequence. Most characters have this flag.
|1 Fallback for unicode -> encoding. When seen, enc2xs adds this character for the encode map only.
|2 Skip sub-char mapping should there be no code point.
|3 Fallback for encoding -> unicode. When seen, enc2xs adds this character for the decode map only.
* And finally, END OF CHARMAP ends the section.
When you are manually creating a UCM file, you should copy ascii.ucm or an existing encoding which is close to yours, rather than write your own from scratch.
When you do so, make sure you leave at least **U0000** to **U0020** as is, unless your environment is EBCDIC.
**CAVEAT**: not all features in UCM are implemented. For example, icu:state is not used. Because of that, you need to write a perl module if you want to support algorithmical encodings, notably the ISO-2022 series. Such modules include <Encode::JP::2022_JP>, <Encode::KR::2022_KR>, and <Encode::TW::HZ>.
###
Coping with duplicate mappings
When you create a map, you SHOULD make your mappings round-trip safe. That is, `encode('your-encoding', decode('your-encoding', $data)) eq $data` stands for all characters that are marked as `|0`. Here is how to make sure:
* Sort your map in Unicode order.
* When you have a duplicate entry, mark either one with '|1' or '|3'.
* And make sure the '|1' or '|3' entry FOLLOWS the '|0' entry.
Here is an example from big5-eten.
```
<U2550> \xF9\xF9 |0
<U2550> \xA2\xA4 |3
```
Internally Encoding -> Unicode and Unicode -> Encoding Map looks like this;
```
E to U U to E
--------------------------------------
\xF9\xF9 => U2550 U2550 => \xF9\xF9
\xA2\xA4 => U2550
```
So it is round-trip safe for \xF9\xF9. But if the line above is upside down, here is what happens.
```
E to U U to E
--------------------------------------
\xA2\xA4 => U2550 U2550 => \xF9\xF9
(\xF9\xF9 => U2550 is now overwritten!)
```
The Encode package comes with *ucmlint*, a crude but sufficient utility to check the integrity of a UCM file. Check under the Encode/bin directory for this.
When in doubt, you can use *ucmsort*, yet another utility under Encode/bin directory.
Bookmarks
---------
* ICU Home Page <http://www.icu-project.org/>
* ICU Character Mapping Tables <http://site.icu-project.org/charts/charset>
* ICU:Conversion Data <http://www.icu-project.org/userguide/conversion-data.html>
SEE ALSO
---------
[Encode](encode), <perlmod>, <perlpod>
perl Pod::Perldoc::ToTerm Pod::Perldoc::ToTerm
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [PAGER FORMATTING](#PAGER-FORMATTING)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToTerm - render Pod with terminal escapes
SYNOPSIS
--------
```
perldoc -o term 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 term -w indent:5 Some::Modulename
```
PAGER FORMATTING
-----------------
Depending on the platform, and because this class emits terminal escapes it will attempt to set the `-R` flag on your pager by injecting the flag into your environment variable for `less` or `more`.
On Windows and DOS, this class will not modify any environment variables.
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::Text::Termcap>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2017 Mark Allen.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.
AUTHOR
------
Mark Allen `<[email protected]>`
perl ExtUtils::MakeMaker::Tutorial ExtUtils::MakeMaker::Tutorial
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The Mantra](#The-Mantra)
+ [The Layout](#The-Layout)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MakeMaker::Tutorial - Writing a module with MakeMaker
SYNOPSIS
--------
```
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Your::Module',
VERSION_FROM => 'lib/Your/Module.pm'
);
```
DESCRIPTION
-----------
This is a short tutorial on writing a simple module with MakeMaker. It's really not that hard.
###
The Mantra
MakeMaker modules are installed using this simple mantra
```
perl Makefile.PL
make
make test
make install
```
There are lots more commands and options, but the above will do it.
###
The Layout
The basic files in a module look something like this.
```
Makefile.PL
MANIFEST
lib/Your/Module.pm
```
That's all that's strictly necessary. There's additional files you might want:
```
lib/Your/Other/Module.pm
t/some_test.t
t/some_other_test.t
Changes
README
INSTALL
MANIFEST.SKIP
bin/some_program
```
Makefile.PL When you run Makefile.PL, it makes a Makefile. That's the whole point of MakeMaker. The Makefile.PL is a simple program which loads ExtUtils::MakeMaker and runs the WriteMakefile() function to generate a Makefile.
Here's an example of what you need for a simple module:
```
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Your::Module',
VERSION_FROM => 'lib/Your/Module.pm'
);
```
NAME is the top-level namespace of your module. VERSION\_FROM is the file which contains the $VERSION variable for the entire distribution. Typically this is the same as your top-level module.
MANIFEST A simple listing of all the files in your distribution.
```
Makefile.PL
MANIFEST
lib/Your/Module.pm
```
File paths in a MANIFEST always use Unix conventions (ie. /) even if you're not on Unix.
You can write this by hand or generate it with 'make manifest'.
See <ExtUtils::Manifest> for more details.
lib/ This is the directory where the .pm and .pod files you wish to have installed go. They are laid out according to namespace. So Foo::Bar is *lib/Foo/Bar.pm*.
t/ Tests for your modules go here. Each test filename ends with a .t. So *t/foo.t* 'make test' will run these tests.
Typically, the *t/* test directory is flat, with all test files located directly within it. However, you can nest tests within subdirectories, for example:
```
t/foo/subdir_test.t
```
To do this, you need to inform `WriteMakeFile()` in your *Makefile.PL* file in the following fashion:
```
test => {TESTS => 't/*.t t/*/*.t'}
```
That will run all tests in *t/*, as well as all tests in all subdirectories that reside under *t/*. You can nest as deeply as makes sense for your project. Simply add another entry in the test location string. For example, to test:
```
t/foo/bar/subdir_test.t
```
You would use the following `test` directive:
```
test => {TESTS => 't/*.t t/*/*/*.t'}
```
Note that in the above example, tests in the first subdirectory will not be run. To run all tests in the intermediary subdirectory preceding the one the test files are in, you need to explicitly note it:
```
test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'}
```
You don't need to specify wildcards if you only want to test within specific subdirectories. The following example will only run tests in *t/foo*:
```
test => {TESTS => 't/foo/*.t'}
```
Tests are run from the top level of your distribution. So inside a test you would refer to ./lib to enter the lib directory, for example.
Changes A log of changes you've made to this module. The layout is free-form. Here's an example:
```
1.01 Fri Apr 11 00:21:25 PDT 2003
- thing() does some stuff now
- fixed the wiggy bug in withit()
1.00 Mon Apr 7 00:57:15 PDT 2003
- "Rain of Frogs" now supported
```
README A short description of your module, what it does, why someone would use it and its limitations. CPAN automatically pulls your README file out of the archive and makes it available to CPAN users, it is the first thing they will read to decide if your module is right for them.
INSTALL Instructions on how to install your module along with any dependencies. Suggested information to include here:
```
any extra modules required for use
the minimum version of Perl required
if only works on certain operating systems
```
MANIFEST.SKIP A file full of regular expressions to exclude when using 'make manifest' to generate the MANIFEST. These regular expressions are checked against each file path found in the distribution (so you're matching against "t/foo.t" not "foo.t").
Here's a sample:
```
~$ # ignore emacs and vim backup files
.bak$ # ignore manual backups
\# # ignore CVS old revision files and emacs temp files
```
Since # can be used for comments, # must be escaped.
MakeMaker comes with a default MANIFEST.SKIP to avoid things like version control directories and backup files. Specifying your own will override this default.
bin/
SEE ALSO
---------
<perlmodstyle> gives stylistic help writing a module.
<perlnewmod> gives more information about how to write a module.
There are modules to help you through the process of writing a module: <ExtUtils::ModuleMaker>, <Module::Starter>, <Minilla::Tutorial>, <Dist::Milla::Tutorial>, <Dist::Zilla::Starter>
perl Encode::KR::2022_KR Encode::KR::2022\_KR
====================
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::KR::2022\_KR -- internally used by Encode::KR
| programming_docs |
perl IO::Socket::IP IO::Socket::IP
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [REPLACING IO::Socket DEFAULT BEHAVIOUR](#REPLACING-IO::Socket-DEFAULT-BEHAVIOUR)
* [CONSTRUCTORS](#CONSTRUCTORS)
+ [new](#new)
+ [new (one arg)](#new-(one-arg))
* [METHODS](#METHODS)
+ [sockhost\_service](#sockhost_service)
+ [sockhost](#sockhost)
+ [sockport](#sockport)
+ [sockhostname](#sockhostname)
+ [sockservice](#sockservice)
+ [sockaddr](#sockaddr)
+ [peerhost\_service](#peerhost_service)
+ [peerhost](#peerhost)
+ [peerport](#peerport)
+ [peerhostname](#peerhostname)
+ [peerservice](#peerservice)
+ [peeraddr](#peeraddr)
+ [as\_inet](#as_inet)
* [NON-BLOCKING](#NON-BLOCKING)
* [PeerHost AND LocalHost PARSING](#PeerHost-AND-LocalHost-PARSING)
+ [split\_addr](#split_addr)
+ [join\_addr](#join_addr)
* [IO::Socket::INET INCOMPATIBILITES](#IO::Socket::INET-INCOMPATIBILITES)
* [TODO](#TODO)
* [AUTHOR](#AUTHOR)
NAME
----
`IO::Socket::IP` - Family-neutral IP socket supporting both IPv4 and IPv6
SYNOPSIS
--------
```
use IO::Socket::IP;
my $sock = IO::Socket::IP->new(
PeerHost => "www.google.com",
PeerPort => "http",
Type => SOCK_STREAM,
) or die "Cannot construct socket - $@";
my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" :
( $sock->sockdomain == PF_INET ) ? "IPv4" :
"unknown";
printf "Connected to google via %s\n", $familyname;
```
DESCRIPTION
-----------
This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement for <IO::Socket::INET>. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see the `IO::Socket::INET` INCOMPATIBILITES section below.
It uses the `getaddrinfo(3)` function to convert hostnames and service names or port numbers into sets of possible addresses to connect to or listen on. This allows it to work for IPv6 where the system supports it, while still falling back to IPv4-only on systems which don't.
REPLACING `IO::Socket` DEFAULT BEHAVIOUR
-----------------------------------------
By placing `-register` in the import list to `IO::Socket::IP`, it will register itself with <IO::Socket> as the class that handles `PF_INET`. It will also ask to handle `PF_INET6` as well, provided that constant is available.
Changing `IO::Socket`'s default behaviour means that calling the `IO::Socket` constructor with either `PF_INET` or `PF_INET6` as the `Domain` parameter will yield an `IO::Socket::IP` object.
```
use IO::Socket::IP -register;
my $sock = IO::Socket->new(
Domain => PF_INET6,
LocalHost => "::1",
Listen => 1,
) or die "Cannot create socket - $@\n";
print "Created a socket of type " . ref($sock) . "\n";
```
Note that `-register` is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope.
CONSTRUCTORS
------------
### new
```
$sock = IO::Socket::IP->new( %args )
```
Creates a new `IO::Socket::IP` object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are:
PeerHost => STRING
PeerService => STRING Hostname and service name for the peer to `connect()` to. The service name may be given as a port number, as a decimal string.
PeerAddr => STRING
PeerPort => STRING For symmetry with the accessor methods and compatibility with `IO::Socket::INET`, these are accepted as synonyms for `PeerHost` and `PeerService` respectively.
PeerAddrInfo => ARRAY Alternate form of specifying the peer to `connect()` to. This should be an array of the form returned by `Socket::getaddrinfo`.
This parameter takes precedence over the `Peer*`, `Family`, `Type` and `Proto` arguments.
LocalHost => STRING
LocalService => STRING Hostname and service name for the local address to `bind()` to.
LocalAddr => STRING
LocalPort => STRING For symmetry with the accessor methods and compatibility with `IO::Socket::INET`, these are accepted as synonyms for `LocalHost` and `LocalService` respectively.
LocalAddrInfo => ARRAY Alternate form of specifying the local address to `bind()` to. This should be an array of the form returned by `Socket::getaddrinfo`.
This parameter takes precedence over the `Local*`, `Family`, `Type` and `Proto` arguments.
Family => INT The address family to pass to `getaddrinfo` (e.g. `AF_INET`, `AF_INET6`). Normally this will be left undefined, and `getaddrinfo` will search using any address family supported by the system.
Type => INT The socket type to pass to `getaddrinfo` (e.g. `SOCK_STREAM`, `SOCK_DGRAM`). Normally defined by the caller; if left undefined `getaddrinfo` may attempt to infer the type from the service name.
Proto => STRING or INT The IP protocol to use for the socket (e.g. `'tcp'`, `IPPROTO_TCP`, `'udp'`,`IPPROTO_UDP`). Normally this will be left undefined, and either `getaddrinfo` or the kernel will choose an appropriate value. May be given either in string name or numeric form.
GetAddrInfoFlags => INT More flags to pass to the `getaddrinfo()` function. If not supplied, a default of `AI_ADDRCONFIG` will be used.
These flags will be combined with `AI_PASSIVE` if the `Listen` argument is given. For more information see the documentation about `getaddrinfo()` in the [Socket](socket) module.
Listen => INT If defined, puts the socket into listening mode where new connections can be accepted using the `accept` method. The value given is used as the `listen(2)` queue size.
ReuseAddr => BOOL If true, set the `SO_REUSEADDR` sockopt
ReusePort => BOOL If true, set the `SO_REUSEPORT` sockopt (not all OSes implement this sockopt)
Broadcast => BOOL If true, set the `SO_BROADCAST` sockopt
Sockopts => ARRAY An optional array of other socket options to apply after the three listed above. The value is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner array relates to a single option, giving the level and option name, and an optional value. If the value element is missing, it will be given the value of a platform-sized integer 1 constant (i.e. suitable to enable most of the common boolean options).
For example, both options given below are equivalent to setting `ReuseAddr`.
```
Sockopts => [
[ SOL_SOCKET, SO_REUSEADDR ],
[ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ],
]
```
V6Only => BOOL If defined, set the `IPV6_V6ONLY` sockopt when creating `PF_INET6` sockets to the given value. If true, a listening-mode socket will only listen on the `AF_INET6` addresses; if false it will also accept connections from `AF_INET` addresses.
If not defined, the socket option will not be changed, and default value set by the operating system will apply. For repeatable behaviour across platforms it is recommended this value always be defined for listening-mode sockets.
Note that not all platforms support disabling this option. Some, at least OpenBSD and MirBSD, will fail with `EINVAL` if you attempt to disable it. To determine whether it is possible to disable, you may use the class method
```
if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) {
...
}
else {
...
}
```
If your platform does not support disabling this option but you still want to listen for both `AF_INET` and `AF_INET6` connections you will have to create two listening sockets, one bound to each protocol.
MultiHomed This `IO::Socket::INET`-style argument is ignored, except if it is defined but false. See the `IO::Socket::INET` INCOMPATIBILITES section below.
However, the behaviour it enables is always performed by `IO::Socket::IP`.
Blocking => BOOL If defined but false, the socket will be set to non-blocking mode. Otherwise it will default to blocking mode. See the NON-BLOCKING section below for more detail.
Timeout => NUM If defined, gives a maximum time in seconds to block per `connect()` call when in blocking mode. If missing, no timeout is applied other than that provided by the underlying operating system. When in non-blocking mode this parameter is ignored.
Note that if the hostname resolves to multiple address candidates, the same timeout will apply to each connection attempt individually, rather than to the operation as a whole. Further note that the timeout does not apply to the initial hostname resolve operation, if connecting by hostname.
This behviour is copied inspired by `IO::Socket::INET`; for more fine grained control over connection timeouts, consider performing a nonblocking connect directly.
If neither `Type` nor `Proto` hints are provided, a default of `SOCK_STREAM` and `IPPROTO_TCP` respectively will be set, to maintain compatibility with `IO::Socket::INET`. Other named arguments that are not recognised are ignored.
If neither `Family` nor any hosts or addresses are passed, nor any `*AddrInfo`, then the constructor has no information on which to decide a socket family to create. In this case, it performs a `getaddinfo` call with the `AI_ADDRCONFIG` flag, no host name, and a service name of `"0"`, and uses the family of the first returned result.
If the constructor fails, it will set `$@` to an appropriate error message; this may be from `$!` or it may be some other string; not every failure necessarily has an associated `errno` value.
###
new (one arg)
```
$sock = IO::Socket::IP->new( $peeraddr )
```
As a special case, if the constructor is passed a single argument (as opposed to an even-sized list of key/value pairs), it is taken to be the value of the `PeerAddr` parameter. This is parsed in the same way, according to the behaviour given in the `PeerHost` AND `LocalHost` PARSING section below.
METHODS
-------
As well as the following methods, this class inherits all the methods in <IO::Socket> and <IO::Handle>.
### sockhost\_service
```
( $host, $service ) = $sock->sockhost_service( $numeric )
```
Returns the hostname and service name of the local address (that is, the socket address given by the `sockname` method).
If `$numeric` is true, these will be given in numeric form rather than being resolved into names.
The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call `getnameinfo(3)` only once.
### sockhost
```
$addr = $sock->sockhost
```
Return the numeric form of the local address as a textual representation
### sockport
```
$port = $sock->sockport
```
Return the numeric form of the local port number
### sockhostname
```
$host = $sock->sockhostname
```
Return the resolved name of the local address
### sockservice
```
$service = $sock->sockservice
```
Return the resolved name of the local port number
### sockaddr
```
$addr = $sock->sockaddr
```
Return the local address as a binary octet string
### peerhost\_service
```
( $host, $service ) = $sock->peerhost_service( $numeric )
```
Returns the hostname and service name of the peer address (that is, the socket address given by the `peername` method), similar to the `sockhost_service` method.
The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call `getnameinfo(3)` only once.
### peerhost
```
$addr = $sock->peerhost
```
Return the numeric form of the peer address as a textual representation
### peerport
```
$port = $sock->peerport
```
Return the numeric form of the peer port number
### peerhostname
```
$host = $sock->peerhostname
```
Return the resolved name of the peer address
### peerservice
```
$service = $sock->peerservice
```
Return the resolved name of the peer port number
### peeraddr
```
$addr = $peer->peeraddr
```
Return the peer address as a binary octet string
### as\_inet
```
$inet = $sock->as_inet
```
Returns a new <IO::Socket::INET> instance wrapping the same filehandle. This may be useful in cases where it is required, for backward-compatibility, to have a real object of `IO::Socket::INET` type instead of `IO::Socket::IP`. The new object will wrap the same underlying socket filehandle as the original, so care should be taken not to continue to use both objects concurrently. Ideally the original `$sock` should be discarded after this method is called.
This method checks that the socket domain is `PF_INET` and will throw an exception if it isn't.
NON-BLOCKING
-------------
If the constructor is passed a defined but false value for the `Blocking` argument then the socket is put into non-blocking mode. When in non-blocking mode, the socket will not be set up by the time the constructor returns, because the underlying `connect(2)` syscall would otherwise have to block.
The non-blocking behaviour is an extension of the `IO::Socket::INET` API, unique to `IO::Socket::IP`, because the former does not support multi-homed non-blocking connect.
When using non-blocking mode, the caller must repeatedly check for writeability on the filehandle (for instance using `select` or `IO::Poll`). Each time the filehandle is ready to write, the `connect` method must be called, with no arguments. Note that some operating systems, most notably `MSWin32` do not report a `connect()` failure using write-ready; so you must also `select()` for exceptional status.
While `connect` returns false, the value of `$!` indicates whether it should be tried again (by being set to the value `EINPROGRESS`, or `EWOULDBLOCK` on MSWin32), or whether a permanent error has occurred (e.g. `ECONNREFUSED`).
Once the socket has been connected to the peer, `connect` will return true and the socket will now be ready to use.
Note that calls to the platform's underlying `getaddrinfo(3)` function may block. If `IO::Socket::IP` has to perform this lookup, the constructor will block even when in non-blocking mode.
To avoid this blocking behaviour, the caller should pass in the result of such a lookup using the `PeerAddrInfo` or `LocalAddrInfo` arguments. This can be achieved by using <Net::LibAsyncNS>, or the `getaddrinfo(3)` function can be called in a child process.
```
use IO::Socket::IP;
use Errno qw( EINPROGRESS EWOULDBLOCK );
my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here
my $socket = IO::Socket::IP->new(
PeerAddrInfo => \@peeraddrinfo,
Blocking => 0,
) or die "Cannot construct socket - $@";
while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) {
my $wvec = '';
vec( $wvec, fileno $socket, 1 ) = 1;
my $evec = '';
vec( $evec, fileno $socket, 1 ) = 1;
select( undef, $wvec, $evec, undef ) or die "Cannot select - $!";
}
die "Cannot connect - $!" if $!;
...
```
The example above uses `select()`, but any similar mechanism should work analogously. `IO::Socket::IP` takes care when creating new socket filehandles to preserve the actual file descriptor number, so such techniques as `poll` or `epoll` should be transparent to its reallocation of a different socket underneath, perhaps in order to switch protocol family between `PF_INET` and `PF_INET6`.
For another example using `IO::Poll` and `Net::LibAsyncNS`, see the *examples/nonblocking\_libasyncns.pl* file in the module distribution.
`PeerHost` AND `LocalHost` PARSING
-----------------------------------
To support the `IO::Socket::INET` API, the host and port information may be passed in a single string rather than as two separate arguments.
If either `LocalHost` or `PeerHost` (or their `...Addr` synonyms) have any of the following special forms then special parsing is applied.
The value of the `...Host` argument will be split to give both the hostname and port (or service name):
```
hostname.example.org:http # Host name
192.0.2.1:80 # IPv4 address
[2001:db8::1]:80 # IPv6 address
```
In each case, the port or service name (e.g. `80`) is passed as the `LocalService` or `PeerService` argument.
Either of `LocalService` or `PeerService` (or their `...Port` synonyms) can be either a service name, a decimal number, or a string containing both a service name and number, in a form such as
```
http(80)
```
In this case, the name (`http`) will be tried first, but if the resolver does not understand it then the port number (`80`) will be used instead.
If the `...Host` argument is in this special form and the corresponding `...Service` or `...Port` argument is also defined, the one parsed from the `...Host` argument will take precedence and the other will be ignored.
### split\_addr
```
( $host, $port ) = IO::Socket::IP->split_addr( $addr )
```
Utility method that provides the parsing functionality described above. Returns a 2-element list, containing either the split hostname and port description if it could be parsed, or the given address and `undef` if it was not recognised.
```
IO::Socket::IP->split_addr( "hostname:http" )
# ( "hostname", "http" )
IO::Socket::IP->split_addr( "192.0.2.1:80" )
# ( "192.0.2.1", "80" )
IO::Socket::IP->split_addr( "[2001:db8::1]:80" )
# ( "2001:db8::1", "80" )
IO::Socket::IP->split_addr( "something.else" )
# ( "something.else", undef )
```
### join\_addr
```
$addr = IO::Socket::IP->join_addr( $host, $port )
```
Utility method that performs the reverse of `split_addr`, returning a string formed by joining the specified host address and port number. The host address will be wrapped in `[]` brackets if required (because it is a raw IPv6 numeric address).
This can be especially useful when combined with the `sockhost_service` or `peerhost_service` methods.
```
say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
```
`IO::Socket::INET` INCOMPATIBILITES
------------------------------------
* The behaviour enabled by `MultiHomed` is in fact implemented by `IO::Socket::IP` as it is required to correctly support searching for a useable address from the results of the `getaddrinfo(3)` call. The constructor will ignore the value of this argument, except if it is defined but false. An exception is thrown in this case, because that would request it disable the `getaddrinfo(3)` search behaviour in the first place.
* `IO::Socket::IP` implements both the `Blocking` and `Timeout` parameters, but it implements the interaction of both in a different way.
In `::INET`, supplying a timeout overrides the non-blocking behaviour, meaning that the `connect()` operation will still block despite that the caller asked for a non-blocking socket. This is not explicitly specified in its documentation, nor does this author believe that is a useful behaviour - it appears to come from a quirk of implementation.
In `::IP` therefore, the `Blocking` parameter takes precedence - if a non-blocking socket is requested, no operation will block. The `Timeout` parameter here simply defines the maximum time that a blocking `connect()` call will wait, if it blocks at all.
In order to specifically obtain the "blocking connect then non-blocking send and receive" behaviour of specifying this combination of options to `::INET` when using `::IP`, perform first a blocking connect, then afterwards turn the socket into nonblocking mode.
```
my $sock = IO::Socket::IP->new(
PeerHost => $peer,
Timeout => 20,
) or die "Cannot connect - $@";
$sock->blocking( 0 );
```
This code will behave identically under both `IO::Socket::INET` and `IO::Socket::IP`.
TODO
----
* Investigate whether `POSIX::dup2` upsets BSD's `kqueue` watchers, and if so, consider what possible workarounds might be applied.
AUTHOR
------
Paul Evans <[email protected]>
| programming_docs |
perl Encode::JP::JIS7 Encode::JP::JIS7
================
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::JP::JIS7 -- internally used by Encode::JP
perl IO::Seekable IO::Seekable
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
IO::Seekable - supply seek based methods for I/O objects
SYNOPSIS
--------
```
use IO::Seekable;
package IO::Something;
@ISA = qw(IO::Seekable);
```
DESCRIPTION
-----------
`IO::Seekable` does not have a constructor of its own as it is intended to be inherited by other `IO::Handle` based objects. It provides methods which allow seeking of the file descriptors.
$io->getpos Returns an opaque value that represents the current position of the IO::File, or `undef` if this is not possible (eg an unseekable stream such as a terminal, pipe or socket). If the fgetpos() function is available in your C library it is used to implements getpos, else perl emulates getpos using C's ftell() function.
$io->setpos Uses the value of a previous getpos call to return to a previously visited position. Returns "0 but true" on success, `undef` on failure.
See <perlfunc> for complete descriptions of each of the following supported `IO::Seekable` methods, which are just front ends for the corresponding built-in functions:
$io->seek ( POS, WHENCE ) Seek the IO::File to position POS, relative to WHENCE:
WHENCE=0 (SEEK\_SET) POS is absolute position. (Seek relative to the start of the file)
WHENCE=1 (SEEK\_CUR) POS is an offset from the current position. (Seek relative to current)
WHENCE=2 (SEEK\_END) POS is an offset from the end of the file. (Seek relative to end)
The SEEK\_\* constants can be imported from the `Fcntl` module if you don't wish to use the numbers `0` `1` or `2` in your code.
Returns `1` upon success, `0` otherwise.
$io->sysseek( POS, WHENCE ) Similar to $io->seek, but sets the IO::File's position using the system call lseek(2) directly, so will confuse most perl IO operators except sysread and syswrite (see <perlfunc> for full details)
Returns the new position, or `undef` on failure. A position of zero is returned as the string `"0 but true"`
$io->tell Returns the IO::File's current position, or -1 on error.
SEE ALSO
---------
<perlfunc>, ["I/O Operators" in perlop](perlop#I%2FO-Operators), <IO::Handle> <IO::File>
HISTORY
-------
Derived from FileHandle.pm by Graham Barr <[email protected]>
perl Pod::Perldoc::ToMan Pod::Perldoc::ToMan
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToMan - let Perldoc render Pod as man pages
SYNOPSIS
--------
```
perldoc -o man Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Man and `groff` for reading Pod pages.
The following options are supported: center, date, fixed, fixedbold, fixeditalic, fixedbolditalic, quotes, release, section
(Those options are explained in <Pod::Man>.)
For example:
```
perldoc -o man -w center:Pod Some::Modulename
```
CAVEAT
------
This module may change to use a different pod-to-nroff formatter class in the future, and this may change what options are supported.
SEE ALSO
---------
<Pod::Man>, <Pod::Perldoc>, <Pod::Perldoc::ToNroff>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2011 brian d foy. All rights reserved.
Copyright (c) 2002,3,4 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 perlembed perlembed
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [PREAMBLE](#PREAMBLE)
+ [ROADMAP](#ROADMAP)
+ [Compiling your C program](#Compiling-your-C-program)
+ [Adding a Perl interpreter to your C program](#Adding-a-Perl-interpreter-to-your-C-program)
+ [Calling a Perl subroutine from your C program](#Calling-a-Perl-subroutine-from-your-C-program)
+ [Evaluating a Perl statement from your C program](#Evaluating-a-Perl-statement-from-your-C-program)
+ [Performing Perl pattern matches and substitutions from your C program](#Performing-Perl-pattern-matches-and-substitutions-from-your-C-program)
+ [Fiddling with the Perl stack from your C program](#Fiddling-with-the-Perl-stack-from-your-C-program)
+ [Maintaining a persistent interpreter](#Maintaining-a-persistent-interpreter)
+ [Execution of END blocks](#Execution-of-END-blocks)
+ [$0 assignments](#%240-assignments)
+ [Maintaining multiple interpreter instances](#Maintaining-multiple-interpreter-instances)
+ [Using Perl modules, which themselves use C libraries, from your C program](#Using-Perl-modules,-which-themselves-use-C-libraries,-from-your-C-program)
+ [Using embedded Perl with POSIX locales](#Using-embedded-Perl-with-POSIX-locales)
* [Hiding Perl\_](#Hiding-Perl_)
* [MORAL](#MORAL)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
perlembed - how to embed perl in your C program
DESCRIPTION
-----------
### PREAMBLE
Do you want to:
**Use C from Perl?**
Read <perlxstut>, <perlxs>, <h2xs>, <perlguts>, and <perlapi>.
**Use a Unix program from Perl?**
Read about back-quotes and about `system` and `exec` in <perlfunc>.
**Use Perl from Perl?**
Read about ["do" in perlfunc](perlfunc#do) and ["eval" in perlfunc](perlfunc#eval) and ["require" in perlfunc](perlfunc#require) and ["use" in perlfunc](perlfunc#use).
**Use C from C?**
Rethink your design.
**Use Perl from C?**
Read on...
### ROADMAP
* Compiling your C program
* Adding a Perl interpreter to your C program
* Calling a Perl subroutine from your C program
* Evaluating a Perl statement from your C program
* Performing Perl pattern matches and substitutions from your C program
* Fiddling with the Perl stack from your C program
* Maintaining a persistent interpreter
* Maintaining multiple interpreter instances
* Using Perl modules, which themselves use C libraries, from your C program
* Embedding Perl under Win32
###
Compiling your C program
If you have trouble compiling the scripts in this documentation, you're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY THE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)
Also, every C program that uses Perl must link in the *perl library*. What's that, you ask? Perl is itself written in C; the perl library is the collection of compiled C programs that were used to create your perl executable (*/usr/bin/perl* or equivalent). (Corollary: you can't use Perl from your C program unless Perl has been compiled on your machine, or installed properly--that's why you shouldn't blithely copy Perl executables from machine to machine without also copying the *lib* directory.)
When you use Perl from C, your C program will--usually--allocate, "run", and deallocate a *PerlInterpreter* object, which is defined by the perl library.
If your copy of Perl is recent enough to contain this documentation (version 5.002 or later), then the perl library (and *EXTERN.h* and *perl.h*, which you'll also need) will reside in a directory that looks like this:
```
/usr/local/lib/perl5/your_architecture_here/CORE
```
or perhaps just
```
/usr/local/lib/perl5/CORE
```
or maybe something like
```
/usr/opt/perl5/CORE
```
Execute this statement for a hint about where to find CORE:
```
perl -MConfig -e 'print $Config{archlib}'
```
Here's how you'd compile the example in the next section, ["Adding a Perl interpreter to your C program"](#Adding-a-Perl-interpreter-to-your-C-program), on my Linux box:
```
% gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
-I/usr/local/lib/perl5/i586-linux/5.003/CORE
-L/usr/local/lib/perl5/i586-linux/5.003/CORE
-o interp interp.c -lperl -lm
```
(That's all one line.) On my DEC Alpha running old 5.003\_05, the incantation is a bit different:
```
% cc -O2 -Olimit 2900 -I/usr/local/include
-I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
-L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
-D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
```
How can you figure out what to add? Assuming your Perl is post-5.001, execute a `perl -V` command and pay special attention to the "cc" and "ccflags" information.
You'll have to choose the appropriate compiler (*cc*, *gcc*, et al.) for your machine: `perl -MConfig -e 'print $Config{cc}'` will tell you what to use.
You'll also have to choose the appropriate library directory (*/usr/local/lib/...*) for your machine. If your compiler complains that certain functions are undefined, or that it can't locate *-lperl*, then you need to change the path following the `-L`. If it complains that it can't find *EXTERN.h* and *perl.h*, you need to change the path following the `-I`.
You may have to add extra libraries as well. Which ones? Perhaps those printed by
```
perl -MConfig -e 'print $Config{libs}'
```
Provided your perl binary was properly configured and installed the **ExtUtils::Embed** module will determine all of this information for you:
```
% cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
```
If the **ExtUtils::Embed** module isn't part of your Perl distribution, you can retrieve it from <https://metacpan.org/pod/ExtUtils::Embed> (If this documentation came from your Perl distribution, then you're running 5.004 or better and you already have it.)
The **ExtUtils::Embed** kit on CPAN also contains all source code for the examples in this document, tests, additional examples and other information you may find useful.
###
Adding a Perl interpreter to your C program
In a sense, perl (the C program) is a good example of embedding Perl (the language), so I'll demonstrate embedding with *miniperlmain.c*, included in the source distribution. Here's a bastardized, non-portable version of *miniperlmain.c* containing the essentials of embedding:
```
#include <EXTERN.h> /* from the Perl distribution */
#include <perl.h> /* from the Perl distribution */
static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
int main(int argc, char **argv, char **env)
{
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
perl_run(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
```
Notice that we don't use the `env` pointer. Normally handed to `perl_parse` as its final argument, `env` here is replaced by `NULL`, which means that the current environment will be used.
The macros PERL\_SYS\_INIT3() and PERL\_SYS\_TERM() provide system-specific tune up of the C runtime environment necessary to run Perl interpreters; they should only be called once regardless of how many interpreters you create or destroy. Call PERL\_SYS\_INIT3() before you create your first interpreter, and PERL\_SYS\_TERM() after you free your last interpreter.
Since PERL\_SYS\_INIT3() may change `env`, it may be more appropriate to provide `env` as an argument to perl\_parse().
Also notice that no matter what arguments you pass to perl\_parse(), PERL\_SYS\_INIT3() must be invoked on the C main() argc, argv and env and only once.
Mind that argv[argc] must be NULL, same as those passed to a main function in C.
Now compile this program (I'll call it *interp.c*) into an executable:
```
% cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
```
After a successful compilation, you'll be able to use *interp* just like perl itself:
```
% interp
print "Pretty Good Perl \n";
print "10890 - 9801 is ", 10890 - 9801;
<CTRL-D>
Pretty Good Perl
10890 - 9801 is 1089
```
or
```
% interp -e 'printf("%x", 3735928559)'
deadbeef
```
You can also read and execute Perl statements from a file while in the midst of your C program, by placing the filename in *argv[1]* before calling *perl\_run*.
###
Calling a Perl subroutine from your C program
To call individual Perl subroutines, you can use any of the **call\_\*** functions documented in <perlcall>. In this example we'll use `call_argv`.
That's shown below, in a program I'll call *showtime.c*.
```
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
int main(int argc, char **argv, char **env)
{
char *args[] = { NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
perl_parse(my_perl, NULL, argc, argv, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
/*** skipping perl_run() ***/
call_argv("showtime", G_DISCARD | G_NOARGS, args);
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
```
where *showtime* is a Perl subroutine that takes no arguments (that's the *G\_NOARGS*) and for which I'll ignore the return value (that's the *G\_DISCARD*). Those flags, and others, are discussed in <perlcall>.
I'll define the *showtime* subroutine in a file called *showtime.pl*:
```
print "I shan't be printed.";
sub showtime {
print time;
}
```
Simple enough. Now compile and run:
```
% cc -o showtime showtime.c \
`perl -MExtUtils::Embed -e ccopts -e ldopts`
% showtime showtime.pl
818284590
```
yielding the number of seconds that elapsed between January 1, 1970 (the beginning of the Unix epoch), and the moment I began writing this sentence.
In this particular case we don't have to call *perl\_run*, as we set the PL\_exit\_flag PERL\_EXIT\_DESTRUCT\_END which executes END blocks in perl\_destruct.
If you want to pass arguments to the Perl subroutine, you can add strings to the `NULL`-terminated `args` list passed to *call\_argv*. For other data types, or to examine return values, you'll need to manipulate the Perl stack. That's demonstrated in ["Fiddling with the Perl stack from your C program"](#Fiddling-with-the-Perl-stack-from-your-C-program).
###
Evaluating a Perl statement from your C program
Perl provides two API functions to evaluate pieces of Perl code. These are ["eval\_sv" in perlapi](perlapi#eval_sv) and ["eval\_pv" in perlapi](perlapi#eval_pv).
Arguably, these are the only routines you'll ever need to execute snippets of Perl code from within your C program. Your code can be as long as you wish; it can contain multiple statements; it can employ ["use" in perlfunc](perlfunc#use), ["require" in perlfunc](perlfunc#require), and ["do" in perlfunc](perlfunc#do) to include external Perl files.
*eval\_pv* lets us evaluate individual Perl strings, and then extract variables for coercion into C types. The following program, *string.c*, executes three Perl strings, extracting an `int` from the first, a `float` from the second, and a `char *` from the third.
```
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
main (int argc, char **argv, char **env)
{
char *embedding[] = { "", "-e", "0", NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct( my_perl );
perl_parse(my_perl, NULL, 3, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_run(my_perl);
/** Treat $a as an integer **/
eval_pv("$a = 3; $a **= 2", TRUE);
printf("a = %d\n", SvIV(get_sv("a", 0)));
/** Treat $a as a float **/
eval_pv("$a = 3.14; $a **= 2", TRUE);
printf("a = %f\n", SvNV(get_sv("a", 0)));
/** Treat $a as a string **/
eval_pv(
"$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
printf("a = %s\n", SvPV_nolen(get_sv("a", 0)));
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
}
```
All of those strange functions with *sv* in their names help convert Perl scalars to C types. They're described in <perlguts> and <perlapi>.
If you compile and run *string.c*, you'll see the results of using *SvIV()* to create an `int`, *SvNV()* to create a `float`, and *SvPV()* to create a string:
```
a = 9
a = 9.859600
a = Just Another Perl Hacker
```
In the example above, we've created a global variable to temporarily store the computed value of our eval'ed expression. It is also possible and in most cases a better strategy to fetch the return value from *eval\_pv()* instead. Example:
```
...
SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
printf("%s\n", SvPV_nolen(val));
...
```
This way, we avoid namespace pollution by not creating global variables and we've simplified our code as well.
###
Performing Perl pattern matches and substitutions from your C program
The *eval\_sv()* function lets us evaluate strings of Perl code, so we can define some functions that use it to "specialize" in matches and substitutions: *match()*, *substitute()*, and *matches()*.
```
I32 match(SV *string, char *pattern);
```
Given a string and a pattern (e.g., `m/clasp/` or `/\b\w*\b/`, which in your C program might appear as "/\\b\\w\*\\b/"), match() returns 1 if the string matches the pattern and 0 otherwise.
```
int substitute(SV **string, char *pattern);
```
Given a pointer to an `SV` and an `=~` operation (e.g., `s/bob/robert/g` or `tr[A-Z][a-z]`), substitute() modifies the string within the `SV` as according to the operation, returning the number of substitutions made.
```
SSize_t matches(SV *string, char *pattern, AV **matches);
```
Given an `SV`, a pattern, and a pointer to an empty `AV`, matches() evaluates `$string =~ $pattern` in a list context, and fills in *matches* with the array elements, returning the number of matches found.
Here's a sample program, *match.c*, that uses all three (long lines have been wrapped here):
```
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
/** my_eval_sv(code, error_check)
** kinda like eval_sv(),
** but we pop the return value off the stack
**/
SV* my_eval_sv(SV *sv, I32 croak_on_error)
{
dSP;
SV* retval;
PUSHMARK(SP);
eval_sv(sv, G_SCALAR);
SPAGAIN;
retval = POPs;
PUTBACK;
if (croak_on_error && SvTRUE(ERRSV))
croak_sv(ERRSV);
return retval;
}
/** match(string, pattern)
**
** Used for matches in a scalar context.
**
** Returns 1 if the match was successful; 0 otherwise.
**/
I32 match(SV *string, char *pattern)
{
SV *command = newSV(0), *retval;
sv_setpvf(command, "my $string = '%s'; $string =~ %s",
SvPV_nolen(string), pattern);
retval = my_eval_sv(command, TRUE);
SvREFCNT_dec(command);
return SvIV(retval);
}
/** substitute(string, pattern)
**
** Used for =~ operations that
** modify their left-hand side (s/// and tr///)
**
** Returns the number of successful matches, and
** modifies the input string if there were any.
**/
I32 substitute(SV **string, char *pattern)
{
SV *command = newSV(0), *retval;
sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
SvPV_nolen(*string), pattern);
retval = my_eval_sv(command, TRUE);
SvREFCNT_dec(command);
*string = get_sv("string", 0);
return SvIV(retval);
}
/** matches(string, pattern, matches)
**
** Used for matches in a list context.
**
** Returns the number of matches,
** and fills in **matches with the matching substrings
**/
SSize_t matches(SV *string, char *pattern, AV **match_list)
{
SV *command = newSV(0);
SSize_t num_matches;
sv_setpvf(command, "my $string = '%s'; @array = ($string =~ %s)",
SvPV_nolen(string), pattern);
my_eval_sv(command, TRUE);
SvREFCNT_dec(command);
*match_list = get_av("array", 0);
num_matches = av_top_index(*match_list) + 1;
return num_matches;
}
main (int argc, char **argv, char **env)
{
char *embedding[] = { "", "-e", "0", NULL };
AV *match_list;
I32 num_matches, i;
SV *text;
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
perl_parse(my_perl, NULL, 3, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
text = newSV(0);
sv_setpv(text, "When he is at a convenience store and the "
"bill comes to some amount like 76 cents, Maynard is "
"aware that there is something he *should* do, something "
"that will enable him to get back a quarter, but he has "
"no idea *what*. He fumbles through his red squeezey "
"changepurse and gives the boy three extra pennies with "
"his dollar, hoping that he might luck into the correct "
"amount. The boy gives him back two of his own pennies "
"and then the big shiny quarter that is his prize. "
"-RICHH");
if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
printf("match: Text contains the word 'quarter'.\n\n");
else
printf("match: Text doesn't contain the word 'quarter'.\n\n");
if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
printf("match: Text contains the word 'eighth'.\n\n");
else
printf("match: Text doesn't contain the word 'eighth'.\n\n");
/** Match all occurrences of /wi../ **/
num_matches = matches(text, "m/(wi..)/g", &match_list);
printf("matches: m/(wi..)/g found %d matches...\n", num_matches);
for (i = 0; i < num_matches; i++)
printf("match: %s\n",
SvPV_nolen(*av_fetch(match_list, i, FALSE)));
printf("\n");
/** Remove all vowels from text **/
num_matches = substitute(&text, "s/[aeiou]//gi");
if (num_matches) {
printf("substitute: s/[aeiou]//gi...%lu substitutions made.\n",
(unsigned long)num_matches);
printf("Now text is: %s\n\n", SvPV_nolen(text));
}
/** Attempt a substitution **/
if (!substitute(&text, "s/Perl/C/")) {
printf("substitute: s/Perl/C...No substitution made.\n\n");
}
SvREFCNT_dec(text);
PL_perl_destruct_level = 1;
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
}
```
which produces the output (again, long lines have been wrapped here)
```
match: Text contains the word 'quarter'.
match: Text doesn't contain the word 'eighth'.
matches: m/(wi..)/g found 2 matches...
match: will
match: with
substitute: s/[aeiou]//gi...139 substitutions made.
Now text is: Whn h s t cnvnnc str nd th bll cms t sm mnt lk 76 cnts,
Mynrd s wr tht thr s smthng h *shld* d, smthng tht wll nbl hm t gt
bck qrtr, bt h hs n d *wht*. H fmbls thrgh hs rd sqzy chngprs nd
gvs th by thr xtr pnns wth hs dllr, hpng tht h mght lck nt th crrct
mnt. Th by gvs hm bck tw f hs wn pnns nd thn th bg shny qrtr tht s
hs prz. -RCHH
substitute: s/Perl/C...No substitution made.
```
###
Fiddling with the Perl stack from your C program
When trying to explain stacks, most computer science textbooks mumble something about spring-loaded columns of cafeteria plates: the last thing you pushed on the stack is the first thing you pop off. That'll do for our purposes: your C program will push some arguments onto "the Perl stack", shut its eyes while some magic happens, and then pop the results--the return value of your Perl subroutine--off the stack.
First you'll need to know how to convert between C types and Perl types, with newSViv() and sv\_setnv() and newAV() and all their friends. They're described in <perlguts> and <perlapi>.
Then you'll need to know how to manipulate the Perl stack. That's described in <perlcall>.
Once you've understood those, embedding Perl in C is easy.
Because C has no builtin function for integer exponentiation, let's make Perl's \*\* operator available to it (this is less useful than it sounds, because Perl implements \*\* with C's *pow()* function). First I'll create a stub exponentiation function in *power.pl*:
```
sub expo {
my ($a, $b) = @_;
return $a ** $b;
}
```
Now I'll create a C program, *power.c*, with a function *PerlPower()* that contains all the perlguts necessary to push the two arguments into *expo()* and to pop the return value out. Take a deep breath...
```
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
static void
PerlPower(int a, int b)
{
dSP; /* initialize stack pointer */
ENTER; /* everything created after here */
SAVETMPS; /* ...is a temporary variable. */
PUSHMARK(SP); /* remember the stack pointer */
XPUSHs(sv_2mortal(newSViv(a))); /* push the base onto the stack */
XPUSHs(sv_2mortal(newSViv(b))); /* push the exponent onto stack */
PUTBACK; /* make local stack pointer global */
call_pv("expo", G_SCALAR); /* call the function */
SPAGAIN; /* refresh stack pointer */
/* pop the return value from stack */
printf ("%d to the %dth power is %d.\n", a, b, POPi);
PUTBACK;
FREETMPS; /* free that return value */
LEAVE; /* ...and the XPUSHed "mortal" args.*/
}
int main (int argc, char **argv, char **env)
{
char *my_argv[] = { "", "power.pl", NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct( my_perl );
perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_run(my_perl);
PerlPower(3, 4); /*** Compute 3 ** 4 ***/
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
```
Compile and run:
```
% cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
% power
3 to the 4th power is 81.
```
###
Maintaining a persistent interpreter
When developing interactive and/or potentially long-running applications, it's a good idea to maintain a persistent interpreter rather than allocating and constructing a new interpreter multiple times. The major reason is speed: since Perl will only be loaded into memory once.
However, you have to be more cautious with namespace and variable scoping when using a persistent interpreter. In previous examples we've been using global variables in the default package `main`. We knew exactly what code would be run, and assumed we could avoid variable collisions and outrageous symbol table growth.
Let's say your application is a server that will occasionally run Perl code from some arbitrary file. Your server has no way of knowing what code it's going to run. Very dangerous.
If the file is pulled in by `perl_parse()`, compiled into a newly constructed interpreter, and subsequently cleaned out with `perl_destruct()` afterwards, you're shielded from most namespace troubles.
One way to avoid namespace collisions in this scenario is to translate the filename into a guaranteed-unique package name, and then compile the code into that package using ["eval" in perlfunc](perlfunc#eval). In the example below, each file will only be compiled once. Or, the application might choose to clean out the symbol table associated with the file after it's no longer needed. Using ["call\_argv" in perlapi](perlapi#call_argv), We'll call the subroutine `Embed::Persistent::eval_file` which lives in the file `persistent.pl` and pass the filename and boolean cleanup/cache flag as arguments.
Note that the process will continue to grow for each file that it uses. In addition, there might be `AUTOLOAD`ed subroutines and other conditions that cause Perl's symbol table to grow. You might want to add some logic that keeps track of the process size, or restarts itself after a certain number of requests, to ensure that memory consumption is minimized. You'll also want to scope your variables with ["my" in perlfunc](perlfunc#my) whenever possible.
```
package Embed::Persistent;
#persistent.pl
use strict;
our %Cache;
use Symbol qw(delete_package);
sub valid_package_name {
my($string) = @_;
$string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
# second pass only for words starting with a digit
$string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
# Dress it up as a real package name
$string =~ s|/|::|g;
return "Embed" . $string;
}
sub eval_file {
my($filename, $delete) = @_;
my $package = valid_package_name($filename);
my $mtime = -M $filename;
if(defined $Cache{$package}{mtime}
&&
$Cache{$package}{mtime} <= $mtime)
{
# we have compiled this subroutine already,
# it has not been updated on disk, nothing left to do
print STDERR "already compiled $package->handler\n";
}
else {
local *FH;
open FH, $filename or die "open '$filename' $!";
local($/) = undef;
my $sub = <FH>;
close FH;
#wrap the code into a subroutine inside our unique package
my $eval = qq{package $package; sub handler { $sub; }};
{
# hide our variables within this block
my($filename,$mtime,$package,$sub);
eval $eval;
}
die $@ if $@;
#cache it unless we're cleaning out each time
$Cache{$package}{mtime} = $mtime unless $delete;
}
eval {$package->handler;};
die $@ if $@;
delete_package($package) if $delete;
#take a look if you want
#print Devel::Symdump->rnew($package)->as_string, $/;
}
1;
__END__
/* persistent.c */
#include <EXTERN.h>
#include <perl.h>
/* 1 = clean out filename's symbol table after each request,
0 = don't
*/
#ifndef DO_CLEAN
#define DO_CLEAN 0
#endif
#define BUFFER_SIZE 1024
static PerlInterpreter *my_perl = NULL;
int
main(int argc, char **argv, char **env)
{
char *embedding[] = { "", "persistent.pl", NULL };
char *args[] = { "", DO_CLEAN, NULL };
char filename[BUFFER_SIZE];
int failing, exitstatus;
PERL_SYS_INIT3(&argc,&argv,&env);
if((my_perl = perl_alloc()) == NULL) {
fprintf(stderr, "no memory!");
exit(EXIT_FAILURE);
}
perl_construct(my_perl);
PL_origalen = 1; /* don't let $0 assignment update the
proctitle or embedding[0] */
failing = perl_parse(my_perl, NULL, 2, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
if(!failing)
failing = perl_run(my_perl);
if(!failing) {
while(printf("Enter file name: ") &&
fgets(filename, BUFFER_SIZE, stdin)) {
filename[strlen(filename)-1] = '\0'; /* strip \n */
/* call the subroutine,
passing it the filename as an argument */
args[0] = filename;
call_argv("Embed::Persistent::eval_file",
G_DISCARD | G_EVAL, args);
/* check $@ */
if(SvTRUE(ERRSV))
fprintf(stderr, "eval error: %s\n", SvPV_nolen(ERRSV));
}
}
PL_perl_destruct_level = 0;
exitstatus = perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(exitstatus);
}
```
Now compile:
```
% cc -o persistent persistent.c \
`perl -MExtUtils::Embed -e ccopts -e ldopts`
```
Here's an example script file:
```
#test.pl
my $string = "hello";
foo($string);
sub foo {
print "foo says: @_\n";
}
```
Now run:
```
% persistent
Enter file name: test.pl
foo says: hello
Enter file name: test.pl
already compiled Embed::test_2epl->handler
foo says: hello
Enter file name: ^C
```
###
Execution of END blocks
Traditionally END blocks have been executed at the end of the perl\_run. This causes problems for applications that never call perl\_run. Since perl 5.7.2 you can specify `PL_exit_flags |= PERL_EXIT_DESTRUCT_END` to get the new behaviour. This also enables the running of END blocks if the perl\_parse fails and `perl_destruct` will return the exit value.
###
$0 assignments
When a perl script assigns a value to $0 then the perl runtime will try to make this value show up as the program name reported by "ps" by updating the memory pointed to by the argv passed to perl\_parse() and also calling API functions like setproctitle() where available. This behaviour might not be appropriate when embedding perl and can be disabled by assigning the value `1` to the variable `PL_origalen` before perl\_parse() is called.
The *persistent.c* example above is for instance likely to segfault when $0 is assigned to if the `PL_origalen = 1;` assignment is removed. This because perl will try to write to the read only memory of the `embedding[]` strings.
###
Maintaining multiple interpreter instances
Some rare applications will need to create more than one interpreter during a session. Such an application might sporadically decide to release any resources associated with the interpreter.
The program must take care to ensure that this takes place *before* the next interpreter is constructed. By default, when perl is not built with any special options, the global variable `PL_perl_destruct_level` is set to `0`, since extra cleaning isn't usually needed when a program only ever creates a single interpreter in its entire lifetime.
Setting `PL_perl_destruct_level` to `1` makes everything squeaky clean:
```
while(1) {
...
/* reset global variables here with PL_perl_destruct_level = 1 */
PL_perl_destruct_level = 1;
perl_construct(my_perl);
...
/* clean and reset _everything_ during perl_destruct */
PL_perl_destruct_level = 1;
perl_destruct(my_perl);
perl_free(my_perl);
...
/* let's go do it again! */
}
```
When *perl\_destruct()* is called, the interpreter's syntax parse tree and symbol tables are cleaned up, and global variables are reset. The second assignment to `PL_perl_destruct_level` is needed because perl\_construct resets it to `0`.
Now suppose we have more than one interpreter instance running at the same time. This is feasible, but only if you used the Configure option `-Dusemultiplicity` or the options `-Dusethreads -Duseithreads` when building perl. By default, enabling one of these Configure options sets the per-interpreter global variable `PL_perl_destruct_level` to `1`, so that thorough cleaning is automatic and interpreter variables are initialized correctly. Even if you don't intend to run two or more interpreters at the same time, but to run them sequentially, like in the above example, it is recommended to build perl with the `-Dusemultiplicity` option otherwise some interpreter variables may not be initialized correctly between consecutive runs and your application may crash.
See also ["Thread-aware system interfaces" in perlxs](perlxs#Thread-aware-system-interfaces).
Using `-Dusethreads -Duseithreads` rather than `-Dusemultiplicity` is more appropriate if you intend to run multiple interpreters concurrently in different threads, because it enables support for linking in the thread libraries of your system with the interpreter.
Let's give it a try:
```
#include <EXTERN.h>
#include <perl.h>
/* we're going to embed two interpreters */
#define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
int main(int argc, char **argv, char **env)
{
PerlInterpreter *one_perl, *two_perl;
char *one_args[] = { "one_perl", SAY_HELLO, NULL };
char *two_args[] = { "two_perl", SAY_HELLO, NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
one_perl = perl_alloc();
two_perl = perl_alloc();
PERL_SET_CONTEXT(one_perl);
perl_construct(one_perl);
PERL_SET_CONTEXT(two_perl);
perl_construct(two_perl);
PERL_SET_CONTEXT(one_perl);
perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
PERL_SET_CONTEXT(two_perl);
perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
PERL_SET_CONTEXT(one_perl);
perl_run(one_perl);
PERL_SET_CONTEXT(two_perl);
perl_run(two_perl);
PERL_SET_CONTEXT(one_perl);
perl_destruct(one_perl);
PERL_SET_CONTEXT(two_perl);
perl_destruct(two_perl);
PERL_SET_CONTEXT(one_perl);
perl_free(one_perl);
PERL_SET_CONTEXT(two_perl);
perl_free(two_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
```
Note the calls to PERL\_SET\_CONTEXT(). These are necessary to initialize the global state that tracks which interpreter is the "current" one on the particular process or thread that may be running it. It should always be used if you have more than one interpreter and are making perl API calls on both interpreters in an interleaved fashion.
PERL\_SET\_CONTEXT(interp) should also be called whenever `interp` is used by a thread that did not create it (using either perl\_alloc(), or the more esoteric perl\_clone()).
Compile as usual:
```
% cc -o multiplicity multiplicity.c \
`perl -MExtUtils::Embed -e ccopts -e ldopts`
```
Run it, Run it:
```
% multiplicity
Hi, I'm one_perl
Hi, I'm two_perl
```
###
Using Perl modules, which themselves use C libraries, from your C program
If you've played with the examples above and tried to embed a script that *use()*s a Perl module (such as *Socket*) which itself uses a C or C++ library, this probably happened:
```
Can't load module Socket, dynamic loading not available in this perl.
(You may need to build a new perl executable which either supports
dynamic loading or has the Socket module statically linked into it.)
```
What's wrong?
Your interpreter doesn't know how to communicate with these extensions on its own. A little glue will help. Up until now you've been calling *perl\_parse()*, handing it NULL for the second argument:
```
perl_parse(my_perl, NULL, argc, my_argv, NULL);
```
That's where the glue code can be inserted to create the initial contact between Perl and linked C/C++ routines. Let's take a look some pieces of *perlmain.c* to see how Perl does this:
```
static void xs_init (pTHX);
EXTERN_C void boot_DynaLoader (pTHX_ CV* cv);
EXTERN_C void boot_Socket (pTHX_ CV* cv);
EXTERN_C void
xs_init(pTHX)
{
char *file = __FILE__;
/* DynaLoader is a special case */
newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
newXS("Socket::bootstrap", boot_Socket, file);
}
```
Simply put: for each extension linked with your Perl executable (determined during its initial configuration on your computer or when adding a new extension), a Perl subroutine is created to incorporate the extension's routines. Normally, that subroutine is named *Module::bootstrap()* and is invoked when you say *use Module*. In turn, this hooks into an XSUB, *boot\_Module*, which creates a Perl counterpart for each of the extension's XSUBs. Don't worry about this part; leave that to the *xsubpp* and extension authors. If your extension is dynamically loaded, DynaLoader creates *Module::bootstrap()* for you on the fly. In fact, if you have a working DynaLoader then there is rarely any need to link in any other extensions statically.
Once you have this code, slap it into the second argument of *perl\_parse()*:
```
perl_parse(my_perl, xs_init, argc, my_argv, NULL);
```
Then compile:
```
% cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
% interp
use Socket;
use SomeDynamicallyLoadedModule;
print "Now I can use extensions!\n"'
```
**ExtUtils::Embed** can also automate writing the *xs\_init* glue code.
```
% perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
% cc -c perlxsi.c `perl -MExtUtils::Embed -e ccopts`
% cc -c interp.c `perl -MExtUtils::Embed -e ccopts`
% cc -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e ldopts`
```
Consult <perlxs>, <perlguts>, and <perlapi> for more details.
###
Using embedded Perl with POSIX locales
(See <perllocale> for information about these.) When a Perl interpreter normally starts up, it tells the system it wants to use the system's default locale. This is often, but not necessarily, the "C" or "POSIX" locale. Absent a `"use locale"` within the perl code, this mostly has no effect (but see ["Not within the scope of "use locale"" in perllocale](perllocale#Not-within-the-scope-of-%22use-locale%22)). Also, there is not a problem if the locale you want to use in your embedded perl is the same as the system default. However, this doesn't work if you have set up and want to use a locale that isn't the system default one. Starting in Perl v5.20, you can tell the embedded Perl interpreter that the locale is already properly set up, and to skip doing its own normal initialization. It skips if the environment variable `PERL_SKIP_LOCALE_INIT` is set (even if set to 0 or `""`). A perl that has this capability will define the C pre-processor symbol `HAS_SKIP_LOCALE_INIT`. This allows code that has to work with multiple Perl versions to do some sort of work-around when confronted with an earlier Perl.
If your program is using the POSIX 2008 multi-thread locale functionality, you should switch into the global locale and set that up properly before starting the Perl interpreter. It will then properly switch back to using the thread-safe functions.
Hiding Perl\_
--------------
If you completely hide the short forms of the Perl public API, add -DPERL\_NO\_SHORT\_NAMES to the compilation flags. This means that for example instead of writing
```
warn("%d bottles of beer on the wall", bottlecount);
```
you will have to write the explicit full form
```
Perl_warn(aTHX_ "%d bottles of beer on the wall", bottlecount);
```
(See ["Background and MULTIPLICITY" in perlguts](perlguts#Background-and-MULTIPLICITY) for the explanation of the `aTHX_`. ) Hiding the short forms is very useful for avoiding all sorts of nasty (C preprocessor or otherwise) conflicts with other software packages (Perl defines about 2400 APIs with these short names, take or leave few hundred, so there certainly is room for conflict.)
MORAL
-----
You can sometimes *write faster code* in C, but you can always *write code faster* in Perl. Because you can use each from the other, combine them as you wish.
AUTHOR
------
Jon Orwant <*[email protected]*> and Doug MacEachern <*[email protected]*>, with small contributions from Tim Bunce, Tom Christiansen, Guy Decoux, Hallvard Furuseth, Dov Grobgeld, and Ilya Zakharevich.
Doug MacEachern has an article on embedding in Volume 1, Issue 4 of The Perl Journal ( <http://www.tpj.com/> ). Doug is also the developer of the most widely-used Perl embedding: the mod\_perl system (perl.apache.org), which embeds Perl in the Apache web server. Oracle, Binary Evolution, ActiveState, and Ben Sugars's nsapi\_perl have used this model for Oracle, Netscape and Internet Information Server Perl plugins.
COPYRIGHT
---------
Copyright (C) 1995, 1996, 1997, 1998 Doug MacEachern and Jon Orwant. All Rights Reserved.
This document may be distributed under the same terms as Perl itself.
| programming_docs |
perl Encode::CJKConstants Encode::CJKConstants
====================
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::CJKConstants.pm -- Internally used by Encode::??::ISO\_2022\_\*
perl Time::localtime Time::localtime
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
Time::localtime - by-name interface to Perl's built-in localtime() function
SYNOPSIS
--------
```
use Time::localtime;
printf "Year is %d\n", localtime->year() + 1900;
$now = ctime();
use Time::localtime;
use File::stat;
$date_string = ctime(stat($file)->mtime);
```
DESCRIPTION
-----------
This module's default exports override the core localtime() function, replacing it with a version that returns "Time::tm" objects. This object has methods that return the similarly named structure field name from the C's tm structure from *time.h*; namely sec, min, hour, mday, mon, year, wday, yday, and isdst.
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 `tm_` in front their method names. Thus, `$tm_obj->mday()` corresponds to $tm\_mday if you import the fields.
The ctime() function provides a way of getting at the scalar sense of the original CORE::localtime() function.
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 TAP::Parser::Iterator TAP::Parser::Iterator
=====================
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)
- [handle\_unicode](#handle_unicode)
- [get\_select\_handles](#get_select_handles)
- [wait](#wait)
- [exit](#exit)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Iterator - Base class for TAP source iterators
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
# to subclass:
use TAP::Parser::Iterator ();
use base 'TAP::Parser::Iterator';
sub _initialize {
# see TAP::Object...
}
sub next_raw { ... }
sub wait { ... }
sub exit { ... }
```
DESCRIPTION
-----------
This is a simple iterator base class that defines <TAP::Parser>'s iterator API. Iterators are typically created from <TAP::Parser::SourceHandler>s.
METHODS
-------
###
Class Methods
#### `new`
Create an iterator. Provided by <TAP::Object>.
###
Instance Methods
#### `next`
```
while ( my $item = $iter->next ) { ... }
```
Iterate through it, of course.
#### `next_raw`
**Note:** this method is abstract and should be overridden.
```
while ( my $item = $iter->next_raw ) { ... }
```
Iterate raw input without applying any fixes for quirky input syntax.
#### `handle_unicode`
If necessary switch the input stream to handle unicode. This only has any effect for I/O handle based streams.
The default implementation does nothing.
#### `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.
The default implementation does nothing.
#### `wait`
**Note:** this method is abstract and should be overridden.
```
my $wait_status = $iter->wait;
```
Return the `wait` status for this iterator.
#### `exit`
**Note:** this method is abstract and should be overridden.
```
my $wait_status = $iter->exit;
```
Return the `exit` status for this iterator.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
You must override the abstract methods as noted above.
### Example
<TAP::Parser::Iterator::Array> is probably the easiest example to follow. There's not much point repeating it here.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Iterator::Array>, <TAP::Parser::Iterator::Stream>, <TAP::Parser::Iterator::Process>,
perl SelfLoader SelfLoader
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The \_\_DATA\_\_ token](#The-__DATA__-token)
+ [SelfLoader autoloading](#SelfLoader-autoloading)
+ [Autoloading and package lexicals](#Autoloading-and-package-lexicals)
+ [SelfLoader and AutoLoader](#SelfLoader-and-AutoLoader)
+ [\_\_DATA\_\_, \_\_END\_\_, and the FOOBAR::DATA filehandle.](#__DATA__,-__END__,-and-the-FOOBAR::DATA-filehandle.)
+ [Classes and inherited methods.](#Classes-and-inherited-methods.)
* [Multiple packages and fully qualified subroutine names](#Multiple-packages-and-fully-qualified-subroutine-names)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
SelfLoader - load functions only on demand
SYNOPSIS
--------
```
package FOOBAR;
use SelfLoader;
... (initializing code)
__DATA__
sub {....
```
DESCRIPTION
-----------
This module tells its users that functions in the FOOBAR package are to be autoloaded from after the `__DATA__` token. See also ["Autoloading" in perlsub](perlsub#Autoloading).
###
The \_\_DATA\_\_ token
The `__DATA__` token tells the perl compiler that the perl code for compilation is finished. Everything after the `__DATA__` token is available for reading via the filehandle FOOBAR::DATA, where FOOBAR is the name of the current package when the `__DATA__` token is reached. This works just the same as `__END__` does in package 'main', but for other modules data after `__END__` is not automatically retrievable, whereas data after `__DATA__` is. The `__DATA__` token is not recognized in versions of perl prior to 5.001m.
Note that it is possible to have `__DATA__` tokens in the same package in multiple files, and that the last `__DATA__` token in a given package that is encountered by the compiler is the one accessible by the filehandle. This also applies to `__END__` and main, i.e. if the 'main' program has an `__END__`, but a module 'require'd (\_not\_ 'use'd) by that program has a 'package main;' declaration followed by an '`__DATA__`', then the `DATA` filehandle is set to access the data after the `__DATA__` in the module, \_not\_ the data after the `__END__` token in the 'main' program, since the compiler encounters the 'require'd file later.
###
SelfLoader autoloading
The **SelfLoader** works by the user placing the `__DATA__` token *after* perl code which needs to be compiled and run at 'require' time, but *before* subroutine declarations that can be loaded in later - usually because they may never be called.
The **SelfLoader** will read from the FOOBAR::DATA filehandle to load in the data after `__DATA__`, and load in any subroutine when it is called. The costs are the one-time parsing of the data after `__DATA__`, and a load delay for the \_first\_ call of any autoloaded function. The benefits (hopefully) are a speeded up compilation phase, with no need to load functions which are never used.
The **SelfLoader** will stop reading from `__DATA__` if it encounters the `__END__` token - just as you would expect. If the `__END__` token is present, and is followed by the token DATA, then the **SelfLoader** leaves the FOOBAR::DATA filehandle open on the line after that token.
The **SelfLoader** exports the `AUTOLOAD` subroutine to the package using the **SelfLoader**, and this loads the called subroutine when it is first called.
There is no advantage to putting subroutines which will \_always\_ be called after the `__DATA__` token.
###
Autoloading and package lexicals
A 'my $pack\_lexical' statement makes the variable $pack\_lexical local \_only\_ to the file up to the `__DATA__` token. Subroutines declared elsewhere \_cannot\_ see these types of variables, just as if you declared subroutines in the package but in another file, they cannot see these variables.
So specifically, autoloaded functions cannot see package lexicals (this applies to both the **SelfLoader** and the Autoloader). The `vars` pragma provides an alternative to defining package-level globals that will be visible to autoloaded routines. See the documentation on **vars** in the pragma section of <perlmod>.
###
SelfLoader and AutoLoader
The **SelfLoader** can replace the AutoLoader - just change 'use AutoLoader' to 'use SelfLoader' (though note that the **SelfLoader** exports the AUTOLOAD function - but if you have your own AUTOLOAD and are using the AutoLoader too, you probably know what you're doing), and the `__END__` token to `__DATA__`. You will need perl version 5.001m or later to use this (version 5.001 with all patches up to patch m).
There is no need to inherit from the **SelfLoader**.
The **SelfLoader** works similarly to the AutoLoader, but picks up the subs from after the `__DATA__` instead of in the 'lib/auto' directory. There is a maintenance gain in not needing to run AutoSplit on the module at installation, and a runtime gain in not needing to keep opening and closing files to load subs. There is a runtime loss in needing to parse the code after the `__DATA__`. Details of the **AutoLoader** and another view of these distinctions can be found in that module's documentation.
###
\_\_DATA\_\_, \_\_END\_\_, and the FOOBAR::DATA filehandle.
This section is only relevant if you want to use the `FOOBAR::DATA` together with the **SelfLoader**.
Data after the `__DATA__` token in a module is read using the FOOBAR::DATA filehandle. `__END__` can still be used to denote the end of the `__DATA__` section if followed by the token DATA - this is supported by the **SelfLoader**. The `FOOBAR::DATA` filehandle is left open if an `__END__` followed by a DATA is found, with the filehandle positioned at the start of the line after the `__END__` token. If no `__END__` token is present, or an `__END__` token with no DATA token on the same line, then the filehandle is closed.
The **SelfLoader** reads from wherever the current position of the `FOOBAR::DATA` filehandle is, until the EOF or `__END__`. This means that if you want to use that filehandle (and ONLY if you want to), you should either
1. Put all your subroutine declarations immediately after the `__DATA__` token and put your own data after those declarations, using the `__END__` token to mark the end of subroutine declarations. You must also ensure that the **SelfLoader** reads first by calling 'SelfLoader->load\_stubs();', or by using a function which is selfloaded;
or
2. You should read the `FOOBAR::DATA` filehandle first, leaving the handle open and positioned at the first line of subroutine declarations.
You could conceivably do both.
###
Classes and inherited methods.
For modules which are not classes, this section is not relevant. This section is only relevant if you have methods which could be inherited.
A subroutine stub (or forward declaration) looks like
```
sub stub;
```
i.e. it is a subroutine declaration without the body of the subroutine. For modules which are not classes, there is no real need for stubs as far as autoloading is concerned.
For modules which ARE classes, and need to handle inherited methods, stubs are needed to ensure that the method inheritance mechanism works properly. You can load the stubs into the module at 'require' time, by adding the statement 'SelfLoader->load\_stubs();' to the module to do this.
The alternative is to put the stubs in before the `__DATA__` token BEFORE releasing the module, and for this purpose the `Devel::SelfStubber` module is available. However this does require the extra step of ensuring that the stubs are in the module. If this is done I strongly recommend that this is done BEFORE releasing the module - it should NOT be done at install time in general.
Multiple packages and fully qualified subroutine names
-------------------------------------------------------
Subroutines in multiple packages within the same file are supported - but you should note that this requires exporting the `SelfLoader::AUTOLOAD` to every package which requires it. This is done automatically by the **SelfLoader** when it first loads the subs into the cache, but you should really specify it in the initialization before the `__DATA__` by putting a 'use SelfLoader' statement in each package.
Fully qualified subroutine names are also supported. For example,
```
__DATA__
sub foo::bar {23}
package baz;
sub dob {32}
```
will all be loaded correctly by the **SelfLoader**, and the **SelfLoader** will ensure that the packages 'foo' and 'baz' correctly have the **SelfLoader** `AUTOLOAD` method when the data after `__DATA__` is first parsed.
AUTHOR
------
`SelfLoader` 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 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.
perl prove prove
=====
CONTENTS
--------
* [NAME](#NAME)
* [USAGE](#USAGE)
* [OPTIONS](#OPTIONS)
* [NOTES](#NOTES)
+ [.proverc](#.proverc)
+ [Reading from STDIN](#Reading-from-STDIN)
+ [Default Test Directory](#Default-Test-Directory)
+ [Colored Test Output](#Colored-Test-Output)
+ [Exit Code](#Exit-Code)
+ [Arguments to Tests](#Arguments-to-Tests)
+ [--exec](#-exec)
+ [--merge](#-merge)
+ [--trap](#-trap)
+ [--state](#-state)
+ [--rules](#-rules)
- [--rules examples](#-rules-examples)
- [--rules resolution](#-rules-resolution)
- [--rules Glob-style pattern matching](#-rules-Glob-style-pattern-matching)
- [More advanced specifications for parallel vs sequence run rules](#More-advanced-specifications-for-parallel-vs-sequence-run-rules)
+ [@INC](#@INC)
+ [Taint Mode](#Taint-Mode)
* [FORMATTERS](#FORMATTERS)
* [SOURCE HANDLERS](#SOURCE-HANDLERS)
* [PLUGINS](#PLUGINS)
+ [Available Plugins](#Available-Plugins)
+ [Writing Plugins](#Writing-Plugins)
NAME
----
prove - Run tests through a TAP harness.
USAGE
-----
```
prove [options] [files or directories]
```
OPTIONS
-------
Boolean options:
```
-v, --verbose Print all test lines.
-l, --lib Add 'lib' to the path for your tests (-Ilib).
-b, --blib Add 'blib/lib' and 'blib/arch' to the path for
your tests
-s, --shuffle Run the tests in random order.
-c, --color Colored test output (default).
--nocolor Do not color test output.
--count Show the X/Y test count when not verbose
(default)
--nocount Disable the X/Y test count.
-D --dry Dry run. Show test that would have run.
-f, --failures Show failed tests.
-o, --comments Show comments.
--ignore-exit Ignore exit status from test scripts.
-m, --merge Merge test scripts' STDERR with their STDOUT.
-r, --recurse Recursively descend into directories.
--reverse Run the tests in reverse order.
-q, --quiet Suppress some test output while running tests.
-Q, --QUIET Only print summary results.
-p, --parse Show full list of TAP parse errors, if any.
--directives Only show results with TODO or SKIP directives.
--timer Print elapsed time after each test.
--trap Trap Ctrl-C and print summary on interrupt.
--normalize Normalize TAP output in verbose output
-T Enable tainting checks.
-t Enable tainting warnings.
-W Enable fatal warnings.
-w Enable warnings.
-h, --help Display this help
-?, Display this help
-V, --version Display the version
-H, --man Longer manpage for prove
--norc Don't process default .proverc
```
Options that take arguments:
```
-I Library paths to include.
-P Load plugin (searches App::Prove::Plugin::*.)
-M Load a module.
-e, --exec Interpreter to run the tests ('' for compiled
tests.)
--ext Set the extension for tests (default '.t')
--harness Define test harness to use. See TAP::Harness.
--formatter Result formatter to use. See FORMATTERS.
--source Load and/or configure a SourceHandler. See
SOURCE HANDLERS.
-a, --archive out.tgz Store the resulting TAP in an archive file.
-j, --jobs N Run N test jobs in parallel (try 9.)
--state=opts Control prove's persistent state.
--statefile=file Use `file` instead of `.prove` for state
--rc=rcfile Process options from rcfile
--rules Rules for parallel vs sequential processing.
```
NOTES
-----
###
.proverc
If *~/.proverc* or *./.proverc* exist they will be read and any options they contain processed before the command line options. Options in *.proverc* are specified in the same way as command line options:
```
# .proverc
--state=hot,fast,save
-j9
```
Additional option files may be specified with the `--rc` option. Default option file processing is disabled by the `--norc` option.
Under Windows and VMS the option file is named *\_proverc* rather than *.proverc* and is sought only in the current directory.
###
Reading from `STDIN`
If you have a list of tests (or URLs, or anything else you want to test) in a file, you can add them to your tests by using a '-':
```
prove - < my_list_of_things_to_test.txt
```
See the `README` in the `examples` directory of this distribution.
###
Default Test Directory
If no files or directories are supplied, `prove` looks for all files matching the pattern `t/*.t`.
###
Colored Test Output
Colored test output using <TAP::Formatter::Color> is the default, but if output is not to a terminal, color is disabled. You can override this by adding the `--color` switch.
Color support requires <Term::ANSIColor> and, on windows platforms, also <Win32::Console::ANSI>. If the necessary module(s) are not installed colored output will not be available.
###
Exit Code
If the tests fail `prove` will exit with non-zero status.
###
Arguments to Tests
It is possible to supply arguments to tests. To do so separate them from prove's own arguments with the arisdottle, '::'. For example
```
prove -v t/mytest.t :: --url http://example.com
```
would run *t/mytest.t* with the options '--url http://example.com'. When running multiple tests they will each receive the same arguments.
###
`--exec`
Normally you can just pass a list of Perl tests and the harness will know how to execute them. However, if your tests are not written in Perl or if you want all tests invoked exactly the same way, use the `-e`, or `--exec` switch:
```
prove --exec '/usr/bin/ruby -w' t/
prove --exec '/usr/bin/perl -Tw -mstrict -Ilib' t/
prove --exec '/path/to/my/customer/exec'
```
###
`--merge`
If you need to make sure your diagnostics are displayed in the correct order relative to test results you can use the `--merge` option to merge the test scripts' STDERR into their STDOUT.
This guarantees that STDOUT (where the test results appear) and STDERR (where the diagnostics appear) will stay in sync. The harness will display any diagnostics your tests emit on STDERR.
Caveat: this is a bit of a kludge. In particular note that if anything that appears on STDERR looks like a test result the test harness will get confused. Use this option only if you understand the consequences and can live with the risk.
###
`--trap`
The `--trap` option will attempt to trap SIGINT (Ctrl-C) during a test run and display the test summary even if the run is interrupted
###
`--state`
You can ask `prove` to remember the state of previous test runs and select and/or order the tests to be run based on that saved state.
The `--state` switch requires an argument which must be a comma separated list of one or more of the following options.
`last` Run the same tests as the last time the state was saved. This makes it possible, for example, to recreate the ordering of a shuffled test.
```
# Run all tests in random order
$ prove -b --state=save --shuffle
# Run them again in the same order
$ prove -b --state=last
```
`failed` Run only the tests that failed on the last run.
```
# Run all tests
$ prove -b --state=save
# Run failures
$ prove -b --state=failed
```
If you also specify the `save` option newly passing tests will be excluded from subsequent runs.
```
# Repeat until no more failures
$ prove -b --state=failed,save
```
`passed` Run only the passed tests from last time. Useful to make sure that no new problems have been introduced.
`all` Run all tests in normal order. Multiple options may be specified, so to run all tests with the failures from last time first:
```
$ prove -b --state=failed,all,save
```
`hot` Run the tests that most recently failed first. The last failure time of each test is stored. The `hot` option causes tests to be run in most-recent- failure order.
```
$ prove -b --state=hot,save
```
Tests that have never failed will not be selected. To run all tests with the most recently failed first use
```
$ prove -b --state=hot,all,save
```
This combination of options may also be specified thus
```
$ prove -b --state=adrian
```
`todo` Run any tests with todos.
`slow` Run the tests in slowest to fastest order. This is useful in conjunction with the `-j` parallel testing switch to ensure that your slowest tests start running first.
```
$ prove -b --state=slow -j9
```
`fast` Run test tests in fastest to slowest order.
`new` Run the tests in newest to oldest order based on the modification times of the test scripts.
`old` Run the tests in oldest to newest order.
`fresh` Run those test scripts that have been modified since the last test run.
`save` Save the state on exit. The state is stored in a file called *.prove* (*\_prove* on Windows and VMS) in the current directory.
The `--state` switch may be used more than once.
```
$ prove -b --state=hot --state=all,save
```
###
--rules
The `--rules` option is used to control which tests are run sequentially and which are run in parallel, if the `--jobs` option is specified. The option may be specified multiple times, and the order matters.
The most practical use is likely to specify that some tests are not "parallel-ready". Since mentioning a file with --rules doesn't cause it to be selected to run as a test, you can "set and forget" some rules preferences in your .proverc file. Then you'll be able to take maximum advantage of the performance benefits of parallel testing, while some exceptions are still run in parallel.
####
--rules examples
```
# All tests are allowed to run in parallel, except those starting with "p"
--rules='seq=t/p*.t' --rules='par=**'
# All tests must run in sequence except those starting with "p", which should be run parallel
--rules='par=t/p*.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 them run in parallel. You still need specify the number of parallel `jobs` in your Harness object.
####
--rules Glob-style pattern matching
We implement our own glob-style pattern matching for --rules. Here are the supported patterns:
```
** 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
```
####
More advanced specifications for parallel vs sequence run rules
If you need more advanced management of what runs in parallel vs in sequence, see the associated 'rules' documentation in <TAP::Harness> and <TAP::Parser::Scheduler>. If what's possible directly through `prove` is not sufficient, you can write your own harness to access these features directly.
###
@INC
prove introduces a separation between "options passed to the perl which runs prove" and "options passed to the perl which runs tests"; this distinction is by design. Thus the perl which is running a test starts with the default `@INC`. Additional library directories can be added via the `PERL5LIB` environment variable, via -Ifoo in `PERL5OPT` or via the `-Ilib` option to *prove*.
###
Taint Mode
Normally when a Perl program is run in taint mode the contents of the `PERL5LIB` environment variable do not appear in `@INC`.
Because `PERL5LIB` is often used during testing to add build directories to `@INC` prove passes the names of any directories found in `PERL5LIB` as -I switches. The net effect of this is that `PERL5LIB` is honoured even when prove is run in taint mode.
FORMATTERS
----------
You can load a custom <TAP::Parser::Formatter>:
```
prove --formatter MyFormatter
```
SOURCE HANDLERS
----------------
You can load custom <TAP::Parser::SourceHandler>s, to change the way the parser interprets particular *sources* of TAP.
```
prove --source MyHandler --source YetAnother t
```
If you want to provide config to the source you can use:
```
prove --source MyCustom \
--source Perl --perl-option 'foo=bar baz' --perl-option avg=0.278 \
--source File --file-option extensions=.txt --file-option extensions=.tmp t
--source pgTAP --pgtap-option pset=format=html --pgtap-option pset=border=2
```
Each `--$source-option` option must specify a key/value pair separated by an `=`. If an option can take multiple values, just specify it multiple times, as with the `extensions=` examples above. If the option should be a hash reference, specify the value as a second pair separated by a `=`, as in the `pset=` examples above (escape `=` with a backslash).
All `--sources` are combined into a hash, and passed to ["new" in TAP::Harness](TAP::Harness#new)'s `sources` parameter.
See <TAP::Parser::IteratorFactory> for more details on how configuration is passed to *SourceHandlers*.
PLUGINS
-------
Plugins can be loaded using the `-P*plugin*` syntax, eg:
```
prove -PMyPlugin
```
This will search for a module named `App::Prove::Plugin::MyPlugin`, or failing that, `MyPlugin`. If the plugin can't be found, `prove` will complain & exit.
You can pass arguments to your plugin by appending `=arg1,arg2,etc` to the plugin name:
```
prove -PMyPlugin=fou,du,fafa
```
Please check individual plugin documentation for more details.
###
Available Plugins
For an up-to-date list of plugins available, please check CPAN:
<http://search.cpan.org/search?query=App%3A%3AProve+Plugin>
###
Writing Plugins
Please see ["PLUGINS" in App::Prove](App::Prove#PLUGINS).
| programming_docs |
perl perlcall perlcall
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [THE CALL\_ FUNCTIONS](#THE-CALL_-FUNCTIONS)
* [FLAG VALUES](#FLAG-VALUES)
+ [G\_VOID](#G_VOID)
+ [G\_SCALAR](#G_SCALAR)
+ [G\_LIST](#G_LIST)
+ [G\_DISCARD](#G_DISCARD)
+ [G\_NOARGS](#G_NOARGS)
+ [G\_EVAL](#G_EVAL)
+ [G\_KEEPERR](#G_KEEPERR)
+ [Determining the Context](#Determining-the-Context)
* [EXAMPLES](#EXAMPLES)
+ [No Parameters, Nothing Returned](#No-Parameters,-Nothing-Returned)
+ [Passing Parameters](#Passing-Parameters)
+ [Returning a Scalar](#Returning-a-Scalar)
+ [Returning a List of Values](#Returning-a-List-of-Values)
+ [Returning a List in Scalar Context](#Returning-a-List-in-Scalar-Context)
+ [Returning Data from Perl via the Parameter List](#Returning-Data-from-Perl-via-the-Parameter-List)
+ [Using G\_EVAL](#Using-G_EVAL)
+ [Using G\_KEEPERR](#Using-G_KEEPERR)
+ [Using call\_sv](#Using-call_sv)
+ [Using call\_argv](#Using-call_argv)
+ [Using call\_method](#Using-call_method)
+ [Using GIMME\_V](#Using-GIMME_V)
+ [Using Perl to Dispose of Temporaries](#Using-Perl-to-Dispose-of-Temporaries)
+ [Strategies for Storing Callback Context Information](#Strategies-for-Storing-Callback-Context-Information)
+ [Alternate Stack Manipulation](#Alternate-Stack-Manipulation)
+ [Creating and Calling an Anonymous Subroutine in C](#Creating-and-Calling-an-Anonymous-Subroutine-in-C)
* [LIGHTWEIGHT CALLBACKS](#LIGHTWEIGHT-CALLBACKS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [DATE](#DATE)
NAME
----
perlcall - Perl calling conventions from C
DESCRIPTION
-----------
The purpose of this document is to show you how to call Perl subroutines directly from C, i.e., how to write *callbacks*.
Apart from discussing the C interface provided by Perl for writing callbacks the document uses a series of examples to show how the interface actually works in practice. In addition some techniques for coding callbacks are covered.
Examples where callbacks are necessary include
* An Error Handler
You have created an XSUB interface to an application's C API.
A fairly common feature in applications is to allow you to define a C function that will be called whenever something nasty occurs. What we would like is to be able to specify a Perl subroutine that will be called instead.
* An Event-Driven Program
The classic example of where callbacks are used is when writing an event driven program, such as for an X11 application. In this case you register functions to be called whenever specific events occur, e.g., a mouse button is pressed, the cursor moves into a window or a menu item is selected.
Although the techniques described here are applicable when embedding Perl in a C program, this is not the primary goal of this document. There are other details that must be considered and are specific to embedding Perl. For details on embedding Perl in C refer to <perlembed>.
Before you launch yourself head first into the rest of this document, it would be a good idea to have read the following two documents--<perlxs> and <perlguts>.
THE CALL\_ FUNCTIONS
---------------------
Although this stuff is easier to explain using examples, you first need be aware of a few important definitions.
Perl has a number of C functions that allow you to call Perl subroutines. They are
```
I32 call_sv(SV* sv, I32 flags);
I32 call_pv(char *subname, I32 flags);
I32 call_method(char *methname, I32 flags);
I32 call_argv(char *subname, I32 flags, char **argv);
```
The key function is *call\_sv*. All the other functions are fairly simple wrappers which make it easier to call Perl subroutines in special cases. At the end of the day they will all call *call\_sv* to invoke the Perl subroutine.
All the *call\_\** functions have a `flags` parameter which is used to pass a bit mask of options to Perl. This bit mask operates identically for each of the functions. The settings available in the bit mask are discussed in ["FLAG VALUES"](#FLAG-VALUES).
Each of the functions will now be discussed in turn.
call\_sv *call\_sv* takes two parameters. The first, `sv`, is an SV\*. This allows you to specify the Perl subroutine to be called either as a C string (which has first been converted to an SV) or a reference to a subroutine. The section, ["Using call\_sv"](#Using-call_sv), shows how you can make use of *call\_sv*.
call\_pv The function, *call\_pv*, is similar to *call\_sv* except it expects its first parameter to be a C char\* which identifies the Perl subroutine you want to call, e.g., `call_pv("fred", 0)`. If the subroutine you want to call is in another package, just include the package name in the string, e.g., `"pkg::fred"`.
call\_method The function *call\_method* is used to call a method from a Perl class. The parameter `methname` corresponds to the name of the method to be called. Note that the class that the method belongs to is passed on the Perl stack rather than in the parameter list. This class can be either the name of the class (for a static method) or a reference to an object (for a virtual method). See <perlobj> for more information on static and virtual methods and ["Using call\_method"](#Using-call_method) for an example of using *call\_method*.
call\_argv *call\_argv* calls the Perl subroutine specified by the C string stored in the `subname` parameter. It also takes the usual `flags` parameter. The final parameter, `argv`, consists of a NULL-terminated list of C strings to be passed as parameters to the Perl subroutine. See ["Using call\_argv"](#Using-call_argv).
All the functions return an integer. This is a count of the number of items returned by the Perl subroutine. The actual items returned by the subroutine are stored on the Perl stack.
As a general rule you should *always* check the return value from these functions. Even if you are expecting only a particular number of values to be returned from the Perl subroutine, there is nothing to stop someone from doing something unexpected--don't say you haven't been warned.
FLAG VALUES
------------
The `flags` parameter in all the *call\_\** functions is one of `G_VOID`, `G_SCALAR`, or `G_LIST`, which indicate the call context, OR'ed together with a bit mask of any combination of the other G\_\* symbols defined below.
### G\_VOID
Calls the Perl subroutine in a void context.
This flag has 2 effects:
1. It indicates to the subroutine being called that it is executing in a void context (if it executes *wantarray* the result will be the undefined value).
2. It ensures that nothing is actually returned from the subroutine.
The value returned by the *call\_\** function indicates how many items have been returned by the Perl subroutine--in this case it will be 0.
### G\_SCALAR
Calls the Perl subroutine in a scalar context. This is the default context flag setting for all the *call\_\** functions.
This flag has 2 effects:
1. It indicates to the subroutine being called that it is executing in a scalar context (if it executes *wantarray* the result will be false).
2. It ensures that only a scalar is actually returned from the subroutine. The subroutine can, of course, ignore the *wantarray* and return a list anyway. If so, then only the last element of the list will be returned.
The value returned by the *call\_\** function indicates how many items have been returned by the Perl subroutine - in this case it will be either 0 or 1.
If 0, then you have specified the G\_DISCARD flag.
If 1, then the item actually returned by the Perl subroutine will be stored on the Perl stack - the section ["Returning a Scalar"](#Returning-a-Scalar) shows how to access this value on the stack. Remember that regardless of how many items the Perl subroutine returns, only the last one will be accessible from the stack - think of the case where only one value is returned as being a list with only one element. Any other items that were returned will not exist by the time control returns from the *call\_\** function. The section ["Returning a List in Scalar Context"](#Returning-a-List-in-Scalar-Context) shows an example of this behavior.
### G\_LIST
Calls the Perl subroutine in a list context. Prior to Perl version 5.35.1 this was called `G_ARRAY`.
As with G\_SCALAR, this flag has 2 effects:
1. It indicates to the subroutine being called that it is executing in a list context (if it executes *wantarray* the result will be true).
2. It ensures that all items returned from the subroutine will be accessible when control returns from the *call\_\** function.
The value returned by the *call\_\** function indicates how many items have been returned by the Perl subroutine.
If 0, then you have specified the G\_DISCARD flag.
If not 0, then it will be a count of the number of items returned by the subroutine. These items will be stored on the Perl stack. The section ["Returning a List of Values"](#Returning-a-List-of-Values) gives an example of using the G\_LIST flag and the mechanics of accessing the returned items from the Perl stack.
### G\_DISCARD
By default, the *call\_\** functions place the items returned from by the Perl subroutine on the stack. If you are not interested in these items, then setting this flag will make Perl get rid of them automatically for you. Note that it is still possible to indicate a context to the Perl subroutine by using either G\_SCALAR or G\_LIST.
If you do not set this flag then it is *very* important that you make sure that any temporaries (i.e., parameters passed to the Perl subroutine and values returned from the subroutine) are disposed of yourself. The section ["Returning a Scalar"](#Returning-a-Scalar) gives details of how to dispose of these temporaries explicitly and the section ["Using Perl to Dispose of Temporaries"](#Using-Perl-to-Dispose-of-Temporaries) discusses the specific circumstances where you can ignore the problem and let Perl deal with it for you.
### G\_NOARGS
Whenever a Perl subroutine is called using one of the *call\_\** functions, it is assumed by default that parameters are to be passed to the subroutine. If you are not passing any parameters to the Perl subroutine, you can save a bit of time by setting this flag. It has the effect of not creating the `@_` array for the Perl subroutine.
Although the functionality provided by this flag may seem straightforward, it should be used only if there is a good reason to do so. The reason for being cautious is that, even if you have specified the G\_NOARGS flag, it is still possible for the Perl subroutine that has been called to think that you have passed it parameters.
In fact, what can happen is that the Perl subroutine you have called can access the `@_` array from a previous Perl subroutine. This will occur when the code that is executing the *call\_\** function has itself been called from another Perl subroutine. The code below illustrates this
```
sub fred
{ print "@_\n" }
sub joe
{ &fred }
&joe(1,2,3);
```
This will print
```
1 2 3
```
What has happened is that `fred` accesses the `@_` array which belongs to `joe`.
### G\_EVAL
It is possible for the Perl subroutine you are calling to terminate abnormally, e.g., by calling *die* explicitly or by not actually existing. By default, when either of these events occurs, the process will terminate immediately. If you want to trap this type of event, specify the G\_EVAL flag. It will put an *eval { }* around the subroutine call.
Whenever control returns from the *call\_\** function you need to check the `$@` variable as you would in a normal Perl script.
The value returned from the *call\_\** function is dependent on what other flags have been specified and whether an error has occurred. Here are all the different cases that can occur:
* If the *call\_\** function returns normally, then the value returned is as specified in the previous sections.
* If G\_DISCARD is specified, the return value will always be 0.
* If G\_LIST is specified *and* an error has occurred, the return value will always be 0.
* If G\_SCALAR is specified *and* an error has occurred, the return value will be 1 and the value on the top of the stack will be *undef*. This means that if you have already detected the error by checking `$@` and you want the program to continue, you must remember to pop the *undef* from the stack.
See ["Using G\_EVAL"](#Using-G_EVAL) for details on using G\_EVAL.
### G\_KEEPERR
Using the G\_EVAL flag described above will always set `$@`: clearing it if there was no error, and setting it to describe the error if there was an error in the called code. This is what you want if your intention is to handle possible errors, but sometimes you just want to trap errors and stop them interfering with the rest of the program.
This scenario will mostly be applicable to code that is meant to be called from within destructors, asynchronous callbacks, and signal handlers. In such situations, where the code being called has little relation to the surrounding dynamic context, the main program needs to be insulated from errors in the called code, even if they can't be handled intelligently. It may also be useful to do this with code for `__DIE__` or `__WARN__` hooks, and `tie` functions.
The G\_KEEPERR flag is meant to be used in conjunction with G\_EVAL in *call\_\** functions that are used to implement such code, or with `eval_sv`. This flag has no effect on the `call_*` functions when G\_EVAL is not used.
When G\_KEEPERR is used, any error in the called code will terminate the call as usual, and the error will not propagate beyond the call (as usual for G\_EVAL), but it will not go into `$@`. Instead the error will be converted into a warning, prefixed with the string "\t(in cleanup)". This can be disabled using `no warnings 'misc'`. If there is no error, `$@` will not be cleared.
Note that the G\_KEEPERR flag does not propagate into inner evals; these may still set `$@`.
The G\_KEEPERR flag was introduced in Perl version 5.002.
See ["Using G\_KEEPERR"](#Using-G_KEEPERR) for an example of a situation that warrants the use of this flag.
###
Determining the Context
As mentioned above, you can determine the context of the currently executing subroutine in Perl with *wantarray*. The equivalent test can be made in C by using the `GIMME_V` macro, which returns `G_LIST` if you have been called in a list context, `G_SCALAR` if in a scalar context, or `G_VOID` if in a void context (i.e., the return value will not be used). An older version of this macro is called `GIMME`; in a void context it returns `G_SCALAR` instead of `G_VOID`. An example of using the `GIMME_V` macro is shown in section ["Using GIMME\_V"](#Using-GIMME_V).
EXAMPLES
--------
Enough of the definition talk! Let's have a few examples.
Perl provides many macros to assist in accessing the Perl stack. Wherever possible, these macros should always be used when interfacing to Perl internals. We hope this should make the code less vulnerable to any changes made to Perl in the future.
Another point worth noting is that in the first series of examples I have made use of only the *call\_pv* function. This has been done to keep the code simpler and ease you into the topic. Wherever possible, if the choice is between using *call\_pv* and *call\_sv*, you should always try to use *call\_sv*. See ["Using call\_sv"](#Using-call_sv) for details.
###
No Parameters, Nothing Returned
This first trivial example will call a Perl subroutine, *PrintUID*, to print out the UID of the process.
```
sub PrintUID
{
print "UID is $<\n";
}
```
and here is a C function to call it
```
static void
call_PrintUID()
{
dSP;
PUSHMARK(SP);
call_pv("PrintUID", G_DISCARD|G_NOARGS);
}
```
Simple, eh?
A few points to note about this example:
1. Ignore `dSP` and `PUSHMARK(SP)` for now. They will be discussed in the next example.
2. We aren't passing any parameters to *PrintUID* so G\_NOARGS can be specified.
3. We aren't interested in anything returned from *PrintUID*, so G\_DISCARD is specified. Even if *PrintUID* was changed to return some value(s), having specified G\_DISCARD will mean that they will be wiped by the time control returns from *call\_pv*.
4. As *call\_pv* is being used, the Perl subroutine is specified as a C string. In this case the subroutine name has been 'hard-wired' into the code.
5. Because we specified G\_DISCARD, it is not necessary to check the value returned from *call\_pv*. It will always be 0.
###
Passing Parameters
Now let's make a slightly more complex example. This time we want to call a Perl subroutine, `LeftString`, which will take 2 parameters--a string ($s) and an integer ($n). The subroutine will simply print the first $n characters of the string.
So the Perl subroutine would look like this:
```
sub LeftString
{
my($s, $n) = @_;
print substr($s, 0, $n), "\n";
}
```
The C function required to call *LeftString* would look like this:
```
static void
call_LeftString(a, b)
char * a;
int b;
{
dSP;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSVpv(a, 0)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
call_pv("LeftString", G_DISCARD);
FREETMPS;
LEAVE;
}
```
Here are a few notes on the C function *call\_LeftString*.
1. Parameters are passed to the Perl subroutine using the Perl stack. This is the purpose of the code beginning with the line `dSP` and ending with the line `PUTBACK`. The `dSP` declares a local copy of the stack pointer. This local copy should **always** be accessed as `SP`.
2. If you are going to put something onto the Perl stack, you need to know where to put it. This is the purpose of the macro `dSP`--it declares and initializes a *local* copy of the Perl stack pointer.
All the other macros which will be used in this example require you to have used this macro.
The exception to this rule is if you are calling a Perl subroutine directly from an XSUB function. In this case it is not necessary to use the `dSP` macro explicitly--it will be declared for you automatically.
3. Any parameters to be pushed onto the stack should be bracketed by the `PUSHMARK` and `PUTBACK` macros. The purpose of these two macros, in this context, is to count the number of parameters you are pushing automatically. Then whenever Perl is creating the `@_` array for the subroutine, it knows how big to make it.
The `PUSHMARK` macro tells Perl to make a mental note of the current stack pointer. Even if you aren't passing any parameters (like the example shown in the section ["No Parameters, Nothing Returned"](#No-Parameters%2C-Nothing-Returned)) you must still call the `PUSHMARK` macro before you can call any of the *call\_\** functions--Perl still needs to know that there are no parameters.
The `PUTBACK` macro sets the global copy of the stack pointer to be the same as our local copy. If we didn't do this, *call\_pv* wouldn't know where the two parameters we pushed were--remember that up to now all the stack pointer manipulation we have done is with our local copy, *not* the global copy.
4. Next, we come to EXTEND and PUSHs. This is where the parameters actually get pushed onto the stack. In this case we are pushing a string and an integer.
Alternatively you can use the XPUSHs() macro, which combines a `EXTEND(SP, 1)` and `PUSHs()`. This is less efficient if you're pushing multiple values.
See ["XSUBs and the Argument Stack" in perlguts](perlguts#XSUBs-and-the-Argument-Stack) for details on how the PUSH macros work.
5. Because we created temporary values (by means of sv\_2mortal() calls) we will have to tidy up the Perl stack and dispose of mortal SVs.
This is the purpose of
```
ENTER;
SAVETMPS;
```
at the start of the function, and
```
FREETMPS;
LEAVE;
```
at the end. The `ENTER`/`SAVETMPS` pair creates a boundary for any temporaries we create. This means that the temporaries we get rid of will be limited to those which were created after these calls.
The `FREETMPS`/`LEAVE` pair will get rid of any values returned by the Perl subroutine (see next example), plus it will also dump the mortal SVs we have created. Having `ENTER`/`SAVETMPS` at the beginning of the code makes sure that no other mortals are destroyed.
Think of these macros as working a bit like `{` and `}` in Perl to limit the scope of local variables.
See the section ["Using Perl to Dispose of Temporaries"](#Using-Perl-to-Dispose-of-Temporaries) for details of an alternative to using these macros.
6. Finally, *LeftString* can now be called via the *call\_pv* function. The only flag specified this time is G\_DISCARD. Because we are passing 2 parameters to the Perl subroutine this time, we have not specified G\_NOARGS.
###
Returning a Scalar
Now for an example of dealing with the items returned from a Perl subroutine.
Here is a Perl subroutine, *Adder*, that takes 2 integer parameters and simply returns their sum.
```
sub Adder
{
my($a, $b) = @_;
$a + $b;
}
```
Because we are now concerned with the return value from *Adder*, the C function required to call it is now a bit more complex.
```
static void
call_Adder(a, b)
int a;
int b;
{
dSP;
int count;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(a)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
count = call_pv("Adder", G_SCALAR);
SPAGAIN;
if (count != 1)
croak("Big trouble\n");
printf ("The sum of %d and %d is %d\n", a, b, POPi);
PUTBACK;
FREETMPS;
LEAVE;
}
```
Points to note this time are
1. The only flag specified this time was G\_SCALAR. That means that the `@_` array will be created and that the value returned by *Adder* will still exist after the call to *call\_pv*.
2. The purpose of the macro `SPAGAIN` is to refresh the local copy of the stack pointer. This is necessary because it is possible that the memory allocated to the Perl stack has been reallocated during the *call\_pv* call.
If you are making use of the Perl stack pointer in your code you must always refresh the local copy using SPAGAIN whenever you make use of the *call\_\** functions or any other Perl internal function.
3. Although only a single value was expected to be returned from *Adder*, it is still good practice to check the return code from *call\_pv* anyway.
Expecting a single value is not quite the same as knowing that there will be one. If someone modified *Adder* to return a list and we didn't check for that possibility and take appropriate action the Perl stack would end up in an inconsistent state. That is something you *really* don't want to happen ever.
4. The `POPi` macro is used here to pop the return value from the stack. In this case we wanted an integer, so `POPi` was used.
Here is the complete list of POP macros available, along with the types they return.
```
POPs SV
POPp pointer (PV)
POPpbytex pointer to bytes (PV)
POPn double (NV)
POPi integer (IV)
POPu unsigned integer (UV)
POPl long
POPul unsigned long
```
Since these macros have side-effects don't use them as arguments to macros that may evaluate their argument several times, for example:
```
/* Bad idea, don't do this */
STRLEN len;
const char *s = SvPV(POPs, len);
```
Instead, use a temporary:
```
STRLEN len;
SV *sv = POPs;
const char *s = SvPV(sv, len);
```
or a macro that guarantees it will evaluate its arguments only once:
```
STRLEN len;
const char *s = SvPVx(POPs, len);
```
5. The final `PUTBACK` is used to leave the Perl stack in a consistent state before exiting the function. This is necessary because when we popped the return value from the stack with `POPi` it updated only our local copy of the stack pointer. Remember, `PUTBACK` sets the global stack pointer to be the same as our local copy.
###
Returning a List of Values
Now, let's extend the previous example to return both the sum of the parameters and the difference.
Here is the Perl subroutine
```
sub AddSubtract
{
my($a, $b) = @_;
($a+$b, $a-$b);
}
```
and this is the C function
```
static void
call_AddSubtract(a, b)
int a;
int b;
{
dSP;
int count;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(a)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
count = call_pv("AddSubtract", G_LIST);
SPAGAIN;
if (count != 2)
croak("Big trouble\n");
printf ("%d - %d = %d\n", a, b, POPi);
printf ("%d + %d = %d\n", a, b, POPi);
PUTBACK;
FREETMPS;
LEAVE;
}
```
If *call\_AddSubtract* is called like this
```
call_AddSubtract(7, 4);
```
then here is the output
```
7 - 4 = 3
7 + 4 = 11
```
Notes
1. We wanted list context, so G\_LIST was used.
2. Not surprisingly `POPi` is used twice this time because we were retrieving 2 values from the stack. The important thing to note is that when using the `POP*` macros they come off the stack in *reverse* order.
###
Returning a List in Scalar Context
Say the Perl subroutine in the previous section was called in a scalar context, like this
```
static void
call_AddSubScalar(a, b)
int a;
int b;
{
dSP;
int count;
int i;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(a)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
count = call_pv("AddSubtract", G_SCALAR);
SPAGAIN;
printf ("Items Returned = %d\n", count);
for (i = 1; i <= count; ++i)
printf ("Value %d = %d\n", i, POPi);
PUTBACK;
FREETMPS;
LEAVE;
}
```
The other modification made is that *call\_AddSubScalar* will print the number of items returned from the Perl subroutine and their value (for simplicity it assumes that they are integer). So if *call\_AddSubScalar* is called
```
call_AddSubScalar(7, 4);
```
then the output will be
```
Items Returned = 1
Value 1 = 3
```
In this case the main point to note is that only the last item in the list is returned from the subroutine. *AddSubtract* actually made it back to *call\_AddSubScalar*.
###
Returning Data from Perl via the Parameter List
It is also possible to return values directly via the parameter list--whether it is actually desirable to do it is another matter entirely.
The Perl subroutine, *Inc*, below takes 2 parameters and increments each directly.
```
sub Inc
{
++ $_[0];
++ $_[1];
}
```
and here is a C function to call it.
```
static void
call_Inc(a, b)
int a;
int b;
{
dSP;
int count;
SV * sva;
SV * svb;
ENTER;
SAVETMPS;
sva = sv_2mortal(newSViv(a));
svb = sv_2mortal(newSViv(b));
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sva);
PUSHs(svb);
PUTBACK;
count = call_pv("Inc", G_DISCARD);
if (count != 0)
croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
count);
printf ("%d + 1 = %d\n", a, SvIV(sva));
printf ("%d + 1 = %d\n", b, SvIV(svb));
FREETMPS;
LEAVE;
}
```
To be able to access the two parameters that were pushed onto the stack after they return from *call\_pv* it is necessary to make a note of their addresses--thus the two variables `sva` and `svb`.
The reason this is necessary is that the area of the Perl stack which held them will very likely have been overwritten by something else by the time control returns from *call\_pv*.
###
Using G\_EVAL
Now an example using G\_EVAL. Below is a Perl subroutine which computes the difference of its 2 parameters. If this would result in a negative result, the subroutine calls *die*.
```
sub Subtract
{
my ($a, $b) = @_;
die "death can be fatal\n" if $a < $b;
$a - $b;
}
```
and some C to call it
```
static void
call_Subtract(a, b)
int a;
int b;
{
dSP;
int count;
SV *err_tmp;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(a)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
count = call_pv("Subtract", G_EVAL|G_SCALAR);
SPAGAIN;
/* Check the eval first */
err_tmp = ERRSV;
if (SvTRUE(err_tmp))
{
printf ("Uh oh - %s\n", SvPV_nolen(err_tmp));
POPs;
}
else
{
if (count != 1)
croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
count);
printf ("%d - %d = %d\n", a, b, POPi);
}
PUTBACK;
FREETMPS;
LEAVE;
}
```
If *call\_Subtract* is called thus
```
call_Subtract(4, 5)
```
the following will be printed
```
Uh oh - death can be fatal
```
Notes
1. We want to be able to catch the *die* so we have used the G\_EVAL flag. Not specifying this flag would mean that the program would terminate immediately at the *die* statement in the subroutine *Subtract*.
2. The code
```
err_tmp = ERRSV;
if (SvTRUE(err_tmp))
{
printf ("Uh oh - %s\n", SvPV_nolen(err_tmp));
POPs;
}
```
is the direct equivalent of this bit of Perl
```
print "Uh oh - $@\n" if $@;
```
`PL_errgv` is a perl global of type `GV *` that points to the symbol table entry containing the error. `ERRSV` therefore refers to the C equivalent of `$@`. We use a local temporary, `err_tmp`, since `ERRSV` is a macro that calls a function, and `SvTRUE(ERRSV)` would end up calling that function multiple times.
3. Note that the stack is popped using `POPs` in the block where `SvTRUE(err_tmp)` is true. This is necessary because whenever a *call\_\** function invoked with G\_EVAL|G\_SCALAR returns an error, the top of the stack holds the value *undef*. Because we want the program to continue after detecting this error, it is essential that the stack be tidied up by removing the *undef*.
###
Using G\_KEEPERR
Consider this rather facetious example, where we have used an XS version of the call\_Subtract example above inside a destructor:
```
package Foo;
sub new { bless {}, $_[0] }
sub Subtract {
my($a,$b) = @_;
die "death can be fatal" if $a < $b;
$a - $b;
}
sub DESTROY { call_Subtract(5, 4); }
sub foo { die "foo dies"; }
package main;
{
my $foo = Foo->new;
eval { $foo->foo };
}
print "Saw: $@" if $@; # should be, but isn't
```
This example will fail to recognize that an error occurred inside the `eval {}`. Here's why: the call\_Subtract code got executed while perl was cleaning up temporaries when exiting the outer braced block, and because call\_Subtract is implemented with *call\_pv* using the G\_EVAL flag, it promptly reset `$@`. This results in the failure of the outermost test for `$@`, and thereby the failure of the error trap.
Appending the G\_KEEPERR flag, so that the *call\_pv* call in call\_Subtract reads:
```
count = call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
```
will preserve the error and restore reliable error handling.
###
Using call\_sv
In all the previous examples I have 'hard-wired' the name of the Perl subroutine to be called from C. Most of the time though, it is more convenient to be able to specify the name of the Perl subroutine from within the Perl script, and you'll want to use [call\_sv](perlapi#call_sv).
Consider the Perl code below
```
sub fred
{
print "Hello there\n";
}
CallSubPV("fred");
```
Here is a snippet of XSUB which defines *CallSubPV*.
```
void
CallSubPV(name)
char * name
CODE:
PUSHMARK(SP);
call_pv(name, G_DISCARD|G_NOARGS);
```
That is fine as far as it goes. The thing is, the Perl subroutine can be specified as only a string, however, Perl allows references to subroutines and anonymous subroutines. This is where *call\_sv* is useful.
The code below for *CallSubSV* is identical to *CallSubPV* except that the `name` parameter is now defined as an SV\* and we use *call\_sv* instead of *call\_pv*.
```
void
CallSubSV(name)
SV * name
CODE:
PUSHMARK(SP);
call_sv(name, G_DISCARD|G_NOARGS);
```
Because we are using an SV to call *fred* the following can all be used:
```
CallSubSV("fred");
CallSubSV(\&fred);
$ref = \&fred;
CallSubSV($ref);
CallSubSV( sub { print "Hello there\n" } );
```
As you can see, *call\_sv* gives you much greater flexibility in how you can specify the Perl subroutine.
You should note that, if it is necessary to store the SV (`name` in the example above) which corresponds to the Perl subroutine so that it can be used later in the program, it not enough just to store a copy of the pointer to the SV. Say the code above had been like this:
```
static SV * rememberSub;
void
SaveSub1(name)
SV * name
CODE:
rememberSub = name;
void
CallSavedSub1()
CODE:
PUSHMARK(SP);
call_sv(rememberSub, G_DISCARD|G_NOARGS);
```
The reason this is wrong is that, by the time you come to use the pointer `rememberSub` in `CallSavedSub1`, it may or may not still refer to the Perl subroutine that was recorded in `SaveSub1`. This is particularly true for these cases:
```
SaveSub1(\&fred);
CallSavedSub1();
SaveSub1( sub { print "Hello there\n" } );
CallSavedSub1();
```
By the time each of the `SaveSub1` statements above has been executed, the SV\*s which corresponded to the parameters will no longer exist. Expect an error message from Perl of the form
```
Can't use an undefined value as a subroutine reference at ...
```
for each of the `CallSavedSub1` lines.
Similarly, with this code
```
$ref = \&fred;
SaveSub1($ref);
$ref = 47;
CallSavedSub1();
```
you can expect one of these messages (which you actually get is dependent on the version of Perl you are using)
```
Not a CODE reference at ...
Undefined subroutine &main::47 called ...
```
The variable $ref may have referred to the subroutine `fred` whenever the call to `SaveSub1` was made but by the time `CallSavedSub1` gets called it now holds the number `47`. Because we saved only a pointer to the original SV in `SaveSub1`, any changes to $ref will be tracked by the pointer `rememberSub`. This means that whenever `CallSavedSub1` gets called, it will attempt to execute the code which is referenced by the SV\* `rememberSub`. In this case though, it now refers to the integer `47`, so expect Perl to complain loudly.
A similar but more subtle problem is illustrated with this code:
```
$ref = \&fred;
SaveSub1($ref);
$ref = \&joe;
CallSavedSub1();
```
This time whenever `CallSavedSub1` gets called it will execute the Perl subroutine `joe` (assuming it exists) rather than `fred` as was originally requested in the call to `SaveSub1`.
To get around these problems it is necessary to take a full copy of the SV. The code below shows `SaveSub2` modified to do that.
```
/* this isn't thread-safe */
static SV * keepSub = (SV*)NULL;
void
SaveSub2(name)
SV * name
CODE:
/* Take a copy of the callback */
if (keepSub == (SV*)NULL)
/* First time, so create a new SV */
keepSub = newSVsv(name);
else
/* Been here before, so overwrite */
SvSetSV(keepSub, name);
void
CallSavedSub2()
CODE:
PUSHMARK(SP);
call_sv(keepSub, G_DISCARD|G_NOARGS);
```
To avoid creating a new SV every time `SaveSub2` is called, the function first checks to see if it has been called before. If not, then space for a new SV is allocated and the reference to the Perl subroutine `name` is copied to the variable `keepSub` in one operation using `newSVsv`. Thereafter, whenever `SaveSub2` is called, the existing SV, `keepSub`, is overwritten with the new value using `SvSetSV`.
Note: using a static or global variable to store the SV isn't thread-safe. You can either use the `MY_CXT` mechanism documented in ["Safely Storing Static Data in XS" in perlxs](perlxs#Safely-Storing-Static-Data-in-XS) which is fast, or store the values in perl global variables, using get\_sv(), which is much slower.
###
Using call\_argv
Here is a Perl subroutine which prints whatever parameters are passed to it.
```
sub PrintList
{
my(@list) = @_;
foreach (@list) { print "$_\n" }
}
```
And here is an example of *call\_argv* which will call *PrintList*.
```
static char * words[] = {"alpha", "beta", "gamma", "delta", NULL};
static void
call_PrintList()
{
call_argv("PrintList", G_DISCARD, words);
}
```
Note that it is not necessary to call `PUSHMARK` in this instance. This is because *call\_argv* will do it for you.
###
Using call\_method
Consider the following Perl code:
```
{
package Mine;
sub new
{
my($type) = shift;
bless [@_]
}
sub Display
{
my ($self, $index) = @_;
print "$index: $$self[$index]\n";
}
sub PrintID
{
my($class) = @_;
print "This is Class $class version 1.0\n";
}
}
```
It implements just a very simple class to manage an array. Apart from the constructor, `new`, it declares methods, one static and one virtual. The static method, `PrintID`, prints out simply the class name and a version number. The virtual method, `Display`, prints out a single element of the array. Here is an all-Perl example of using it.
```
$a = Mine->new('red', 'green', 'blue');
$a->Display(1);
Mine->PrintID;
```
will print
```
1: green
This is Class Mine version 1.0
```
Calling a Perl method from C is fairly straightforward. The following things are required:
* A reference to the object for a virtual method or the name of the class for a static method
* The name of the method
* Any other parameters specific to the method
Here is a simple XSUB which illustrates the mechanics of calling both the `PrintID` and `Display` methods from C.
```
void
call_Method(ref, method, index)
SV * ref
char * method
int index
CODE:
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(ref);
PUSHs(sv_2mortal(newSViv(index)));
PUTBACK;
call_method(method, G_DISCARD);
void
call_PrintID(class, method)
char * class
char * method
CODE:
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(class, 0)));
PUTBACK;
call_method(method, G_DISCARD);
```
So the methods `PrintID` and `Display` can be invoked like this:
```
$a = Mine->new('red', 'green', 'blue');
call_Method($a, 'Display', 1);
call_PrintID('Mine', 'PrintID');
```
The only thing to note is that, in both the static and virtual methods, the method name is not passed via the stack--it is used as the first parameter to *call\_method*.
###
Using GIMME\_V
Here is a trivial XSUB which prints the context in which it is currently executing.
```
void
PrintContext()
CODE:
U8 gimme = GIMME_V;
if (gimme == G_VOID)
printf ("Context is Void\n");
else if (gimme == G_SCALAR)
printf ("Context is Scalar\n");
else
printf ("Context is Array\n");
```
And here is some Perl to test it.
```
PrintContext;
$a = PrintContext;
@a = PrintContext;
```
The output from that will be
```
Context is Void
Context is Scalar
Context is Array
```
###
Using Perl to Dispose of Temporaries
In the examples given to date, any temporaries created in the callback (i.e., parameters passed on the stack to the *call\_\** function or values returned via the stack) have been freed by one of these methods:
* Specifying the G\_DISCARD flag with *call\_\**
* Explicitly using the `ENTER`/`SAVETMPS`--`FREETMPS`/`LEAVE` pairing
There is another method which can be used, namely letting Perl do it for you automatically whenever it regains control after the callback has terminated. This is done by simply not using the
```
ENTER;
SAVETMPS;
...
FREETMPS;
LEAVE;
```
sequence in the callback (and not, of course, specifying the G\_DISCARD flag).
If you are going to use this method you have to be aware of a possible memory leak which can arise under very specific circumstances. To explain these circumstances you need to know a bit about the flow of control between Perl and the callback routine.
The examples given at the start of the document (an error handler and an event driven program) are typical of the two main sorts of flow control that you are likely to encounter with callbacks. There is a very important distinction between them, so pay attention.
In the first example, an error handler, the flow of control could be as follows. You have created an interface to an external library. Control can reach the external library like this
```
perl --> XSUB --> external library
```
Whilst control is in the library, an error condition occurs. You have previously set up a Perl callback to handle this situation, so it will get executed. Once the callback has finished, control will drop back to Perl again. Here is what the flow of control will be like in that situation
```
perl --> XSUB --> external library
...
error occurs
...
external library --> call_* --> perl
|
perl <-- XSUB <-- external library <-- call_* <----+
```
After processing of the error using *call\_\** is completed, control reverts back to Perl more or less immediately.
In the diagram, the further right you go the more deeply nested the scope is. It is only when control is back with perl on the extreme left of the diagram that you will have dropped back to the enclosing scope and any temporaries you have left hanging around will be freed.
In the second example, an event driven program, the flow of control will be more like this
```
perl --> XSUB --> event handler
...
event handler --> call_* --> perl
|
event handler <-- call_* <----+
...
event handler --> call_* --> perl
|
event handler <-- call_* <----+
...
event handler --> call_* --> perl
|
event handler <-- call_* <----+
```
In this case the flow of control can consist of only the repeated sequence
```
event handler --> call_* --> perl
```
for practically the complete duration of the program. This means that control may *never* drop back to the surrounding scope in Perl at the extreme left.
So what is the big problem? Well, if you are expecting Perl to tidy up those temporaries for you, you might be in for a long wait. For Perl to dispose of your temporaries, control must drop back to the enclosing scope at some stage. In the event driven scenario that may never happen. This means that, as time goes on, your program will create more and more temporaries, none of which will ever be freed. As each of these temporaries consumes some memory your program will eventually consume all the available memory in your system--kapow!
So here is the bottom line--if you are sure that control will revert back to the enclosing Perl scope fairly quickly after the end of your callback, then it isn't absolutely necessary to dispose explicitly of any temporaries you may have created. Mind you, if you are at all uncertain about what to do, it doesn't do any harm to tidy up anyway.
###
Strategies for Storing Callback Context Information
Potentially one of the trickiest problems to overcome when designing a callback interface can be figuring out how to store the mapping between the C callback function and the Perl equivalent.
To help understand why this can be a real problem first consider how a callback is set up in an all C environment. Typically a C API will provide a function to register a callback. This will expect a pointer to a function as one of its parameters. Below is a call to a hypothetical function `register_fatal` which registers the C function to get called when a fatal error occurs.
```
register_fatal(cb1);
```
The single parameter `cb1` is a pointer to a function, so you must have defined `cb1` in your code, say something like this
```
static void
cb1()
{
printf ("Fatal Error\n");
exit(1);
}
```
Now change that to call a Perl subroutine instead
```
static SV * callback = (SV*)NULL;
static void
cb1()
{
dSP;
PUSHMARK(SP);
/* Call the Perl sub to process the callback */
call_sv(callback, G_DISCARD);
}
void
register_fatal(fn)
SV * fn
CODE:
/* Remember the Perl sub */
if (callback == (SV*)NULL)
callback = newSVsv(fn);
else
SvSetSV(callback, fn);
/* register the callback with the external library */
register_fatal(cb1);
```
where the Perl equivalent of `register_fatal` and the callback it registers, `pcb1`, might look like this
```
# Register the sub pcb1
register_fatal(\&pcb1);
sub pcb1
{
die "I'm dying...\n";
}
```
The mapping between the C callback and the Perl equivalent is stored in the global variable `callback`.
This will be adequate if you ever need to have only one callback registered at any time. An example could be an error handler like the code sketched out above. Remember though, repeated calls to `register_fatal` will replace the previously registered callback function with the new one.
Say for example you want to interface to a library which allows asynchronous file i/o. In this case you may be able to register a callback whenever a read operation has completed. To be of any use we want to be able to call separate Perl subroutines for each file that is opened. As it stands, the error handler example above would not be adequate as it allows only a single callback to be defined at any time. What we require is a means of storing the mapping between the opened file and the Perl subroutine we want to be called for that file.
Say the i/o library has a function `asynch_read` which associates a C function `ProcessRead` with a file handle `fh`--this assumes that it has also provided some routine to open the file and so obtain the file handle.
```
asynch_read(fh, ProcessRead)
```
This may expect the C *ProcessRead* function of this form
```
void
ProcessRead(fh, buffer)
int fh;
char * buffer;
{
...
}
```
To provide a Perl interface to this library we need to be able to map between the `fh` parameter and the Perl subroutine we want called. A hash is a convenient mechanism for storing this mapping. The code below shows a possible implementation
```
static HV * Mapping = (HV*)NULL;
void
asynch_read(fh, callback)
int fh
SV * callback
CODE:
/* If the hash doesn't already exist, create it */
if (Mapping == (HV*)NULL)
Mapping = newHV();
/* Save the fh -> callback mapping */
hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0);
/* Register with the C Library */
asynch_read(fh, asynch_read_if);
```
and `asynch_read_if` could look like this
```
static void
asynch_read_if(fh, buffer)
int fh;
char * buffer;
{
dSP;
SV ** sv;
/* Get the callback associated with fh */
sv = hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE);
if (sv == (SV**)NULL)
croak("Internal error...\n");
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(fh)));
PUSHs(sv_2mortal(newSVpv(buffer, 0)));
PUTBACK;
/* Call the Perl sub */
call_sv(*sv, G_DISCARD);
}
```
For completeness, here is `asynch_close`. This shows how to remove the entry from the hash `Mapping`.
```
void
asynch_close(fh)
int fh
CODE:
/* Remove the entry from the hash */
(void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD);
/* Now call the real asynch_close */
asynch_close(fh);
```
So the Perl interface would look like this
```
sub callback1
{
my($handle, $buffer) = @_;
}
# Register the Perl callback
asynch_read($fh, \&callback1);
asynch_close($fh);
```
The mapping between the C callback and Perl is stored in the global hash `Mapping` this time. Using a hash has the distinct advantage that it allows an unlimited number of callbacks to be registered.
What if the interface provided by the C callback doesn't contain a parameter which allows the file handle to Perl subroutine mapping? Say in the asynchronous i/o package, the callback function gets passed only the `buffer` parameter like this
```
void
ProcessRead(buffer)
char * buffer;
{
...
}
```
Without the file handle there is no straightforward way to map from the C callback to the Perl subroutine.
In this case a possible way around this problem is to predefine a series of C functions to act as the interface to Perl, thus
```
#define MAX_CB 3
#define NULL_HANDLE -1
typedef void (*FnMap)();
struct MapStruct {
FnMap Function;
SV * PerlSub;
int Handle;
};
static void fn1();
static void fn2();
static void fn3();
static struct MapStruct Map [MAX_CB] =
{
{ fn1, NULL, NULL_HANDLE },
{ fn2, NULL, NULL_HANDLE },
{ fn3, NULL, NULL_HANDLE }
};
static void
Pcb(index, buffer)
int index;
char * buffer;
{
dSP;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(buffer, 0)));
PUTBACK;
/* Call the Perl sub */
call_sv(Map[index].PerlSub, G_DISCARD);
}
static void
fn1(buffer)
char * buffer;
{
Pcb(0, buffer);
}
static void
fn2(buffer)
char * buffer;
{
Pcb(1, buffer);
}
static void
fn3(buffer)
char * buffer;
{
Pcb(2, buffer);
}
void
array_asynch_read(fh, callback)
int fh
SV * callback
CODE:
int index;
int null_index = MAX_CB;
/* Find the same handle or an empty entry */
for (index = 0; index < MAX_CB; ++index)
{
if (Map[index].Handle == fh)
break;
if (Map[index].Handle == NULL_HANDLE)
null_index = index;
}
if (index == MAX_CB && null_index == MAX_CB)
croak ("Too many callback functions registered\n");
if (index == MAX_CB)
index = null_index;
/* Save the file handle */
Map[index].Handle = fh;
/* Remember the Perl sub */
if (Map[index].PerlSub == (SV*)NULL)
Map[index].PerlSub = newSVsv(callback);
else
SvSetSV(Map[index].PerlSub, callback);
asynch_read(fh, Map[index].Function);
void
array_asynch_close(fh)
int fh
CODE:
int index;
/* Find the file handle */
for (index = 0; index < MAX_CB; ++ index)
if (Map[index].Handle == fh)
break;
if (index == MAX_CB)
croak ("could not close fh %d\n", fh);
Map[index].Handle = NULL_HANDLE;
SvREFCNT_dec(Map[index].PerlSub);
Map[index].PerlSub = (SV*)NULL;
asynch_close(fh);
```
In this case the functions `fn1`, `fn2`, and `fn3` are used to remember the Perl subroutine to be called. Each of the functions holds a separate hard-wired index which is used in the function `Pcb` to access the `Map` array and actually call the Perl subroutine.
There are some obvious disadvantages with this technique.
Firstly, the code is considerably more complex than with the previous example.
Secondly, there is a hard-wired limit (in this case 3) to the number of callbacks that can exist simultaneously. The only way to increase the limit is by modifying the code to add more functions and then recompiling. None the less, as long as the number of functions is chosen with some care, it is still a workable solution and in some cases is the only one available.
To summarize, here are a number of possible methods for you to consider for storing the mapping between C and the Perl callback
1. Ignore the problem - Allow only 1 callback For a lot of situations, like interfacing to an error handler, this may be a perfectly adequate solution.
2. Create a sequence of callbacks - hard wired limit If it is impossible to tell from the parameters passed back from the C callback what the context is, then you may need to create a sequence of C callback interface functions, and store pointers to each in an array.
3. Use a parameter to map to the Perl callback A hash is an ideal mechanism to store the mapping between C and Perl.
###
Alternate Stack Manipulation
Although I have made use of only the `POP*` macros to access values returned from Perl subroutines, it is also possible to bypass these macros and read the stack using the `ST` macro (See <perlxs> for a full description of the `ST` macro).
Most of the time the `POP*` macros should be adequate; the main problem with them is that they force you to process the returned values in sequence. This may not be the most suitable way to process the values in some cases. What we want is to be able to access the stack in a random order. The `ST` macro as used when coding an XSUB is ideal for this purpose.
The code below is the example given in the section ["Returning a List of Values"](#Returning-a-List-of-Values) recoded to use `ST` instead of `POP*`.
```
static void
call_AddSubtract2(a, b)
int a;
int b;
{
dSP;
I32 ax;
int count;
ENTER;
SAVETMPS;
PUSHMARK(SP);
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(a)));
PUSHs(sv_2mortal(newSViv(b)));
PUTBACK;
count = call_pv("AddSubtract", G_LIST);
SPAGAIN;
SP -= count;
ax = (SP - PL_stack_base) + 1;
if (count != 2)
croak("Big trouble\n");
printf ("%d + %d = %d\n", a, b, SvIV(ST(0)));
printf ("%d - %d = %d\n", a, b, SvIV(ST(1)));
PUTBACK;
FREETMPS;
LEAVE;
}
```
Notes
1. Notice that it was necessary to define the variable `ax`. This is because the `ST` macro expects it to exist. If we were in an XSUB it would not be necessary to define `ax` as it is already defined for us.
2. The code
```
SPAGAIN;
SP -= count;
ax = (SP - PL_stack_base) + 1;
```
sets the stack up so that we can use the `ST` macro.
3. Unlike the original coding of this example, the returned values are not accessed in reverse order. So `ST(0)` refers to the first value returned by the Perl subroutine and `ST(count-1)` refers to the last.
###
Creating and Calling an Anonymous Subroutine in C
As we've already shown, `call_sv` can be used to invoke an anonymous subroutine. However, our example showed a Perl script invoking an XSUB to perform this operation. Let's see how it can be done inside our C code:
```
...
SV *cvrv
= eval_pv("sub {
print 'You will not find me cluttering any namespace!'
}", TRUE);
...
call_sv(cvrv, G_VOID|G_NOARGS);
```
`eval_pv` is used to compile the anonymous subroutine, which will be the return value as well (read more about `eval_pv` in ["eval\_pv" in perlapi](perlapi#eval_pv)). Once this code reference is in hand, it can be mixed in with all the previous examples we've shown.
LIGHTWEIGHT CALLBACKS
----------------------
Sometimes you need to invoke the same subroutine repeatedly. This usually happens with a function that acts on a list of values, such as Perl's built-in sort(). You can pass a comparison function to sort(), which will then be invoked for every pair of values that needs to be compared. The first() and reduce() functions from <List::Util> follow a similar pattern.
In this case it is possible to speed up the routine (often quite substantially) by using the lightweight callback API. The idea is that the calling context only needs to be created and destroyed once, and the sub can be called arbitrarily many times in between.
It is usual to pass parameters using global variables (typically $\_ for one parameter, or $a and $b for two parameters) rather than via @\_. (It is possible to use the @\_ mechanism if you know what you're doing, though there is as yet no supported API for it. It's also inherently slower.)
The pattern of macro calls is like this:
```
dMULTICALL; /* Declare local variables */
U8 gimme = G_SCALAR; /* context of the call: G_SCALAR,
* G_LIST, or G_VOID */
PUSH_MULTICALL(cv); /* Set up the context for calling cv,
and set local vars appropriately */
/* loop */ {
/* set the value(s) af your parameter variables */
MULTICALL; /* Make the actual call */
} /* end of loop */
POP_MULTICALL; /* Tear down the calling context */
```
For some concrete examples, see the implementation of the first() and reduce() functions of List::Util 1.18. There you will also find a header file that emulates the multicall API on older versions of perl.
SEE ALSO
---------
<perlxs>, <perlguts>, <perlembed>
AUTHOR
------
Paul Marquess
Special thanks to the following people who assisted in the creation of the document.
Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy and Larry Wall.
DATE
----
Last updated for perl 5.23.1.
| programming_docs |
perl Pod::Simple::Search Pod::Simple::Search
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [ACCESSORS](#ACCESSORS)
* [MAIN SEARCH METHODS](#MAIN-SEARCH-METHODS)
+ [$search->survey( @directories )](#%24search-%3Esurvey(-@directories-))
+ [$search->simplify\_name( $str )](#%24search-%3Esimplify_name(-%24str-))
+ [$search->find( $pod )](#%24search-%3Efind(-%24pod-))
+ [$search->find( $pod, @search\_dirs )](#%24search-%3Efind(-%24pod,-@search_dirs-))
+ [$self->contains\_pod( $file )](#%24self-%3Econtains_pod(-%24file-))
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Search - find POD documents in directory trees
SYNOPSIS
--------
```
use Pod::Simple::Search;
my $name2path = Pod::Simple::Search->new->limit_glob('LWP::*')->survey;
print "Looky see what I found: ",
join(' ', sort keys %$name2path), "\n";
print "LWPUA docs = ",
Pod::Simple::Search->new->find('LWP::UserAgent') || "?",
"\n";
```
DESCRIPTION
-----------
**Pod::Simple::Search** is a class that you use for running searches for Pod files. An object of this class has several attributes (mostly options for controlling search options), and some methods for searching based on those attributes.
The way to use this class is to make a new object of this class, set any options, and then call one of the search options (probably `survey` or `find`). The sections below discuss the syntaxes for doing all that.
CONSTRUCTOR
-----------
This class provides the one constructor, called `new`. It takes no parameters:
```
use Pod::Simple::Search;
my $search = Pod::Simple::Search->new;
```
ACCESSORS
---------
This class defines several methods for setting (and, occasionally, reading) the contents of an object. With two exceptions (discussed at the end of this section), these attributes are just for controlling the way searches are carried out.
Note that each of these return `$self` when you call them as `$self->*whatever(value)*`. That's so that you can chain together set-attribute calls like this:
```
my $name2path =
Pod::Simple::Search->new
-> inc(0) -> verbose(1) -> callback(\&blab)
->survey(@there);
```
...which works exactly as if you'd done this:
```
my $search = Pod::Simple::Search->new;
$search->inc(0);
$search->verbose(1);
$search->callback(\&blab);
my $name2path = $search->survey(@there);
```
$search->inc( *true-or-false* ); This attribute, if set to a true value, means that searches should implicitly add perl's *@INC* paths. This automatically considers paths specified in the `PERL5LIB` environment as this is prepended to *@INC* by the Perl interpreter itself. This attribute's default value is **TRUE**. If you want to search only specific directories, set $self->inc(0) before calling $inc->survey or $inc->find.
$search->verbose( *nonnegative-number* ); This attribute, if set to a nonzero positive value, will make searches output (via `warn`) notes about what they're doing as they do it. This option may be useful for debugging a pod-related module. This attribute's default value is zero, meaning that no `warn` messages are produced. (Setting verbose to 1 turns on some messages, and setting it to 2 turns on even more messages, i.e., makes the following search(es) even more verbose than 1 would make them.)
$search->limit\_glob( *some-glob-string* ); This option means that you want to limit the results just to items whose podnames match the given glob/wildcard expression. For example, you might limit your search to just "LWP::\*", to search only for modules starting with "LWP::\*" (but not including the module "LWP" itself); or you might limit your search to "LW\*" to see only modules whose (full) names begin with "LW"; or you might search for "\*Find\*" to search for all modules with "Find" somewhere in their full name. (You can also use "?" in a glob expression; so "DB?" will match "DBI" and "DBD".)
$search->callback( *\&some\_routine* ); This attribute means that every time this search sees a matching Pod file, it should call this callback routine. The routine is called with two parameters: the current file's filespec, and its pod name. (For example: `("/etc/perljunk/File/Crunk.pm", "File::Crunk")` would be in `@_`.)
The callback routine's return value is not used for anything.
This attribute's default value is false, meaning that no callback is called.
$search->laborious( *true-or-false* ); Unless you set this attribute to a true value, Pod::Search will apply Perl-specific heuristics to find the correct module PODs quickly. This attribute's default value is false. You won't normally need to set this to true.
Specifically: Turning on this option will disable the heuristics for seeing only files with Perl-like extensions, omitting subdirectories that are numeric but do *not* match the current Perl interpreter's version ID, suppressing *site\_perl* as a module hierarchy name, etc.
$search->recurse( *true-or-false* ); Unless you set this attribute to a false value, Pod::Search will recurse into subdirectories of the search directories.
$search->shadows( *true-or-false* ); Unless you set this attribute to a true value, Pod::Simple::Search will consider only the first file of a given modulename as it looks thru the specified directories; that is, with this option off, if Pod::Simple::Search has seen a `somepathdir/Foo/Bar.pm` already in this search, then it won't bother looking at a `somelaterpathdir/Foo/Bar.pm` later on in that search, because that file is merely a "shadow". But if you turn on `$self->shadows(1)`, then these "shadow" files are inspected too, and are noted in the pathname2podname return hash.
This attribute's default value is false; and normally you won't need to turn it on.
$search->is\_case\_insensitive( *true-or-false* ); Pod::Simple::Search will by default internally make an assumption based on the underlying filesystem where the class file is found whether it is case insensitive or not.
If it is determined to be case insensitive, during survey() it may skip pod files/modules that happen to be equal to names it's already seen, ignoring case.
However, it's possible to have distinct files in different directories that intentionally has the same name, just differing in case, that should be reported. Hence, you may force the behavior by setting this to true or false.
$search->limit\_re( *some-regxp* ); Setting this attribute (to a value that's a regexp) means that you want to limit the results just to items whose podnames match the given regexp. Normally this option is not needed, and the more efficient `limit_glob` attribute is used instead.
$search->dir\_prefix( *some-string-value* ); Setting this attribute to a string value means that the searches should begin in the specified subdirectory name (like "Pod" or "File::Find", also expressible as "File/Find"). For example, the search option `$search->limit_glob("File::Find::R*")` is the same as the combination of the search options `$search->limit_re("^File::Find::R") -> dir_prefix("File::Find")`.
Normally you don't need to know about the `dir_prefix` option, but I include it in case it might prove useful for someone somewhere.
(Implementationally, searching with limit\_glob ends up setting limit\_re and usually dir\_prefix.)
$search->progress( *some-progress-object* ); If you set a value for this attribute, the value is expected to be an object (probably of a class that you define) that has a `reach` method and a `done` method. This is meant for reporting progress during the search, if you don't want to use a simple callback.
Normally you don't need to know about the `progress` option, but I include it in case it might prove useful for someone somewhere.
While a search is in progress, the progress object's `reach` and `done` methods are called like this:
```
# Every time a file is being scanned for pod:
$progress->reach($count, "Scanning $file"); ++$count;
# And then at the end of the search:
$progress->done("Noted $count Pod files total");
```
Internally, we often set this to an object of class Pod::Simple::Progress. That class is probably undocumented, but you may wish to look at its source.
$name2path = $self->name2path; This attribute is not a search parameter, but is used to report the result of `survey` method, as discussed in the next section.
$path2name = $self->path2name; This attribute is not a search parameter, but is used to report the result of `survey` method, as discussed in the next section.
MAIN SEARCH METHODS
--------------------
Once you've actually set any options you want (if any), you can go ahead and use the following methods to search for Pod files in particular ways.
###
`$search->survey( @directories )`
The method `survey` searches for POD documents in a given set of files and/or directories. This runs the search according to the various options set by the accessors above. (For example, if the `inc` attribute is on, as it is by default, then the perl @INC directories are implicitly added to the list of directories (if any) that you specify.)
The return value of `survey` is two hashes:
`name2path` A hash that maps from each pod-name to the filespec (like "Stuff::Thing" => "/whatever/plib/Stuff/Thing.pm")
`path2name` A hash that maps from each Pod filespec to its pod-name (like "/whatever/plib/Stuff/Thing.pm" => "Stuff::Thing")
Besides saving these hashes as the hashref attributes `name2path` and `path2name`, calling this function also returns these hashrefs. In list context, the return value of `$search->survey` is the list `(\%name2path, \%path2name)`. In scalar context, the return value is `\%name2path`. Or you can just call this in void context.
Regardless of calling context, calling `survey` saves its results in its `name2path` and `path2name` attributes.
E.g., when searching in *$HOME/perl5lib*, the file *$HOME/perl5lib/MyModule.pm* would get the POD name *MyModule*, whereas *$HOME/perl5lib/Myclass/Subclass.pm* would be *Myclass::Subclass*. The name information can be used for POD translators.
Only text files containing at least one valid POD command are found.
In verbose mode, a warning is printed if shadows are found (i.e., more than one POD file with the same POD name is found, e.g. *CPAN.pm* in different directories). This usually indicates duplicate occurrences of modules in the *@INC* search path, which is occasionally inadvertent (but is often simply a case of a user's path dir having a more recent version than the system's general path dirs in general.)
The options to this argument is a list of either directories that are searched recursively, or files. (Usually you wouldn't specify files, but just dirs.) Or you can just specify an empty-list, as in $name2path; with the `inc` option on, as it is by default.
The POD names of files are the plain basenames with any Perl-like extension (.pm, .pl, .pod) stripped, and path separators replaced by `::`'s.
Calling Pod::Simple::Search->search(...) is short for Pod::Simple::Search->new->search(...). That is, a throwaway object with default attribute values is used.
###
`$search->simplify_name( $str )`
The method **simplify\_name** is equivalent to **basename**, but also strips Perl-like extensions (.pm, .pl, .pod) and extensions like *.bat*, *.cmd* on Win32 and OS/2, or *.com* on VMS, respectively.
###
`$search->find( $pod )`
###
`$search->find( $pod, @search_dirs )`
Returns the location of a Pod file, given a Pod/module/script name (like "Foo::Bar" or "perlvar" or "perldoc"), and an idea of what files/directories to look in. It searches according to the various options set by the accessors above. (For example, if the `inc` attribute is on, as it is by default, then the perl @INC directories are implicitly added to the list of directories (if any) that you specify.)
This returns the full path of the first occurrence to the file. Package names (eg 'A::B') are automatically converted to directory names in the selected directory. Additionally, '.pm', '.pl' and '.pod' are automatically appended to the search as required. (So, for example, under Unix, "A::B" is converted to "somedir/A/B.pm", "somedir/A/B.pod", or "somedir/A/B.pl", as appropriate.)
If no such Pod file is found, this method returns undef.
If any of the given search directories contains a *pod/* subdirectory, then it is searched. (That's how we manage to find *perlfunc*, for example, which is usually in *pod/perlfunc* in most Perl dists.)
The `verbose` and `inc` attributes influence the behavior of this search; notably, `inc`, if true, adds @INC *and also $Config::Config{'scriptdir'}* to the list of directories to search.
It is common to simply say `$filename = Pod::Simple::Search-> new ->find("perlvar")` so that just the @INC (well, and scriptdir) directories are searched. (This happens because the `inc` attribute is true by default.)
Calling Pod::Simple::Search->find(...) is short for Pod::Simple::Search->new->find(...). That is, a throwaway object with default attribute values is used.
###
`$self->contains_pod( $file )`
Returns true if the supplied filename (not POD module) contains some Pod documentation.
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]> with code borrowed from Marek Rouchal's <Pod::Find>, which in turn heavily borrowed code from Nick Ing-Simmons' `PodToHtml`.
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 Encode::MIME::Name Encode::MIME::Name
==================
CONTENTS
--------
* [NAME](#NAME)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::MIME::NAME -- internally used by Encode
SEE ALSO
---------
<I18N::Charset>
perl perlxstypemap perlxstypemap
=============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Anatomy of a typemap](#Anatomy-of-a-typemap)
+ [The Role of the typemap File in Your Distribution](#The-Role-of-the-typemap-File-in-Your-Distribution)
+ [Sharing typemaps Between CPAN Distributions](#Sharing-typemaps-Between-CPAN-Distributions)
+ [Writing typemap Entries](#Writing-typemap-Entries)
+ [Full Listing of Core Typemaps](#Full-Listing-of-Core-Typemaps)
NAME
----
perlxstypemap - Perl XS C/Perl type mapping
DESCRIPTION
-----------
The more you think about interfacing between two languages, the more you'll realize that the majority of programmer effort has to go into converting between the data structures that are native to either of the languages involved. This trumps other matter such as differing calling conventions because the problem space is so much greater. There are simply more ways to shove data into memory than there are ways to implement a function call.
Perl XS' attempt at a solution to this is the concept of typemaps. At an abstract level, a Perl XS typemap is nothing but a recipe for converting from a certain Perl data structure to a certain C data structure and vice versa. Since there can be C types that are sufficiently similar to one another to warrant converting with the same logic, XS typemaps are represented by a unique identifier, henceforth called an **XS type** in this document. You can then tell the XS compiler that multiple C types are to be mapped with the same XS typemap.
In your XS code, when you define an argument with a C type or when you are using a `CODE:` and an `OUTPUT:` section together with a C return type of your XSUB, it'll be the typemapping mechanism that makes this easy.
###
Anatomy of a typemap
In more practical terms, the typemap is a collection of code fragments which are used by the **xsubpp** compiler to map C function parameters and values to Perl values. The typemap file may consist of three sections labelled `TYPEMAP`, `INPUT`, and `OUTPUT`. An unlabelled initial section is assumed to be a `TYPEMAP` section. The INPUT section tells the compiler how to translate Perl values into variables of certain C types. The OUTPUT section tells the compiler how to translate the values from certain C types into values Perl can understand. The TYPEMAP section tells the compiler which of the INPUT and OUTPUT code fragments should be used to map a given C type to a Perl value. The section labels `TYPEMAP`, `INPUT`, or `OUTPUT` must begin in the first column on a line by themselves, and must be in uppercase.
Each type of section can appear an arbitrary number of times and does not have to appear at all. For example, a typemap may commonly lack `INPUT` and `OUTPUT` sections if all it needs to do is associate additional C types with core XS types like T\_PTROBJ. Lines that start with a hash `#` are considered comments and ignored in the `TYPEMAP` section, but are considered significant in `INPUT` and `OUTPUT`. Blank lines are generally ignored.
Traditionally, typemaps needed to be written to a separate file, conventionally called `typemap` in a CPAN distribution. With ExtUtils::ParseXS (the XS compiler) version 3.12 or better which comes with perl 5.16, typemaps can also be embedded directly into XS code using a HERE-doc like syntax:
```
TYPEMAP: <<HERE
...
HERE
```
where `HERE` can be replaced by other identifiers like with normal Perl HERE-docs. All details below about the typemap textual format remain valid.
The `TYPEMAP` section should contain one pair of C type and XS type per line as follows. An example from the core typemap file:
```
TYPEMAP
# all variants of char* is handled by the T_PV typemap
char * T_PV
const char * T_PV
unsigned char * T_PV
...
```
The `INPUT` and `OUTPUT` sections have identical formats, that is, each unindented line starts a new in- or output map respectively. A new in- or output map must start with the name of the XS type to map on a line by itself, followed by the code that implements it indented on the following lines. Example:
```
INPUT
T_PV
$var = ($type)SvPV_nolen($arg)
T_PTR
$var = INT2PTR($type,SvIV($arg))
```
We'll get to the meaning of those Perlish-looking variables in a little bit.
Finally, here's an example of the full typemap file for mapping C strings of the `char *` type to Perl scalars/strings:
```
TYPEMAP
char * T_PV
INPUT
T_PV
$var = ($type)SvPV_nolen($arg)
OUTPUT
T_PV
sv_setpv((SV*)$arg, $var);
```
Here's a more complicated example: suppose that you wanted `struct netconfig` to be blessed into the class `Net::Config`. One way to do this is to use underscores (\_) to separate package names, as follows:
```
typedef struct netconfig * Net_Config;
```
And then provide a typemap entry `T_PTROBJ_SPECIAL` that maps underscores to double-colons (::), and declare `Net_Config` to be of that type:
```
TYPEMAP
Net_Config T_PTROBJ_SPECIAL
INPUT
T_PTROBJ_SPECIAL
if (sv_derived_from($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")){
IV tmp = SvIV((SV*)SvRV($arg));
$var = INT2PTR($type, tmp);
}
else
croak(\"$var is not of type ${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\")
OUTPUT
T_PTROBJ_SPECIAL
sv_setref_pv($arg, \"${(my $ntt=$ntype)=~s/_/::/g;\$ntt}\",
(void*)$var);
```
The INPUT and OUTPUT sections substitute underscores for double-colons on the fly, giving the desired effect. This example demonstrates some of the power and versatility of the typemap facility.
The `INT2PTR` macro (defined in perl.h) casts an integer to a pointer of a given type, taking care of the possible different size of integers and pointers. There are also `PTR2IV`, `PTR2UV`, `PTR2NV` macros, to map the other way, which may be useful in OUTPUT sections.
###
The Role of the typemap File in Your Distribution
The default typemap in the *lib/ExtUtils* directory of the Perl source contains many useful types which can be used by Perl extensions. Some extensions define additional typemaps which they keep in their own directory. These additional typemaps may reference INPUT and OUTPUT maps in the main typemap. The **xsubpp** compiler will allow the extension's own typemap to override any mappings which are in the default typemap. Instead of using an additional *typemap* file, typemaps may be embedded verbatim in XS with a heredoc-like syntax. See the documentation on the `TYPEMAP:` XS keyword.
For CPAN distributions, you can assume that the XS types defined by the perl core are already available. Additionally, the core typemap has default XS types for a large number of C types. For example, if you simply return a `char *` from your XSUB, the core typemap will have this C type associated with the T\_PV XS type. That means your C string will be copied into the PV (pointer value) slot of a new scalar that will be returned from your XSUB to Perl.
If you're developing a CPAN distribution using XS, you may add your own file called *typemap* to the distribution. That file may contain typemaps that either map types that are specific to your code or that override the core typemap file's mappings for common C types.
###
Sharing typemaps Between CPAN Distributions
Starting with ExtUtils::ParseXS version 3.13\_01 (comes with perl 5.16 and better), it is rather easy to share typemap code between multiple CPAN distributions. The general idea is to share it as a module that offers a certain API and have the dependent modules declare that as a built-time requirement and import the typemap into the XS. An example of such a typemap-sharing module on CPAN is `ExtUtils::Typemaps::Basic`. Two steps to getting that module's typemaps available in your code:
* Declare `ExtUtils::Typemaps::Basic` as a build-time dependency in `Makefile.PL` (use `BUILD_REQUIRES`), or in your `Build.PL` (use `build_requires`).
* Include the following line in the XS section of your XS file: (don't break the line)
```
INCLUDE_COMMAND: $^X -MExtUtils::Typemaps::Cmd
-e "print embeddable_typemap(q{Basic})"
```
###
Writing typemap Entries
Each INPUT or OUTPUT typemap entry is a double-quoted Perl string that will be evaluated in the presence of certain variables to get the final C code for mapping a certain C type.
This means that you can embed Perl code in your typemap (C) code using constructs such as `${ perl code that evaluates to scalar reference here }`. A common use case is to generate error messages that refer to the true function name even when using the ALIAS XS feature:
```
${ $ALIAS ? \q[GvNAME(CvGV(cv))] : \qq[\"$pname\"] }
```
For many typemap examples, refer to the core typemap file that can be found in the perl source tree at *lib/ExtUtils/typemap*.
The Perl variables that are available for interpolation into typemaps are the following:
* *$var* - the name of the input or output variable, eg. RETVAL for return values.
* *$type* - the raw C type of the parameter, any `:` replaced with `_`. e.g. for a type of `Foo::Bar`, *$type* is `Foo__Bar`
* *$ntype* - the supplied type with `*` replaced with `Ptr`. e.g. for a type of `Foo*`, *$ntype* is `FooPtr`
* *$arg* - the stack entry, that the parameter is input from or output to, e.g. `ST(0)`
* *$argoff* - the argument stack offset of the argument. ie. 0 for the first argument, etc.
* *$pname* - the full name of the XSUB, with including the `PACKAGE` name, with any `PREFIX` stripped. This is the non-ALIAS name.
* *$Package* - the package specified by the most recent `PACKAGE` keyword.
* *$ALIAS* - non-zero if the current XSUB has any aliases declared with `ALIAS`.
###
Full Listing of Core Typemaps
Each C type is represented by an entry in the typemap file that is responsible for converting perl variables (SV, AV, HV, CV, etc.) to and from that type. The following sections list all XS types that come with perl by default.
T\_SV This simply passes the C representation of the Perl variable (an SV\*) in and out of the XS layer. This can be used if the C code wants to deal directly with the Perl variable.
T\_SVREF Used to pass in and return a reference to an SV.
Note that this typemap does not decrement the reference count when returning the reference to an SV\*. See also: T\_SVREF\_REFCOUNT\_FIXED
T\_SVREF\_FIXED Used to pass in and return a reference to an SV. This is a fixed variant of T\_SVREF that decrements the refcount appropriately when returning a reference to an SV\*. Introduced in perl 5.15.4.
T\_AVREF From the perl level this is a reference to a perl array. From the C level this is a pointer to an AV.
Note that this typemap does not decrement the reference count when returning an AV\*. See also: T\_AVREF\_REFCOUNT\_FIXED
T\_AVREF\_REFCOUNT\_FIXED From the perl level this is a reference to a perl array. From the C level this is a pointer to an AV. This is a fixed variant of T\_AVREF that decrements the refcount appropriately when returning an AV\*. Introduced in perl 5.15.4.
T\_HVREF From the perl level this is a reference to a perl hash. From the C level this is a pointer to an HV.
Note that this typemap does not decrement the reference count when returning an HV\*. See also: T\_HVREF\_REFCOUNT\_FIXED
T\_HVREF\_REFCOUNT\_FIXED From the perl level this is a reference to a perl hash. From the C level this is a pointer to an HV. This is a fixed variant of T\_HVREF that decrements the refcount appropriately when returning an HV\*. Introduced in perl 5.15.4.
T\_CVREF From the perl level this is a reference to a perl subroutine (e.g. $sub = sub { 1 };). From the C level this is a pointer to a CV.
Note that this typemap does not decrement the reference count when returning an HV\*. See also: T\_HVREF\_REFCOUNT\_FIXED
T\_CVREF\_REFCOUNT\_FIXED From the perl level this is a reference to a perl subroutine (e.g. $sub = sub { 1 };). From the C level this is a pointer to a CV.
This is a fixed variant of T\_HVREF that decrements the refcount appropriately when returning an HV\*. Introduced in perl 5.15.4.
T\_SYSRET The T\_SYSRET typemap is used to process return values from system calls. It is only meaningful when passing values from C to perl (there is no concept of passing a system return value from Perl to C).
System calls return -1 on error (setting ERRNO with the reason) and (usually) 0 on success. If the return value is -1 this typemap returns `undef`. If the return value is not -1, this typemap translates a 0 (perl false) to "0 but true" (which is perl true) or returns the value itself, to indicate that the command succeeded.
The [POSIX](posix) module makes extensive use of this type.
T\_UV An unsigned integer.
T\_IV A signed integer. This is cast to the required integer type when passed to C and converted to an IV when passed back to Perl.
T\_INT A signed integer. This typemap converts the Perl value to a native integer type (the `int` type on the current platform). When returning the value to perl it is processed in the same way as for T\_IV.
Its behaviour is identical to using an `int` type in XS with T\_IV.
T\_ENUM An enum value. Used to transfer an enum component from C. There is no reason to pass an enum value to C since it is stored as an IV inside perl.
T\_BOOL A boolean type. This can be used to pass true and false values to and from C.
T\_U\_INT This is for unsigned integers. It is equivalent to using T\_UV but explicitly casts the variable to type `unsigned int`. The default type for `unsigned int` is T\_UV.
T\_SHORT Short integers. This is equivalent to T\_IV but explicitly casts the return to type `short`. The default typemap for `short` is T\_IV.
T\_U\_SHORT Unsigned short integers. This is equivalent to T\_UV but explicitly casts the return to type `unsigned short`. The default typemap for `unsigned short` is T\_UV.
T\_U\_SHORT is used for type `U16` in the standard typemap.
T\_LONG Long integers. This is equivalent to T\_IV but explicitly casts the return to type `long`. The default typemap for `long` is T\_IV.
T\_U\_LONG Unsigned long integers. This is equivalent to T\_UV but explicitly casts the return to type `unsigned long`. The default typemap for `unsigned long` is T\_UV.
T\_U\_LONG is used for type `U32` in the standard typemap.
T\_CHAR Single 8-bit characters.
T\_U\_CHAR An unsigned byte.
T\_FLOAT A floating point number. This typemap guarantees to return a variable cast to a `float`.
T\_NV A Perl floating point number. Similar to T\_IV and T\_UV in that the return type is cast to the requested numeric type rather than to a specific type.
T\_DOUBLE A double precision floating point number. This typemap guarantees to return a variable cast to a `double`.
T\_PV A string (char \*).
T\_PTR A memory address (pointer). Typically associated with a `void *` type.
T\_PTRREF Similar to T\_PTR except that the pointer is stored in a scalar and the reference to that scalar is returned to the caller. This can be used to hide the actual pointer value from the programmer since it is usually not required directly from within perl.
The typemap checks that a scalar reference is passed from perl to XS.
T\_PTROBJ Similar to T\_PTRREF except that the reference is blessed into a class. This allows the pointer to be used as an object. Most commonly used to deal with C structs. The typemap checks that the perl object passed into the XS routine is of the correct class (or part of a subclass).
The pointer is blessed into a class that is derived from the name of type of the pointer but with all '\*' in the name replaced with 'Ptr'.
For `DESTROY` XSUBs only, a T\_PTROBJ is optimized to a T\_PTRREF. This means the class check is skipped.
T\_REF\_IV\_REF NOT YET
T\_REF\_IV\_PTR Similar to T\_PTROBJ in that the pointer is blessed into a scalar object. The difference is that when the object is passed back into XS it must be of the correct type (inheritance is not supported) while T\_PTROBJ supports inheritance.
The pointer is blessed into a class that is derived from the name of type of the pointer but with all '\*' in the name replaced with 'Ptr'.
For `DESTROY` XSUBs only, a T\_REF\_IV\_PTR is optimized to a T\_PTRREF. This means the class check is skipped.
T\_PTRDESC NOT YET
T\_REFREF Similar to T\_PTRREF, except the pointer stored in the referenced scalar is dereferenced and copied to the output variable. This means that T\_REFREF is to T\_PTRREF as T\_OPAQUE is to T\_OPAQUEPTR. All clear?
Only the INPUT part of this is implemented (Perl to XSUB) and there are no known users in core or on CPAN.
T\_REFOBJ Like T\_REFREF, except it does strict type checking (inheritance is not supported).
For `DESTROY` XSUBs only, a T\_REFOBJ is optimized to a T\_REFREF. This means the class check is skipped.
T\_OPAQUEPTR This can be used to store bytes in the string component of the SV. Here the representation of the data is irrelevant to perl and the bytes themselves are just stored in the SV. It is assumed that the C variable is a pointer (the bytes are copied from that memory location). If the pointer is pointing to something that is represented by 8 bytes then those 8 bytes are stored in the SV (and length() will report a value of 8). This entry is similar to T\_OPAQUE.
In principle the unpack() command can be used to convert the bytes back to a number (if the underlying type is known to be a number).
This entry can be used to store a C structure (the number of bytes to be copied is calculated using the C `sizeof` function) and can be used as an alternative to T\_PTRREF without having to worry about a memory leak (since Perl will clean up the SV).
T\_OPAQUE This can be used to store data from non-pointer types in the string part of an SV. It is similar to T\_OPAQUEPTR except that the typemap retrieves the pointer directly rather than assuming it is being supplied. For example, if an integer is imported into Perl using T\_OPAQUE rather than T\_IV the underlying bytes representing the integer will be stored in the SV but the actual integer value will not be available. i.e. The data is opaque to perl.
The data may be retrieved using the `unpack` function if the underlying type of the byte stream is known.
T\_OPAQUE supports input and output of simple types. T\_OPAQUEPTR can be used to pass these bytes back into C if a pointer is acceptable.
Implicit array xsubpp supports a special syntax for returning packed C arrays to perl. If the XS return type is given as
```
array(type, nelem)
```
xsubpp will copy the contents of `nelem * sizeof(type)` bytes from RETVAL to an SV and push it onto the stack. This is only really useful if the number of items to be returned is known at compile time and you don't mind having a string of bytes in your SV. Use T\_ARRAY to push a variable number of arguments onto the return stack (they won't be packed as a single string though).
This is similar to using T\_OPAQUEPTR but can be used to process more than one element.
T\_PACKED Calls user-supplied functions for conversion. For `OUTPUT` (XSUB to Perl), a function named `XS_pack_$ntype` is called with the output Perl scalar and the C variable to convert from. `$ntype` is the normalized C type that is to be mapped to Perl. Normalized means that all `*` are replaced by the string `Ptr`. The return value of the function is ignored.
Conversely for `INPUT` (Perl to XSUB) mapping, the function named `XS_unpack_$ntype` is called with the input Perl scalar as argument and the return value is cast to the mapped C type and assigned to the output C variable.
An example conversion function for a typemapped struct `foo_t *` might be:
```
static void
XS_pack_foo_tPtr(SV *out, foo_t *in)
{
dTHX; /* alas, signature does not include pTHX_ */
HV* hash = newHV();
hv_stores(hash, "int_member", newSViv(in->int_member));
hv_stores(hash, "float_member", newSVnv(in->float_member));
/* ... */
/* mortalize as thy stack is not refcounted */
sv_setsv(out, sv_2mortal(newRV_noinc((SV*)hash)));
}
```
The conversion from Perl to C is left as an exercise to the reader, but the prototype would be:
```
static foo_t *
XS_unpack_foo_tPtr(SV *in);
```
Instead of an actual C function that has to fetch the thread context using `dTHX`, you can define macros of the same name and avoid the overhead. Also, keep in mind to possibly free the memory allocated by `XS_unpack_foo_tPtr`.
T\_PACKEDARRAY T\_PACKEDARRAY is similar to T\_PACKED. In fact, the `INPUT` (Perl to XSUB) typemap is identical, but the `OUTPUT` typemap passes an additional argument to the `XS_pack_$ntype` function. This third parameter indicates the number of elements in the output so that the function can handle C arrays sanely. The variable needs to be declared by the user and must have the name `count_$ntype` where `$ntype` is the normalized C type name as explained above. The signature of the function would be for the example above and `foo_t **`:
```
static void
XS_pack_foo_tPtrPtr(SV *out, foo_t *in, UV count_foo_tPtrPtr);
```
The type of the third parameter is arbitrary as far as the typemap is concerned. It just has to be in line with the declared variable.
Of course, unless you know the number of elements in the `sometype **` C array, within your XSUB, the return value from `foo_t ** XS_unpack_foo_tPtrPtr(...)` will be hard to decipher. Since the details are all up to the XS author (the typemap user), there are several solutions, none of which particularly elegant. The most commonly seen solution has been to allocate memory for N+1 pointers and assign `NULL` to the (N+1)th to facilitate iteration.
Alternatively, using a customized typemap for your purposes in the first place is probably preferable.
T\_DATAUNIT NOT YET
T\_CALLBACK NOT YET
T\_ARRAY This is used to convert the perl argument list to a C array and for pushing the contents of a C array onto the perl argument stack.
The usual calling signature is
```
@out = array_func( @in );
```
Any number of arguments can occur in the list before the array but the input and output arrays must be the last elements in the list.
When used to pass a perl list to C the XS writer must provide a function (named after the array type but with 'Ptr' substituted for '\*') to allocate the memory required to hold the list. A pointer should be returned. It is up to the XS writer to free the memory on exit from the function. The variable `ix_$var` is set to the number of elements in the new array.
When returning a C array to Perl the XS writer must provide an integer variable called `size_$var` containing the number of elements in the array. This is used to determine how many elements should be pushed onto the return argument stack. This is not required on input since Perl knows how many arguments are on the stack when the routine is called. Ordinarily this variable would be called `size_RETVAL`.
Additionally, the type of each element is determined from the type of the array. If the array uses type `intArray *` xsubpp will automatically work out that it contains variables of type `int` and use that typemap entry to perform the copy of each element. All pointer '\*' and 'Array' tags are removed from the name to determine the subtype.
T\_STDIO This is used for passing perl filehandles to and from C using `FILE *` structures.
T\_INOUT This is used for passing perl filehandles to and from C using `PerlIO *` structures. The file handle can used for reading and writing. This corresponds to the `+<` mode, see also T\_IN and T\_OUT.
See <perliol> for more information on the Perl IO abstraction layer. Perl must have been built with `-Duseperlio`.
There is no check to assert that the filehandle passed from Perl to C was created with the right `open()` mode.
Hint: The <perlxstut> tutorial covers the T\_INOUT, T\_IN, and T\_OUT XS types nicely.
T\_IN Same as T\_INOUT, but the filehandle that is returned from C to Perl can only be used for reading (mode `<`).
T\_OUT Same as T\_INOUT, but the filehandle that is returned from C to Perl is set to use the open mode `+>`.
| programming_docs |
Subsets and Splits