假设我有一个配置文件。
Config.csv
Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"
我需要使用perl脚本从文件中检索服务器和属性,以便在我的脚本中使用varible的值。我们的客户端服务器也不希望我们安装任何模块。
那么如何在不使用模块的情况下在变量中阅读本文档?
open(FILE,"Config.csv");
undef($/); #sucks the entire file in at once
while(<FILE>){
(@words)=split(/\s+/);
}
close FILE;
for (@words){
s/[\,|\.|\!|\?|\:|\;]//g; #removed punctuation
$word{$_}++;
}
for (sort keys %word){
print "$_ occurred $word{$_} times\n";
}
我确实尝试了上述内容,但它没有把它放到我想要的哈希值上。
编辑:我复制代码太快而错过了一行。
编辑:我刚刚发现StackOverflow中存在类似这样的问题。 How can I parse quoted CSV in Perl with a regex?
答案 0 :(得分:2)
按照“你应该使用CSV模块”的常规警告,这有效:
#!/usr/bin/env perl
use warnings;
use strict;
my $header_str=<DATA>;
chomp $header_str;
my @header=$header_str =~ /(?:^|,)("(?:[^"]+|"")*"|[^,]*)/g;
my %fields;
my @temp;
my $line;
while($line=<DATA>){
chomp $line;
@temp = $line =~ /(?:^|,)("(?:[^"]+|"")*"|[^,]*)/g;
for (@temp) {
if (s/^"//) {
s/"$//; s/""/"/g;
}
}
$fields{$temp[0]}=$temp[1];
}
print "$_\t\t" for (@header);
print "\n";
print map { "$_\t\t$fields{$_}\n" } sort keys %fields;
__DATA__
Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"
输出:
Server Properties
so-al-1 48989
so-al-3 43278
so-al-5 12345
答案 1 :(得分:0)
#!/usr/bin/perl
use warnings;
use strict;
while (<DATA>) {
chomp;
next unless my($key,$value) = split /,/;
s/^"//, s/"$// for $key, $value;
print "key=$key value=$value\n";
}
__DATA__
Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"