如何在Perl中从多行字符串创建集合?
我有一个多行字符串作为输入。例如:如何在Perl中从多行字符串创建集合?,perl,Perl,我有一个多行字符串作为输入。例如:my$input=“a\nb\nc\nd” 我想从这个输入创建一个集合,这样我就可以确定集合中是否存在字符串向量中的元素。我的问题是,如何在Perl中从多行字符串创建集合?可用于将行存储到数组变量中: use warnings; use strict; use Data::Dumper; my $input = "a\nb\nc\nd"; my @lines = split /\n/, $input; print Dumper(\@lines); __EN
my$input=“a\nb\nc\nd”
我想从这个输入创建一个集合,这样我就可以确定集合中是否存在字符串向量中的元素。我的问题是,如何在Perl中从多行字符串创建集合?可用于将行存储到数组变量中:
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是对的;执行捕获输入的技巧
但如果以后要检查集合成员资格,您可能需要更进一步,将这些值放入散列。大概是这样的:
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 );
}
然后可以像这样快速检查集合成员资格:
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没有本机集类型,因此哈希通常填充该角色,因此在我看来,这正是要求的,而不是“更进一步”