http://www.perlmonks.org?node_id=296122


in reply to How can I split a string into chunks of size n bytes?

If by "bytes" you mean ASCII characters from a string, this is a simple and relatively fast solution:

my $string = "1234567890abcdefghijABCDEFGHIJK"; my $n = 2; # $n is group size. my @groups = unpack "a$n" x (length( $string ) /$n ), $string;

This solution has a couple of nice bonuses. First, it will only return complete groups. If you have extra characters that don't complete out a group, it won't give them to you. Second, it is easily adaptable to any other data type that pack and unpack support.

UPDATE: As Aristotle pointed out here, if you want the last group even if it's incomplete you may do this:

my @groups = unpack "a$n" x ((length($string)/$n)-1) . "a*", $string;

Replies are listed 'Best First'.
Re: Answer: How can I split a string into chunks of size n bytes?
by Aristotle (Chancellor) on Oct 02, 2003 at 23:55 UTC
    And in case you don't care whether the last group is complete,
    my @groups = unpack "a$n" x ( ( length($string) / $n ) - 1 ) . "a*", $ +string;

    Makeshifts last the longest.