2012-11-22 196 views
2

我有两个数组,一个固定为8个字母,另一个取决于用户。我必须采取用户输入并放入一个数组(完成),但我需要检查用户输入(它是一个字)字母在另一个数组中吗?我该怎么做 ?如何检查一个数组的元素是否在另一个数组中?

+4

向我们展示你有什么至今。 –

+0

查看Perl常见问题的[本节](http://perldoc.perl.org/perlfaq4.html#Data:-Arrays),其中涵盖了Perl数组操作的大部分内容。 –

回答

4

您可以使用Perl的(v5.10 +)smartmatch运算符~~来检查字符串是否是数组的一个元素。匹配是大小写敏感的:

use strict; 
use warnings; 

my @words = map lc, qw/This is a test/; 

print 'Enter a word: '; 
chomp(my $entry = <>); 

print qq{The word "$entry" is} 
    . (lc $entry ~~ @words ? '' : ' not') 
    . ' in @words.' 

采样运行:

Enter a word: This 
The word "This" is in @words. 
+0

以及如果我不使用5.10或更大。我有5.8.8 –

+0

@PavelMalinov如果'@ words'很短,您可以使用'grep'而不是智能匹配。对于较大的单词列表,来自[List :: Util](http://p3rl.org/List::Util)的“first”应该更高效 – memowe

+1

@memowe - 好的建议。另一个选择是'使用Syntax :: Keyword :: Junction qw/any /;'然后'any(@words)eq lc $ entry'。 – Kenosis

相关问题