class IO::Handle
Opened file or stream
Methods
method open
Defined as:
method open(IO::Handle::, :, :, :, Str :,Str :,:, :, :, :, :, :, :, :,:, :, :, :,:,--> IO::Handle)
Opens the handle in one of the modes. Fails with appropriate exception if the open fails.
See description of individual methods for the accepted values and behaviour of :$chomp
, :$nl-in
, :$nl-out
, and :$enc
. The values for parameters default to the invocant's attributes and if any of them are provided, the attributes will be updated to the new values. Specify :$bin
set to True
instead of :$enc
to indicate the handle should be opened in binary mode. Specifying undefined value as :$enc
is equivalent to not specifying :$enc
at all. Specifying both a defined encoding as :$enc
and :$bin
set to true will cause X::IO::BinaryAndEncoding
exception to be thrown.
The open mode defaults to non-exclusive, read only (same as specifying :r
) and can be controlled by a mix of the following arguments:
:r same as specifying :mode<ro> same as specifying nothing:w same as specifying :mode<wo>, :create, :truncate:a same as specifying :mode<wo>, :create, :append:x same as specifying :mode<wo>, :create, :exclusive:update same as specifying :mode<rw>:rw same as specifying :mode<rw>, :create:ra same as specifying :mode<rw>, :create, :append:rx same as specifying :mode<rw>, :create, :exclusive
Support for combinations of modes other than what is listed above is implementation-dependent and should be assumed unsupported. That is, specifying, for example, .open(:r :create)
or .open(:mode<wo> :append :truncate)
might work or might cause the Universe to implode, depending on a particular implementation. This applies to reads/writes to a handle opened in such unsupported modes as well.
The mode details are:
:mode<ro> means "read only":mode<wo> means "write only":mode<rw> means "read and write":create means the file will be created, if it does not exist:truncate means the file will be emptied, if it exists:exclusive means .open will fail if the file already exists:append means writes will be done at the end of file's current contents
Attempts to open a directory, write to a handle opened in read-only mode or read from a handle opened in write-only mode, or using text-reading methods on a handle opened in binary mode will fail or throw.
In 6.c language, it's possible to open path '-'
, which will cause open
to open (if closed
) the $*IN
handle if opening in read-only mode or to open the $*OUT
handle if opening in write-only mode. All other modes in this case will result in exception being thrown.
In 6.d language, path '-'
has no special meaning.
The :out-buffer
controls output buffering and by default behaves as if it were Nil
. See method out-buffer for details.
Note (Rakudo versions before 2017.09): File handles are NOT flushed or closed when they go out of scope. While they will get closed when garbage collected, garbage collection isn't guaranteed to get run. This means you should use an explicit close
on handles opened for writing, to avoid data loss, and an explicit close
is recommended on handles opened for reading as well, so that your program does not open too many files at the same time, triggering exceptions on further open
calls.
Note (Rakudo versions 2017.09 and after): Open file handles are automatically closed on program exit, but it is still highly recommended that you close
opened handles explicitly.
method comb
Defined as:
method comb(IO::Handle: Bool :, |args --> Seq)
Read the handle and processes its contents the same way Str.comb
does, taking the same arguments, closing the handle when done if $close
is set to a true value. Implementations may slurp the file in its entirety when this method is called.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = 'path/to/file'.IO.open;say "The file has ♥s in it";
method chomp
Defined as:
has is rw = True
One of the attributes that can be set via .new
or open. Defaults to True
. Takes a Bool specifying whether the line separators (as defined by .nl-in
) should be removed from content when using .get
or .lines
methods.
routine get
Defined as:
method get(IO::Handle: --> Str)multi sub get (IO::Handle = --> Str)
Reads a single line of input from the handle, removing the trailing newline characters (as set by .nl-in
) if the handle's .chomp
attribute is set to True
. Returns Nil
, if no more input is available. The subroutine form defaults to $*ARGFILES
if no handle is given.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
.get.say; # Read one line from the standard inputmy = open 'filename';.get.say; # Read one line from a file.close;say get; # Read one line from $*ARGFILES
routine getc
Defined as:
method getc(IO::Handle: --> Str)multi sub getc (IO::Handle = --> Str)
Reads a single character from the input stream. Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown. The subroutine form defaults to $*ARGFILES
if no handle is given. Returns Nil
, if no more input is available, otherwise operation will block, waiting for at least one character to be available; these caveats apply:
Buffering terminals
Using getc to get a single keypress from a terminal will only work properly if you've set the terminal to "unbuffered". Otherwise the terminal will wait for the return key to be struck or the buffer to be filled up before perl6 gets even a single byte of data.
Waiting for potential combiners
If your handle's encoding allows combining characters to be read, perl6 will wait for more data to be available before it provides a character. This means that inputting an "e" followed by a combining acute will give you an e with an acute rather than giving an "e" and letting the next reading function give you a dangling combiner. However, it also means that when the user inputs just an "e" and has no intention to also input a combining acute, your program will be waiting for another keypress before the initial "e" is returned.
submethod DESTROY
Defined as:
submethod DESTROY(IO::Handle:)
Closes the filehandle, unless its native-descriptor is 2
or lower. This ensures the standard file handles do not get inadvertently closed.
Note that garbage collection is not guaranteed to happen, so you must NOT rely on DESTROY
for closing the handles you write to and instead close them yourself. Programs that open a lot of files should close the handles explicitly as well, regardless of whether they were open for writing, since too many files might get opened before garbage collection happens and the no longer used handles get closed.
method gist
Defined as:
method gist(IO::Handle: --> Str)
Returns a string containing information which .path
, if any, the handle is created for and whether it is .opened
.
say IO::Handle.new; # IO::Handle<(Any)>(closed)say "foo".IO.open; # IO::Handle<"foo".IO>(opened)
method eof
Defined as:
method eof(IO::Handle: --> Bool)
Non-blocking. Returns True
if the read operations have exhausted the contents of the handle. For seekable handles, this means current position is at or beyond the end of file and seeking an exhausted handle back into the file's contents will result in eof returning False
again.
On non-seekable handles and handles opened to zero-size files (including special files in /proc/
), EOF won't be set until a read operation fails to read any bytes. For example, in this code, the first read
consumes all of the data, but it's only until the second read
that reads nothing would the EOF on a TTY handle be set:
$ echo "x" | perl6 -e 'with $*IN { .read: 10000; .eof.say; .read: 10; .eof.say }'FalseTrue
method encoding
Defined as:
multi method encoding(IO::Handle: --> Str)multi method encoding(IO::Handle: --> Str)
Returns a Str representing the encoding currently used by the handle, defaulting to "utf8"
. Nil
indicates the file handle is currently in binary mode. Specifying an optional positional $enc
argument switches the encoding used by the handle; specify Nil
as encoding to put the handle into binary mode.
The accepted values for encoding are case-insensitive. The available encodings vary by implementation and backend. On Rakudo MoarVM the following are supported:
utf8utf16utf8-c8iso-8859-1windows-1251windows-1252ascii
The default encoding is utf8, which undergoes normalization into Unicode NFC (normalization form canonical). In some cases you may want to ensure no normalization is done; for this you can use utf8-c8
. Before using utf8-c8
please read Unicode: File Handles and I/O for more information on utf8-c8
and NFC.
Implementation may choose to also provide support for aliases, e.g. Rakudo allows aliases latin-1
for iso-8859-1
encoding and dashed utf versions: utf-8
and utf-16
.
with 'foo'.IO
routine lines
Defined as:
sub lines(IO::Handle = , = Inf, : --> Seq)method lines(IO::Handle: = Inf, : --> Seq)
Return a Seq each element of which is a line from the handle (that is chunks delineated by .nl-in
). If the handle's .chomp
attribute is set to True
, then characters specified by .nl-in
will be stripped from each line.
Reads up to $limit
lines, where $limit
can be a non-negative Int, Inf
, or Whatever (which is interpreted to mean Inf
). If :$close
is set to True
, will close the handle when the file ends or $limit
is reached. Subroutine form defaults to $*ARGFILES
, if no handle is provided.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
NOTE: the lines are read lazily, so ensure the returned Seq is either fully reified or is no longer needed when you close the handle or attempt to use any other methods that change the file position.
say "The file contains ",'50GB-file'.IO.open.lines.grep(*.contains: 'Perl').elems," lines that mention Perl";# OUTPUT: «The file contains 72 lines that mention Perl»
method lock
Defined as:
method lock(IO::Handle: Bool : = False, Bool : = False --> True)
Places an advisory lock on the filehandle. If :$non-blocking
is True
will fail
with X::IO::Lock
if lock could not be obtained, otherwise will block until the lock can be placed. If :$shared
is True
will place a shared (read) lock, otherwise will place an exclusive (write) lock. On success, returns True
; fails with X::IO::Lock
if lock cannot be placed (e.g. when trying to place a shared lock on a filehandle opened in write mode or trying to place an exclusive lock on a filehandle opened in read mode).
You can use lock
again to replace an existing lock with another one. To remove a lock, close
the filehandle or use unlock
.
# One program writes, the other reads, and thanks to locks either# will wait for the other to finish before proceeding to read/write# Writergiven "foo".IO.open(:w)# Readergiven "foo".IO.open
method unlock
Defined as:
method unlock(IO::Handle: --> True)
Removes a lock
from the filehandle.
routine words
Defined as:
multi sub words(IO::Handle = , = Inf, : --> Seq)multi method words(IO::Handle: = Inf, : --> Seq)
Similar to Str.words
, separates the handle's stream on contiguous chunks of whitespace (as defined by Unicode) and returns a Seq of the resultant "words." Takes an optional $limit
argument that can be a non-negative Int, Inf
, or Whatever (which is interpreted to mean Inf
), to indicate only up-to $limit
words must be returned. If Bool :$close
named argument is set to True
, will automatically close the handle when the returned Seq is exhausted. Subroutine form defaults to $*ARGFILES
, if no handle is provided.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my := bag .words;say "Most common words: ", .sort(-*.value).head: 5;
NOTE: implementations may read more data than necessary when a call to .words
is made. That is, $handle.words(2)
may read more data than two "words" worth of data and subsequent calls to read methods might not read from the place right after the two fetched words. After a call to .words
, the file position should be treated as undefined.
method split
Defined as:
method split(IO::Handle: :, |c)
Slurps the handle's content and calls Str.split
on it, forwarding any of the given arguments. If :$close
named parameter is set to True
, will close the invocant after slurping.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = 'path/to/file'.IO.open;.split: '♥', :close; # Returns file content split on ♥
method spurt
Defined as:
multi method spurt(IO::Handle: Blob , : = False)multi method spurt(IO::Handle: Cool , : = False)
Writes all of the $data
into the filehandle, closing it when finished, if $close
is True
. For Cool
$data
, will use the encoding the handle is set to use (IO::Handle.open
or IO::Handle.encoding
).
Behaviour for spurting a Cool
when the handle is in binary mode or spurting a Blob
when the handle is NOT in binary mode is undefined.
method print
Defined as:
multi method print(** --> True)multi method print(Junction --> True)
Writes the given @text
to the handle, coercing any non-Str objects to Str by calling .Str
method on them. Junction arguments autothread and the order of printed strings is not guaranteed. See write to write bytes.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = 'path/to/file'.IO.open: :w;.print: 'some text';.close;
method print-nl
Defined as:
method print-nl(IO::Handle: --> True)
Writes the value of $.nl-out
attribute into the handle.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = 'path/to/file'.IO.open: :w, :nl-out("\r\n");.print: "some text";.print-nl; # prints \r\n.close;
method printf
Defined as:
multi method printf(IO::Handle: Cool , *)
Formats a string based on the given format and arguments and .print
s the result into the filehandle. See sub sprintf for details on acceptable format directives.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = open 'path/to/file', :w;.printf: "The value is %d\n", 32;.close;
method out-buffer
Defined as:
method out-buffer(--> Int) is rw
Controls output buffering and can be set via an argument to open. Takes an int
as the size of the buffer to use (zero is acceptable). Can take a Bool: True
means to use default, implementation-defined buffer size; False
means to disable buffering (equivalent to using 0
as buffer size).
Lastly, can take a Nil
to enable TTY-based buffering control: if the handle is a TTY, the buffering is disabled, otherwise, default, implementation-defined buffer size is used.
See flush to write out data currently in the buffer. Changing buffer size flushes the filehandle.
given 'foo'.IO.open: :w, :1000out-buffer
method put
Defined as:
multi method put(** --> True)multi method put(Junction --> True)
Writes the given @text
to the handle, coercing any non-Str objects to Str by calling .Str
method on them, and appending the value of .nl-out
at the end. Junction arguments autothread and the order of printed strings is not guaranteed.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = 'path/to/file'.IO.open: :w;.print: 'some text';.close;
method say
Defined as:
multi method say(IO::Handle: ** --> True)
This method is identical to put except that it stringifies its arguments by calling .gist
instead of .Str
.
Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
my = open 'path/to/file', :w;.say(Complex.new(3, 4)); # RESULT: «3+4i\n».close;
method read
Defined as:
method read(IO::Handle: Int(Cool) = 65536 --> Buf)
Binary reading; reads and returns up to $bytes
bytes from the filehandle. $bytes
defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS
, which by default is set to 65536
). This method can be called even when the handle is not in binary mode.
(my = 'foo'.IO).spurt: 'I ♥ Perl';given .open
method readchars
Defined as:
method readchars(IO::Handle: Int(Cool) = 65536 --> Str)
Reading chars; reads and returns up to $chars
chars (graphemes) from the filehandle. $chars
defaults to an implementation-specific value (in Rakudo, the value of $*DEFAULT-READ-ELEMS
, which by default is set to 65536
). Attempting to call this method when the handle is in binary mode will result in X::IO::BinaryMode
exception being thrown.
(my = 'foo'.IO).spurt: 'I ♥ Perl';given .open
method write
Defined as:
method write(IO::Handle: Blob --> True)
Writes $buf
to the filehandle. This method can be called even when the handle is not in binary mode.
method seek
Defined as:
method seek(IO::Handle: Int , SeekType --> True)
Move the file pointer (that is, the position at which any subsequent read or write operations will begin) to the byte position specified by $offset
relative to the location specified by $whence
which may be one of:
SeekFromBeginning
The beginning of the file.
SeekFromCurrent
The current position in the file.
SeekFromEnd
The end of the file. Please note that you need to specify a negative offset if you want to position before the end of the file.
method tell
Defined as:
method tell(IO::Handle: --> Int)
Return the current position of the file pointer in bytes.
method slurp-rest
Defined as:
multi method slurp-rest(IO::Handle: :! --> Buf)multi method slurp-rest(IO::Handle: : --> Str)
DEPRECATION NOTICE: this method will be deprecated in 6.d
language. Do not use it for new code. Use .slurp
method method instead.
Return the remaining content of the file from the current file position (which may have been set by previous reads or by seek
.) If the adverb :bin
is provided a Buf will be returned, otherwise the return will be a Str
with the optional encoding :enc
.
method slurp
Defined as:
method slurp(IO::Handle: :, :)
Returns all the content from the current file position to the end. If the invocant is in binary mode or if $bin
is set to True
, will return a Buf, otherwise will decode the content using invocant's current .encoding
and return a Str.
If :$close
is set to True
, will close the handle when finished reading.
Note: On Rakudo this method was introduced with release 2017.04 and $bin
arg was added in 2017.10.
method Supply
Defined as:
multi method Supply(IO::Handle: : = 65536)
Returns a Supply
that will emit the contents of the handle in chunks. The chunks will be Buf
if the handle is in binary mode or, if it isn't, Str
decoded using same encoding as IO::Handle.encoding
.
The size of the chunks is determined by the optional :size
named parameter and 65536
bytes in binary mode or 65536
characters in non-binary mode.
"foo".IO.open(:bin).Supply(:size<10>).tap: *.perl.say;# OUTPUT:# Buf[uint8].new(73,32,226,153,165,32,80,101,114,108)# Buf[uint8].new(32,54,33,10)"foo".IO.open.Supply(:size<10>).tap: *.perl.say;# OUTPUT:# "I ♥ Perl 6"# "!\n"
method path
Defined as:
method path(IO::Handle:)
For a handle opened on a file this returns the IO::Path that represents the file. For the standard I/O handles $*IN
, $*OUT
, and $*ERR
it returns an IO::Special object.
method IO
Defined as:
method IO(IO::Handle:)
Alias for .path
method Str
Returns the value of .path
, coerced to Str.
say "foo".IO.open.path; # OUTPUT: «"foo".IO»
routine close
Defined as:
method close(IO::Handle: --> Bool)multi sub close(IO::Handle )
Closes an open file handle. It's not an error to call close
on an already-closed filehandle. Returns True
on success. If you close one of the standard file handles (by default: $*IN
, $*OUT
, or $*ERR
), that is any handle with native-descriptor 2
or lower, you won't be able to re-open such a handle.
It's a common idiom to use LEAVE
phaser for closing the handles, which ensures the handle is closed regardless of how the block is left.
ifsub do-stuff-with-the-file (IO )my = .open;# stick a `try` on it, since this will get run even when the sub is# called with wrong arguments, in which case the `$fh` will be an `Any`LEAVE try close ;# ... do stuff with the file}given "foo/bar".IO.open(:w)
Note: unlike some other languages, Perl 6 does not use reference counting, and so the file handles are NOT closed when they go out of scope. While they will get closed when garbage collected, garbage collection isn't guaranteed to get run. This means you must use an explicit close
on handles opened for writing, to avoid data loss, and an explicit close
is recommended on handles opened for reading as well, so that your program does not open too many files at the same time, triggering exceptions on further open
calls.
Note several methods allow for providing :close
argument, to close the handle after the operation invoked by the method completes. As a simpler alternative, the IO::Path type provides many reading and writing methods that let you work with files without dealing with file handles directly.
method flush
Defined as:
method flush(IO::Handle: --> True)
Will flush the handle, writing any of the buffered data. Returns True
on success; otherwise, fails with X::IO::Flush
.
given "foo".IO.open: :w
method native-descriptor
Defined as:
method native-descriptor()
This returns a value that the operating system would understand as a "file descriptor" and is suitable for passing to a native function that requires a file descriptor as an argument such as fcntl
or ioctl
.
method nl-in
Defined as:
method nl-in(--> Str) is rw
One of the attributes that can be set via .new
or open. Defaults to ["\x0A", "\r\n"]
. Takes either a Str or Array of Str
specifying input line ending(s) for this handle. If .chomp
attribute is set to True
, will strip these endings in routines that chomp
, such as get
and lines
.
with 'test'.IO
method nl-out
Defined as:
has Str is rw = "\n";
One of the attributes that can be set via .new
or open. Defaults to "\n"
. Takes a Str specifying output line ending for this handle, to be used by methods .put
and .say
.
with 'test'.IO
method opened
Defined as:
method opened(IO::Handle: --> Bool)
Returns True
if the handle is open, False
otherwise.
method t
Defined as:
method t(IO::Handle: --> Bool)
Returns True
if the handle is opened to a TTY, False
otherwise.
Related roles and classes
See also the related role IO and the related class IO::Path.
Type Graph
IO::Handle
Stand-alone image: vector
Routines supplied by class Any
IO::Handle inherits from class Any, which provides the following methods:
(Any) method ACCEPTS
Defined as:
multi method ACCEPTS(Any: Mu )
Usage:
EXPR.ACCEPTS(EXPR);
Returns True
if $other === self
(i.e. it checks object identity).
Many built-in types override this for more specific comparisons
(Any) method any
Defined as:
method any(--> Junction)
Interprets the invocant as a list and creates an any-Junction from it.
say so 2 == <1 2 3>.any; # OUTPUT: «True»say so 5 == <1 2 3>.any; # OUTPUT: «False»
(Any) method all
Defined as:
method all(--> Junction)
Interprets the invocant as a list and creates an all-Junction from it.
say so 1 < <2 3 4>.all; # OUTPUT: «True»say so 3 < <2 3 4>.all; # OUTPUT: «False»
(Any) method one
Defined as:
method one(--> Junction)
Interprets the invocant as a list and creates a one-Junction from it.
say so 1 == (1, 2, 3).one; # OUTPUT: «True»say so 1 == (1, 2, 1).one; # OUTPUT: «False»
(Any) method none
Defined as:
method none(--> Junction)
Interprets the invocant as a list and creates a none-Junction from it.
say so 1 == (1, 2, 3).none; # OUTPUT: «False»say so 4 == (1, 2, 3).none; # OUTPUT: «True»
(Any) method list
Defined as:
multi method list(Any: -->List)multi method list(Any \SELF: -->List)
Applies the infix ,
operator to the invocant and returns the resulting List:
say 42.list.^name; # OUTPUT: «List»say 42.list.elems; # OUTPUT: «1»
(Any) method push
Defined as:
method push(|values --> Positional)
The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.
my ;say <a>; # OUTPUT: «(Any)» <-- Undefined<a>.push(1); # .push on Anysay ; # OUTPUT: «{a => [1]}» <-- Note the Array
(Any) routine reverse
Defined as:
multi sub reverse(* --> Seq)multi method reverse(List: --> Seq)
Returns a Seq with the same elements in reverse order.
Note that reverse
always refers to reversing elements of a list; to reverse the characters in a string, use flip.
Examples:
say <hello world!>.reverse; # OUTPUT: «(world! hello)»say reverse ^10; # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)»
(Any) method sort
Defined as:
multi method sort()multi method sort()
Sorts iterables with cmp or given code object and returns a new Seq. Optionally, takes a Callable as a positional parameter, specifying how to sort.
Examples:
say <b c a>.sort; # OUTPUT: «(a b c)»say 'bca'.comb.sort.join; # OUTPUT: «abc»say 'bca'.comb.sort().join; # OUTPUT: «cba»say '231'.comb.sort(:«<=>»).join; # OUTPUT: «123»
(Any) method map
Defined as:
multi method map(\SELF: ;; :, :)
map
will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.
The :$label
and :$item
are useful only internally, since for
loops get converted to map
s. The :$label
takes an existing Label to label the .map
's loop with and :$item
controls whether the iteration will occur over (SELF,)
(if :$item
is set) or SELF
.
(Any) method deepmap
Defined as:
method deepmap( --> List) is nodal
deepmap
will apply &block
to each element and return a new List with the return values of &block
, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.
say [[1,2,3],[[4,5],6,7]].deepmap(* + 1);# OUTPUT: «[[2 3 4] [[5 6] 7 8]]»
(Any) method duckmap
Defined as:
method duckmap() is rw is nodal
duckmap
will apply &block
on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.
<a b c d e f g>.duckmap(-> where <c d e>.any ).say;# OUTPUT: «(a b C D E f g)»(('d', 'e'), 'f').duckmap(-> where <e f>.any ).say;# OUTPUT: «((d E) F)»
(Any) method nodemap
Defined as:
method nodemap( --> List) is nodal
nodemap
will apply &block
to each element and return a new List with the return values of &block
. In contrast to deepmap it will not descend recursively into sublists if it finds elements which does the Iterable role.
say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);# OUTPUT: «(4, 4, 8)»say [[2, 3], [4, [5, 6]]]».nodemap(*+1)# OUTPUT: «((3 4) (5 3))»
The examples above would have produced the exact same results if we had used map instead of nodemap
. The difference between the two lies in the fact that map flattens out slips while nodemap
doesn't.
say [[2,3], [[4,5],6,7], 7].nodemap();# OUTPUT: «(() () 7)»say [[2,3], [[4,5],6,7], 7].map();# OUTPUT: «(7)»
(Any) method flat
Defined as:
method flat(--> Seq) is nodal
Interprets the invocant as a list, flattens non-containerized Iterables into a flat list, and returns that list. Keep in mind Map and Hash types are Iterable and so will be flattened into lists of pairs.
say ((1, 2), (3), %(:42a)); # OUTPUT: «((1 2) 3 {a => 42})»say ((1, 2), (3), %(:42a)).flat; # OUTPUT: «(1 2 3 a => 42)»
Note that Arrays containerize their elements by default, and so flat
will not flatten them. You can use hyper method call to call .List
method on all the inner Iterables and so de-containerize them, so that flat
can flatten them:
say [[1, 2, 3], [(4, 5), 6, 7]] .flat; # OUTPUT: «([1 2 3] [(4 5) 6 7])»say [[1, 2, 3], [(4, 5), 6, 7]]».List.flat; # OUTPUT: «(1 2 3 4 5 6 7)»
For more fine-tuned options, see deepmap, duckmap, and signature destructuring
(Any) method eager
Defined as:
method eager(--> Seq) is nodal
Interprets the invocant as a List, evaluates it eagerly, and returns that List.
my = 1..5;say ; # OUTPUT: «1..5»say .eager; # OUTPUT: «(1 2 3 4 5)»
(Any) method elems
Defined as:
method elems(--> Int) is nodal
Interprets the invocant as a list, and returns the number of elements in the list.
say 42.elems; # OUTPUT: «1»say <a b c>.elems; # OUTPUT: «3»
(Any) method end
method end(--> Any) is nodal
Interprets the invocant as a list, and returns the last index of that list.
say 6.end; # OUTPUT: «0»say <a b c>.end; # OUTPUT: «2»
(Any) method pairup
Defined as:
method pairup(--> Seq) is nodal
Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed is passed through, and the next list item, if any, is considered to be a key again).
say (a => 1, 'b', 'c').pairup.perl; # OUTPUT: «(:a(1), :b("c")).Seq»
(Any) sub exit
Defined as:
sub exit(Int() = 0)
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).
exit
does prevent the LEAVE phaser to be executed.
exit
should be used as last resort only to signal the parent process about an exit code different from zero, and should not be used to terminate exceptionally a method or a sub: use exceptions instead.
It is worth noting that the only way to return an exit code different from zero from a Main function is by means of using exit
.
(Any) sub item
Defined as:
proto sub item(|) is puremulti item(\x)multi item(|c)multi item(Mu )
Forces given object to be evaluated in item context and returns the value of it.
say item([1,2,3]).perl; # OUTPUT: «$[1, 2, 3]»say item( %( apple => 10 ) ).perl; # OUTPUT: «${:apple(10)}»say item("abc").perl; # OUTPUT: «"abc"»
You can also use $
as item contextualizer.
say $[1,2,3].perl; # OUTPUT: «$[1, 2, 3]»say $("abc").perl; # OUTPUT: «"abc"»
(Any) method Array
Defined as:
method Array(--> Array) is nodal
Coerce the invocant to Array.
(Any) method List
Defined as:
method List(--> List) is nodal
Coerce the invocant to List, using the list method.
(Any) method Hash
Defined as:
proto method Hash(|) is nodalmulti method Hash( --> Hash)
Coerce the invocant to Hash by invoking the method hash
on it.
(Any) method hash
Defined as:
proto method hash(|) is nodalmulti method hash(Any: --> Hash)multi method hash(Any: --> Hash)
Creates a new Hash, empty in the case the invocant is undefined, or coerces the invocant to an Hash
in the case it is defined.
my ; # $d is Anysay .hash; # OUTPUT: {}.append: 'a', 'b';say .hash; # OUTPUT: {a => b}
(Any) method Slip
Defined as:
method Slip(--> Slip) is nodal
Coerce the invocant to Slip.
(Any) method Map
Defined as:
method Map(--> Map) is nodal
Coerce the invocant to Map.
(Any) method Bag
Defined as:
method Bag(--> Bag) is nodal
Coerce the invocant to Bag, whereby Positionals are treated as lists of values.
(Any) method BagHash
Defined as:
method BagHash(--> BagHash) is nodal
Coerce the invocant to BagHash, whereby Positionals are treated as lists of values.
(Any) method Set
Defined as:
method Set(--> Set) is nodal
Coerce the invocant to Set, whereby Positionals are treated as lists of values.
(Any) method SetHash
Defined as:
method SetHash(--> SetHash) is nodal
Coerce the invocant to SetHash, whereby Positionals are treated as lists of values.
(Any) method Mix
Defined as:
method Mix(--> Mix) is nodal
Coerce the invocant to Mix, whereby Positionals are treated as lists of values.
(Any) method MixHash
Defined as:
method MixHash(--> MixHash) is nodal
Coerce the invocant to MixHash, whereby Positionals are treated as lists of values.
(Any) method Supply
Defined as:
method Supply(--> Supply) is nodal
Coerce the invocant first to a list
by applying the invocant's .list
method, and then to a Supply.
(Any) method min
Defined As:
multi method min(--> Any)multi method min( --> Any)
Coerces to Iterable and returns the numerically smallest element.
If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from min
.
say (1,7,3).min(); # OUTPUT:«1»say (1,7,3).min(); # OUTPUT:«7»
(Any) method max
Defined As:
multi method max(--> Any)multi method max( --> Any)
Coerces to Iterable and returns the numerically largest element.
If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original value is still the one returned from max
.
say (1,7,3).max(); # OUTPUT:«7»say (1,7,3).max(); # OUTPUT:«1»
(Any) method minmax
Defined As:
multi method minmax(--> Range)multi method minmax( --> Range)
Returns a Range from the smallest to the largest element.
If a Callable positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original values are still used in the returned Range.
say (1,7,3).minmax(); # OUTPUT:«1..7»say (1,7,3).minmax(); # OUTPUT:«7..1»
(Any) method minpairs
Defined As:
multi method minpairs(Any: --> Seq)
Calls .pairs
and returns a Seq with all of the Pairs with minimum values, as judged by the cmp
operator:
<a b c a b c>.minpairs.perl.put; # OUTPUT: «(0 => "a", 3 => "a").Seq»%(:42a, :75b).minpairs.perl.put; # OUTPUT: «(:a(42),).Seq»
(Any) method maxpairs
Defined As:
multi method maxpairs(Any: --> Seq)
Calls .pairs
and returns a Seq with all of the Pairs with maximum values, as judged by the cmp
operator:
<a b c a b c>.maxpairs.perl.put; # OUTPUT: «(2 => "c", 5 => "c").Seq»%(:42a, :75b).maxpairs.perl.put; # OUTPUT: «(:b(75),).Seq»
(Any) method keys
Defined As:
multi method keys(Any: --> List)multi method keys(Any: --> List)
For defined Any returns its keys after calling list
on it, otherwise calls list
and returns it.
say Any.keys; # OUTPUT: «()»
(Any) method flatmap
Defined As:
method flatmap(Any: --> Seq)
Coerces the Any to a list
by applying the .list
method and uses List.flatmap
on it.
say Any.flatmap(); # OUTPUT: «((Any))»
In the case of Any, Any.list
returns a 1-item list, as is shown.
(Any) method roll
Defined As:
multi method roll(--> Any)multi method roll( --> Seq)
Coerces the invocant Any to a list
by applying the .list
method and uses List.roll
on it.
say Any.roll; # OUTPUT: «(Any)»say Any.roll(5); # OUTPUT: «((Any) (Any) (Any) (Any) (Any))»
(Any) method pick
Defined As:
multi method pick(--> Any)multi method pick( --> Seq)
Coerces the Any to a list
by applying the .list
method and uses List.pick
on it.
say Any.pick; # OUTPUT: «(Any)»say Any.pick(5); # OUTPUT: «((Any))»
(Any) method skip
Defined As:
multi method skip(--> Seq)multi method skip( --> Seq)
Creates a Seq from 1-item list's iterator and uses Seq.skip
on it.
say Any.skip; # OUTPUT: «()»say Any.skip(5); # OUTPUT: «()»say Any.skip(-1); # OUTPUT: «((Any))»say Any.skip(*-1); # OUTPUT: «((Any))»
(Any) method prepend
Defined As:
multi method prepend(--> Array)multi method prepend( --> Array)
Initializes Any variable as empty Array and calls Array.prepend
on it.
my ;say .prepend; # OUTPUT: «[]»say ; # OUTPUT: «[]»my ;say .prepend(1,2,3); # OUTPUT: «[1 2 3]»
(Any) method unshift
Defined As:
multi method unshift(--> Array)multi method unshift( --> Array)
Initializes Any variable as empty Array and calls Array.unshift
on it.
my ;say .unshift; # OUTPUT: «[]»say ; # OUTPUT: «[]»my ;say .unshift([1,2,3]); # OUTPUT: «[[1 2 3]]»
(Any) method first
Defined As:
method first(Mu ?, :, :, :, :)
Treats the Any
as a 1-item list and uses List.first
on it.
say Any.first; # OUTPUT: «(Any)»
(Any) method unique
Defined As:
method unique(:, : --> Seq)
Treats the Any
as a 1-item list and uses List.unique
on it.
say Any.unique; # OUTPUT: «((Any))»
(Any) method repeated
Defined As:
method repeated(:, : --> Seq)
Treats the Any
as a 1-item list and uses List.repeated
on it.
say Any.repeated; # OUTPUT: «()»
(Any) method squish
Defined As:
method squish(:, : --> Seq)
Treats the Any
as a 1-item list and uses List.squish
on it.
say Any.squish; # OUTPUT: «((Any))»
(Any) method permutations
Defined As:
method permutations(--> Seq)
Treats the Any
as a 1-item list and uses List.permutations
on it.
say Any.permutations; # OUTPUT: «(((Any)))»
(Any) method categorize
Defined As:
method categorize( --> Hash)
Treats the Any
as a 1-item list and uses List.categorize
on it.
say Any.categorize(); # OUTPUT: «{(Any) => [(Any)]}»
(Any) method classify
Defined As:
method classify( -->Hash)
Treats the Any
as a 1-item list and uses List.classify
on it.
say Any.classify(); # OUTPUT: «{(Any) => [(Any)]}»
(Any) method produce
(Any) method pairs
Defined As:
multi method pairs(Any: -->List)multi method pairs(Any: -->List)
Returns an empty List if the invocant is undefined, otherwise converts the invocant to a List via the list
method and calls List.pairs on it:
say Any.pairs; # OUTPUT: «()»my ;say .pairs; # OUTPUT: «()»= Any.new;say .pairs; # OUTPUT: «(0 => Any.new)»
(Any) method antipairs
Defined As:
multi method antipairs(Any: -->List)multi method antipairs(Any: -->List)
Applies the method List.antipairs to the invocant, if it is defined, after having invoked list
on it. If the invocant is not defined, it returns an empty List:
my ;say .antipairs; # OUTPUT: «()»= Any.new;say .antipairs; # OUTPUT: «(Any.new => 0)»
(Any) method kv
Defined As:
multi method kv(Any: -->List)multi method kv(Any: -->List)
Returns an empty List if the invocant is not defined, otherwise it does invoke list
on the invocant and then returns the result of List.kv on the latter:
my ;say .kv; # OUTPUT: «()»= Any.new;say .kv; # OUTPUT: «(0 Any.new)»say Any.kv; # OUTPUT: «()»
(Any) method toggle
Defined as:
method toggle(Any: * where .all ~~ Callable, Bool : --> Seq)
Iterates over the invocant, producing a Seq, toggling whether the received values are propagated to the result on and off, depending on the results of calling Callables in @conditions
:
say ^10 .toggle: * < 4, * %% 2, ; # OUTPUT: «(0 1 2 3 6 7)»say ^10 .toggle: :off, * > 4; # OUTPUT: «(5 6 7 8 9)»
Imagine a switch that's either on or off (True
or False
), and values are produced if it's on. By default, the initial state of that switch is in "on" position, unless :$off
is set to a true value, in which case the initial state will be "off".
A Callable from the head of @conditions
is taken (if any are available) and it becomes the current tester. Each value from the original sequence is tested by calling the tester Callable with that value. The state of our imaginary switch is set to the return value from the tester: if it's truthy, set switch to "on", otherwise set it to "off".
Whenever the switch is toggled (i.e. switched from "off" to "on" or from "on" to "off"), the current tester Callable is replaced by the next Callable in @conditions
, if available, which will be used to test any further values. If no more tester Callables are available, the switch will remain in its current state until the end of iteration.
# our original sequence of elements:say list ^10; # OUTPUT: «(0 1 2 3 4 5 6 7 8 9)»# toggled result:say ^10 .toggle: * < 4, * %% 2, ; # OUTPUT: «(0 1 2 3 6 7)»# First tester Callable is `* < 4` and initial state of switch is "on".# As we iterate over our original sequence:# 0 => 0 < 4 === True switch is on, value gets into result, switch is# toggled, so we keep using the same Callable:# 1 => 1 < 4 === True same# 2 => 2 < 4 === True same# 3 => 3 < 4 === True same# 4 => 4 < 4 === False switch is now off, "4" does not make it into the# result. In addition, our switch got toggled, so# we're switching to the next tester Callable# 5 => 5 %% 2 === False switch is still off, keep trying to find a value# 6 => 6 %% 2 === True switch is now on, take "6" into result. The switch# toggled, so we'll use the next tester Callable# 7 => is-prime(7) === True switch is still on, take value and keep going# 8 => is-prime(8) === False switch is now off, "8" does not make it into# the result. The switch got toggled, but we# don't have any more tester Callables, so it# will remain off for the rest of the sequence.
Since the toggle of the switch's state loads the next tester Callable, setting :$off
to a True
value affects when first tester is discarded:
# our original sequence of elements:say <0 1 2>; # OUTPUT: «(0 1 2)»# toggled result:say <0 1 2>.toggle: * > 1; # OUTPUT: «()»# First tester Callable is `* > 1` and initial state of switch is "on".# As we iterate over our original sequence:# 0 => 0 > 1 === False switch is off, "0" does not make it into result.# In addition, switch got toggled, so we change the# tester Callable, and since we don't have any more# of them, the switch will remain "off" until the end
# our original sequence of elements:say <0 1 2>; # OUTPUT: «(0 1 2)»# toggled result:say <0 1 2>.toggle: :off, * > 1; # OUTPUT: «(2)»# First tester Callable is `* > 1` and initial state of switch is "off".# As we iterate over our original sequence:# 0 => 0 > 1 === False switch is off, "0" does not make it into result.# The switch did NOT get toggled this time, so we# keep using our current tester Callable# 1 => 1 > 1 === False same# 2 => 2 > 1 === True switch is on, "2" makes it into the result
(Any) method tree
Defined As:
method tree(--> Any)
Returns the class if it's undefined or if it's not iterable, returns the result of applying the tree
method to the elements if it's Iterable.
say Any.tree; # OUTPUT: «Any»
.tree
has different prototypes for Iterable elements.
my = ( 'A', ('B','C', ('E','F','G')));say .tree(1).flat.elems; # OUTPUT: «6»say .tree(2).flat.elems; # OUTPUT: «2»say .tree( *.join("-"), *.join("—"), *.join("|" )); # OUTPUT: «A-B—C—E|F|G»
With a number, it iteratively applies tree
to every element in the lower level; the first instance will apply .tree(0)
to every element in the array, and likewise for the next example.
The second prototype applies the Whatever
code passed as arguments to every level in turn; the first argument will go to level 1 and so on. tree
can, thus, be a great way to process complex all levels of complex, multi-level, data structures.
(Any) method nl-out
Defined As:
method nl-out(--> Str)
Returns Str with the value of "\n". See IO::Handle.nl-out
for the details.
say Any.nl-out; # OUTPUT: «»
(Any) method invert
Defined As:
method invert(--> List)
Returns an empty List.
say Any.invert; # OUTPUT: «()»
(Any) method combinations
Defined As:
method combinations(--> Seq)
Treats the Any
as a 1-item list and uses List.combinations
on it.
say Any.combinations; # OUTPUT: «(() ((Any)))»
(Any) method iterator
Defined As:
method iterator(--> Iterator)
Coerces the Any
to a list
by applying the .list
method and uses iterator
on it.
my = Any.iterator;say .pull-one; # OUTPUT: «(Any)»say .pull-one; # OUTPUT: «IterationEnd»
(Any) method grep
Defined As:
method grep(Mu , :, :, :, : --> Seq)
Coerces the Any
to a list
by applying the .list
method and uses List.grep
on it.
Based on $matcher
value can be either ((Any))
or empty List.
my ;say .grep(); # OUTPUT: «((Any))»say .grep(); # OUTPUT: «()»
(Any) method append
Defined As:
proto method append(|) is nodalmulti method append(Any \SELF: |values --> Array)
In the case the instance is not a positional-thing, it instantiate it as a new Array, otherwise clone the current instance. After that, it appends the values passed as arguments to the array obtained calling Array.append
on it.
my ;say .append; # OUTPUT: «[]»my ;say .append((1,2,3)); # OUTPUT: «[1 2 3]»
(Any) method values
Defined As:
method values(--> List)
Returns an empty List.
(Any) method collate
Defined As:
method collate(--> Seq)
TODO
(Any) method cache
Defined As:
method cache(--> List)
Provides a List representation of the object itself, calling the method list
on the instance.
Routines supplied by class Mu
IO::Handle inherits from class Mu, which provides the following methods:
(Mu) method defined
Declared as
multi method defined( --> Bool)
Returns False
on the type object, and True
otherwise.
say Int.defined; # OUTPUT: «False»say 42.defined; # OUTPUT: «True»
Very few types (like Failure) override defined
to return False
even for instances:
sub fails() ;say fails().defined; # OUTPUT: «False»
(Mu) routine defined
Declared as
multi sub defined(Mu --> Bool)
invokes the .defined
method on the object and returns its result.
(Mu) routine isa
multi method isa(Mu --> Bool)multi method isa(Str --> Bool)
Returns True
if the invocant is an instance of class $type
, a subset type or a derived class (through inheritance) of $type
.
my = 17;say .isa("Int"); # OUTPUT: «True»say .isa(Any); # OUTPUT: «True»
A more idiomatic way to do this is to use the smartmatch operator ~~ instead.
my = "String";say ~~ Str; # OUTPUT: «True»
(Mu) routine does
method does(Mu --> Bool)
Returns True
if and only if the invocant conforms to type $type
.
my = Date.new('2016-06-03');say .does(Dateish); # True (Date does role Dateish)say .does(Any); # True (Date is a subclass of Any)say .does(DateTime); # False (Date is not a subclass of DateTime)
Using the smart match operator ~~ is a more idiomatic alternative.
my = Date.new('2016-06-03');say ~~ Dateish; # OUTPUT: «True»say ~~ Any; # OUTPUT: «True»say ~~ DateTime; # OUTPUT: «False»
(Mu) routine Bool
multi sub Bool(Mu --> Bool)multi method Bool( --> Bool)
Returns False
on the type object, and True
otherwise.
Many built-in types override this to be False
for empty collections, the empty string or numerical zeros
say Mu.Bool; # OUTPUT: «False»say Mu.new.Bool; # OUTPUT: «True»say [1, 2, 3].Bool; # OUTPUT: «True»say [].Bool; # OUTPUT: «False»say %( hash => 'full' ).Bool; # OUTPUT: «True»say .Bool; # OUTPUT: «False»say "".Bool; # OUTPUT: «False»say 0.Bool; # OUTPUT: «False»say 1.Bool; # OUTPUT: «True»say "0".Bool; # OUTPUT: «True»
(Mu) method Capture
Declared as:
method Capture(Mu: --> Capture)
Returns a Capture with named arguments corresponding to invocant's public attributes:
.new.Capture.say; # OUTPUT: «\(:bar("something else"), :foo(42))»
(Mu) method Str
multi method Str(--> Str)
Returns a string representation of the invocant, intended to be machine readable. Method Str
warns on type objects, and produces the empty string.
say Mu.Str; # Use of uninitialized value of type Mu in string context.
(Mu) routine gist
multi sub gist(+args --> Str)multi method gist( --> Str)
Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use .perl
to get all elements.
The default gist
method in Mu
re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific that may truncate output.
gist
is the method that say calls implicitly, so say $something
and say $something.gist
generally produce the same output.
say Mu.gist; # OUTPUT: «(Mu)»say Mu.new.gist; # OUTPUT: «Mu.new»
(Mu) routine perl
multi method perl(--> Str)
Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl
is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value
(Mu) method item
method item(Mu \item:) is raw
Forces the invocant to be evaluated in item context and returns the value of it.
say [1,2,3].item.perl; # OUTPUT: «$[1, 2, 3]»say %( apple => 10 ).item.perl; # OUTPUT: «${:apple(10)}»say "abc".item.perl; # OUTPUT: «"abc"»
(Mu) method self
method self(--> Mu)
Returns the object it is called on.
(Mu) method clone
method clone(*)
Creates a shallow clone of the invocant, including shallow cloning of private attributes. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.
my = Point2D.new(x => 2, y => 3);say ; # OUTPUT: «Point(2, 3)»say .clone(y => -5); # OUTPUT: «Point(2, -5)»
Note that .clone
does not go the extra mile to shallow-copy @.
and %.
sigiled attributes and, if modified, the modifications will still be available in the original object:
my = Foo.new;with my = .clone# Hash and Array attribute modifications in clone appear in original as well:say ; # OUTPUT: «Foo.new(foo => 42, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …»say ; # OUTPUT: «Foo.new(foo => 70, bar => ["Z", "Y"], baz => {:X("W"), :Z("Y")}, …».boo.(); # OUTPUT: «Hi».boo.(); # OUTPUT: «Bye»
To clone those, you could implement your own .clone
that clones the appropriate attributes and passes the new values to Mu.clone
, for example, via nextwith
. Alternatively, your own .clone
could clone self first (using self.Mu::clone
or callsame
) and then manipulate the clone as needed, before returning it.
my = Bar.new;with my = .clone# Hash and Array attribute modifications in clone do not affect original:say ; # OUTPUT: «Bar.new(foo => ["a", "b"], bar => {:a("b"), :c("d")})»say ; # OUTPUT: «Bar.new(foo => ["Z", "Y"], bar => {:X("W"), :Z("Y")})»
(Mu) method new
multi method new(*)
Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.
Classes may provide their own new
method to override this default.
new
triggers an object construction mechanism that calls submethods named BUILD
in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.
(Mu) method bless
method bless(* --> Mu)
Lower-level object construction method than new
.
Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.
You can use this method when writing custom constructors:
my = Point.new(-1, 1);
(Though each time you write a custom constructor, remember that it makes subclassing harder).
(Mu) method CREATE
method CREATE(--> Mu)
Allocates a new object of the same type as the invocant, without initializing any attributes.
say Mu.CREATE.defined; # OUTPUT: «True»
(Mu) method print
multi method print(--> Bool)
Prints value to $*OUT
after stringification using .Str
method without adding a newline at end.
"abc\n".print; # RESULT: «abc»
(Mu) method put
multi method put(--> Bool)
Prints value to $*OUT
, adding a newline at end, and if necessary, stringifying non-Str
object using the .Str
method.
"abc".put; # RESULT: «abc»
(Mu) method say
multi method say(--> Bool)
Prints value to $*OUT
after stringification using gist method with newline at end. To produce machine readable output use .put
.
say 42; # OUTPUT: «42»
(Mu) method ACCEPTS
multi method ACCEPTS(Mu: )
ACCEPTS
is the method that smart matching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).
The Mu:U
multi performs a type check. Returns True
if $other
conforms to the invocant (which is always a type object or failure).
say 42 ~~ Mu; # OUTPUT: «True»say 42 ~~ Int; # OUTPUT: «True»say 42 ~~ Str; # OUTPUT: «False»
Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.
(Mu) method WHICH
multi method WHICH(--> ObjAt)
Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH
.
say 42.WHICH eq 42.WHICH; # OUTPUT: «True»
(Mu) method WHERE
method WHERE(--> Int)
Returns an Int
representing the memory address of the object.
(Mu) method WHY
multi method WHY(--> Pod::Block::Declarator)
Returns the attached Pod::Block::Declarator.
For instance:
sub cast(Spell )say .WHY;# OUTPUT: «Initiate a specified spell normally(do not use for class 7 spells)»
See Pod declarator blocks for details about attaching Pod to variables, classes, functions, methods, etc.
(Mu) trait is export
multi sub trait_mod:<is>(Mu \type, :!)
Marks a type as being exported, that is, available to external users.
my is export
A user of a module or class automatically gets all the symbols imported that are marked as is export
.
See Exporting and Selective Importing Modules for more details.
(Mu) method return
method return()
The method return
will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil
. A control exception is raised and can be caught with CONTROL.
sub f ;say f(); # OUTPUT: «any(1, 2, 3)»
(Mu) method return-rw
Same as method return
except that return-rw
returns a writable container to the invocant (see more details here: return-rw
).
(Mu) method emit
method emit()
Emits the invocant into the enclosing supply or react block.
react# OUTPUT:# received Str (foo)# received Int (42)# received Rat (0.5)
(Mu) method take
method take()
Returns the invocant in the enclosing gather block.
sub insert(, +)say insert ':', <a b c>;# OUTPUT: «(a : b : c)»
(Mu) routine take
sub take(\item)
Takes the given item and passes it to the enclosing gather
block.
my = 6;my = 49;gather for ^.say; # six random values
(Mu) routine take-rw
sub take-rw(\item)
Returns the given item to the enclosing gather
block, without introducing a new container.
my = 1...3;sub f();for f() ;say ;# OUTPUT: «[2 3 4]»
(Mu) method so
method so()
Returns a Bool
value representing the logical non-negation of an expression. One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,
my = <-a -e -b -v>;my = any() eq '-v' | '-V';if .so# OUTPUT: «Verbose option detected in arguments»
(Mu) method not
method not()
Returns a Bool
value representing the logical negation of an expression. Thus it is the opposite of so
.
my = <-a -e -b>;my = any() eq '-v' | '-V';if .not# OUTPUT: «Verbose option not present in arguments»
Since there is also a prefix version of not
, the above code reads better like so:
my = <-a -e -b>;my = any() eq '-v' | '-V';if not# OUTPUT: «Verbose option not present in arguments»