简体   繁体   English

Perl读取文件并将每一行存储为变量/值

[英]Perl reading a file and storing each line as variable/value

I'm pretty new to perl, but so far got to do pretty much everything I needed to, until now. 我对perl还是很陌生,但是到目前为止,到目前为止,我几乎已经要做我需要做的所有事情。

I have a file formatted like so: 我有一个格式如下的文件:

#IPAAS

@NX_iPaaS_AuthKey=dGstaG9zaGlub0BqcCasdpasdHN1LmNvbTppUGFhUzAw
@NX_iPaaS_href=live/661134565/process/75231

I'd like to read each line that begins with @NX_iPaaS into a similar named variable, eg @NX_iPaaS_AuthKey would create a new variable called $NX_IPAAS_AUTHKEY and hold the value, NX_iPaaS_href would result in a new variable called $NX_IPAAS_HREF with a value and so on? 我想将以@NX_iPaaS开头的每一行读入一个类似的命名变量,例如@NX_iPaaS_AuthKey将创建一个名为$ NX_IPAAS_AUTHKEY的新变量并保存该值,NX_iPaaS_href将导致一个名为$ NX_IPAAS_HREF的新变量,并带有一个值,因此上?

--Update-- -更新-

Hey guys, I need a slight tweak required to the above solution... 大家好,我需要对上述解决方案进行一些微调。

So I've just discovered that the file I'm reading in will have 'sections', eg 所以我刚刚发现,我正在阅读的文件将具有“部分”,例如

----- SECTION=cr 
NX_NTF_PERSISTENT_ID=cr:400017 
NX_NTF_REF_NUM=45 
----- SECTION=cnt 
NX_NTF_PERSISTENT_ID=cnt:F9F342055699954C93DE36923835A182 

You can see that one of the variables appears in both sections, which (because I don't have 'next unless defined') results in the previous value being overwritten. 您可以看到两个部分都出现了一个变量,这是因为我没有“除非定义,否则”,这将导致先前的值被覆盖。 Is there a way to prefix the NX_NTF_ variable names with the value provided on the 'section=' line at the top of each section? 是否可以使用每个部分顶部的“ section =”行中提供的值为NX_NTF_变量名添加前缀?

Thanks 谢谢

The good practice is to use hashes. 优良作法是使用散列。

my %hash;
while (<>) {
    chomp;
    my ($key, $value) = split /=/;
    next unless defined $value;
    $hash{$key} = $value;
}

See Why it's stupid to "use a variable as a variable name" on why it is not a good idea to use variable variable names. 请参阅为什么“使用变量作为变量名”是愚蠢的,以了解为什么使用变量变量名不是一个好主意。

What you want to use is a hash. 您要使用的是哈希。 Something like: 就像是:

use strict;
use warnings;

my $input = "yourfilename.txt";
open(my $IN, "<", $input) or die "$0: Can't open input file $input: $!\n";

my %NX_iPaaS_vars;

while (<$IN>) {
    chomp;
    if ($_ =~ /^\@NX_iPaaS/) {
        my ($key, $value) = split(/=/, $_);
        $NX_iPaaS_vars{$key} = $value;
    }
}

To use a variable later on, use $NX_iPaaS_vars{"name of variable you want"} , for example: 要稍后使用变量,请使用$NX_iPaaS_vars{"name of variable you want"} ,例如:

my $href_path = $NX_iPaaS_vars{'@NX_iPaaS_href'};
# Do something with $href_path here...
#!/usr/bin/perl -w
use strict;

open(FILE,"test.txt");

my %hash;

foreach (<FILE>)
{
       if($_=~/@(\S+)=(\S+)/)
       {
               $hash{$1}=$2;
       }

}
close(FILE);

# Test Code

foreach (keys %hash)
{
       printf("%s=%s\n",$_,$hash{$_});
}

This solution works well if variable names are unique. 如果变量名称是唯一的,则此解决方案效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM