从perl中的文本文件读取后为变量赋值

时间:2015-01-07 05:10:21

标签: perl variables filehandle

我是perl的新手,并尝试编写一个代码,我想从文本文件中读取值。

代码 -

 my $cp_server_attrib_value = $adminDB->GetTbl('cp_server_attribute_value');

my $insert_attribs = qq[
    INSERT INTO $cp_server_attrib_value(def_id, cp_server_attribute_id, value)
    VALUES ($defId,10,"30")
];

服务器属性id可以在db中进行chanegd,因此将来可以进一步使用,所以我想从文本配置文件中获取它。

创建了一个文件:

- config.txt

可能会有以下值 -

cp_server_attribute_id= 10;
new_value=30;

请有人帮我打开文件并读取我在db查询中使用的值。我是否使用哈希?有没有一种简单的方法可以做到。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

# Read in lines from file and assign to temp variables
open(FILE, $file_path) or die sprintf ("FATAL: Could not open '%s' (%s)", $file_path, $!);

my ($cp_server_attribute_id, $new_value);
foreach my $line (<FILE>) {

    # Remove all whitespace because I just spotted that in your config.txt file
    $line =~ s/\s//g;

    # If the line matches our interesting attributes, extract the integer value associated
    if ( $line =~ m/^cp_server_attribute_id=(\d+);/ ) {
         $cp_server_attribute_id = $1;
    }
    elsif ( $line =~ m/^new_value=(\d+);/ ) {
         $new_value = $1;
    }
    else {
        # Do nothing
    }
}
close(FILE) || die sprintf ("FATAL: Could not close '%s' (%s)", $file_path, $!);

# Side note: This query is not recommended best practice. You should consider bind values.
my $insert_attribs = qq[
    INSERT INTO $cp_server_attrib_value(def_id, cp_server_attribute_id, value)
    VALUES ($defId, $cp_server_attribute_id, $new_value)
];

其他建议:

  1. 为配置文件选择更常用的格式。即。 XML,YAML,JSON,而不是文本文件
  2. 找一个将解析该文件的CPAN模块
相关问题