in reply to Re: how to store text file information into my sql database
in thread how to store text file information into my sql database

You can also generate the unpack string from the header itself if you know that the position of the keys in the header defines the columns in the rest of the file:

#!/usr/bin/perl use strict; use warnings; my $header = <DATA>; my @p; push @p, length $1 while $header =~ /(\S+\s*)/g; my $unpack_pattern = join "", map { 'A'.$_ } @p[0..$#p-1]; $unpack_pattern .= "A*"; while (<DATA>){ chomp; my @vals = unpack($unpack_pattern,$_); print join "|", @vals,"\n"; #$sth->execute(@vals); } __DATA__ StudentId Name Dept address city 1 Chellappa CSE 22 xx-colony 2nd street coimbatore 2 Vijay IT 23 yy colony coimbatore

Replies are listed 'Best First'.
Re^3: how to store text file information into my sql database
by mr_ron (Deacon) on Dec 28, 2015 at 20:47 UTC

    There is a CPAN module DataExtract::FixedWidth for handling the fixed unpacking details. I tried it on the test sample and it seems to work fine.

    use strict; use warnings; use DataExtract::FixedWidth; use Data::Dumper; my $de = DataExtract::FixedWidth->new({ header_row => scalar(<DATA>) }); while (my $l = <DATA>) { my $fields = $de->parse($l); print Dumper($fields); } __DATA__ StudentId Name Dept address city 1 Chellappa CSE 22 xx-colony 2nd street coimbatore 2 Vijay IT 23 yy colony coimbatore
    Ron