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