Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to parse a fix width text file

Tags:

perl

I'm trying to parse a text file that look like this:

aaa aaa aaa
111 111 111
bbb bbb bbb
222 222 222
ccc ccc ccc
333 555 666
ddd ddd ddd
444 444 444

In order to get a result like this :

 aaa aaa111 aaa
 bbb bbb222 bbb
 ccc ccc333 ccc
 ddd ddd444 ddd

My code looks like this:

use strict;
use warnings;
use Data::Dumper;

my @array;  
my $flag = "";
my $permit;
my $adrr;
my $descr;
my $str_no;

my $file = 'Permit.txt';
open my $fh, '+<', $file
    or die "Cannot open 'file ' for writing: $!";

while (my $line = <$fh>) {
    chomp($line);
    if ($line =~ /^[abcd]/) {
        $str_no = substr($flag,0,3);
        $permit = substr($line, 0, 3);
        $adrr = substr($line, 4, 3);
        $descr = substr($line, 8, 3);
        if($flag) {
            if ($str_no) {
                $adrr .= $str_no;   
        }       

        }
        push @array, {permi => $permit, adr => $adrr, desc => $descr};
        $flag = ""; 

    } else {
            $flag = $line;
    }
}
print Dumper(\@array);

But this pushes all my values from the numbers row down concatenating the first number to the second letters row.

like image 759
Dragos Trif Avatar asked Feb 17 '26 16:02

Dragos Trif


1 Answers

Read the file two lines at a time:

use strict;
use warnings;

while (<DATA>) {
    my @fields  = split;
    my @numbers = split(' ', <DATA>);
    $fields[1] .= $numbers[0];

    print "@fields\n";
}

__DATA__
aaa aaa aaa
111 111 111
bbb bbb bbb
222 222 222
ccc ccc ccc
333 555 666
ddd ddd ddd
444 444 444

Output:

aaa aaa111 aaa
bbb bbb222 bbb
ccc ccc333 ccc
ddd ddd444 ddd
like image 91
Matt Jacob Avatar answered Feb 21 '26 13:02

Matt Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!