2014-09-25 50 views
-1

你能幫我怎麼得到perl中不同值的唯一密鑰嗎?,這些日誌文件經常產生,值不斷變化。Perl密鑰和多個值查詢

"cloning": true 
"cmdline": "git-upload-pack 
"features": "" 
"frontend": "github.com" 
"frontend_pid": 14421 
"frontend_ppid": 1 
"git_dir": "/repositories/xorg/myrepo.git" 
"hostname": "github.com" 
"pgroup": "20603" 
"pid": 20603 
"ppid": 20600 
"program": "upload-pack" 

"cloning": false 
"cmdline": "git-upload-pack 
"features": "" 
"frontend": "github.com" 
"frontend_pid": 14422 
"frontend_ppid": 2 
"git_dir": "/repositories/yorg/myrepo2.git" 
"hostname": "github.com" 
"pgroup": "20604" 
"pid": 20604 
"ppid": 20500 
"program": "upload-pack" 

由於提前

+1

請告訴我們你有什麼到目前爲止已經試過,並參見[如何在Stack Overflow上提出一個好問題](http:// stackoverflow .COM /幫助/如何對問)。 – 2014-09-25 09:29:55

+0

另請參閱此問題:http://stackoverflow.com/questions/17218110/can-a-hash-key-have-multiple-subvalues-in-perl – 2014-09-25 09:32:10

+0

這不是Perl散列。它看起來更像是一個JSON對象,但逗號不見了。或者是這部分日誌文件? – simbabque 2014-09-25 09:33:37

回答

0
use Data::Dump; 

my %h; 
while (my $line = <DATA>) { 
    next if $line !~ /\S/; 

    my @r = split /:/, $line; 
    s/^["\s]+ | ["\s]+//xg for @r; 

    push @{ $h{$r[0]} }, $r[1]; 
} 

dd \%h; 

__DATA__ 
"cloning": true 
"cmdline": "git-upload-pack 
"features": "" 
"frontend": "github.com" 
"frontend_pid": 14421 
"frontend_ppid": 1 
"git_dir": "/repositories/xorg/myrepo.git" 
"hostname": "github.com" 
"pgroup": "20603" 
"pid": 20603 
"ppid": 20600 
"program": "upload-pack" 

"cloning": false 
"cmdline": "git-upload-pack 
"features": "" 
"frontend": "github.com" 
"frontend_pid": 14422 
"frontend_ppid": 2 
"git_dir": "/repositories/yorg/myrepo2.git" 
"hostname": "github.com" 
"pgroup": "20604" 
"pid": 20604 
"ppid": 20500 
"program": "upload-pack" 

輸出

{ 
    cloning  => ["true", "false"], 
    cmdline  => ["git-upload-pack", "git-upload-pack"], 
    features  => ["", ""], 
    frontend  => ["github.com", "github.com"], 
    frontend_pid => [14421, 14422], 
    frontend_ppid => [1, 2], 
    git_dir  => [ 
        "/repositories/xorg/myrepo.git", 
        "/repositories/yorg/myrepo2.git", 
        ], 
    hostname  => ["github.com", "github.com"], 
    pgroup  => [20603, 20604], 
    pid   => [20603, 20604], 
    ppid   => [20600, 20500], 
    program  => ["upload-pack", "upload-pack"], 
} 
+0

OP不太可能理解這段代碼,所以他們不會從中學到任何東西。 :\ – 2014-09-25 10:47:37

+0

@mpapec,感謝您的回答 – organicuser 2014-09-25 11:57:40

0

我只想用一個數組哈希表:

#!/usr/bin/env perl 
use strict; 
my %hash; 
## read input line by line into $_ 
while (<>) { 
    ## remove trailing newlines 
    chomp; 
    ## skip empty lines 
    next if /^\s*$/; 
    ## split the line on `:` into the @F array 
    my @F=split(/:\s*/); 
    ## Add this value to the list associated with 
    ## this key. 
    push @{$hash{$F[0]}},$F[1]; 
} 
## Set the output field separator to a comma 
$"=","; 
## Print each key and the array of its values separated 
## by a comma. 
print "$_ : ", join(",",@{$hash{$_}}),"\n" for keys(%hash)