Perl subroutine array and scalar variable parameters

后端 未结 3 1842
离开以前
离开以前 2021-02-14 06:53

How exactly can I pass both scalar variables and array variables to a subroutine in Perl?

 my $currVal = 1;
 my $currValTwo = 1;
 my @currArray = (\'one\',\'two\         


        
3条回答
  •  太阳男子
    2021-02-14 07:05

    So, for example: This is a using statement to search something in an array:

    use List::Util qw(first);
    

    This is the sub declaration:

    sub GetIndex($$$);
    

    This is the call to the sub (last parameter is: Default index value to give back if not found)

    $searchedIndex = GetIndex(\@theArr, "valuesearched", 1);
    

    This is the routine:

    sub GetIndex($$$)
    {
        my $inArray=shift;
        my @theArray= @{$inArray};
        my $searchedTag= shift;
        my $defaultVal= shift;
    
        my $retVal = first { $theArray[$_] eq $searchedTag} 0 .. $#theArray;
        if ((! defined $retVal)|| ($retVal<0)||($retVal>@theArray))
        {
            $retVal = $defaultVal;
        }
        return $retVal;
    }
    

提交回复
热议问题