首页 文章

Perl文件,新行到HASH,然后到CSV

提问于
浏览
0

你好Perl专家,

我很抱歉,如果我问得太多,但刚开始学习perl,并希望了解更多有关散列到csv的信息 . 试着打破我的头几天,但没有得到太多 . 我的要求是我想转换下面的文件并将其打印为csv而不使用cpan中的自定义模块 . 由于此处不允许使用自定义模块 .

我尝试的逻辑是将输入文件转换为哈希并像csv一样打印 . 第一个问题我的代码有问题 . 我有一个复杂的部分,我需要在空格之前使用第一个关键字进行搜索,如果我没找到它,需要添加一个''(空格) . 例如 . ovpa_type不存在于第二个中 . 像这样,文件中有5L行 .

我想学习如何在哈希数组中添加行,就像powershell一样 . 并转换成我想要的csv .

My input file contains the below data.

begin node
name ccaita23.contoso.com
on_off on
group SYSTEM_PING_UNIX
suppress no
auto_delete yes
read_community public
write_community public
address 2.1.52.36
port 161
ovpa_type router
trace off
snmp_version 1
engineid 0
auth_protocol 1
is_key_ok 0
error_status 0
security_level 0
v3_user 0
priv_protocol 0
end node

begin node
name ccaidi7c.contoso.com
on_off on
group SYSTEM_PING_UNIX
suppress no
auto_delete yes
read_community public
write_community public
address 1.1.210.76
port 161
trace off
snmp_version 1
engineid 0
auth_protocol 1
is_key_ok 0
error_status 0
security_level 0
v3_user 0
priv_protocol 0
end node

Output required ccaita23.contoso.com,on,SYSTEM_PING_UNIX,no,yes,public,public,2.11.52.36,161,router,off,1,0,1,0,0,0,0,0 ccaidi7c.contoso.com,上SYSTEM_PING_UNIX,没有,是的,公共的,公开的,1.1.210.76,161,关闭,1,0,1,0,0,0,0,0

open FILE1, "File.node" or die;
my %hash;
while (my $line=<FILE1>) {
   chomp($line);
   (my $key,my $value) = split / /, $line;
    $hash{$key} .= $value;
}
my $name = $hash{'name'};
my $group = $hash{'group'};
my $csv = "$name,$group\n";
print $csv;

1 回答

  • 0
    my @fields = qw(
      name on_off group suppress auto_delete read_community write_community 
      address port ovpa_type trace snmp_version engineid auth_protocol 
      is_key_ok error_status security_level v3_user priv_protocol
    );
    
    open my $FILE1, "<", "File.node" or die $!;
    local $/ = "";  # paragraph reading mode/reads whole node at once
    
    while (my $rec = <$FILE1>) {
      # $rec =~ s/(?:begin|end)\s+node//g; # get rid of begin/end
      my %hash = split ' ', $rec;        # split node on spaces and feed into hash, in key/value fashion
    
      # get hash slice for @fields keys, map every undef to "", so join wont warn under warnings
      print join(",", map { $_ // "" } @hash{@fields}), "\n";
    }
    

相关问题