Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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

( #296122=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How can I split a string into chunks of size n bytes? 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;

Comment on Answer: How can I split a string into chunks of size n bytes?
Select or Download Code
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 studying the Monastery: (9)
As of 2014-09-18 12:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (113 votes), past polls