Perl - split string in 2 character groups

Possible duplicate:
How to split a string into pieces of two characters in Perl?

I wanted to split a string into an array grouping it using two-character fragments:

$input = "DEADBEEF"; @output = split(/(..)/,$input); 

This approach makes every other element empty.

  $VAR1 = ''; $VAR2 = 'DE'; $VAR3 = ''; $VAR4 = 'AD'; $VAR5 = ''; $VAR6 = 'BE'; $VAR7 = ''; $VAR8 = 'EF'; 

How to get a continuous array?

  $VAR1 = 'DE'; $VAR2 = 'AD'; $VAR3 = 'BE'; $VAR4 = 'EF'; 

(... other than getting the first result and deleting any other line ...)

+4
source share
2 answers

you can easily filter out empty entries with:

 @output = grep { /.+/ } @output ; 

Edit: You can get the same thing easier:

 $input = "DEADBEEF"; my @output = ( $input =~ m/.{2}/g ); 

Change 2 more versions:

 $input = "DEADBEEF"; my @output = unpack("(A2)*", $input); 

Hello

+3
source

Try the following:

 $input = "DEADBEEF"; @output = (); while ($input =~ /(.{2})/g) { push @output, $1; } 
+2
source

All Articles