How can I slice a string like Python in Perl 6?

In Python, I can concatenate a string like this:

solo = A quick brown fox jump over the lazy dog
solo[3:5]

I konw substrand combenough, I want, if possible, I want, however. Should I use a role for this?

+3
source share
1 answer

How to cut a string

Strings (represented as a class Str) are treated as separate values, not positional data structures in Perl 6 and therefore cannot be indexed / sliced ​​using the built-in array indexing operator [ ].

As you said, combor substris the way to go:

my $solo = "A quick brown fox jumps over the lazy dog";

dd $solo.comb[3..4].join;   # "ui"
dd $solo.comb[3..^5].join;  # "ui"

dd $solo.substr(3, 2);      # "ui"
dd $solo.substr(3..4);      # "ui"
dd $solo.substr(3..^5);     # "ui"

If you want to change the slice, use substr-rw:

$solo.substr-rw(2..6) = "slow";
dd $solo;  # "A slow brown fox jumps over the lazy dog"

[ ]

, , AT-POS, [ ] :

my $solo = "A quick brown fox jumps over the lazy dog" but role {
    method AT-POS ($i) { self.substr($i, 1) }
}

dd $solo[3..5]; ("u", "i", "c")

, , , [ ] . , [ ] Str:

multi postcircumfix:<[ ]>(Str $string, Int:D $index) {
    $string.substr($index, 1)
}
multi postcircumfix:<[ ]>(Str $string, Range:D $slice) {
    $string.substr($slice)
}
multi postcircumfix:<[ ]>(Str $string, Iterable:D \slice) {
    slice.map({ $string.substr($_, 1) }).join
}

my $solo = "A quick brown fox jumps over the lazy dog";

dd $solo[3];     # "u"
dd $solo[3..4];  # "ui"
dd $solo[3, 5];  # "uc"

[ ] , , , , :

  • , . $solo[*-1]
  • , . $solo[3..*]
  • , . $solo[3..5]:kv
  • . $solo[2..6] = "slow"

, .

, , , , Perl 6, .

+13

Source: https://habr.com/ru/post/1682177/


All Articles