Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl - split string into 2-character groups [duplicate]

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

like image 709
SF. Avatar asked May 19 '11 13:05

SF.


2 Answers

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

like image 55
Tudor Constantin Avatar answered Oct 10 '22 10:10

Tudor Constantin


Try this:

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

while ($input =~ /(.{2})/g) {
  push @output, $1;
}
like image 34
Doug Avatar answered Oct 10 '22 09:10

Doug