Perl将文件拆分为行和变量

时间:2017-02-14 20:58:31

标签: perl parsing

我目前正在分割一个Perl文件,该文件包含一些用户/密码信息,并且正在成功完成,但我对我的代码不满意。我确信在Perl中有更好的方法(我是初学者)。如果有人能想出一个更棒的方式!

my $i = 1;
my $DB;
my $DBHOST;
my $DBUSER;
my $DBPASS;    
my $filename = "some_file";
open(my $fh, '<:encoding(UTF-8)', $filename)
    or die "Could not open file '$filename' $!";

while (my $row = <$fh>) {
    chomp $row;
    if ($i == 1) {
        $DB = (split /=/, $row)[1];
    }
    if ($i == 2) {
        $DBHOST = (split /=/, $row)[1];
    }
    if ($i == 3) {
        $DBUSER = (split /=/, $row)[1];
    }
    if ($i == 4) {  
        $DBPASS = (split /=/, $row)[1];
    }
    $i++;
}

2 个答案:

答案 0 :(得分:0)

对于这样的事情,

map()非常方便:

my ($DB, $DBHOST, $DBUSER, $DBPASS) = map {$_ =~ /.*?=(.*)/} <$fh>;

发生了什么:

  • map()对列表进行操作,因此将<$fh>视为一个
  • 对于列表中的每个元素(在本例中为文件行),将其分配到默认变量($_
  • 然后,使用正则表达式捕获我们想要的行的部分,返回它,并将其分配给左侧的相关变量(在文件的每次迭代中,每个接收变量都被移位为孔)
  • 正则表达式的操作如下:

    / .*? # ignore everything, non greedy until we match a = # our delimiter ( # begin capture .* # capture everything until end of line (less the newline char) ) # end capture /

请注意,即使在填充了所有四个变量之后,此解决方案也会一直遍历整个文件(就像您在OP中完成的那样)。

另请注意,此处没有错误检查,因此如果未捕获值,您将收到与未定义变量相关的警告。

答案 1 :(得分:0)

我想我会废除你的个别变量并将连接信息存储在哈希中。

string[] xmlLines = File.ReadAllLines(path);    
int linesFrom = 5;
int exceptionLine = 10; //Your  line number
int startLine = exceptionLine - linesFrom - 1 > 0 ? exceptionLine - linesFrom - 1: 0;
int endLine = exceptionLine + linesFrom - 1 > xmlLines.Count - 1 ? exceptionLine + linesFrom  - 1: xmlLines.Count - 1;
StringBuilder sb = new StringBuilder();
for (int i = startLine ; i < endLine ; i++)
{
    sb.Append(xmlLines[i]);
}
return sb.ToString();

当然,这假设每行my %db_conn; while (<$fh>) { my ($key, $val) = split /=/, $_, 2; $db_conn{$key} = $val; } 左侧的任何内容都是该值的唯一标识符。