my $oldrow; my(@fields,@values); while() { chomp; my ($row,$col,$data) = /^\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)\s*=>(.*)$/; # that puts the row number in $1, col number in $2 and data in $3, and in the variable respectively if($oldrow != $row) { if(@fields) { #make sure there is data $query = "INSERT INTO tablename(".(join ',', @fields)." VALUES(".(join ',', @values).')'; ... do DB calls ... @fields = @values = (); } $oldrow = $row; } push @fields, $field_names[$col]; # field name with proper data push @values, db->quote($data); #run data through DB quoter }