in reply to Re: Using split() to divide a string by length
in thread Using split() to divide a string by length
# deal with any short remainders
substr does it for us: "If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned". This is my version. Doesn't implement $limit (nor parameter checking) but features $start:
sub split_len { my ($str, $start, $len) = @_; my @ret; for (my $strlen = length $str; $start <= $strlen; $start += $len) +{ push @ret, substr $str, $start, $len; } return @ret; } my $c = join '', 'a'..'z'; print "@{[ split_len $c, 0, 3 ]}\n"; print "@{[ split_len $c, 0, 4 ]}\n"; print "@{[ split_len $c, 3, 4 ]}\n"; __END__ abc def ghi jkl mno pqr stu vwx yz abcd efgh ijkl mnop qrst uvwx yz defg hijk lmno pqrs tuvw xyz
--
David Serrano
|
---|