Perl Script to search and replace in .SQL query file with user inputs

Posted by T.Mount on Stack Overflow See other posts from Stack Overflow or by T.Mount
Published on 2010-06-01T20:40:47Z Indexed on 2010/06/01 20:43 UTC
Read the original article Hit count: 164

Filed under:
|

I have a .SQL file containing a large number of queries. They are being run against a database containing data for multiple states over multiple years. The machine I am running this on can only handle running the queries for one state, in one year, at a time.

I am trying to create a Perl script that takes user input for the state abbreviation, the state id number, and the year. It then creates a directory for that state and year. Then it opens the "base" .SQL file and searches and replaces the base state id and year with the user input, and saves this new .SQL file to the created directory.

The current script I have (below) stops at

open(IN,'<$infile')

with

"Can't open [filename]"

It seems that it is having difficulty finding or opening the .SQL file. I have quadruple-checked to make sure the paths are correct, and I have even tried replacing the

$path

with an absolute path for the base file. If it was having trouble with creating the new file I'd have more direction, but since it can't find/open the base file I do not know how to proceed.

 #!/usr/local/bin/perl

use Cwd;
$path = getcwd();
#Cleans up the path
$path =~ s/\\/\//sg;

#User inputs
print "What is the 2 letter state abbreviation for the state? Ex. 'GA'\n";
$stlet = <>;
print "What is the 2 digit state abbreviation for the state? Ex. '13'\n";
$stdig = <>;
print "What four-digit year are you doing the calculations for? Ex. '2008'\n";
$year = <>;

chomp $stlet;
chomp $stdig;
chomp $year;

#Creates the directory
mkdir($stlet);
$new = $path."\/".$stlet;
mkdir("$new/$year");

$infile = '$path/Base/TABLE_1-26.sql';
$outfile = '$path/$stlet/$year/TABLE_1-26.sql';

open(IN,'<$infile') or die "Can't open $infile: $!\n";
open(OUT,">$infile2") or die "Can't open $outfile: $!\n";
print "Working...";

while (my $search = <IN>) {
chomp $search;
$search =~ s/WHERE pop.grp  = 132008/WHERE pop.grp  = $stdig$year/g;

print OUT "$search\n";  
}
close(IN);

close(OUT);

I know I also probably need to tweak the regular expression some, but I'm trying to take things one at a time. This is my first Perl script, and I haven't really been able to find anything that handles .SQL files like this that I can understand.

Thank you!

© Stack Overflow or respective owner

Related posts about mysql

Related posts about perl