[Israel.pm] splitting a string

Gaal Yahas gaal at forum2.org
Tue Sep 26 00:18:35 PDT 2006

On Tue, Sep 26, 2006 at 08:40:19AM +0300, Levenglick Dov-RM07994 wrote:
> I am looking for the most efficient and most elegant (not necessarily
> the same) way of splitting a string in to chunks of a given length.
> E.g. if I have a string '123456' which I want to split in to two chunks
> of 3 characters, I should have ('123', '456') when done.

1) Are you allowed to destroy the input?

2) If there's a remainder, should it be emitted as the last list item?

The simplest way I know for this is:

  @chunks = $input =~ /(.{1,$chunklen})/g;

This assumes (no, yes) as answers to the above questions. If #2 is "no",

  @chunks = $input =~ /(.{$chunklen})/g;

If you want efficiency you'll have to benchmark, but there's a chance a
loop with substr in it might be faster. That'll be destructive.

You might also change your requirements a little and ask for an iterator
interface: call a piece of code each time you want the next chunk. This
will require copying the whole string once per input string. But it's
not destructive.

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list