1

如果我有一个与我的 perl 脚本分开的可配置变量页面,我如何在其中使用它们?

假设我在文件中有这些变量..

database.properties:

    database = "dbi:Oracle:host=host-321;sid=XE;port=1337","User","Passwd"

    table1 = CHANNEL

    table2 = NODE

...我的 perl 脚本的这些部分需要它们:

my $dbh = DBI->connect($database);

open ROW,">","./report/archive/rprt-$now/row_counts.txt" or die "Unable to create file: $!";
    my $chanRows = $dbh->selectrow_array("SELECT COUNT(*) FROM $table1");
    my $nodeElemsRows = $dbh->selectrow_array("SELECT COUNT(*) FROM $table2 WHERE NODE_TYPE > 1");
    my $nodeDeviceRows = $dbh->selectrow_array("SELECT COUNT(*) FROM $table2 WHERE NODE_TYPE = 1");
    print ROW "Channels: $chanRows\n";
    print ROW "Network Elements: $nodeElemsRows\n";
    print ROW "Devices: $nodeDeviceRows";
close ROW;

显然,只是简单地将 $database、$table1 和 $table2 放在那里不会有任何好处,那么正确的方法是什么?提前致谢。

4

1 回答 1

3

您可以使用Config::Tiny。您的配置文件可能如下所示:

[databaseproperties]

    database = "dbi:Oracle:host=host-321;sid=XE;port=1337","User","Passwd"

    table1 = CHANNEL

    table2 = NODE

你的脚本是这样的:

#!/usr/bin/env perl
use strict;
use warnings;
use Config::Tiny;
my $config = Config::Tiny->new;
$config = Config::Tiny->read('myconfig');
my $database = $config->{databaseproperties}->{database};
print "DATABASE = $database\n";
my $table1 = $config->{databaseproperties}->{table1};
print "TABLE-1  = $table1\n";
my $table2 = $config->{databaseproperties}->{table2};
print "TABLE-2  = $table2\n";
于 2012-06-27T13:42:34.840 回答