我对perl不太熟悉,但我想知道这是否可行?
所以我有一个看起来像的文件:
Stringa = Stringx Stringz
Stringb = Stringy
Stringc = Stringw Stringx Stringu
在左侧我只有一个单词。在右边我有多个单词。我想创建一个哈希表,其中键是左边的单词(即stringa),值是包含右边元素的数组(即stringx stringz)。在右侧,元素只被空格打破,我需要包括 - * $ @,所有垃圾。
感谢。
答案 0 :(得分:4)
这样的事情:
my %hash;
foreach my $line (@lines) {
chomp $line;
my ( $key, $value ) = split ' = ', $line;
my @elems = split '\s+', $value;
$hash{$key} = \@elems;
}
您的哈希将由=
左侧的字符串键入,您的值将是基于=
右侧的数组引用。
答案 1 :(得分: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 )
;
答案 2 :(得分: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
答案 3 :(得分:1)
哈希只能包含值的标量,因此您无法将数组直接存储到哈希中,但可以存储对数组的引用。
my %hash;
while (<>) {
chomp;
my ($key, $val) = split(/' = '/, $_);
push @{ $hash{$key} }, split(/\s+/, $val);
}
my @abcs = @{ $hash{abc} };
my $abc = $hash{abc}[0];
与先前发布的解决方案不同,如果碰巧发生重复密钥,则会接受重复密钥。