2011-03-30 29 views
0

我對perl不是很熟悉,但是我想知道這是否可以做到?如何查找由獨特字符分隔的變量?

所以我有一個看起來像文件:

Stringa = Stringx Stringz 
Stringb = Stringy 
Stringc = Stringw Stringx Stringu 

凡在左邊我有一個字。在右邊我有多個詞。我想創建一個哈希表,其中關鍵字是左邊的單詞(即stringa),值是包含右側元素(即stringx stringz)的數組。在右側,元素只能被空格分隔,我需要包含 - * $ @,所有這些垃圾。

謝謝。

回答

4

事情是這樣的:

my %hash; 
foreach my $line (@lines) { 
    chomp $line; 
    my ($key, $value) = split ' = ', $line; 
    my @elems = split '\s+', $value; 
    $hash{$key} = \@elems; 
} 

你的哈希將通過在=左側的字符串被鍵入,和你的價值觀將根據=右側是數組引用。

+0

如果我真的想要一條線來表示一個鍵值* pair *,我會做'split/\ s * = \ s * /,$ line,2'。 – Axeman 2011-03-30 22:55:11

1
#!/usr/bin/perl -w 

my $hash = {}; 
while (my $line = <DATA>) { 
    chomp($line); 
    my @vals = split(/(?: = |)/, $line); 
    my $key = shift(@vals); 
    $hash->{$key} = \@vals; 
} 

for (keys %$hash) { 
    print "OK: $_ => ", join(', ', @{$hash->{$_}}), "\n"; 
} 

__END__ 
Stringa = Stringx Stringz 
Stringb = Stringy 
Stringc = Stringw Stringx Stringu 
+0

爲什麼不能'my($ key,@ vals)= split(/(?: = |)/,$ line);' – 2011-03-30 20:53:54

1

散列只能有值的標量,所以你不能直接存儲一個數組到一個散列,但你可以存儲對一個數組的引用。

my %hash; 
while (<>) { 
    chomp; 
    my ($key, $val) = split(/' = '/, $_); 
    push @{ $hash{$key} }, split(/\s+/, $val); 
} 

my @abcs = @{ $hash{abc} }; 
my $abc = $hash{abc}[0]; 

與以前發佈的解決方案不同,它接受重複鍵,如果它們碰巧發生。

2

只是讓你可以看到有線性的方式來做到這一點:

my %hash 
    = map { $_->[0] => [ split /\s+/, $_->[1] ] } 
     map { chomp; [ split /\s*=\s*/, $_, 2 ] } 
     <DATA> 
    ; 

__DATA__ 
Stringa = Stringx Stringz 
Stringb = Stringy 
Stringc = Stringw Stringx Stringu 

哎呀,而你在它,如果添加File::Slurp,你可以這樣做:

use File::Slurp qw<read_file>; 
my %hash 
    = map { $_->[0] => [ split /\s+/, $_->[1] ] } 
     map { chomp; [ split /\s*=\s*/, $_, 2 ] } 
     # now you can have #-comments in your file 
     grep { !m/^\s*#/ } 
     read_file($my_config_path) 
    ; 
相關問題