Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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

Prints:

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (11)
As of 2018-11-14 13:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My code is most likely broken because:
















    Results (172 votes). Check out past polls.

    Notices?