This function builds and returns a hash when passed a filename and the number of fields. Rudimentary best guess on the number of fields is implemented, but in reality just takes the first line and uses the number of fields in it to compare against the rest. It would be called as such my %hash = build_hash("somefile.csv", "10");
This is from a work in progress which takes a csv file pulls out the fields specified by the user and drops them in another file. This other file is processed by mailing software. Once the mailing software is finished it spits out a csv file and the script puts it all back together again with the new data.
#############
sub build_hash
#############
{
my ( $file_, $numfields_ ) = @_;
my $line = 0;
my ( %hash, $cvsfile, $errorfile );
open $cvsfile, $file_ or
confess "Unable to open $file_\n";
open $errorfile, ">", "${file_}\.err" or
confess "Unable to open ${file_}\.err\n";
for (<$cvsfile>)
{
chomp($_);
s/"//g;
$line++;
my (@linedata) = split /,/, $_;
# Make a best guess (using line 1)
if ( $line == 1 and ! defined ( $numfields_ ) )
{
$numfields_ = scalar(@linedata)
}
unless ( scalar(@linedata) == $numfields_ )
{
print $errorfile "$_\n";
next;
}
my $fieldnum = 0;
for my $info (@linedata)
{
$fieldnum++;
$hash{$line}{$fieldnum} = $info;
}
}
close ($cvsfile);
close ($errorfile);
return %hash or confess "unable to return\n";
}