2010-06-01 55 views
1

我有一个包含大量查询的.SQL文件。它们针对包含多年来多个州的数据的数据库运行。我运行这台机器只能处理一年内一次运行一个状态的查询。Perl脚本在.SQL查询文件中用用户输入搜索和替换

我正在尝试创建一个Perl脚本,它为用户输入状态缩写,状态ID号和年份。然后它为该州和该年创建一个目录。然后它打开“base”.SQL文件,并用用户输入搜索并替换基本状态ID和年份,并将这个新的.SQL文件保存到创建的目录中。

当前脚本我有(下图)在

open(IN,'<$infile') 

停止与

"Can't open [filename]" 

看来,它是很难找到或打开.SQL文件。我进行了四次检查以确保路径正确,并且我甚至尝试用基准文件的绝对路径替换

$path 

。如果创建新文件时遇到问题,我会有更多的方向,但由于无法找到/打开基本文件,我不知道如何继续。

#!/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); 

我知道我也可能需要调整一些正则表达式,但我试图一次只取一个。这是我的第一个Perl脚本,而且我还没有真正能够找到任何可以处理这种我能理解的.SQL文件的东西。

谢谢!

回答

2
$infile = '$path/Base/TABLE_1-26.sql'; 

在该行的字符串单引号,所以$path不会插值,所以你的程序正在寻找一个名为字面上文件$path/Base/TABLE_1-26.sql

你想

$infile = "$path/Base/TABLE_1-26.sql"; 

或者,更好,

use File::Spec; 
.... 
$infile = File::Spec->catfile($path, 'Base', 'TABLE_1-26.sql'); 

,类似的还有$outfile - 或者是$infile2? :)我强烈建议把use strict;use warnings;放在这个和你未来的脚本的顶部。

+0

非常感谢!而且,呃...我保证我已经注意到了$ infile2/$ outfile的问题......我保证。 – 2010-06-01 21:00:32