Thursday, July 10, 2008

Make CREATE TABLE syntax from a csv file using perl

I have a csv file and i have to make the CREATE TABLE statement (which later will be used to create an Oracle table) by reading first and second line of the csv file. First line in the csv file is column headers and the second line is actual data. By reading the first line, i will create column name and by reading the second line, i'll decide the data type for the column.
Below is the perl script for the same: (i am assuming that data in the csv file is tab seperated)

#!/usr/bin/perl

$filename = "test.csv";
open(INFILE, "<", $filename) or die "Can't open $filename for reading: $!\n";
@lines = <INFILE>;
$line1 = $lines[0];
$line2 = $lines[1];

print "$line1 \n";
print "$line2 \n";

close(INFILE);

$tablename = "mytable";
$query = "Create table " . $tablename . "(";

@var1 = split("\t", $line1);
@var2 = split("\t", $line2);
$i = 0;
for $item1 (@var1){
chomp($item1);
$query = $query . $item1 . " ";
$data = $var2[$i++];
print "$item1\t : $data\n";
if($data =~ /^-?\d+$/){
$query = $query . "number(10,0), ";
}
elsif ($data =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/){
$query = $query . "number(10,2), ";
}
else{
$query = $query . "varchar2(50), ";
}
}
$query = substr($query,0, -2);
$query = $query . ");";
print "$query\n";

No comments: