# class Num

Floating-point number

A `Num` object stores a floating-point number. It is immutable. On most platforms, it's an IEEE 754 64-bit floating point numbers, aka "double precision".

## Inf

The value `Inf` is an instance of `Num` and represents value that's too large to represent in 64-bit double-precision floating point number (roughly, above `1.7976931348623158e308` for positive `Inf` and below `-1.7976931348623157e308` for negative `Inf`) as well as returned from certain operations as defined by the IEEE 754-2008 standard.

The `∞` `U+221E` Unicode character can be used instead of the word `Inf` and can be handy when `Inf` would otherwise require an unspace, such as when writing Complex numbers:

Note that there are just two infinities (positive and negative), so even if an operation that would instinctively give a "larger" infinity is performed, the result in still an infinity of the original magnitude. The infinities can be compared, operated and used as an argument as if they were simply a number that's too big to represent or to signify "without bounds" or limits:

In some cases, it's used as an implicit value to represent "all of them"

In the example above, `Inf` can be eliminated, since it's the default value for the second argument of `.comb`, used to indicate how many parts should be returned.

Division of an infinity by another infinity results in a `NaN`:

## NaN

The value `NaN` is an instance of `Num` and represents a floating point not-a-number value, which is returned from some routines where a concrete number as the answer is not defined, but a Numeric value is still acceptable. `NaN` is defined and boolifies to `True`, but is not numerically equal to any value (including itself).

To test for `NaN`, use isNaN method or === operator:

## method rand

Returns a pseudo random number between 0 and the invocant.

## sub srand

Seeds the pseudo random number generator used by Num.rand with the provided value. Note that `srand` is called with a platform dependent value when a Perl 6 program is started.

## method Capture

Defined as:

Throws `X::Cannot::Capture`.

## Int

Converts the number to an Int. Fails with `X::Numeric::CannotConvert` if the invocant is a `NaN` or `Inf`/`-Inf`. No rounding is performed.

## Rat

Converts the number to a Rat with `\$epsilon` precision. If the invocant is a `Inf`, `-Inf`, or a `NaN`, converts them to a Rat with `0` denominator and `1`, `-1`, or `0` numerator, respectively.

## FatRat

Converts the number to a FatRat with the precision `\$epsilon`. If invocant is a `Inf`, `-Inf`, or a `NaN`, converts them to a FatRat with `0` denominator and `1`, `-1`, or `0` numerator, respectively.

# Routines supplied by role Real

Num does role Real, which provides the following routines:

## (Real) method Bridge

Defined as:

Default implementation coerces the invocant to Num and that's the behavior of this method in core Real types. This method primarily exist to make it easy to implement custom Real types by users, with the `Bridge` method returning one of the core `Real` types (NOT necessarily a Num) that best represent the custom `Real` type. In turn, this lets all the core operators and methods obtain a usable value they can work with.

As an example, we can implement a custom `Temperature` type. It has a unit of measure and the value, which are given during instantiation. We can implement custom operators or conversion methods that work with this type. When it comes to regular mathematical operators, however, we can simply use the `.Bridge` method to convert the `Temperature` to Kelvin expressed in one of the core numeric types:

As we can see from the last two lines of the output, the type of the bridged result is not forced to be any particular core type. It is a Rat, when we instantiated `Temperature` with a `Rat` or when conversion was involved, and it is an Int when we instantiated `Temperature` with an Int.

## (Real) method Complex

Converts the number to a `Complex` with the number converted to a `Num` as its real part and 0e0 as the imaginary part.

## (Real) method Rat

Converts the number to a `Rat` with the precision `\$epsilon`.

## (Real) method Real

Defined as:

The `:D` variant simply returns the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns `self.new`.

## (Real) routine rand

Returns a pseudo-random number between zero (inclusive) and the number (non-inclusive). The `Bridge` method is used to coerce the `Real` to a numeric that supports rand method.

The term form returns a pseudo-random `Num` between 0e0 (inclusive) and 1e0 (non-inclusive.)

## (Real) method sign

Returns `-1` if the number is negative, `0` if it is zero and `1` otherwise.

## (Real) method round

Rounds the number to scale `\$scale`. If `\$scale` is 1, rounds to an integer. If scale is `0.1`, rounds to one digit after the comma etc.

