Majian wrote:
Dear list:

Hello,

 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;

Or more simply as:

my @groups = unpack "(a$n)*", $string;

Or as:

my @groups = $string =~ /.{$n}/sg;


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 .

print @groups;

Is the same as saying:

print join '', @groups;


Each $n byte string is printed next to each other because the default value of the $, variable is ''.


You could print it like this:

print "@groups";

Which is the same as saying:

print join ' ', @groups;

Because the default value of the $" variable is ' '.




John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to