sub substr

Documentation for sub substr, assembled from the following types:

class Cool

From Cool

(Cool) routine substr

Defined as:

sub substr(Str(Cool$str$from$chars?)
method substr($from$chars?)

Coerces the invocant (or in the sub form, the first argument) to Str, and returns the string starting from offset $from. If $chars is supplied, at most $chars characters are returned.

say 'zenith'.substr(2);         # OUTPUT: «nith␤» 
say 'zenith'.substr(03);      # OUTPUT: «zen␤» 
# works on non-strings too: 
say 20151224.substr(6);         # OUTPUT: «24␤» 
# sub form: 
say substr "zenith"03;      # OUTPUT: «zen␤» 

If the $from parameter is a Callable, it is called with the number of chars in the string as argument. This allows easy indexing relative to the end:

say 20151224.substr(*-2);       # OUTPUT: «24␤» 

class Str

From Str

(Str) routine substr

multi sub    substr(Str:D $sInt:D $fromInt:D $chars = $s.chars - $from --> Str:D)
multi sub    substr(Str:D $sRange $from-to --> Str:D)
multi method substr(Str:D $s: Int:D $fromInt:D $chars = $s.chars - $from --> Str:D)
multi method substr(Str:D $s: Range $from-to --> Str:D)

Returns a part of the string, starting from the character with index $from (where the first character has index 0) and with length $chars. If a range is specified, its first and last indices are used to determine the size of the substring.


substr("Long string"63);     # RESULT: «tri» 
substr("Long string"6);        # RESULT: «tring» 
substr("Long string"6*-1);   # RESULT: «trin» 
substr("Long string"*-3*-1); # RESULT: «in»