-2
我有一個多行字符串作爲輸入。例如:my $input="a\nb\nc\nd"
如何從Perl中的多行字符串創建一個集合?
我想從這個輸入創建一個集合,這樣我就可以確定集合中是否存在字符串向量中的元素。我的問題是,我如何從Perl中的多行字符串創建一個集合?
我有一個多行字符串作爲輸入。例如:my $input="a\nb\nc\nd"
如何從Perl中的多行字符串創建一個集合?
我想從這個輸入創建一個集合,這樣我就可以確定集合中是否存在字符串向量中的元素。我的問題是,我如何從Perl中的多行字符串創建一個集合?
split可用於存儲線到一個數組變量:
use warnings;
use strict;
use Data::Dumper;
my $input = "a\nb\nc\nd";
my @lines = split /\n/, $input;
print Dumper(\@lines);
__END__
$VAR1 = [
'a',
'b',
'c',
'd'
];
@toolic是正確的; split會抓住輸入。
但是,如果您想稍後檢查設置成員身份,您可能需要更進一步並將這些值放入散列值中。事情是這樣的:
use warnings;
use strict;
my $input = "a\nb\nc\nd";
my @lines = split /\n/, $input;
my %set_contains;
# set a flag for each line in the set
for my $line (@lines) {
$set_contains{ $line } = 1;
}
然後你就可以快速檢查組成員這樣的:
if ($set_contains{ $my_value }) {
do_something($my_value);
}
Perl並不具有天然的集合類型,所以通常哈希填補這個角色,所以國際海事組織這正是正在被要求,而不是「更進一步」 – ysth