Perl读取文件并将每一行存储为变量/值 [英] Perl reading a file and storing each line as variable/value

查看:495
本文介绍了Perl读取文件并将每一行存储为变量/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对perl还是很陌生,但是到目前为止,到目前为止,我几乎已经要做我需要做的所有事情.

I'm pretty new to perl, but so far got to do pretty much everything I needed to, until now.

我的文件格式如下:

#IPAAS

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

我想将以@NX_iPaaS开头的每一行读入一个类似的命名变量,例如 @NX_iPaaS_AuthKey会创建一个名为$ NX_IPAAS_AUTHKEY的新变量并保存该值,NX_iPaaS_href会导致一个名为$ NX_IPAAS_HREF的新变量并具有值,等等吗?

I'd like to read each line that begins with @NX_iPaaS into a similar named variable, e.g. @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?

-更新-

嘿,我需要对上述解决方案进行一些微调...

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', e.g.

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

您会看到两个部分都出现了一个变量,这是因为我没有除非定义,否则",这将导致先前的值被覆盖.是否可以使用每个部分顶部的"section ="行中提供的值作为NX_NTF_变量名的前缀?

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?

谢谢

推荐答案

您要使用的是哈希.像这样:

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;
    }
}

要在以后使用变量,请使用$NX_iPaaS_vars{"name of variable you want"},例如:

To use a variable later on, use $NX_iPaaS_vars{"name of variable you want"}, for example:

my $href_path = $NX_iPaaS_vars{'@NX_iPaaS_href'};
# Do something with $href_path here...

这篇关于Perl读取文件并将每一行存储为变量/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