develooper Front page | perl.beginners | Postings from October 2009

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

Thread Next
From:
Majian
Date:
October 20, 2009 18:37
Subject:
How can I split a string into chunks of size n bytes?
Message ID:
eb686fc70910201837h7d13080bx50f7afd8dbf0b972@mail.gmail.com
Dear list:
 I have a  question  on learning Perl . Please give me a help .

 The problem is :

How can I split a string into chunks of size n bytes?Like this :
#!/usr/bin/perl

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

print @groups;


when I run it, the screen displays the $string value, like
"1234567890abcdefghijABCDEFGHIJK"

but I want the groups and the group size is 2 .

Is it wrong that this phrase (length($string)/$n ?


Thanks in advance !!

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About