[ACCEPTED]-How can I split a string into chunks of two characters each in Perl?-split
@array = ( $string =~ m/../g );
The pattern-matching operator behaves in 6 a special way in a list context in Perl. It 5 processes the operation iteratively, matching 4 the pattern against the remainder of the 3 text after the previous match. Then the 2 list is formed from all the text that matched 1 during each application of the pattern-matching.
If you really must use split
, you can do a :
grep {length > 0} split(/(..)/, $string);
But 4 I think the fastest way would be with unpack
:
unpack("(A2)*", $string);
Both 3 these methods have the "advantage" that 2 if the string has an odd number of characters, it 1 will output the last one on it's own.
Actually, to catch the odd character, you 1 want to make the second character optional:
@array = ( $string =~ m/..?/g );
The pattern passed to split
identifies what separates that 3 which you want. If you wanted to use split, you'd 2 use something like
my @pairs = split /(?(?{ pos() % 2 })(?!))/, $string;
or
my @pairs = split /(?=(?:.{2})+\z)/s, $string;
Those are rather poor 1 solutions. Better solutions include:
my @pairs = $string =~ /..?/sg; # Accepts odd-length strings.
my @pairs = $string =~ /../sg;
my @pairs = unpack '(a2)*', $string;
I see a more-intuitive (if perhaps less-efficient) way 5 to solve this issue: slice-off the required 4 2-character strings from the string with 3 "substr" and push them onto the 2 array with "push":
# Start with a string (a hex number in this case):
my $string = "526f62626965204861746c6579";
# Declare an array to hold the desired 2-char snippets:
my @array;
# Snip snippets from string and put in array:
while ($string) {push @array, substr($string,0,2,"");}
# Say, those look like ASCII codes, don't they?
for (@array) {print chr(hex($_));}
Run that and 1 see what it prints. :-)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.