## (Real) method floor

Return the largest integer not greater than the number.

## (Real) method ceiling

Returns the smallest integer not less than the number.

## (Real) method truncate

Rounds the number towards zero.

## (Real) method polymod

Returns the remainders after applying sequentially all divisors in the `@mods` argument; the last element of the array will be the last remainder.

`10 xx 8` is simply an array with eight number 10s; the first division by 10 will return `1` as a remainder, while the rest, up to the last, will return 0. With 8 divisors, as above, the result will have one more elements, in this case for the last remainder.

## (Real) method base

Converts the number to a string, using `\$base` as base. For `\$base` larger than ten, capital Latin letters are used.

The optional `\$digits` argument asks for that many digits of fraction (which may not be negative). If omitted, a reasonable default is chosen based on type. For Int this default is 0. For Num, the default is 8. For Rational, the number of places is scaled to the size of the denominator, with a minimum of 6.

A special value of `Whatever` (`*`) can be given as `\$digits`, which functions the same as when `\$digits` is not specified for all `Real` types except the `Rationals`. For `Rationals`, the `Whatever` indicates that you wish all of the possible digits of the fractional part, but use caution: since there's no detection of repeating fractional parts (the algorithm will eventually stop after generating 2**63 digits).

The final digit produced is always rounded.

For reverse operation, see `parse-base`

# Routines supplied by role Numeric

Num does role Numeric, which provides the following routines:

## (Numeric) method Numeric

Defined as:

The `:D` variant simply returns the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns `self.new`.

## (Numeric) method Int

If this `Numeric` is equivalent to a `Real`, return the equivalent of calling `truncate` on that `Real` to get an `Int`. Fail with `X::Numeric::Real` otherwise.

## (Numeric) method Rat

If this `Numeric` is equivalent to a `Real`, return a `Rat` which is within `\$epsilon` of that `Real`'s value. Fail with `X::Numeric::Real` otherwise.

## (Numeric) method Num

If this `Numeric` is equivalent to a `Real`, return that `Real` as a `Num` as accurately as is possible. Fail with `X::Numeric::Real` otherwise.

## (Numeric) method narrow

Returns the number converted to the narrowest type that can hold it without loss of precision.

## (Numeric) method ACCEPTS

Returns `True` if `\$other` can be coerced to Numeric and is numerically equal to the invocant (or both evaluate to `NaN`).

## (Numeric) routine log

Calculates the logarithm to base `\$base`. Defaults to the natural logarithm. Returns `NaN` if `\$base` is negative. Throws an exception if `\$base` is `1`.

## (Numeric) routine log10

Calculates the logarithm to base 10. Returns `NaN` for negative arguments and `-Inf` for `0`.

## (Numeric) routine exp

Returns `\$base` to the power of the number, or `e` to the power of the number if called without a second argument.

## (Numeric) method roots

Returns a list of the `\$n` complex roots, which evaluate to the original number when raised to the `\$n`th power.

## (Numeric) routine abs

Returns the absolute value of the number.

## (Numeric) routine sqrt

Returns a square root of the number. For real numbers the positive square root is returned.

On negative real numbers, `sqrt` returns `NaN` rather than a complex number, in order to not confuse people who are not familiar with complex arithmetic. If you want to calculate complex square roots, coerce to `Complex` first, or use the `roots` method.

## (Numeric) method conj

Returns the complex conjugate of the number. Returns the number itself for real numbers.

## (Numeric) method Bool

Returns `False` if the number is equivalent to zero, and `True` otherwise.

## (Numeric) method succ

Returns the number incremented by one (successor).

## (Numeric) method pred

Returns the number decremented by one (predecessor).

# Routines supplied by class Cool

Num inherits from class Cool, which provides the following routines:

## (Cool) routine abs

Defined as:

Coerces the invocant (or in the sub form, the argument) to Numeric and returns the absolute value (that is, a non-negative number).

## (Cool) method conj

Defined as:

Coerces the invocant to Numeric and returns the complex conjugate (that is, the number with the sign of the imaginary part negated).

## (Cool) routine sqrt

Defined as:

Coerces the invocant to Numeric (or in the sub form, the argument) and returns the square root, that is, a non-negative number that, when multiplied with itself, produces the original number.

## (Cool) method sign

Defined as:

