在数组中每4个字符分隔数组元素

时间:2016-09-26 13:03:02

标签: perl

我有一个像这样的数组

my @array=(0x0B0x0C0x4A0x000x010x000x000x020)

我想为4个字符中的每一个插入逗号,我的意思是

my @array=(0x0B,0x0C,0x4A,0x00,0x01,0x00,0x00,0x02)

我的Perl代码

#! /usr/bin/env perl
use strict;
use warnings;
my @hex_array;
# Name of the input file
my $input_filename = 'input.txt';

# Open the file
open my $input_fh, "<", $input_filename or die $!;

# Name of the output file
my $outut_filename = 'output.txt';

# Open the file
open my $output_fh, "<", $output_filename or die $!;

# reading input file by line by line.
while (<input_fh>)
{
    # here i am extracting all hex value
    while ($_ =~ m/(0x(\d+)(?:[0-9]|[A-f])+)/gi)
    {
        push @hex_array, $1; #push the element
    } # end of second while loop
} # end of first while loop

print @hex_array;

第一种方法

unpack("(A2)*", $hex_array);
print {$output_fh} join("U, ", @hex_array);

第二种方法

foreach my $element (@hex_array)
{
   if (length $element eq 4)
   {
       #print @hex_array;
       print {$output_fh} join("U, ", @hex_array);
   }
}

但两种方法都不起作用。什么是合适的解决方案?

3 个答案:

答案 0 :(得分:0)

如果该数组赋值是它自己的行而不是多行,这将完全适用于您的示例。

use strict;
use warnings;

while (my $line = <DATA>) {
    # find and grab the chunk of hex values inside of the array assignment
    ( my $match ) = $line =~ m/\(((?:0x[0-9A-F]{2})+)\)/;

    next unless $match;

    # make a copy that we will change
    my $replaced = $match;

    # add a comma every four until the last one
    # and insert comma
    $replaced =~ s/(....)(?!$)/$1,/g;

    # but the replacement back into the current line
    $line =~ s/\Q$match\E/$replaced/;

    print $line;
}

__DATA__
my@array=(0x0B0x0C0x4A0x000x010x000x000x02)

只要$line的初始模式不匹配,它就会分崩离析。另请注意,在长字符串十六进制数字的末尾有一个额外的0。我的代码只有在您解决此问题时才有效。

输出:

my@array=(0x0B,0x0C,0x4A,0x00,0x01,0x00,0x00,0x02)

答案 1 :(得分:-1)

你没有

my @hex_array = ( 0x0B0x0C0x4A0x000x010x000x000x020 );

对于初学者来说,这甚至都不能编译。你实际拥有的是以下内容:

my @hex_array = ( '0x0B', '0x0C', '0x4A', '0x00', '0x01', '0x00', '0x00', '0x02' );

获得

my @num_array = ( 0x0B, 0x0C, 0x4A, 0x00, 0x01, 0x00, 0x00, 0x02 );

只需更改

push @hex_array, $1;

push @num_array, hex($1);

答案 2 :(得分:-4)

请试试这个:

my @array = ("0x0B0x0C0x4A0x000x010x000x000x020");
my @outarray = map { (my $vars = $_) =~ s/\w{4}/$&\,/g; $vars; } @array ;
use Data::Dumper;
print Dumper @outarray;

Thanks to @derobert