#!/user/bin/perl
use strict;
use warnings;
#----------- define field mappings ---------------------
# hash to map from field i in input to field j in output
# field i is the key to hash, field j is the value of hash
my %from_to = (
1 => 4,
2 => 2,
3 => 1,
4 => 3,
);
# field length hash...key is the field number, value of hash
# is the length in characters. Presumes the length of the
# input and output fields are the same.
my %field_len = (
1 => 10,
2 => 4,
3 => 6,
4 => 6,
);
#---------- setup decode string --------
my $decode_string = "";
foreach my $num (sort keys %from_to)
{$decode_string .= 'A' . $field_len{$num} . ' '};
#-------------- process files ----------
my @input;
my @output;
foreach my $in_record (<DATA>)
{
chomp($in_record);
print $in_record . " ---> ";
@input =(unpack $decode_string,$in_record);
foreach my $index (sort keys %from_to)
{$output[($from_to{$index}-1)] = $input[($index-1)]};
my $out_record = join "",@output;
print $out_record . "\n";
}
exit(0);
__END__
AAAAAAAAAA1111BBBBBB222222
BBBBBBBBBB2222CCCCCC333333
CCCCCCCCCC3333DDDDDD444444
I used the two hashes to contain the mapping of the input field to the output field (%from_to) and the field lengths (%field_len). You, of course, could use whatever strategy you want. I also have prints in to see how things work. I had tried to make it more compact by trying to use a dynamic strategy for specifying the array slice as part of the join..decode line. But I couln't figure out (or remember) how to do that.
|