tags:

views:

3698

answers:

3

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
+15  A: 
@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.

Bill Karwin
thanks, that worked perfectly!
Jax
+16  A: 

If you really mean to 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 one it's own.

mat
Unpack is the way to go! +1
Axeman
Since it looks like he is working with hex characters, so this is a bit of a moot point, but A only works for ASCII characters. The split should work for any encoding, but you might want to add a /s to the regex so "\n" will be matched by ".".
Chas. Owens
+5  A: 

Actually, to catch the odd character, you want to make the second character optional:

@array = ( $string =~ m/..?/g );
ChrisD
yup, but it's way slower than unpack.
mat