While playing with some strings I realized that I really wanted strings to do the Positional role. When I’m inspecting or modifying strings I’m often doing things based on positions so the Positional
interface seems interesting. Just for fun I can adapt the [ ]
to be the interface to substr
:
multi postcircumfix:<[ ]> ( Str:D $s, Int:D $n --> Str ) { $s.substr: $n, 1 } multi postcircumfix:<[ ]> ( Str:D $s, Range:D $r --> Str ) { $s.substr: $r.min, $r.max - $r.min + 1 } multi postcircumfix:<[ ]> ( Str:D $s, List:D $i --> List ) { map( { $s.substr: $_, 1 }, @$i ).List } my $string = 'The quick, purple butterfly'; { # Works my $single = $string[0]; say $single; } { # Works my $substring = $string[5..9]; say $substring; } { # Works my $substring = $string[1,3,5,7]; say $substring; }
This outputs:
T uick, (h u c)
I don’t want to make a habit of this though even if it is interesting.