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

tadman has asked for the wisdom of the Perl Monks concerning the following question: (strings)

As in:     @bits = chunk($scalar, $bytes); Which would return $scalar in @bits, each $bytes size, plus the remainder in the last entry.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I split a string into chunks of size n bytes?
by Masem (Monsignor) on Apr 23, 2001 at 22:37 UTC
    @bits = ( $scalar =~ /.{1,$bytes}/gs );

    Edited by tye to add "s" on the end otherwise "." won't match newlines.

    Edited by chipmunk to change {0,$bytes} to {1,$bytes}; otherwise a null string is matched at the end.

Re: How can I split a string into chunks of size n bytes?
by davido (Cardinal) on Oct 02, 2003 at 23:35 UTC
    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;

      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.

Re: How can I split a string into chunks of size n bytes?
by MeowChow (Vicar) on Apr 24, 2001 at 10:15 UTC
    push @bits, substr $scalar, 0, $bytes, '' while length $scalar;