xref: /openbsd-src/gnu/usr.bin/perl/lib/builtin.pm (revision 5486feefcc8cb79b19e014ab332cc5dfd05b3b33)
1package builtin 0.014;
2
3use strict;
4use warnings;
5
6# All code, including &import, is implemented by always-present
7# functions in the perl interpreter itself.
8# See also `builtin.c` in perl source
9
101;
11__END__
12
13=head1 NAME
14
15builtin - Perl pragma to import built-in utility functions
16
17=head1 SYNOPSIS
18
19    use builtin qw(
20        true false is_bool
21        inf nan
22        weaken unweaken is_weak
23        blessed refaddr reftype
24        created_as_string created_as_number
25        stringify
26        ceil floor
27        indexed
28        trim
29        is_tainted
30        export_lexically
31        load_module
32    );
33
34    use builtin ':5.40';  # most of the above
35
36=head1 DESCRIPTION
37
38Perl provides several utility functions in the C<builtin> package. These are
39plain functions, and look and behave just like regular user-defined functions
40do. They do not provide new syntax or require special parsing. These functions
41are always present in the interpreter and can be called at any time by their
42fully-qualified names. By default they are not available as short names, but
43can be requested for convenience.
44
45Individual named functions can be imported by listing them as import
46parameters on the C<use> statement for this pragma.
47
48B<Warning>:  At present, many of the functions in the C<builtin> namespace are
49experimental.  Calling them will trigger warnings of the
50C<experimental::builtin> category.
51
52=head2 Lexical Import
53
54This pragma module creates I<lexical> aliases in the currently-compiling scope
55to these builtin functions. This is similar to the lexical effect of other
56pragmas such as L<strict> and L<feature>.
57
58    sub classify
59    {
60        my $val = shift;
61
62        use builtin 'is_bool';
63        return is_bool($val) ? "boolean" : "not a boolean";
64    }
65
66    # the is_bool() function is no longer visible here
67    # but may still be called by builtin::is_bool()
68
69Because these functions are imported lexically, rather than by package
70symbols, the user does not need to take any special measures to ensure they
71don't accidentally appear as object methods from a class.
72
73    package An::Object::Class {
74        use builtin 'true', 'false';
75        ...
76    }
77
78    # does not appear as a method
79    An::Object::Class->true;
80
81    # Can't locate object method "true" via package "An::Object::Class"
82    #   at ...
83
84Once imported, a lexical function is much like any other lexical symbol
85(such as a variable) in that it cannot be removed again.  If you wish to
86limit the visiblity of an imported C<builtin> function, put it inside its
87own scope:
88
89    {
90      use builtin 'refaddr';
91      ...
92    }
93
94=head2 Version Bundles
95
96The entire set of builtin functions that were considered non-experimental by a
97version of perl can be imported all at once, by requesting a version bundle.
98This is done by giving the perl release version (without its subversion
99suffix) after a colon character:
100
101    use builtin ':5.40';
102
103The following bundles currently exist:
104
105    Version    Includes
106    -------    --------
107
108    :5.40      true false weaken unweaken is_weak blessed refaddr reftype
109               ceil floor is_tainted trim indexed
110
111=head1 FUNCTIONS
112
113=head2 true
114
115    $val = true;
116
117Returns the boolean truth value. While any scalar value can be tested for
118truth and most defined, non-empty and non-zero values are considered "true"
119by perl, this one is special in that L</is_bool> considers it to be a
120distinguished boolean value.
121
122This gives an equivalent value to expressions like C<!!1> or C<!0>.
123
124=head2 false
125
126    $val = false;
127
128Returns the boolean fiction value. While any non-true scalar value is
129considered "false" by perl, this one is special in that L</is_bool> considers
130it to be a distinguished boolean value.
131
132This gives an equivalent value to expressions like C<!!0> or C<!1>.
133
134=head2 is_bool
135
136    $bool = is_bool($val);
137
138This function is currently B<experimental>.
139
140Returns true when given a distinguished boolean value, or false if not. A
141distinguished boolean value is the result of any boolean-returning builtin
142function (such as C<true> or C<is_bool> itself), boolean-returning operator
143(such as the C<eq> or C<==> comparison tests or the C<!> negation operator),
144or any variable containing one of these results.
145
146This function used to be named C<isbool>. A compatibility alias is provided
147currently but will be removed in a later version.
148
149=head2 inf
150
151    $num = inf;
152
153This function is currently B<experimental>.
154
155Returns the floating-point infinity value.
156
157=head2 nan
158
159    $num = nan;
160
161This function is currently B<experimental>.
162
163Returns the floating-point "Not-a-Number" value.
164
165=head2 weaken
166
167    weaken($ref);
168
169Weakens a reference. A weakened reference does not contribute to the reference
170count of its referent. If only weakened references to a referent remain, it
171will be disposed of, and all remaining weak references to it will have their
172value set to C<undef>.
173
174=head2 unweaken
175
176    unweaken($ref);
177
178Strengthens a reference, undoing the effects of a previous call to L</weaken>.
179
180=head2 is_weak
181
182    $bool = is_weak($ref);
183
184Returns true when given a weakened reference, or false if not a reference or
185not weak.
186
187This function used to be named C<isweak>. A compatibility alias is provided
188currently but will be removed in a later version.
189
190=head2 blessed
191
192    $str = blessed($ref);
193
194Returns the package name for an object reference, or C<undef> for a
195non-reference or reference that is not an object.
196
197=head2 refaddr
198
199    $num = refaddr($ref);
200
201Returns the memory address for a reference, or C<undef> for a non-reference.
202This value is not likely to be very useful for pure Perl code, but is handy as
203a means to test for referential identity or uniqueness.
204
205=head2 reftype
206
207    $str = reftype($ref);
208
209Returns the basic container type of the referent of a reference, or C<undef>
210for a non-reference. This is returned as a string in all-capitals, such as
211C<ARRAY> for array references, or C<HASH> for hash references.
212
213=head2 created_as_string
214
215    $bool = created_as_string($val);
216
217This function is currently B<experimental>.
218
219Returns a boolean representing if the argument value was originally created as
220a string. It will return true for any scalar expression whose most recent
221assignment or modification was of a string-like nature - such as assignment
222from a string literal, or the result of a string operation such as
223concatenation or regexp. It will return false for references (including any
224object), numbers, booleans and undef.
225
226It is unlikely that you will want to use this for regular data validation
227within Perl, as it will not return true for regular numbers that are still
228perfectly usable as strings, nor for any object reference - especially objects
229that overload the stringification operator in an attempt to behave more like
230strings. For example
231
232    my $val = URI->new( "https://metacpan.org/" );
233
234    if( created_as_string $val ) { ... }    # this will not execute
235
236=head2 created_as_number
237
238    $bool = created_as_number($val);
239
240This function is currently B<experimental>.
241
242Returns a boolean representing if the argument value was originally created as
243a number. It will return true for any scalar expression whose most recent
244assignment or modification was of a numerical nature - such as assignment from
245a number literal, or the result of a numerical operation such as addition. It
246will return false for references (including any object), strings, booleans and
247undef.
248
249It is unlikely that you will want to use this for regular data validation
250within Perl, as it will not return true for regular strings of decimal digits
251that are still perfectly usable as numbers, nor for any object reference -
252especially objects that overload the numification operator in an attempt to
253behave more like numbers. For example
254
255    my $val = Math::BigInt->new( 123 );
256
257    if( created_as_number $val ) { ... }    # this will not execute
258
259While most Perl code should operate on scalar values without needing to know
260their creation history, these two functions are intended to be used by data
261serialisation modules such as JSON encoders or similar situations, where
262language interoperability concerns require making a distinction between values
263that are fundamentally stringlike versus numberlike in nature.
264
265=head2 stringify
266
267    $str = stringify($val);
268
269Returns a new plain perl string that represents the given argument.
270
271When given a value that is already a string, a copy of this value is returned
272unchanged. False booleans are treated like the empty string.
273
274Numbers are turned into a decimal representation. True booleans are treated
275like the number 1.
276
277References to objects in classes that have L<overload> and define the C<"">
278overload entry will use the delegated method to provide a value here.
279
280Non-object references, or references to objects in classes without a C<"">
281overload will return a string that names the underlying container type of
282the reference, its memory address, and possibly its class name if it is an
283object.
284
285=head2 ceil
286
287    $num = ceil($num);
288
289Returns the smallest integer value greater than or equal to the given
290numerical argument.
291
292=head2 floor
293
294    $num = floor($num);
295
296Returns the largest integer value less than or equal to the given numerical
297argument.
298
299=head2 indexed
300
301    @ivpairs = indexed(@items)
302
303Returns an even-sized list of number/value pairs, where each pair is formed
304of a number giving an index in the original list followed by the value at that
305position in it.  I.e. returns a list twice the size of the original, being
306equal to
307
308    (0, $items[0], 1, $items[1], 2, $items[2], ...)
309
310Note that unlike the core C<values> function, this function returns copies of
311its original arguments, not aliases to them. Any modifications of these copies
312are I<not> reflected in modifications to the original.
313
314    my @x = ...;
315    $_++ for indexed @x;  # The @x array remains unaffected
316
317This function is primarily intended to be useful combined with multi-variable
318C<foreach> loop syntax; as
319
320    foreach my ($index, $value) (indexed LIST) {
321        ...
322    }
323
324In scalar context this function returns the size of the list that it would
325otherwise have returned, and provokes a warning in the C<scalar> category.
326
327=head2 trim
328
329    $stripped = trim($string);
330
331Returns the input string with whitespace stripped from the beginning
332and end. trim() will remove these characters:
333
334" ", an ordinary space.
335
336"\t", a tab.
337
338"\n", a new line (line feed).
339
340"\r", a carriage return.
341
342and all other Unicode characters that are flagged as whitespace.
343A complete list is in L<perlrecharclass/Whitespace>.
344
345    $var = "  Hello world   ";            # "Hello world"
346    $var = "\t\t\tHello world";           # "Hello world"
347    $var = "Hello world\n";               # "Hello world"
348    $var = "\x{2028}Hello world\x{3000}"; # "Hello world"
349
350C<trim> is equivalent to:
351
352    $str =~ s/\A\s+|\s+\z//urg;
353
354For Perl versions where this feature is not available look at the
355L<String::Util> module for a comparable implementation.
356
357=head2 is_tainted
358
359    $bool = is_tainted($var);
360
361Returns true when given a tainted variable.
362
363=head2 export_lexically
364
365    export_lexically($name1, $ref1, $name2, $ref2, ...)
366
367This function is currently B<experimental>.
368
369Exports new lexical names into the scope currently being compiled. Names given
370by the first of each pair of values will refer to the corresponding item whose
371reference is given by the second. Types of item that are permitted are
372subroutines, and scalar, array, and hash variables. If the item is a
373subroutine, the name may optionally be prefixed with the C<&> sigil, but for
374convenience it doesn't have to. For items that are variables the sigil is
375required, and must match the type of the variable.
376
377    export_lexically func    => \&func,
378                     '&func' => \&func;  # same as above
379
380    export_lexically '$scalar' => \my $var;
381
382Z<>
383
384    # The following are not permitted
385    export_lexically '$var' => \@arr;   # sigil does not match
386    export_lexically name => \$scalar;  # implied '&' sigil does not match
387
388    export_lexically '*name' => \*globref;  # globrefs are not supported
389
390This must be called at compile time; which typically means during a C<BEGIN>
391block. Usually this would be used as part of an C<import> method of a module,
392when invoked as part of a C<use ...> statement.
393
394=head2 load_module
395
396    load_module($module_name);
397
398This function is currently B<experimental>.
399
400Loads a named module from the inclusion paths (C<@INC>).  C<$module_name> must
401be a string that provides a module name.  It cannot be omitted, and providing
402an invalid module name will result in an exception.  Not providing any argument
403results in a compilation error.  Returns the loaded module's name on success.
404
405The effect of C<load_module>-ing a module is mostly the same as C<require>-ing,
406down to the same error conditions when the module does not exist, does not
407compile, or does not evaluate to a true value.  See also
408L<the C<module_true> feature|feature/"The 'module_true' feature">.
409
410C<load_module> can't be used to require a particular version of Perl, nor can
411it be given a bareword module name as an argument.
412
413=head1 SEE ALSO
414
415L<perlop>, L<perlfunc>, L<Scalar::Util>
416