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

前端 未结 5 1376
感情败类
感情败类 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 15:11

    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");
    

提交回复
热议问题