문제

Hello Perl experts,

Im sorry if I m asking too much, but just started learning perl, and want to know more on hash to csv. Tried breaking my head for few days, but didnt get much. My requirement is I want to convert the below file & print it as a csv without using a custom module from cpan. Since custom modules are not allowed in here.

The logic i tried was take the input file into a hash and printing like a csv. First problem something wrong with my code. I have a complicated part in this, I need to search using first keyword before space, if I dont find it, need to add a ''(space). eg. ovpa_type is not present in the second. Like this there are 5L lines in the file.

I want to learn about adding lines into the hash array, like powershell does. and converting into csv whereever I want.

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,on,SYSTEM_PING_UNIX,no,yes,public,public,1.1.210.76,161,,off,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;
도움이 되었습니까?

해결책

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";
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top