2015-01-07 49 views
0

Iam新的perl并试图编写代码,我想从文本文件中读取值。在从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可以在分贝chanegd,因此可以进一步在未来的价值,所以我想从一个文本配置文件中得到它来代替。

创建的文件:

- config.txt 

这可能会具有以下值 -

cp_server_attribute_id= 10; 
new_value=30; 

请有人可以帮助我打开文件和读取值在我的数据库查询中使用。我应该使用散列吗?有没有一种简单的方法来做到这一点。

任何帮助,将不胜感激。

回答

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模块,如果我想在全球范围内使用它,该文件包含超过15个参数的值,这将解析文件
+0

感谢这个..what。有很多地方会使用这个变量。请你也建议如何将这些值存储在一个散列中,然后在需要的地方使用这个散列 – perlbegin

+0

你的需求不清楚。全球使用它意味着什么? Global是否在脚本范围内,还是全局的,因为您希望配置在整个应用程序实例中保留下来? – rurouni88