开发者

Perl reading configuration file without using Modules

Let's say I have a configuration file.

Config.csv

Server,Properties
"so-al-1","48989"
"so-al-3","43278"
"so-al-5","12345"

I need to use a perl script to retrieve the server and properties from the file in order to use the varible's values in my script. Also our client server doesn't want us to install any modules.

So how do I read this document in variables without using a module?

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";
}
开发者_运维知识库

I did try the above but it doesn't put it to a hash that I wanted.

Edited: I copied the code too fast and missed a line.

Edited: I just found out that there's a question like this in StackOverflow already. How can I parse quoted CSV in Perl with a regex?


Following the usual warning of "you should use a CSV module", this works:

#!/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"

Output:

Server      Properties      
so-al-1     48989
so-al-3     43278
so-al-5     12345


#!/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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