routines Reference
Routines not defined within any class or role.
What it is #
Routines #
Signatures are reproduced from the documentation, including their declared return types. A routine listed here is part of the type's published interface; whether Raku++ implements it is a separate question, answered by the examples below.
routine EVAL #
sub infix:<mean>(*@a) is assoc<list> {
This routine executes at runtime a fragment of code, $code, of a given language, $lang, which defaults to Raku. It coerces Cool $code to Str. If $code is a Blob, it'll be processed using the same encoding as the $lang compiler would: for Raku $lang, uses utf-8; for Perl5, processes using the same rules as Perl. This works as-is with a literal string parameter. More complex input,
sub EVALFILE #
sub EVALFILE($filename where Blob|Cool, :$lang = 'Raku', :$check)
Slurps the specified file and evaluates it. Behaves the same way as EVAL with regard to Blob decoding, scoping, the $lang parameter and the $check parameter. Evaluates to the value produced by the final statement in the file when $check is not True.
sub repl #
sub repl()
Note: repl was introduced in release 2021.06 of the Rakudo compiler. Pauses execution and enters a REPL (read-eval-print loop) in the current context. This REPL is exactly like the one created when you run raku without any arguments except that you can access/modify the program's current context (such as lexical variables). For example, if you run this code:
sub get #
multi get (IO::Handle:D $fh = $*ARGFILES) { $fh.get }
This routine is a wrapper for the method of the same name in IO::Handle. If no Handle is specified, defaults to $*ARGFILES.
sub getc #
multi getc (IO::Handle:D $fh = $*ARGFILES) { $fh.getc }
This routine is a wrapper for the method of the same name in IO::Handle>. If no Handle is specified, defaults to $*ARGFILES.
sub mkdir #
sub mkdir(IO() $path, Int() $mode = 0o777 --> IO::Path:D)
Returns IO::Path:D.
Creates a new directory; see mode for explanation and valid values for $mode. Returns the IO::Path object pointing to the newly created directory on success; fails with X::IO::Mkdir if directory cannot be created. Also creates parent directories, as needed (similar to *nix utility mkdir with -p option); that is, mkdir "foo/bar/ber/meow" will
sub chdir #
sub chdir(IO() $path, :$d = True, :$r, :$w, :$x --> IO::Path:D)
Returns IO::Path:D.
Changes value of $*CWD variable to the provided $path, optionally ensuring the new path passes several file tests. NOTE: that this routine does NOT alter the process's current directory (see &*chdir). Returns IO::Path representing new $*CWD on success. On failure, returns Failure and leaves $*CWD untouched. The $path can be any object with an IO method that returns an
sub &*chdir #
Changes value of $*CWD variable to the provided $path and sets the process's current directory to the value of $path.absolute. NOTE: that in most cases, you want to use chdir routine instead. Returns an IO::Path representing the new $*CWD on success. On failure, returns Failure and leaves $*CWD untouched.
sub chmod #
sub chmod(Int() $mode, *@filenames --> List)
Returns List.
Coerces all @filenames to IO::Path and calls IO::Path.chmod with $mode on them. Returns a List containing a subset of @filenames for which chmod was successfully executed.
sub indir #
sub indir(IO() $path, &code, :$d = True, :$r, :$w, :$x)
Takes Callable &code and executes it after locally (to &code) changing $*CWD variable to an IO::Path object based on $path, optionally ensuring the new path passes several file tests. If $path is relative, it will be turned into an absolute path, even if an IO::Path object was given. NOTE: that this routine does NOT alter the process's
sub print #
multi print(**@args --> True)
multi print(Junction:D --> True)
Returns True.
Prints the given text on standard output (the $*OUT filehandle), coercing non-Str objects to Str by calling .Str method. Junction arguments autothread and the order of printed strings is not guaranteed. To print text and include the trailing newline, use
sub put #
multi put()
multi put(**@args --> True)
multi put(Junction:D --> True)
multi put(Str:D \x)
multi put(\x)
Returns True.
Same as print, except it uses print-nl (which prints a newline, by default) at the end. Junction arguments autothread and the order of printed strings is not guaranteed. By itself, put() will print a new line but please note that we have used parentheses after put. Without these
sub say #
multi say(**@args --> True)
Returns True.
Prints the "gist" of given objects; it will always invoke .gist in the case the object is a subclass of Str. Same as put, except it uses .gist method to obtain string representation of the object; as in the case of put, it will also autothread for Junctions. NOTE: the .gist method of some objects, such as
routine note #
method note(Mu: -->Bool:D)
multi note( --> Bool:D)
multi note(Str:D $note --> Bool:D)
multi note(**@args --> Bool:D)
Returns Bool:D.
Like say (in the sense it will invoke the .gist method of the printed object), except it prints output to $*ERR handle (STDERR). If no arguments are given to subroutine forms, will use string "Noted". This command will also autothread on Junctions, and is guaranteed to call gist on the object if it's a subclass of Str.
sub prompt #
multi prompt()
multi prompt($msg)
Prints $msg to $*OUT handle if $msg was provided, then gets a line of input from $*IN handle. By default, this is equivalent to printing $msg to STDOUT, reading a line from STDIN, removing the trailing new line, and returning the resultant string. As of Rakudo
sub open #
multi open(IO() $path, |args --> IO::Handle:D)
Returns IO::Handle:D.
Creates a handle with the given $path, and calls IO::Handle.open, passing any of the remaining arguments to it. Note that IO::Path type provides numerous methods for reading and writing from files, so in many common cases you do not need to open files or deal with IO::Handle type directly.
sub slurp #
multi slurp(IO::Handle:D $fh = $*ARGFILES, |c)
multi slurp(IO() $path, |c)
Slurps the contents of the entire file into a Str (or Buf if :bin). Accepts :bin and :enc optional named parameters, with the same meaning as open(); possible encodings are the same as in all the other IO methods and are listed in encoding routine. The routine will fail if the file does not exist, or is a directory. Without any
sub spurt #
multi spurt(IO() $path, |c)
The $path can be any object with an IO method that returns an IO::Path object. Calls IO::Path.spurt on the $path, forwarding any of the remaining arguments. The encoding with which the contents will be written. Boolean indicating whether to append to a (potentially) existing file. If the file did not exist yet, it will be created. Defaults to False.
sub run #
sub run(
Runs an external command without involving a shell and returns a Proc object. By default, the external command will print to standard output and error, and read from standard input. If you want to pass some variables you can still use < >, but try to avoid using « » as it will do word splitting if you forget to quote variables: Note that -- is required for many programs to disambiguate between
sub shell #
Runs a command through the system shell, which defaults to C<%*ENV<ComSpec> /c> in Windows, /bin/sh -c otherwise. All shell metacharacters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. Shell escapes are a severe security concern and can cause confusion with unusual file names. Use run if you want to be safe. The return value is of type Proc.
routine unpolar #
method unpolar(Real $angle)
multi unpolar(Real $mag, Real $angle)
Returns a Complex with the coordinates corresponding to the angle in radians and magnitude corresponding to the object value or $mag in the case it's being used as a sub
routine printf #
multi printf(Cool:D $format, *@args)
Produces output according to a format. The format used is the invocant (if called in method form) or the first argument (if called as a routine). The rest of the arguments will be substituted in the format following the format conventions. See sprintf for details on acceptable format directives. On Junctions, it will also autothread, without a guaranteed order.
routine sprintf #
multi sprintf(Cool:D $format, *@args)
Returns a string according to a format as described below. The format used is the invocant (if called in method form) or the first argument (if called as a routine). This function is mostly identical to the C library's sprintf and printf functions. The only difference between the two functions is that sprintf returns a string while the printf function writes to a filehandle. sprintf
sub flat #
multi flat(**@list)
multi flat(Iterable \a)
Constructs a list which contains any arguments provided, and returns the result of calling the .flat method (inherited from Any) on that list or Iterable:
routine unique #
multi unique(+values, |c)
Returns a sequence of unique values from the invocant/argument list, such that only the first occurrence of each duplicated value remains in the result list. unique uses the semantics of the === operator to decide whether two objects are the same, unless the optional :with parameter is specified with another comparator. The order of the original list is preserved even as duplicates are removed.
routine repeated #
multi repeated(+values, |c)
This returns a sequence of repeated values from the invocant/argument list. It takes the same parameters as unique, but instead of passing through any elements when they're first seen, they're only passed through as soon as they're seen for the second time (or more). Examples: As in the case of unique the associative argument :as takes a Callable that normalizes the element before comparison, and
routine squish #
sub squish( +values, |c)
Returns a sequence of values from the invocant/argument list where runs of one or more values are replaced with only the first instance. Like unique, squish uses the semantics of the === operator to decide whether two objects are the same. Unlike unique, this function only removes adjacent duplicates; identical values further apart are still kept. The order of the
sub sleep #
sub sleep($seconds = Inf --> Nil)
Returns Nil.
Attempt to sleep for the given number of $seconds. Returns Nil on completion. Accepts Int, Num, Rat, or Duration types as an argument since all of these also do Real. It is thus possible to sleep for a non-integer amount of time. For instance, the following code shows that sleep (5/2) sleeps for 2.5
sub sleep-timer #
sub sleep-timer(Real() $seconds = Inf --> Duration:D)
Returns Duration:D.
This function is implemented like sleep, but unlike the former it does return a Duration instance with the number of seconds the system did not sleep. In particular, the returned Duration will handle the number of seconds remaining when the process has been awakened by some external event (e.g., Virtual Machine or Operating System events). Under normal condition, when sleep is not interrupted, the returned Duration
sub sleep-until #
sub sleep-until(Instant $until --> Bool)
Returns Bool.
Works similar to sleep but checks the current time and keeps sleeping until the required instant in the future has been reached. It uses internally the sleep-timer method in a loop to ensure that, if accidentally woken up early, it will wait again for the specified amount of time remaining to reach the specified instant. goes back to sleep Returns True if the Instant in the future has been achieved (either
sub emit #
sub emit(\value --> Nil)
Returns Nil.
If used outside any supply or react block, throws an exception emit without supply or react. Within a Supply block, it will add a message to the stream. emit is implemented as a control exception and can therefore be used by something called from the supply block that it refers to. See also the page for emit methods.
sub undefine #
multi undefine(Mu \x)
multi undefine(Array \x)
multi undefine(Hash \x)
DEPRECATED in 6.d language version and will be removed in 6.e. For Array and Hash, it will become equivalent to assigning Empty; for everything else, equivalent to assigning Nil or Empty in the case of arrays or hashes, whose use is advised. Routines that manipulate arrays and other mutable collections.
sub pop #
multi pop(@a) is raw
Calls method pop on the Positional argument. That method is supposed to remove and return the last element, or return a Failure wrapping an X::Cannot::Empty if the collection is empty. See the documentation of the Array method for an example.
sub shift #
multi shift(@a) is raw
Calls method shift on the Positional argument. That method, on a mutable collection that actually implements it (such as an Array or a Buf), is supposed to remove and return the first element, or return a Failure if the collection is empty. Example:
sub push #
multi push(\a, **@b is raw)
multi push(\a, \b)
Calls method push on the first argument, passing the remaining arguments. Method push is supposed to add the provided values to the end of the collection or parts thereof. See the documentation of the Hash method for an example where indirection via this subroutine can be helpful. The push method is supposed to flatten all arguments of type Slip.
sub append #
multi append(\a, **@b is raw)
multi append(\a, \b)
Calls method append on the first argument, passing the remaining arguments. Method append is supposed to add the provided values to the end of the collection or parts thereof. Unlike method push, method append should follow the single argument rule. So if you want to implement a conforming method append for a new collection type, it should behave as if its signature was just:
sub exit #
multi exit()
multi exit(Int(Any) $status)
Exits the current process with return code $status or zero if no value has been specified. The exit value ($status), when different from zero, has to be opportunely evaluated from the process that catches it (e.g., a shell); it is the only way to return an exit code different from zero from a Main. exit prevents the LEAVE phaser to be executed, but it will run the code in the
sub done #
sub done(--> Nil)
Returns Nil.
If used outside any supply or react block, throws an exception done without supply or react. Within a Supply block, it will signal that the supply will not emit further values, and leaves the supply block. See also documentation on method done. done is implemented as a control exception and can therefore be used by something called from the supply or react block
sub lastcall #
sub lastcall(--> True)
Returns True.
Truncates the current dispatch chain, which means any calls to nextsame, callsame, nextwith, and callwith will not find any of the next candidates. Note that since samewith restarts the dispatch from the start, it's not affected by the truncation of current chain with lastcall. Consider example below. foo(6) uses nextsame when lastcall hasn't been called, and so it reaches the Any
Examples, run three ways #
Every example below comes from the official documentation, together with the output that documentation asserts. Each was then executed by Rakudo and by Raku++ when this page was built. Where the three agree, one result is shown; where they do not, all three are — because which of them is wrong is exactly the information worth having.
8 all-differ · 7 doc-drift · 46 no-output · 7 not-runnable · 24 ok · 2 rakudo-differs · 3 rakupp-differs · 1 unrun
proto EVAL($code where Blob|Cool|Callable, Str() :$lang = 'Raku',
PseudoStash :$context, Str() :$filename, Bool() :$check, *%_)Not executed: the documentation states no expected output for this example.
multi EVAL($code, Str :$lang where { ($lang // '') eq 'Perl5' },
PseudoStash :$context, Str() :$filename, :$check)Not executed: the documentation states no expected output for this example.
use MONKEY-SEE-NO-EVAL; # Or... use MONKEY; # shortcut that turns on all MONKEY pragmas, or... use Test; # a module that activates MONKEY-SEE-NO-EVAL.
Not executed: the documentation states no expected output for this example.
my $init = 0; my $diff = 10; my Str $changer = '$init += ' ~ $diff; # contains a Str object with value '$init += 10' # any of the above allows: EVAL $changer; EVAL $changer; say $init; # OUTPUT: «20»
20
20
Raku++ matches the documentation; Rakudo does not. This is the one class where neither engine can be assumed right: it may be a stale doc that Raku++ was built from, or it may be a Rakudo bug that the documentation predates. Each case is examined individually.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
my $answer = 42; EVAL 'say $answer;'; # OUTPUT: «42»
42
Documentation, Rakudo and Raku++ all agree.
EVAL 'my $lives = 9'; say $lives; # error, $lives not declared
Not executed: the documentation states no expected output for this example.
module M {
EVAL 'our $answer = 42'
}
say $M::answer; # OUTPUT: «42»42
Documentation, Rakudo and Raku++ all agree.
@a.sum / @a.elems } EVAL 'say 2 mean 6 mean 4'; # OUTPUT: «4»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
sub infix:<mean>(*@a) is assoc<list> {
@a.sum / @a.elems
}
say EVAL 'say 1; 2 mean 6 mean 4'; # OUTPUT: «14»1
4
Documentation, Rakudo and Raku++ all agree.
EVAL "use v5.20; say 'Hello from perl!'", :lang<Perl5>;
Not executed: the documentation states no expected output for this example.
use MONKEY-SEE-NO-EVAL; EVAL 'say $?FILE'; # OUTPUT: «/tmp/EVAL_0» EVAL 'say $?FILE', filename => '/my-eval-code'; # OUTPUT: «/my-eval-code»
/tmp/EVAL_0
/my-eval-code
/private/tmp/typerun-sandbox/EVAL_0
/my-eval-code
/private/tmp/typerun-sandbox/-e
/private/tmp/typerun-sandbox/-e
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
EVALFILE "foo.raku";
Not executed: the documentation states no expected output for this example.
my $name = "Alice"; say "Hello, $name"; repl(); say "Goodbye, $name"
Not executed: the documentation states no expected output for this example.
=begin code :lang<shell> Type 'exit' to leave [0] > $name Alice [1] > $name = "Bob" Bob [2] > exit =end code
Not executed: the documentation states no expected output for this example.
chdir '/tmp'; # change $*CWD to '/tmp' and check its .d is True chdir :r, :w, '/tmp'; # … check its .r and .w are True chdir '/not-there'; # returns Failure
Not executed: the documentation states no expected output for this example.
# WRONG! DO NOT DO THIS! my $*CWD = chdir '/tmp/';
Not executed: the documentation states no expected output for this example.
PROCESS::<&chdir> = sub (IO() $path --> IO::Path:D) { }Not executed: the documentation states no expected output for this example.
&*chdir('/tmp'); # change $*CWD and process's current directory to '/tmp'
&*chdir('/not-there'); # returns FailureNot executed: the documentation states no expected output for this example.
# WRONG! DO NOT DO THIS!
my $*CWD = &*chdir('/tmp');Not executed: the documentation states no expected output for this example.
temp $*CWD;
&*chdir('/tmp');Not executed: the documentation states no expected output for this example.
chmod 0o755, <myfile1 myfile2>; # make two files executable by the owner
Not executed: the documentation states no expected output for this example.
say indir("/tmp", {
gather { take ".".IO }
})».CWD; # OUTPUT: «(/home/camelia)»(/home/camelia)
(/private/tmp/typerun-sandbox)
(/private/tmp/typerun-sandbox)
Both engines agree; the documentation states something else. Trust the engines.
say indir("/tmp", {
eager gather { take ".".IO }
})».CWD; # OUTPUT: «(/tmp)»(/tmp)
(/tmp)
(/private/tmp/typerun-sandbox)
Raku++ disagrees with both the documentation and Rakudo — a defect.
say indir("/tmp", {
my $cwd = $*CWD;
gather { temp $*CWD = $cwd; take ".".IO }
})».CWD; # OUTPUT: «(/tmp)»(/tmp)
(/tmp)
(/private/tmp/typerun-sandbox)
Raku++ disagrees with both the documentation and Rakudo — a defect.
say $*CWD; # OUTPUT: «"/home/camelia".IO»
indir '/tmp', { say $*CWD }; # OUTPUT: «"/tmp".IO»
say $*CWD; # OUTPUT: «"/home/camelia".IO»"/home/camelia".IO
"/tmp".IO
"/home/camelia".IO
"/private/tmp/typerun-sandbox".IO
"/tmp".IO
"/private/tmp/typerun-sandbox".IO
"/private/tmp/typerun-sandbox".IO
"/private/tmp".IO
"/private/tmp/typerun-sandbox".IO
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
indir '/not-there', {;}; # returns Failure; path does not existNot executed: the documentation states no expected output for this example.
print "Hi there!\n"; # OUTPUT: «Hi there!» print "Hi there!"; # OUTPUT: «Hi there!» print [1, 2, 3]; # OUTPUT: «1 2 3» print "Hello" | "Goodbye"; # OUTPUT: «HelloGoodbye»
Hi there!
Hi there!1 2 3HelloGoodbyeDocumentation, Rakudo and Raku++ all agree.
put "Hi there!\n"; # OUTPUT: «Hi there!» put "Hi there!"; # OUTPUT: «Hi there!» put [1, 2, 3]; # OUTPUT: «1 2 3» put "Hello" | "Goodbye"; # OUTPUT: «HelloGoodbye»
Hi there!
Hi there!
1 2 3
Hello
Goodbye
Documentation, Rakudo and Raku++ all agree.
put "Hey"; put(); put("Hey"); # OUTPUT: «HeyHey»Hey
Hey
Documentation, Rakudo and Raku++ all agree.
.put for <1 2 3>; # OUTPUT: «123»
1
2
3
Documentation, Rakudo and Raku++ all agree.
say Range; # OUTPUT: «(Range)»
say class Foo {}; # OUTPUT: «(Foo)»
say 'I ♥ Raku'; # OUTPUT: «I ♥ Raku»
say 1..Inf; # OUTPUT: «1..Inf»(Range)
(Foo)
I ♥ Raku
1..Inf
Documentation, Rakudo and Raku++ all agree.
note; # STDERR OUTPUT: «Noted» note 'foo'; # STDERR OUTPUT: «foo» note 1..*; # STDERR OUTPUT: «1..Inf»
Not executed: the documentation states no expected output for this example.
my $name = prompt "What's your name? ";
say "Hi, $name! Nice to meet you!";
my $age = prompt("Say your age (number)");
my Int $years = $age;
my Str $age-badge = $age;Not executed: the documentation states no expected output for this example.
my $fh = open :w, '/tmp/some-file.txt'; $fh.say: 'I ♥ writing Raku code'; $fh.close; $fh = open '/tmp/some-file.txt'; print $fh.readchars: 4; $fh.seek: 7, SeekFromCurrent; say $fh.readchars: 4; $fh.close; # OUTPUT: «I ♥ Raku»
I ♥ Raku
I ♥ Raku
I ♥ Raku++ disagrees with both the documentation and Rakudo — a defect.
# read entire file as (Unicode) Str my $text_contents = slurp "path/to/file"; # read entire file as Latin1 Str my $text_contents = slurp "path/to/file", enc => "latin1"; # read entire file as Buf my $binary_contents = slurp "path/to/file", :bin;
Not executed: the documentation states no expected output for this example.
# write directly to a file spurt 'path/to/file', 'default text, directly written'; # write directly with a non-Unicode encoding spurt 'path/to/latin1_file', 'latin1 text: äöüß', :enc<latin1>; spurt 'file-that-already-exists', 'some text'; # overwrite file's contents: spurt 'file-that-already-exists', ' new text', :append; # append to file's contents: say slurp 'file-that-already-exists'; # OUTPUT: «some text new text» # fail when writing to a pre-existing file spurt 'file-that-already-exists', 'new text', :createonly; # OUTPUT: «Failed to open file /home/camelia/file-that-already-exists: file already exists …»
some text new text
Failed to open file /home/camelia/file-that-already-exists: file already exists …some text new text
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
multi spurt(IO() $path)
Not executed: the documentation states no expected output for this example.
# create an empty file / truncate a file spurt 'path/to/file';
Not executed: the documentation states no expected output for this example.
*@args ($, *@), :$in = '-', :$out = '-', :$err = '-', Bool :$bin = False, Bool :$chomp = True, Bool :$merge = False, Str:D :$enc = 'UTF-8', Str:D :$nl = "\n", :$cwd = $*CWD, Hash() :$env = %*ENV, :$arg0, :$win-verbatim-args = False --> Proc:D)
Not executed: the documentation states no expected output for this example.
run 'touch', '--', '*.txt'; # Create a file named “*.txt”
Not executed: the documentation states no expected output for this example.
run <rm -- *.txt>; # Another way to use run, using word quoting for the
# argumentsNot executed: the documentation states no expected output for this example.
my $file = ‘--my arbitrary filename’; run ‘touch’, ‘--’, $file; # RIGHT run <touch -->, $file; # RIGHT run «touch -- "$file"»; # RIGHT but WRONG if you forget quotes run «touch -- $file»; # WRONG; touches ‘--my’, ‘arbitrary’ and ‘filename’ run ‘touch’, $file; # WRONG; error from `touch` run «touch "$file"»; # WRONG; error from `touch`
Not executed: the documentation states no expected output for this example.
run 'false'; # SUNK! Will throw an Exception
run('false').so; # OK. Evaluates Proc in Bool context; no sinking. Ignore returned Proc
my $a = run('false'); # Can call methods on the Proc in $a.Not executed: the documentation states no expected output for this example.
my $proc = run 'echo', 'Raku is Great!', :out, :err; $proc.out.slurp(:close).say; # OUTPUT: «Raku is Great!» $proc.err.slurp(:close).say; # OUTPUT: «»
Raku is Great!
Documentation, Rakudo and Raku++ all agree.
my $ls-alt-handle = open :w, '/tmp/cur-dir-ls-alt.txt'; my $proc = run "ls", "-alt", :out($ls-alt-handle); # (The file will contain the output of the ls -alt command)
Not executed: the documentation states no expected output for this example.
multi shell($cmd, :$in = '-', :$out = '-', :$err = '-',
Bool :$bin, Bool :$chomp = True, Bool :$merge,
Str :$enc, Str:D :$nl = "\n", :$cwd = $*CWD, :$env)Not executed: the documentation states no expected output for this example.
shell 'ls -lR | gzip -9 > ls-lR.gz';
Not executed: the documentation states no expected output for this example.
say 1.unpolar(⅓*pi); # OUTPUT: «0.5000000000000001+0.8660254037844386i»
0.5000000000000001+0.8660254037844386i
Documentation, Rakudo and Raku++ all agree.
"%s is %s".printf("þor", "mighty"); # OUTPUT: «þor is mighty»
printf( "%s is %s", "þor", "mighty"); # OUTPUT: «þor is mighty»þor is mightyþor is mightyDocumentation, Rakudo and Raku++ all agree.
printf( "%.2f ", ⅓ | ¼ | ¾ ); # OUTPUT: «0.33 0.25 0.75 »
0.33 0.25 0.75 Documentation, Rakudo and Raku++ all agree.
sprintf( "%s the %d%s", "þor", 1, "st").put; # OUTPUT: «þor the 1st» sprintf( "%s is %s", "þor", "mighty").put; # OUTPUT: «þor is mighty» "%s's weight is %.2f %s".sprintf( "Mjölnir", 3.3392, "kg").put; # OUTPUT: «Mjölnir's weight is 3.34 kg» # OUTPUT: «Mjölnir's weight is 3.34 kg»
þor the 1st
þor is mighty
Mjölnir's weight is 3.34 kg
Mjölnir's weight is 3.34 kg
þor the 1st
þor is mighty
Mjölnir's weight is 3.34 kg
þor the 1st
þor is mighty
Mjölnir's weight is 3.34 kg
Both engines agree; the documentation states something else. Trust the engines.
my $prod = "Ab-%x-42";
my $cost = "30";
sprintf("Product $prod; cost: \$%d", $cost).put;
# OUTPUT: «Your printf-style directives specify 2 arguments, but 1 argument was supplied»
« in block <unit> at <unknown file> line 1»Your printf-style directives specify 2 arguments, but 1 argument was supplied
Product Ab-1e-42; cost: $0
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
sprintf("2 x \$20 = \$%d", 2*20).put; # OUTPUT: «2 x $20 = $40»
sprintf('2 x $20 = $%d', 2*20).put; # OUTPUT: «2 x $20 = $40»2 x $20 = $40
2 x $20 = $40
Documentation, Rakudo and Raku++ all agree.
| h | interpret integer as native "short" (typically int16)
Not executed: the documentation states no expected output for this example.
sprintf '%d %d', 12, 34; # OUTPUT: «12 34» sprintf '%d %d %d', 1, 2, 3; # OUTPUT: «1 2 3»
12 34
1 2 3
Both engines agree; the documentation states something else. Trust the engines.
sprintf '%2$d %1$d', 12, 34; # OUTPUT: «34 12»
34 12
Both engines agree; the documentation states something else. Trust the engines.
sprintf '%3$d %d %1$d', 1, 2, 3; # OUTPUT: «3 1 1»
3 1 1
Both engines agree; the documentation states something else. Trust the engines.
| prefix non-zero hexadecimal with "0x" or "0X",
| prefix non-zero binary with "0b" or "0B"Not executed: the documentation states no expected output for this example.
# results in no output!
Not executed: the documentation states no expected output for this example.
NYI sprintf "%vd", "AB\x[100]"; # OUTPUT: «65.66.256»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
NYI sprintf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses
@addr[1..3], ":";Not executed: the documentation states no expected output for this example.
sprintf "<%s>", "a"; # OUTPUT: «<a>» sprintf "<%6s>", "a"; # OUTPUT: «< a>» sprintf "<%*s>", 6, "a"; # OUTPUT: «< a>» NYI sprintf '<%*2$s>', "a", 6; # OUTPUT: «< a>» sprintf "<%2s>", "long"; # OUTPUT: «<long>» (does not truncate)
NYI sprintf '<%*1$.*s>', $a, $b;
Not executed: the documentation states no expected output for this example.
sprintf "%2\$d %d\n", 12, 34; # OUTPUT: «34 12» sprintf "%2\$d %d %d\n", 12, 34; # OUTPUT: «34 12 34» sprintf "%3\$d %d %d\n", 12, 34, 56; # OUTPUT: «56 12 34» NYI sprintf "%2\$*3\$d %d\n", 12, 34, 3; # OUTPUT: « 34 12» NYI sprintf "%*1\$.*f\n", 4, 5, 10; # OUTPUT: «5.0000»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
NYI sprintf "%ld a big number", 4294967295;
NYI sprintf "%%lld a bigger number", 4294967296;
sprintf('%c', 97); # OUTPUT: «a»
sprintf("%.2f", 1.969); # OUTPUT: «1.97»
sprintf("%+.3f", 3.141592); # OUTPUT: «+3.142»
sprintf('%2$d %1$d', 12, 34); # OUTPUT: «34 12»
sprintf("%x", 255); # OUTPUT: «ff»Neither engine can run this in isolation — the example depends on context from the surrounding text.
sprintf Q:b "<b>%s</b>\n", "Raku"; # OUTPUT: «<b>Raku</b>» sprintf "<b>\%s</b>\n", "Raku"; # OUTPUT: «<b>Raku</b>» sprintf "<b>%s\</b>\n", "Raku"; # OUTPUT: «<b>Raku</b>»
<b>Raku</b>
<b>Raku</b>
<b>Raku</b>
Both engines agree; the documentation states something else. Trust the engines.
say flat 1, (2, (3, 4), $(5, 6)); # OUTPUT: «(1 2 3 4 (5 6))»
(1 2 3 4 (5 6))
Documentation, Rakudo and Raku++ all agree.
say <a a b b b c c>.unique; # OUTPUT: «(a b c)» say <a b b c c b a>.unique; # OUTPUT: «(a b c)»
(a b c)
(a b c)
Documentation, Rakudo and Raku++ all agree.
say <a A B b c b C>.unique(:as(&lc)) # OUTPUT: «(a B c)»
(a B c)
Documentation, Rakudo and Raku++ all agree.
my @list = %(a => 42), %(b => 13), %(a => 42);
say @list.unique(:with(&[eqv])) # OUTPUT: «({a => 42} {b => 13})»({a => 42} {b => 13})
Documentation, Rakudo and Raku++ all agree.
say <a a b b b c c>.repeated; # OUTPUT: «(a b b c)» say <a b b c c b a>.repeated; # OUTPUT: «(b c b a)» say <a A B b c b C>.repeated(:as(&lc)); # OUTPUT: «(A b b C)»
(a b b c)
(b c b a)
(A b b C)
Documentation, Rakudo and Raku++ all agree.
my @list = %(a => 42), %(b => 13), %(a => 42);
say @list.repeated(:with(&[eqv])) # OUTPUT: «({a => 42})»({a => 42})
Documentation, Rakudo and Raku++ all agree.
say <a a b b b c c>.squish; # OUTPUT: «(a b c)» say <a b b c c b a>.squish; # OUTPUT: «(a b c b a)»
(a b c)
(a b c b a)
Documentation, Rakudo and Raku++ all agree.
say [42, "42"].squish; # OUTPUT: «(42 42)» # Note that the second item in the result is still Str say [42, "42"].squish(with => &infix:<eq>); # OUTPUT: «(42)» # The resulting item is Int
(42 42)
(42)
Documentation, Rakudo and Raku++ all agree.
sleep 5; # Int sleep 5.2; # Num sleep (5/2); # Rat sleep (now - now + 5); # Duration
Not executed: the documentation states no expected output for this example.
my $before = now; sleep (5/2); my $after = now; say $after-$before; # OUTPUT: «2.502411561»
2.502411561
2.506085403
1.0051381587982178
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
$before = now; sleep 5.2; $after = now; say $after-$before; # OUTPUT: «5.20156987»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
say sleep-timer 3.14; # OUTPUT: «0»
0
Documentation, Rakudo and Raku++ all agree.
say sleep-timer -2; # OUTPUT: 0 say sleep-timer 0; # OUTPUT: 0
Not executed: the documentation states no expected output for this example.
say sleep-until now+10; # OUTPUT: «True»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
my $instant = now - 5; say sleep-until $instant; # OUTPUT: «False»
False
Documentation, Rakudo and Raku++ all agree.
my $instant = now + 30; # assuming the two commands are run within 30 seconds of one another... say sleep-until $instant; # OUTPUT: «True»
True
True
Raku++ matches the documentation; Rakudo does not. This is the one class where neither engine can be assumed right: it may be a stale doc that Raku++ was built from, or it may be a Rakudo bug that the documentation predates. Each case is examined individually.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
my $instant = DateTime.new( year => 2023, month => 9, day => 1, hour => 22, minute => 5); say sleep-until $instant.Instant; # OUTPUT: «True» (eventually...)
True
False
False
Both engines agree; the documentation states something else. Trust the engines.
# DateTime.new uses UTC by default, so get timezone from current time
my $timezone = DateTime.now.timezone;
my $instant = DateTime.new(
year => 2015,
month => 9,
day => 4,
hour => 7,
minute => 0,
timezone => $timezone
).Instant;
sleep-until $instant;
qqx{mplayer wake-me-up.mp3};Not executed: the documentation states no expected output for this example.
my $supply = supply {
for 1 .. 10 {
emit($_);
}
}
$supply.tap( -> $v { say "First : $v" });Not executed: the documentation states no expected output for this example.
say shift [1,2]; # OUTPUT: «1»
1
Documentation, Rakudo and Raku++ all agree.
my @a of Int = [1]; say shift @a; # OUTPUT: «1» say shift @a; # ERROR: «Cannot shift from an empty Array[Int]»
Neither engine can run this in isolation — the example depends on context from the surrounding text.
multi method push(::?CLASS:D: **@values is raw --> ::?CLASS:D)
Not executed: the documentation states no expected output for this example.
multi method push(::?CLASS:U: **@values is raw --> ::?CLASS:D)
Not executed: the documentation states no expected output for this example.
multi method append(::?CLASS:D: +values --> ::?CLASS:D)
Not executed: the documentation states no expected output for this example.
multi method append(::?CLASS:U: +values --> ::?CLASS:D)
Not executed: the documentation states no expected output for this example.
my %h = i => 0;
append %h, i => (1, 42);
CATCH { default { put .message } };
# OUTPUT: «Unexpected named argument 'i' passed»Unexpected named argument 'i' passed
Cannot resolve caller append(Hash:D, :i(List)); none of these signatures matches:
(\a, \b)
(\a, **@b is raw)
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
my $supply = supply {
for 1 .. 3 {
emit($_);
}
done;
say "never reached";
}
$supply.tap( -> $v { say "Second : $v" }, done => { say "No more" });
# OUTPUT: «Second : 1Second : 2Second : 3No More»Second : 1
Second : 2
Second : 3
No More
Second : 1
Second : 2
Second : 3
No more
Second : 1
Second : 2
Second : 3
No more
never reached
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
sub done($value --> Nil)
Not executed: the documentation states no expected output for this example.
my $supply = supply {
for 1 .. 3 {
emit($_);
}
done 42; # same as: emit 42; done
}
$supply.tap: -> $v { say "Val: $v" }, done => { say "No more" }
# OUTPUT: OUTPUT: «Val: 1Val: 2Val: 3Val: 42No More»Val: 1
Val: 2
Val: 3
Val: 42
No More
Val: 1
Val: 2
Val: 3
Val: 42
No more
Val: 1
Val: 2
Val: 3
No more
All three differ. Needs a human.
Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.
multi foo (Int $_) {
say "Int: $_";
lastcall when *.is-prime;
nextsame when * %% 2;
samewith 6 when * !%% 2;
}
multi foo (Any $x) { say "Any $x" }Not executed: the documentation states no expected output for this example.
foo 6; say '----'; foo 2; say '----'; foo 1;
Not executed: the documentation states no expected output for this example.
# OUTPUT: # Int: 6 # Any 6 # ---- # Int: 2 # ---- # Int: 1 # Int: 6 # Any 6
Not executed: the documentation states no expected output for this example.