Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: How to process variable length fields in delimited file.

by GrandFather (Sage)
on Oct 06, 2016 at 01:37 UTC ( #1173375=note: print w/replies, xml ) Need Help??

in reply to How to process variable length fields in delimited file.

If the fixed fields really are fixed length rather than space delimited then you can pull the lines apart using a template like this:

use strict; use warnings; my @template = ( 'ssn 9', 'employee number 5', 'employee name *', 'hire date 8', 'address *', 'state 2', 'city *', 'zip 5' ); while (my $line = <DATA>) { chomp $line; my %fields; for my $field (@template) { my ($name, $length) = $field =~ /(.*) (.+)/; $line =~ s/^\s+//; $length = substr $line, 0, index ($line, ' ') + 1, '' if $leng +th eq '*'; $fields{$name} = substr $line, 0, $length, ''; } print "$_: $fields{$_}\n" for keys %fields; } __DATA__ 123445678 45612 11 Steve Smith 11012015 16 1001 Main Street GA 7 Atlan +ta 30553


employee number: 45612 state: GA hire date: 11012015 city: Atlanta zip: 30553 ssn: 123445678 employee name: Steve Smith address: 1001 Main Street

For output I'd strongly recommend using a module like Text::CSV to generate correctly formatted CSV files.

Premature optimization is the root of all job security

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1173375]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2018-09-22 09:08 GMT
Find Nodes?
    Voting Booth?
    Eventually, "covfefe" will come to mean:

    Results (190 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!