in reply to Using split() to divide a string by length

I'm not sure split is the right choice for extracting fixed-length substrings. Isn't that really what substr is for (I mean, if you don't want to use unpack)?

sub split_len { ## split_len( $chars, $string[, $limit] ) ## - splits $string into chunks of $chars chars ## - limits number of segments returned to $limit, if provided my ($chars, $string) = @_; my ($i, @result); for ($i = 0; ($i+$chars) < length($string); $i+=$chars) { last if (defined $limit && @result >= $limit); push @result, substr($string, $i, $chars); } # deal with any short remainders return @result if (defined $limit && @result >= $limit); if ($i > length($string)-$chars) { push @result, substr($string, $i); } return @result; }
<-radiant.matrix->
A collection of thoughts and links from the minds of geeks
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

Replies are listed 'Best First'.
Re^2: Using split() to divide a string by length
by Hue-Bond (Priest) on Apr 19, 2006 at 10:18 UTC
    # 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