【问题标题】:Perl find out if X is an element in an arrayPerl 判断 X 是否是数组中的元素
【发布时间】:2016-10-21 20:22:12
【问题描述】:

我不知道为什么在 Perl 中小事对我不起作用。我对此感到抱歉。

我已经尝试了大约 2 小时,但我无法得到结果。

my $technologies = 'json.jquery..,php.linux.';
my @techarray = split(',',$technologies);

#my @techarray = [
#          'json.jquery..',
#          'php.linux.'
#        ];

my $search_id = 'json.jquery..';

check_val(@techarray, $search_id);

我正在做一个“如果”来搜索数组中的上述项目。但它不适合我。

 sub check_val{
        my @techarray = shift;
        my $search_id = shift;
          if (grep {$_ eq $search_id} @techarray) {
                print "It is there \n";
            }else{
                print "It is not there \n";
            }
     }

输出:它总是处于 else 条件并返回“它不存在!” :(

任何想法。我完成了任何愚蠢的错误吗?

【问题讨论】:

  • 将您的数组分配更改为:my @techarray = ('json.jquery..', 'php.linux.');
  • @techarray 是“split”方法的输出。
  • 如果你的问题不能像问题中写的那样重现,那么你需要创建一个正确的minimal reproducible example
  • 你能解释一下这是什么意思吗,@techarray是“split”方法的输出
  • @zdim。我刚刚更新了拆分方法的问题。

标签: perl grep


【解决方案1】:

您正在使用 匿名数组 [ ... ],然后将其作为标量(引用)分配给 @techarray,作为其唯一元素。就像@arr = 'a';。数组由( ... ) 定义。

一种补救方法是定义一个数组my @techarray = ( ... ),或者正确定义一个arrayref,然后在搜索时取消引用

my $rtecharray = [ .... ];
if (grep {$_ eq $search_id} @$rtecharray) {
    # ....
}

对于各种列表操作,请查看 List::UtilList::MoreUtils


更新了问题的变化,因为添加了子

这还有点别的,更有启发意义。

当您将数组传递给函数时,它会作为其元素的平面列表传递。然后在函数中第一个 shift 拾取第一个元素, 然后第二个shift 拿起第二个。

然后搜索只包含'json.jquery..' 元素的数组,用于'php.linux.' 字符串。

相反,你可以传递一个引用,

check_val(\@techarray, $search_id);

并在函数中使用它。


注意如果你传递数组并在函数中获取参数为

my (@array, $search_id) = @_;  # WRONG

您实际上是 将所有 @_ 放入 @array

例如,参见this post(传递给函数)和this post(从函数返回)。

一般来说,我建议通过引用传递列表。

【讨论】:

  • 哇...你是对的。我刚刚定义了一个arrayref,然后取消引用并开始工作。 :)
  • 在第二个示例中,@array 将包含所有内容,$search_id 将是 undef
猜你喜欢
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 2022-12-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 2011-05-24
相关资源
最近更新 更多