Coerces the invocant to Numeric and returns its sign, that is, 0 if the number is 0, 1 for positive and -1 for negative values.

## (Cool) method rand

Defined as:

Coerces the invocant to Num and returns a pseudo-random value between zero and the number.

## (Cool) routine sin

Defined as:

Coerces the invocant (or in the sub form, the argument) to Numeric, interprets it as radians, returns its sine.

Note that Perl 6 is no computer algebra system, so `sin(pi)` typically does not produce an exact 0, but rather a very small floating-point number.

## (Cool) routine asin

Defined as:

Coerces the invocant (or in the sub form, the argument) to Numeric, and returns its arc-sine in radians.

## (Cool) routine cos

Defined as:

Coerces the invocant (or in sub form, the argument) to Numeric, interprets it as radians, returns its cosine.

## (Cool) routine acos

Defined as:

Coerces the invocant (or in sub form, the argument) to Numeric, and returns its arc-cosine in radians.

## (Cool) routine tan

Defined as:

Coerces the invocant (or in sub form, the argument) to Numeric, interprets it as radians, returns its tangent.

## (Cool) routine atan

Defined as:

Coerces the invocant (or in sub form, the argument) to Numeric, and returns its arc-tangent in radians.

## (Cool) routine atan2

Defined as:

Coerces self and argument to Numeric, using them to compute the two-argument arc-tangent in radians.

The first argument defaults to 1, so in the first case the function will return the angle θ in radians between a vector that goes from origin to the point (3, 1) and the x axis.

## (Cool) routine sec

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its secant, that is, the reciprocal of its cosine.

## (Cool) routine asec

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-secant in radians.

## (Cool) routine cosec

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its cosecant, that is, the reciprocal of its sine.

## (Cool) routine acosec

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-cosecant in radians.

## (Cool) routine cotan

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its cotangent, that is, the reciprocal of its tangent.

## (Cool) routine acotan

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-cotangent in radians.

## (Cool) routine sinh

Defined as:

Coerces the invocant (or in method form, its argument) to Numeric, and returns its Sine hyperbolicus.

## (Cool) routine asinh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse Sine hyperbolicus.

## (Cool) routine cosh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Cosine hyperbolicus.

## (Cool) routine acosh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse Cosine hyperbolicus.

## (Cool) routine tanh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians and returns its Tangent hyperbolicus.

## (Cool) routine atanh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse tangent hyperbolicus.

## (Cool) routine sech

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Secant hyperbolicus.

## (Cool) routine asech

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic secant.

## (Cool) routine cosech

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Hyperbolic cosecant.

## (Cool) routine acosech

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic cosecant.

## (Cool) routine cotanh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Hyperbolic cotangent.

## (Cool) routine acotanh

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic cotangent.

## (Cool) routine cis

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and returns cos(argument) + i*sin(argument).

## (Cool) routine log

Defined as:

