Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Answer: How can I split a string into chunks of size n bytes?

by davido (Archbishop)
on Oct 02, 2003 at 23:35 UTC ( #296122=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > How can I split a string into chunks of size n bytes? - Answer contributed by davido

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2016-08-31 23:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The best thing I ever won in a lottery was:















    Results (437 votes). Check out past polls.