How do pass one array and one string as arguments to a function?

前端 未结 5 1391
感情败类
感情败类 2021-01-13 14:44

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

5条回答
  •  日久生厌
    2021-01-13 15:22

    You could use a prototype, but those are kind of brittle. I would pass in a reference to @f as the first argument, like this:

    use 5.010;
    use strict;
    use warnings;
    
    sub ifin
    {
    my ($array,$str)=@_;
     for my $i (@$array)
     {
      if ($i eq $str)
      {
       return True
      }
     }
     return False
    }
    
    
    my @f= (1,2,3,4);
    my $k=1;
    print ifin(\@f,$k);
    

    For a long list, you avoid making a copy of every list element as well.

提交回复
热议问题