Coerces the arguments (including the invocant in the method form) to Numeric, and returns its Logarithm to base `\$base`, or to base `e` (Euler's Number) if no base was supplied (Natural logarithm). Returns `NaN` if `\$base` is negative. Throws an exception if `\$base` is `1`.

## (Cool) routine log10

Defined as:

Coerces the invocant (or in the sub form, the invocant) to Numeric, and returns its Logarithm to base 10, that is, a number that approximately produces the original number when raised to the power of 10. Returns `NaN` for negative arguments and `-Inf` for `0`.

## (Cool) routine exp

Defined as:

Coerces the arguments (including the invocant in the method from) to Numeric, and returns `\$base` raised to the power of the first number. If no `\$base` is supplied, `e` (Euler's Number) is used.

## (Cool) method unpolar

Defined as:

Coerces the arguments (including the invocant in the method form) to Numeric, and returns a complex number from the given polar coordinates. The invocant (or the first argument in sub form) is the magnitude while the argument (i.e. the second argument in sub form) is the angle. The angle is assumed to be in radians.

## (Cool) routine round

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it to the unit of `\$unit`. If `\$unit` is 1, rounds to the nearest integer.

Always rounds up if the number is at mid-point:

Pay attention to types when using this method, as ending up with the wrong type may affect the precision you seek to achieve. For Real types, the type of the result is the type of the argument (Complex argument gets coerced to Real, ending up a Num). If rounding a Complex, the result is Complex as well, regardless of the type of the argument.

## (Cool) routine floor

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it downwards to the nearest integer.

## (Cool) method fmt

Defined as:

Uses `\$format` to return a formatted representation of the invocant; equivalent to calling sprintf with `\$format` as format and the invocant as the second argument. The `\$format` will be coerced to Stringy and defaults to `'%s'`.

## (Cool) routine ceiling

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it upwards to the nearest integer.

## (Cool) routine truncate

Defined as:

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it towards zero.

## (Cool) routine ord

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the Unicode code point number of the first code point.

The inverse operation is chr.

Mnemonic: returns an ordinal number

## (Cool) method path

Defined as:

DEPRECATED. It's been deprecated as of the 6.d version. Will be removed in the next ones.

Stringifies the invocant and converts it to IO::Path object. Use the `.IO method` instead.

## (Cool) routine chr

Defined as:

Coerces the invocant (or in sub form, its argument) to Int, interprets it as a Unicode code points, and returns a string made of that code point.

The inverse operation is ord.

Mnemonic: turns an integer into a character.

## (Cool) routine chars

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the number of characters in the string. Please note that on the JVM, you currently get codepoints instead of graphemes.

If the string is native, the number of chars will be also returned as a native `int`.

Graphemes are user visible characters. That is, this is what the user thinks of as a “character”.

Graphemes can contain more than one codepoint. Typically the number of graphemes and codepoints differs when `Prepend` or `Extend` characters are involved (also known as Combining characters), but there are many other cases when this may happen. Another example is `\c[ZWJ]` (Zero-width joiner).

You can check `Grapheme_Cluster_Break` property of a character in order to see how it is going to behave:

You can read more about graphemes in the Unicode Standard, which Perl 6 tightly follows, using a method called NFG, normal form graphemes for efficiently representing them.

## (Cool) routine codes

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the number of Unicode code points.

The same result will be obtained with

ords first obtains the actual codepoints, so there might be a difference in speed.

## (Cool) routine flip

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns a reversed version.

## (Cool) routine trim

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with both leading and trailing whitespace stripped.

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with leading whitespace stripped.

## (Cool) routine trim-trailing

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with trailing whitespace stripped.

## (Cool) routine lc

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it case-folded to lower case.

## (Cool) routine uc

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it case-folded to upper case (capital letters).

## (Cool) routine fc

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns the result a Unicode "case fold" operation suitable for doing caseless string comparisons. (In general, the returned string is unlikely to be useful for any purpose other than comparison.)

## (Cool) routine tc

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the first letter case-folded to title case (or where not available, upper case).

## (Cool) routine tclc

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the first letter case-folded to title case (or where not available, upper case), and the rest of the string case-folded to lower case.

## (Cool) routine wordcase

Defined as:

Coerces the invocant (or in sub form, the first argument) to Str, and filters each word that smartmatches against `\$where` through the `&filter`. With the default filter (first character to upper case, rest to lower) and matcher (which accepts everything), this title-cases each word:

With a matcher:

With a customer filter too:

## (Cool) routine samecase

Defined as:

Coerces the invocant (or in sub form, the first argument) to Str, and returns a copy of `\$string` with case information for each individual character changed according to `\$pattern`.

Note: The pattern string can contain three types of characters, i.e. uppercase, lowercase and caseless. For a given character in `\$pattern` its case information determines the case of the corresponding character in the result.

If `\$string` is longer than `\$pattern`, the case information from the last character of `\$pattern` is applied to the remaining characters of `\$string`.

## (Cool) routine uniprop

Defined as:

Returns the unicode property of the first character. If no property is specified returns the General Category. Returns a Bool for Boolean properties. A uniprops routine can be used to get the property for every character in a string.

## (Cool) sub uniprops

Defined as:

Interprets the invocant as a Str, and returns the unicode property for each character as a Seq. If no property is specified returns the General Category. Returns a Bool for Boolean properties. Similar to uniprop, but for each character in the passed string.

## (Cool) routine uniname

Defined as:

Interprets the invocant or first argument as a Str, and returns the Unicode codepoint name of the first codepoint of the first character. See uninames for a routine that works with multiple codepoints, and uniparse for the opposite direction.

## (Cool) routine uninames

Defined as:

Returns of a Seq of Unicode names for the all the codepoints in the Str provided.

Note this example, which gets a Seq where each element is a Seq of all the codepoints in that character.

See uniparse for the opposite direction.

## (Cool) routine unimatch

Defined as:

Checks if the given integer codepoint or the first letter of the string given have a unicode property equal to the value you give. If you supply the Unicode property to be checked it will only return True if that property matches the given value.

## (Cool) routine chop

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the last character removed.

## (Cool) routine chomp

Defined as:

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the last character removed, if it is a logical newline.

## (Cool) routine substr

Defined as:

Coerces the invocant (or in the sub form, the first argument) to Str, and calls Str.substr with the arguments.

## (Cool) routine substr-rw

Defined as:

Coerces the invocant (or in the sub form, the first argument) to Str, and calls Str.substr-rw with the arguments.

## (Cool) routine ords

Defined as:

Coerces the invocant (or in the sub form, the first argument) to Str, and returns a list of Unicode codepoints for each character.

This is the list-returning version of ord. The inverse operation in chrs. If you are only interested in the number of codepoints, codes is a possibly faster option.

## (Cool) routine chrs

Defined as:

Coerces the invocant (or in the sub form, the argument list) to a list of integers, and returns the string created by interpreting each integer as a Unicode codepoint, and joining the characters.

This is the list-input version of chr. The inverse operation is ords.

## (Cool) routine split

Defined as:

[1]

Coerces the invocant (or in the sub form, the second argument) to Str, and splits it into pieces based on delimiters found in the string.

If `\$delimiter` is a string, it is searched for literally and not treated as a regex. You can also provide multiple delimiters by specifying them as a list; mixing Cool and Regex objects is OK.

By default, split omits the matches, and returns a list of only those parts of the string that did not match. Specifying one of the `:k, :v, :kv, :p` adverbs changes that. Think of the matches as a list that is interleaved with the non-matching parts.

The `:v` interleaves the values of that list, which will be either Match objects, if a Regex was used as a matcher in the split, or Str objects, if a Cool was used as matcher. If multiple delimiters are specified, Match objects will be generated for all of them, unless all of the delimiters are Cool.

`:k` interleaves the keys, that is, the indexes:

`:kv` adds both indexes and matches:

and `:p` adds them as Pairs, using the same types for values as `:v` does:

You can only use one of the `:k, :v, :kv, :p` adverbs in a single call to `split`.

Note that empty chunks are not removed from the result list. For that behavior, use the `:skip-empty` named argument:

## (Cool) routine lines

Defined as:

Coerces the invocant (and in sub form, the argument) to Str, decomposes it into lines (with the newline characters stripped), and returns the list of lines.

This method can be used as part of an `IO::Path` to process a file line-by-line, since `IO::Path` objects inherit from `Cool`, e.g.:

Without any arguments, sub `lines` operates on `\$*ARGFILES`, which defaults to `\$*IN` in the absence of any filenames.

To modify values in place use `is copy` to force a writable container.

## (Cool) method words

Defined as:

Coerces the invocant (or first argument, if it is called as a subroutine) to Str, and returns a list of words that make up the string. Check `Str.words` for additional arguments and its meaning.

`Cool` is the base class for many other classes, and some of them, like Match, can be converted to a string. This is what happens in this case:

The example above illustrates two of the ways `words` can be invoked, with the first argument turned into invocant by its signature. Of course, `Inf` is the default value of the second argument, so in both cases (and forms) it can be simply omitted.

Only whitespace (including no-break space) counts as word boundaries

In this case, Perl 6 includes an (visible only in the source) no-break space; `words` still splits the (resulting) `Str` on it, even if the original array only had 4 elements:

Please see `Str.words` for more examples and ways to invoke it.

## (Cool) routine comb

Defined as:

Returns a Seq of all (or if supplied, at most `\$limit`) matches of the invocant (method form) or the second argument (sub form) against the Regex, string or defined number.

The second statement exemplifies the first form of `comb`, with a `Regex` that excludes multiples of ten, and a `Range` (which is `Cool`) as `\$input`. `comb` stringifies the `Range` before applying `.comb` on the resulting string. Check `Str.comb` for its effect on different kind of input strings. When the first argument is an integer, it indicates the (maximum) size of the chunks the input is going to be divided in

In this case the input is a list, which after transformation to `Str` (which includes the spaces) is divided in chunks of size 3.

## (Cool) method contains

Defined as:

Coerces the invocant `Str`, and calls `Str.contains` on it. Please refer to that version of the method for arguments and general syntax.

Since Int is a subclass of `Cool`, `123` is coerced to a `Str` and then `contains` is called on it.

Seqs are also subclasses of `Cool`, and they are stringified to a comma-separated form. In this case we are also using an `Int`, which is going to be stringified also; `"233"` is included in that sequence, so it returns `True`. Please note that this sequence is not lazy; the stringification of lazy sequences does not include each and every one of their components for obvious reasons.

## (Cool) routine index

Defined as:

Coerces the first two arguments (in method form, also counting the invocant) to a Str, and searches for `\$needle` in the string `\$s` starting from `\$startpos`. It returns the offset into the string where `\$needle` was found, and an undefined value if it was not found.

See the documentation in type Str for examples.

## (Cool) routine rindex

Defined as:

Coerces the first two arguments (including the invocant in method form) to Str and `\$startpos` to Int, and returns the last position of `\$needle` in `\$haystack` not after `\$startpos`. Returns an undefined value if `\$needle` wasn't found.

See the documentation in type Str for examples.

## (Cool) method match

Defined as:

Coerces the invocant to Str and calls the method match on it.

## (Cool) routine roots

Defined as:

Coerces the first argument (and in method form, the invocant) to Numeric and the second (`\$n`) to Int, and produces a list of `\$n` Complex `\$n`-roots, which means numbers that, raised to the `\$n`th power, approximately produce the original number.

For example

## (Cool) method match

Defined as:

Coerces the invocant to Stringy and calls Str.match.

## (Cool) method subst

Defined as:

Coerces the invocant to Stringy and calls Str.subst.

## (Cool) method trans

Defined as:

Coerces the invocant to Str and calls Str.trans

## (Cool) method IO

Defined as:

Coerces the invocant to IO::Path.

## (Cool) routine EVAL

Defined as:

If it is invoked as a method, it calls the subroutine form with invocant as the first argument, `\$code`, passing along named args, if any; this coerces Cool `\$code` to Str. If `\$code` is a Blob, it'll be processed using the same encoding as the `\$lang` compiler would: for `perl6` `\$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, such as a variable or string with embedded code, is illegal by default. This can be overridden in any of several ways:

In case the `MONKEY-SEE-NO-EVAL` pragma is not activated, the compiler will complain with a `EVAL is a very dangerous function!!!` exception. And it is essentially right, since that will run arbitrary code with the same permissions as the program. You should take care of cleaning the code that is going to pass through EVAL if you activate the `MONKEY-SEE-NO-EVAL` pragma.

Please note that you can interpolate to create routine names using quotation, as can be seen in this example or other ways to interpolate to create identifier names. This only works, however, for already declared functions and other objects and is thus safer to use.

Symbols in the current lexical scope are visible to code in an `EVAL`.

However, since the set of symbols in a lexical scope is immutable after compile time, an `EVAL` can never introduce symbols into the surrounding scope.

Furthermore, the `EVAL` is evaluated in the current package:

And also in the current language, meaning any added syntax is available:

An `EVAL` statement evaluates to the result of the last statement:

`EVAL` is also a gateway for executing code in other languages:

You need to have `Inline::Perl5` for this to work correctly.

## (Cool) sub EVALFILE

Defined as:

Slurps the specified file and evaluates it. Behaves the same way as `EVAL` with regard to Blob decoding, scoping, and the `\$lang` parameter. Evaluates to the value produced by the final statement in the file.

## (Cool) routine unpolar

Defined as:

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`

## (Cool) routine printf

Defined as:

As a method, takes the object as a format using the same language as `Str.sprintf`; as a sub, its first argument will be the format string, and the rest of the arguments will be substituted in the format following the format conventions.

## (Cool) routine sprintf

Defined as:

Formats and outputs a string, following the same language as `Str.sprintf`, using as such format either the object (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` returns a `Str`, not a literal.

The `\$format` is scanned for `%` characters. Any `%` introduces a format token. Directives guide the use (if any) of the arguments. When a directive other than `%` is used, it indicates how the next argument passed is to be formatted into the string to be created.

[2]

The directives are:

 % a literal percent sign c a character with the given codepoint s a string d a signed integer, in decimal u an unsigned integer, in decimal o an unsigned integer, in octal x an unsigned integer, in hexadecimal e a floating-point number, in scientific notation f a floating-point number, in fixed decimal notation g a floating-point number, in %e or %f notation X like x, but using uppercase letters E like e, but using an uppercase "E" G like g, but with an uppercase "E" (if applicable) b an unsigned integer, in binary

Compatibility:

 i a synonym for %d D a synonym for %ld U a synonym for %lu O a synonym for %lo F a synonym for %f

Modifiers change the meaning of format directives, but are largely no-ops (the semantics are still being determined).

 h interpret integer as native "short" (typically int16) NYI l interpret integer as native "long" (typically int32 or int64) NYI ll interpret integer as native "long long" (typically int64) NYI L interpret integer as native "long long" (typically uint64) NYI q interpret integer as native "quads" (typically int64 or larger)

Between the `%` and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are:

### Format parameter index

An explicit format parameter index, such as `2\$`. By default, `sprintf` will format the next unused argument in the list, but this allows you to take the arguments out of order:

### Flags

One or more of:

 space prefix non-negative number with a space + prefix non-negative number with a plus sign - left-justify within the field 0 use leading zeros, not spaces, for required padding # ensure the leading "0" for any octal, prefix non-zero hexadecimal with "0x" or "0X", prefix non-zero binary with "0b" or "0B"

For example:

When a space and a plus sign are given as the flags at once, the space is ignored:

When the `#` flag and a precision are given in the `%o` conversion, the necessary number of 0s is added at the beginning. If the value of the number is `0` and the precision is 0, it will output nothing; precision 0 or smaller than the actual number of elements will return the number with 0 to the left:

### Vector flag

This flag tells Perl 6 to interpret the supplied string as a vector of integers, one for each character in the string. Perl 6 applies the format to each integer in turn, then joins the resulting strings with a separator (a dot, `'.'`, by default). This can be useful for displaying ordinal values of characters in arbitrary strings:

You can also explicitly specify the argument number to use for the join string using something like `*2\$v`; for example:

### (Minimum) Width

Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with `*` ) or from a specified argument (e.g., with `*2\$`):

If a field width obtained through `*` is negative, it has the same effect as the `-` flag: left-justification.

### Precision, or maximum width

You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a `.` followed by a number. For floating-point formats, except `g` and `G`, this specifies how many places right of the decimal point to show (the default being 6). For example:

For "g" and "G", this specifies the maximum number of digits to show, including those prior to the decimal point and those after it; for example:

For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the `0` flag is ignored:

(Note that this feature currently works for unsigned integer conversions, but not for signed integer.)

For string conversions, specifying a precision truncates the string to fit the specified width:

You can also get the precision from the next argument using `.*`, or from a specified argument (e.g., with `.*2\$`):

If a precision obtained through `*` is negative, it counts as having no precision at all:

### Size

For numeric conversions, you can specify the size to interpret the number as using `l`, `h`, `V`, `q`, `L`, or `ll`. For integer conversions (`d` `u` `o` `x` `X` `b` `i` `D` `U` `O`), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl 6:

(Note: None of the following have been implemented.)

 hh interpret integer as C type "char" or "unsigned char" h interpret integer as C type "short" or "unsigned short" j interpret integer as C type "intmax_t", only with a C99 compiler (unportable) l interpret integer as C type "long" or "unsigned long" q, L, or ll interpret integer as C type "long long", "unsigned long long", or "quad" (typically 64-bit integers) t interpret integer as C type "ptrdiff_t" z interpret integer as C type "size_t"

### Order of arguments

Normally, `sprintf` takes the next unused argument as the value to format for each format specification. If the format specification uses `*` to require additional arguments, these are consumed from the argument list in the order they appear in the format specification before the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument.

So:

uses `\$a` for the width, `\$b` for the precision, and `\$c` as the value to format; while:

would use `\$a` for the width and precision and `\$b` as the value to format.

Here are some more examples; be aware that when using an explicit index, the `\$` may need escaping:

Other examples:

Special case: `sprintf("<b>%s</b>\n", "Perl 6")` will not work, but one of the following will: