I play with a positional interface for strings. I know. How can I slice a string like Python in Perl 6? but I was curious if I could make this thing work only for a giggle.
I came up with this example. The reading positions are fine, but I donβt know how to configure multito handle the assignment:
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
}
multi postcircumfix:<[ ]> ( Str:D $s, Int:D $n, *@a --> Str ) is rw {
put "Calling rw version";
}
my $string = 'The quick, purple butterfly';
{
my $single = $string[0];
say $single;
}
{
my $substring = $string[5..9];
say $substring;
}
{
my $substring = $string[1,3,5,7];
say $substring;
}
{
$string[2] = 'Perl';
say $string;
}
The latter does not work:
T
uick,
(h u c)
Index out of range. Is: 2, should be in 0..0
in block <unit> at substring.p6 line 36
Actually thrown at:
in block <unit> at substring.p6 line 36
I didnβt think it would work. I do not know what signature or features he should do, what I want to do.
Why []does the operator work on Str ?
$ perl6
> "some string"[0]
some string
, [] , Positional, , . [] docs :
@container, a.k.a.
a Str , @container ( ):
> "some string".does( 'Positional' )
True
, - @container?
-, ?
, , [], , ? , [].