Perl subroutine array and scalar variable parameters

后端 未结 3 1849
离开以前
离开以前 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;
    }
    
    0 讨论(0)
  • You pass the arguments as references, so you need to dereference them to use the values. Be careful about whether you want to change the original array or not.

    sub mysub {
        my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
        @{$inArrayTwo} = ('five','six','seven');
    }
    

    This will change the original @currArrayTwo, which might not be what you want.

    sub mysub {
        my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
        my @ATwo = @{$inArrayTwo};
        @ATwo = ('five','six','seven');
    }
    

    This will only copy the values and leave the original array intact.

    Also, you do not need the ampersand in front of the sub name, from perldoc perlsub:

    If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.

    You do not need empty parens after your sub declaration. Those are used to set up prototypes, which is something you do not need to do, unless you really want to.

    0 讨论(0)
  • 2021-02-14 07:24

    You need to fetch them as references because you've already passed them as references (by using the \ operator):

    my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
    

    and then use the references as arrays:

    @{$inArray}
    
    0 讨论(0)
提交回复
热议问题