At 9:35 AM +0800 10/21/09, Majian wrote:
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 ?
'
The line

  print @groups;

will print the elements of @groups with no spaces or other characters separating the elements, so you are actually getting the expected output. To actually see the elements, use join to add a separator:

  print join(',',@groups),"\n";


--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to