如何传递一个数组和一个字符串作为参数的函数吗? [英] How do pass one array and one string as arguments to a function?

查看:164
本文介绍了如何传递一个数组和一个字符串作为参数的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我不能找到一种方便的方法来检查 $ STR @array ,我米试图使一个自己,但它不工作。

我想这是因为数组和字符串的混淆。它一直给 0 $ STR 。请让我知道如何解决它。

 使用5.010;
使用严格的;
使用警告;子IFIN {
    我(@array,$ STR)= @_;
    我的$ I(@array){
        如果($ I $ EQ STR){
            返回1;
        }
    }
    返回0;
}我的@f =(1,2,3,4);
我的$ K = 1;
打印IFIN(@f,$ K);


解决方案

您不能传递数组潜艇,只列出了标量。

  IFIN(@f,$ K);

是相同的

  IFIN($ F [0],$ F [1],$ F [2],$ F [3],$ k)的;

由于 @f 求其元素的列表。

将数组传递给子的一种方式是通过一个参考

 子IFIN {
   我($数组$ STR)= @_;
   我的$ E(@ $数组){
      返回1,如果$ËEQ $海峡;
   }   返回0;
}我@f =(1,2,3,4);
我的$ K = 1;
打印(IFIN(\\ @楼$ K),\\ n);

顺便说一下,该还可以写为:

 我@f =(1,2,3,4);
我的$ K = 1;
打印((grep的{$ _ $ EQ}ķ@f)?1:0,\\ n);

您可以通过使用 弹出

 子IFIN {
   我的$海峡= POP(@_);
   我的$ E(@_){
      返回1,如果$ËEQ $海峡;
   }   返回0;
}我@f =(1,2,3,4);
我的$ K = 1;
打印(IFIN(@f,$ K),\\ n);

Because I can't find a convenient way to check if $str is in @array, I'm trying to make one myself, but it is not working.

I guess it is because of the mix-up of array and string. It keeps giving 0 to $str. Please let me know how to fix it.

use 5.010;
use strict;
use warnings;

sub ifin {
    my (@array, $str) = @_;
    for my $i (@array) {
        if ($i eq $str) {
            return 1;
        }
    }
    return 0;
}

my @f = (1, 2, 3, 4);
my $k = 1;
print ifin(@f, $k);

解决方案

You can't pass arrays to subs, only lists of scalars.

ifin(@f, $k);

is the same as

ifin($f[0], $f[1], $f[2], $f[3], $k);

because @f evaluates to a list of its elements.

One way of passing an array to a sub is to pass a reference.

sub ifin {
   my ($array, $str) = @_;
   for my $e (@$array) {
      return 1 if $e eq $str;
   }

   return 0;
}

my @f = (1,2,3,4);
my $k = 1;
print(ifin(\@f, $k), "\n");

By the way, that can also be written as:

my @f = (1,2,3,4);
my $k = 1;
print(( grep { $_ eq $k } @f ) ? 1 : 0, "\n");

You could keep the existing calling convention by using pop.

sub ifin {
   my $str = pop(@_);
   for my $e (@_) {
      return 1 if $e eq $str;
   }

   return 0;
}

my @f = (1,2,3,4);
my $k = 1;
print(ifin(@f, $k), "\n");

这篇关于如何传递一个数组和一个字符串作为参数的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