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 = '';开发者_JAVA百科
$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...)
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
Try this:
$input = "DEADBEEF";
@output = ();
while ($input =~ /(.{2})/g) {
push @output, $1;
}
精彩评论