Abhishek Abhishek - 1 month ago 4
Perl Question

separating array elements every 4 characters in array

I have an array like this

my @array=(0x0B0x0C0x4A0x000x010x000x000x020)

I want to insert comma for each of the 4 character what i mean here is

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

#! /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;
#first approach
unpack("(A2)*", $hex_array);
print {$output_fh} join("U, ", @hex_array);

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

but both approaches did not work. What would be an appropriate solution?


Please try this:

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

Thanks to @derobert