user2017810 user2017810 - 7 months ago 9
Perl Question

Change order of reading strings perl

I have to read strings from a file, split them into two-character chunks and write it into another file.

I have written the below snippet which works but I need to change the order of the input strings. For example if there are nine strings I need to read it like 2, 8, 4, 5, 7, 6, 3, 1, 9 or something like that

use strict;
use warnings;
use autodie; #So I dont have to worry about my file

open( my $fh, "<", "dataFile.txt" );
open( my $fh1, '>', 'report.txt' );



while ( my $line = <$fh> ) {
chomp $line;

my @line_array = split( /\s+/, $line );
for ( unpack( "(A2)*", $line ) ) {
print "$_\n";
print $fh1 "$_\n";
}
}

Answer

I've tried to work out what your data may look like from the code you've already written

Does this help? It splits each eighteen-character line into nine character pairs and shuffles them according to the order you have in your question before printing them

use strict;
use warnings;
use autodie;

#open my $fh,  '<', dataFile.txt'
open my $fh1, '>', 'report.txt';

my $fh = \*DATA;

use constant FIELD_ORDER => ( 2, 8, 4, 5, 7, 6, 3, 1, 9 );

while ( my $line = <$fh> ) {
    chomp $line;

    my @pairs = unpack '(A2)*', $line;

    print $fh1 "$_\n" for @pairs[ map {$_-1} FIELD_ORDER ];
}

__DATA__
112233445566778899

output

22
88
44
55
77
66
33
11
99
Comments