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

后端 未结 4 1336
暖寄归人
暖寄归人 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 02:42

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

    @array = ( $string =~ m/..?/g );
    
    0 讨论(0)
  • 2020-12-05 02:57
    @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.

    0 讨论(0)
  • 2020-12-05 02:59

    The pattern passed to split identifies what separates that which you want. If you wanted to use split, you'd use something like

    my @pairs = split /(?(?{ pos() % 2 })(?!))/, $string;
    

    or

    my @pairs = split /(?=(?:.{2})+\z)/s, $string;
    

    Those are rather poor solutions. Better solutions include:

    my @pairs = $string =~ /..?/sg;  # Accepts odd-length strings.
    
    my @pairs = $string =~ /../sg;
    
    my @pairs = unpack '(a2)*', $string;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题