5

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

I wanted to split a string into an array grouping it by 2-character pieces:

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

This approach produces 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 removing every other row...)

Community
  • 1
  • 1
SF.
  • 13,549
  • 14
  • 71
  • 107

2 Answers2

3

you can easily filter out the empty entries with:

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

Edit: You can obtain the same thing easier:

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

Edit 2 another version:

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

Regards

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
2

Try this:

$input = "DEADBEEF";
@output = ();

while ($input =~ /(.{2})/g) {
  push @output, $1;
}
Doug
  • 6,322
  • 3
  • 29
  • 48