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

后端 未结 4 1344
暖寄归人
暖寄归人 2020-12-05 02:36

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);
         


        
4条回答
  •  被撕碎了的回忆
    2020-12-05 03:05

    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.

提交回复
热议问题