[DRAFT] Synopsis 29 - Builtin Functions [DRAFT]
Maintainer: Rod Adams <rod@rodadams.net> Date: 12 Mar 2005 Last Modified: 03 Apr 2005
This document attempts to document the list of builtin functions in Perl 6. It assumes familiarity with Perl 5 and prior synopses.
In Perl 6, all builtin functions belong to a named package. Not all functions are guaranteed to be imported into the global package ::*. In addition, the list of functions imported into ::* will be subject to change with each release of Perl. Authors wishing to "Future Proof" their code should either specifically import the functions they will be using, or always refer to the functions by their full name.
::*
After 6.0.0 comes out, global aliases will not be removed lightly, and will never be removed at all without having gone through a deprecation cycle of at least a year. In any event, you can specify that you want the interface for a particular version of Perl, and that can be emulated by later versions of Perl to the extent that security updates allow.
Where code is given here, it is intended to define semantics, not to dictate implementation.
The following type declarations are assumed:
The root class of all "character" types, regardless of level.
This is a subtype of Str, limited to a length of 1 at it's highest supported Unicode level.
Str
Subclasses (things that are isa Char):
isa Char
Yes, Byte is both a string and a number.
type MatchTest ::= Item | Junction;
Used to supply a test to match against. Assume ~~ will be used against it.
~~
multi sub Num::abs ( Num $x ) returns Num multi sub Math::Basic::abs (: Num $x = $CALLER::_ ) returns Num
Absolute Value.
multi sub Num::floor ( Num $x ) returns Int
Returns the highest integer not greater than $x.
multi sub Num::ceiling ( Num $x ) returns Int &Num::ceil ::= &Num::Ceiling;
Returns the lowest integer not less than $x.
multi sub Num::round ( Num $x ) returns Int
Returns the nearest integer to $x, away from zero. In other words, the absolute value, rounded up.
multi sub Num::truncate ( Num $x ) returns Int our &Num::int ::= &Num::truncate;
Returns the closest integer to $x, rounding towards 0. This is the default rounding function used by an int() cast, for historic reasons.
int()
multi sub Num::exp ( Num $exponent : Num :$base) returns Num multi sub Math::Basic::exp (: Num $exponent = $CALLER::_, Num :$base) returns Num
Performs similar to $base ** $exponent. $base defaults to the constant e.
$base ** $exponent
$base
multi sub Num::log ( Num $x : Num :$base) returns Num multi sub Math::Basic::log (: Num $x = $CALLER::_, Num :$base) returns Num
Logarithm of base $base, default Natural. Calling with $x == 0 is an error.
$x == 0
&log10<> := &log<>.assuming:base(10);
multi sub Math::Basic::rand (: Num $x = 1) returns Num
Psuedo random number between 0 and $x.
0
$x
multi sub Num::sign ( Num $x ) returns Int multi sub Math::Basic::sign (: Num $x = $CALLER::_) returns Int { if !defined($x) { return undef }; if $x < 0 { return -1 }; if $x > 0 { return 1 }; if $x == 0 { return 0 }; undef; }
multi sub Math::Basic::srand (: Num $seed)
Seed the generator rand uses. $seed defaults to some combination of various platform dependent characteristics to yield a non- deterministic seed.
rand
$seed
multi sub Num::sqrt ( Num $x ) returns Num multi sub Math::Basic::sqrt (: Num $x = $CALLER::_) returns Num
$x ** 0.5
multi sub Num::func ( Num $x : :$base) returns Num multi sub Math::Trig::func (: Num $x = $CALLER::_, :$base) returns Num
where func is one of: sin, cos, tan, asin, acos, atan, sec, cosec, cotan, asec, acosec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, sech, cosech, cotanh, asech, acosech, acotanh.
Performs the various trigonmetric functions.
Option $base is used to declare your how you measure your angles. Given the value of an arc representing a single full revolution.
$base Result ---- ------- /:i ^r/ Radians (2*pi) /:i ^d/ Degrees (360) /:i ^g/ Gradians (400) Num Units of 1 revolution.
multi sub Math::Trig::atan (Num $y, Num $x : Num :$base) returns Num
This second form of atan computes the arctangent of $y/$x, and takes the quadrant into account. Otherwise behaves as other trigonometric functions. Replaces Perl 5 atan2.
atan
atan2
multi sub Math::Trig::pi () returns Num
multi method Array::delete (@array : *@indices) returns List
Sets elements specified by @indices in the invocant to a non-existent state, as if they never had a value. Deleted elements at the end of an Array shorten the length of the Array, unless doing so would violate an is shape() definition.
@indices
is shape()
@indices is interpreted the same way as subscripting is in terms of slices and multidimensionality. See Synopsis 9 for details.
Returns the value(s) previously held in deleted locations.
An unary form is expected. See Hash::delete.
Hash::delete
multi method Array::exists (@array : Int *@indices) returns Bool
True if the specified Array element has been assigned to. This is not the same as being defined.
Supplying a different number of indices than invocant has dimensions is an error.
&Array::pop<Array> := &Array::splice<Array>.assuming(:offset(-1) :length(1)); multi sub Array::pop () returns Scalar { pop @CALLER::_; }
multi sub Array::push (@array is rw : *@values) returns Int { Array::splice(@array, @array.elems, 0, @values); @array.elems; }
&Array::shift<Array> := &Array::splice<Array>.assuming(:offset(0) :length(1)); multi sub Array::shift () returns Scalar { Array::shift @CALLER::_; }
multi sub Array::splice ( @array is rw : Int $offset = 0, Int $length, *@values ) returns List is rw
Behaves similar as Perl 5 splice.
splice
If @array is multidimensional, splice operates only on the first dimension, and works with Array References.
@array
multi sub Array::unshift (@array is rw : *@values) returns Int { Array::splice(@array, 0, 0, @values); @array.elems; }
multi sub Array::keys (@array : MatchTest *@indextests) returns Int|List multi sub Array::kv (@array : MatchTest *@indextests) returns Int|List multi sub Array::pairs (@array : MatchTest *@indextests) returns Int|(List of Pair) multi sub Array::values (@array : MatchTest *@indextests) returns Int|List
Iterates the elements of @array, in order.
If @indextests are provided, only elements whose indices match $index ~~ any(@indextests) are iterated.
@indextests
$index ~~ any(@indextests)
What is returned at each element of the iteration varies with function. values returns the value of the associated element; kv returns a 2 element list in (index, value) order, pairs a Pair(index, value).
values
kv
pairs
Pair(index, value)
@array is considered single dimensional. If it is in fact multi- dimensional, the values returned will be array references to the sub array.
In Scalar context, they all return the count of elements that would have been iterated.
multi sub Array::grep (@values : Code *&test ) returns Lazy multi sub Array::grep (@values, MatchTest $test ) returns Lazy multi sub List::grep (MatchTest $test : *@values) returns Lazy { gather { for @values -> $x { take $x if $x ~~ $test; } } }
multi sub Array::join (@values, Str $delimiter) returns Str multi sub List::join (Str $delimiter : *@values) returns Str { my $str = ~@values[0]; for 1..@values.end { $str ~= $delimiter ~ @values[$_]; } $str; } &join<> := &join<Str>.assuming:delimiter(' ');
multi sub Array::map (@values, Code $expression) returns Lazy multi sub List::map (Code $expression : *@values) returns Lazy { gather { while @values { take $expression .( splice(@values, 0, $expression.arity) ); } } }
multi sub Array::reduce (@values : Code *&expression) returns Scalar multi sub List::reduce (Code $expression : *@values) returns Scalar { my $res; for @values -> $cur { FIRST {$res = $cur; next;} $res = &$expression($res, $cur); } $res; }
multi sub Hash::reverse (%hash) returns Hash is default { my %result; for %hash.kv -> $k, $v { %result{$v} = $k; } %result; } multi sub Array::reverse ( @values) returns Lazy|Str { multi sub List::reverse (: *@values) returns Lazy|Str { given want { when List { gather { 1 while take pop @values; } } when Scalar { reverse @values ==> join; } } }
type KeyExtractor ::= Code(Any) returns Any; type Comparator ::= Code(Any, Any) returns Int; type SortCriterion ::= KeyExtractor | Comparator | Pair(KeyExtractor, Comparator); multi sub Array::sort( @values is rw, *&by : Bit :$inplace ) returns Array multi sub Array::sort( @values is rw, SortCriterion @by : Bit :$inplace ) returns Array multi sub Array::sort( @values is rw : SortCriterion :$by = &infix:<cmp>, Bit :$inplace ) returns Array multi sub List::sort( SortCriterion @by : *@values ) returns List multi sub List::sort(: SortCriterion $by = &infix:<cmp>, *@values ) returns List
Returns @values sorted, using criteria $by or @by for comparisions. @by differs from $by in that each criteria is applied, in order, until a non-zero (tie) result is achieved.
@values
$by
@by
Criterion can take a few different forms:
A closure with arity of 2, which returns negative/zero/positive, signaling the first arguement should be before/tied with/after the second in the final ordering of the List. aka "The Perl 5 way"
A closure with arity of 1, which returns the "key" by which to sort. If the closure returns a Num, <=> is used for comparison, otherwise cmp.
<=>
cmp
A combination of the two methods above, for when one wishs to take advantage of the internal caching of keys that is expected to happen, but wishes to compare them with something other than <=> or cmp.
Any Criterion may recieve either or both of the traits is descending and is insensitive to reverse the order of sort, or the adjust the case sensitivity of cmp as a Comparator.
is descending
is insensitive
If all criteria are exhausted when comparing two elements, sort should return them in the same relative order they had in @values.
If $inplace is specified, the array is sorted in place.
$inplace
See http://www.nntp.perl.org/group/perl.perl6.language/16578 for more details and examples.
multi sub Lists::zip (: Array *@lists, Bit :$shortest) returns Lazy { gather { while $shortest ?? all (@lists) !! any(@lists) { for @lists -> @list { take shift @list; } } } }
multi method Hash::delete (: *@keys) returns List multi method Hash::delete ( $key ) returns Scalar is default
Deletes the elements specified by $key or $keys from the invocant. returns the value(s) that were associated to those keys.
$key
$keys
Implementations should create a suitable macro, or otherwise support the unary form delete %hash{$key} in all it's forms. Below are some example translations. This list is not exhaustive.
delete %hash{$key}
delete %hash{$key} %hash.delete{$key} delete %hash<key> %hash.delete{'key'} delete %hash<key1>{@keys} %hash<key1>.delete{@keys}
multi method Hash::exists ($key) returns Bool
True if invocant has an element whose key matches $key, false otherwise.
An unary form is expected. See Hash::delete
multi sub Hash::keys (%hash : MatchTest *@keytests) returns Int|List multi sub Hash::kv (%hash : MatchTest *@keytests) returns Int|List multi sub Hash::pairs (%hash : MatchTest *@keytests) returns Int|(List of Pair) multi sub Hash::values (%hash : MatchTest *@keytests) returns Int|List
Iterates the elements of %hash in no apparent order, but the order will be the same between successive calls to these functions, as long as %hash doesn't change.
%hash
If @keytests are provided, only elements whose keys evaluate $key ~~ any(@keytests) as true are iterated.
@keytests
$key ~~ any(@keytests)
What is returned at each element of the iteration varies with function. keys only returns the key; values the value; kv returns both as a 2 element list in (key, value) order, pairs a Pair(key, value).
keys
Pair(key, value)
Note that kv %hash returns the same as zip(keys %hash; values %hash)
kv %hash
zip(keys %hash; values %hash)
The lvalue form of keys is not longer supported. Use the .buckets property instead.
.buckets
General notes about strings:
A Str can exist at several Unicode levels at once. Which level you interact with typically depends on what your current lexical context has declared the "working unicode level to be". Default is LChars.
Attempting to use a string at a level higher it can support is handled without warning. The highest supported level is simply mapped char for char to the desired level. However, attempting to stuff something into the string at a higher level that doesn't map to the lower level is an error (for example, attempting to store Kanji in a Byte uplifted to an LChar).
Attempting to use a string at a level lower than what it supports is not allowed.
If a function takes a Str and returns a Str, the returned Str will support the same levels as the input, unless specified otherwise.
multi sub Str::chop ( Str $string is rw ) returns Char multi sub Str::chop (: Str *@strings = ($CALLER::_) is rw ) returns Char
Trims the last character from $string, and returns it. Called with a list, it chops each item in turn, and returns the last character chopped.
$string
multi sub Str::chomp ( Str $string is rw ) returns Int multi sub Str::chomp (: Str *@strings = ($CALLER::_) is rw ) returns Int
Related to chop, only removes trailing chars that match /\n/. In either case, it returns the number of chars removed.
chop
/\n/
Note: Most users should consider setting their I/O handles to autochomp instead of this step.
multi sub Str::lc ( Str $string ) returns Str multi sub Str::lc (: Str $string = $CALLER::_ ) returns Str
Returns the input string after converting each character to it's lowercase form, if uppercase.
multi sub Str::lcfirst ( Str $string ) returns Str multi sub Str::lcfirst (: Str $string = $CALLER::_ ) returns Str
Like lc, but only affects the first character.
lc
multi sub Str::uc ( Str $string ) returns Str multi sub Str::uc (: Str $string = $CALLER::_ ) returns Str
Returns the input string after converting each character to it's uppercase form, if lowercase. This is not a Unicode "titlecase" operation, but a full "uppercase".
multi sub Str::ucfirst ( Str $string ) returns Str multi sub Str::ucfirst (: Str $string = $CALLER::_ ) returns Str
Performs a Unicode "titlecase" operation on the first character of the string.
multi sub Str::capitalize ( Str $string ) returns Str multi sub Str::capitalize (: Str $string = $CALLER::_ ) returns Str
Has the effect of first doing an lc on the entire string, then performing a s:g/(\w+)/{ucfirst $1}/ on it.
s:g/(\w+)/{ucfirst $1}/
multi sub Str::split ( Str $delimiter , Str $input = $CALLER::_, Int $limit = inf ) returns List multi sub Str::split ( Rule $delimiter , Str $input = $CALLER::_, Int $limit = inf ) returns List multi sub Str::split ( Str $input : Str $delimiter , Int $limit = inf ) returns List multi sub Str::split ( Str $input : Rule $delimiter , Int $limit = inf ) returns List &split<> := &split<Str>.assuming:delimiter(' ');
multi sub substr(Str $s, StrPos $start : StrPos $end, $replace) multi sub substr(Str $s, StrPos $start, StrLen $length : $replace) multi sub substr(Str $s, StrLen $offset : StrLen $length, $replace)
multi sub Control::Basic::eval (: Str $code = $CALLER::_, Str :$lang = 'Perl6')
Execute $code as if it were code written in $lang. Perl6 is the only required language, but supporting Perl5 is strongly recommended.
$code
$lang
Perl6
Perl5
Returns whatever $code returns, or undef on error.
multi sub Control::Basic::evalfile (Str $filename : Str :$lang = 'Perl6')
Behaves like, and replaces Perl 5 do EXPR, with optional $lang support.
do EXPR
multi sub Control::Basic::exit (: Int $status = 0)
Stops all program execution, and returns $status to the calling environment.
$status
multi sub Control::Basic::nothing ()
No operation. Literally does nothing.
multi sub Control::Basic::sleep (: Num $for = Inf ) returns Num
Attempt to sleep for up to $for seconds. Implementations are only obligated to support integral seconds, but higher resolutions are preferred.
$for
TODO: Research the exception handling system.
sub
Question: I think these should be strictly Code Point level activitities, but I'm not sure. They likely need to be renamed, as well.
multi sub Conversions::List:list (: *@list) returns List
Forces List Context on it's arguements, and returns them.
multi sub Conversions::Item:item ($item) returns Item
Forces generic Item context on it's argument, and returns it.
multi sub prefix::<0x> (: Str $hexstr = $CALLER::_) returns Num multi sub prefix::<0o> (: Str $octstr = $CALLER::_) returns Num multi sub prefix::<0b> (: Str $binstr = $CALLER::_) returns Num multi sub prefix::<0d> (: Str $binstr = $CALLER::_) returns Num
Interprets string as a number, with a default hexadecimal/octal/binary/decimal radix. Any radix mentioned inside the string will be override this operator. Returns undef on failure.
undef
Replaces Perl 5 hex and oct.
hex
oct
use DB_File;
With Parrot?
See Hash::kv or Hash::pairs instead.
Hash::kv
Hash::pairs
See Exgesis 7.
use IPC::SysV;
Can be done with $var.meta.name, but you're likely better off performing an isa, or just $var ~~ TYPE.
$var.meta.name
isa
$var ~~ TYPE
Was there a good use for this?
&func.meta.signature;
The following functions are pending a future Apocalypse/Synopsis/p6l Discussion before progress can be made:
tie tied untie
-X accept alarm bind binmode chown close closedir connect eof fcntl fileno flock getc getpeername /[get|set][host|net|proto|serv|sock].*/ glob ioctl link listen lstat mkdir open opendir pipe print printf read readdir readline readlink readpipe recv rename rewinddir rmdir seek seekdir select(both) send setsockopt shutdown slurp socket socketpair stat symlink syscall sysopen sysread sysseek syswrite tell telldir truncate umask unlink utime warn
chroot crypt exec getlogin /[get|set][pw|gr].*/ kill setpgrp setpriority system times
fork lock wait waitpid
Is your favorite function, which you spent weeks successfully arguing on perl6-language to get accepted, nowhere on this document? Have no fear. Email rod@rodadams.net with a brief description and a link to the thread on http://www.nntp.perl.org/group/perl.perl6.language, and it'll get listed.
Post errors to perl6-language.
To install Perl6::Bible, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Perl6::Bible
CPAN shell
perl -MCPAN -e shell install Perl6::Bible
For more information on module installation, please visit the detailed CPAN module installation guide.