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