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
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.
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.
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With