15.8. Process file with fixed width records

Example 15-7. examples/applications/pack.pl

#!/usr/bin/perl
use strict;
use warnings;
  
# You need to parse a log file where the fields are fixed length long 
# and have no delimiters
# The definition is as follows:
# LABEL:       4 chars
# SOURCE:      8 digits
# DESTINATION: 8 digits
# TYPE:        4 chars
# VALUE:       8 digits
my $file = 'examples/pack.txt';

open(my $data, '<', $file) or die "Could not open '$file'\n";
while (my $line = <$data>) {
    print $line;
    chomp $line;
    my ($label, $source, $dest, $type, $value) = unpack ("A4 A8 A8 A4 A8", $line);
    print "LABEL: $label SOURCE: $source DEST: $dest TYPE: $type VALUE: $value\n";
}

Example 15-8. examples/applications/pack.txt

ALD37845566974923342XYZ24023984
QRW49327408234028434ERD24448009

If you are interested in on-site trainings by the author, please contact me directly.

Online courses: