perl - 帮助重新编写代码以包含子例程的使用

时间:2011-02-25 18:55:59

标签: perl

我的测试脚本只是将一个perl dbi连接到一个mysql数据库,并给出一个表列表,每个表提取(1)记录。

对于我列出的每个表,我还想将该(1)记录打印到自己的文件中。例如,如果我有一个包含100个表的列表,我应该期望100个唯一文件,每个文件都有(1)个记录。

到目前为止,代码仍然有效,但我对创建子例程感兴趣,将其称为create_file,用于处理#Create file

的代码片段

我不熟悉编写子例程,如果可能的话需要帮助实现它。 我不确定如何调用构建数据的部分。 $data='';

有人能告诉我这样做的好方法吗?谢谢你的帮助。

代码:

# Get list of tables
my @tblist = qx(mysql -u foo-bar -ppassw0rd --database $dbsrc -h $node --port 3306 -ss -e "show tables");

# Data output
    foreach my $tblist (@tblist)
    {
       my $data = '';
       chomp $tblist;

       #Create file
       my $out_file = "/home/$node-$tblist.$dt.dat";
       open (my $out_fh, '>', $out_file) or die "cannot create $out_file: $!";

       my $dbh = DBI->connect("DBI:mysql:database=$dbsrc;host=$node;port=3306",'foo-bar','passw0rd');
       my $sth = $dbh->prepare("SELECT UUID(), '$node', ab, cd, ef, gh, hi FROM $tblist limit 1");
       $sth->execute();
             while (my($id, $nd,$ab,$cd,$ef,$gh,$hi) = $sth->fetchrow_array() ) {
             $data = $data. "__pk__^A$id^E1^A$nd^E2^A$ab^E3^A$cd^E4^A$ef^E5^A$gh^E6^A$hi^E7^D";
             }
             $sth->finish;
             $dbh->disconnect;

       #Create file
       print $out_fh $data;
       close $out_fh or die "Failed to close file: $!";
    };

2 个答案:

答案 0 :(得分:2)

my $dt = "2011-02-25";
my $dbsrc = "...";
my $node = "...";

# Get list of tables
my @tblist = qx(mysql -u foo-bar -ppassw0rd --database $dbsrc -h $node --port 3306 -ss -e "show tables");
my $dbh = DBI->connect("DBI:mysql:database=$dbsrc;host=$node;port=3306",'foo-bar','passw0rd');
foreach my $tblist (@tblist)
{
   # This breaks - chomp is given a list-context
   #extract_data($dbh, chomp($tblist));
   chomp $tblist;
   extract_data($dbh, $tblist);
};
$dbh->disconnect;

sub extract_table
{
     my($dbh, $tblist) = @_;

     my $out_file = "/home/$node-$tblist.$dt.dat";
     open (my $out_fh, '>', $out_file) or die "cannot create $out_file: $!";

     my $sth = $dbh->prepare("SELECT UUID(), '$node', ab, cd, ef, gh, hi FROM $tblist limit 1");
     $sth->execute();
     while (my($id, $nd,$ab,$cd,$ef,$gh,$hi) = $sth->fetchrow_array() ) {
         print $out_fh "__pk__^A$id^E1^A$nd^E2^A$ab^E3^A$cd^E4^A$ef^E5^A$gh^E6^A$hi^E7^D";
     }
     $sth->finish;

     close $out_fh or die "Failed to close file: $!";
};

除非您确实需要为执行的每个语句连接到数据库,否则请在操作之间保持数据库打开。

答案 1 :(得分:2)

您可以使用File::Slurp中的create_file,而不是创建自己的write_file。 它抽象开/关/模/印。