rovf has asked for the wisdom of the Perl Monks concerning the following question:
Assume I have a string $s with length greater than $ml. I would like to create an array containing the successive pieces of $s, each piece with length $ml (the last piece probably shorter). For example:
Restrictions: Must run under perl 5.8 without additional modules (CPAN) installed.$s='abcdefg'; $ml=3; @result=('abc','def','g');
The first thing which came to my mind, was to use split to turn the string into an array of characters,
and then, using a loop, use Arrayslices to extract the individual parts of the string, i.e. inside a loop something like:@sc=split(//,$s);
But even if we ignore for a moment the problem that the last slice would be out-of-bounds (which is trivial to solve), this solution is terribly ugly. Is there a better way to do it? Maybe with a regexp containing .{1,$ml}, but I don't see how to use this to build up my resulting array (I would need kind of a "generator"). Any ideas?push @result,join('',@sc[$i*$ml .. $i*($ml+1)-1]);
|
|---|