Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string into chunks of two characters each in Perl?

How do I take a string in Perl and split it up into an array with entries two characters long each?

I attempted this:

@array = split(/../, $string); 

but did not get the expected results.

Ultimately I want to turn something like this

F53CBBA476 

in to an array containing

F5 3C BB A4 76 
like image 283
Jax Avatar asked Dec 16 '08 19:12

Jax


People also ask

How do I split a string into a character in Perl?

If you need to split a string into characters, you can do this: @array = split(//); After this statement executes, @array will be an array of characters. split recognizes the empty pattern as a request to make every character into a separate array element.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


2 Answers

@array = ( $string =~ m/../g ); 

The pattern-matching operator behaves in a special way in a list context in Perl. It processes the operation iteratively, matching the pattern against the remainder of the text after the previous match. Then the list is formed from all the text that matched during each application of the pattern-matching.

like image 64
Bill Karwin Avatar answered Sep 26 '22 02:09

Bill Karwin


If you really must use split, you can do a :

grep {length > 0} split(/(..)/, $string); 

But I think the fastest way would be with unpack :

unpack("(A2)*", $string); 

Both these methods have the "advantage" that if the string has an odd number of characters, it will output the last one on it's own.

like image 44
mat Avatar answered Sep 24 '22 02:09

mat