Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
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
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: (6)
As of 2015-07-29 01:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls