Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2018-07-22 16:58 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (454 votes). Check out past polls.