'Handle multiple arguments to a Perl subroutine [closed]

As i have read ,"There’s another problem with this subroutine.This subroutine works properly only if called with exactly two

Excess parameters are ignored—since the subroutine never looks at $_[2] "

but when I passed multiple arguments its working,so I'm not able to conclude the above statement so can anyone help me in sorting out this problem.

 sub privacy{
     $_[0]+$_[1]+$_[2]+$_[3];
 }

 $x=&privacy(3,4,5,6);
 print $x,"\n";`

Expected:

7

Actual:

18

but this result is contradicting.



Solution 1:[1]

I think you're reading Learning Perl. We present a subroutine that finds the maximum of two arguments. It looks something like this:

sub max {
    if( $_[0] > $_[1] ) { ... }
    else { $_[0] }
    }

If you call it with two arguments, it works out:

max( 1, 2 )
max( 5, 6 )
max( 9, 0 )

If you call it with three arguments, that particular subroutine ignores the third argument because that particular subroutine only looks at the first two:

max( 1, 2, 3 )   # ignores 3, so returns 2

You can write some other subroutine that looks at more arguments, but that's a different subroutine.

Unless you tell Perl otherwise (and I'll ignore that here), it will take as many arguments as you care to give it and they all show up in the special variable @_. How you use that is up to you.

Solution 2:[2]

You are misunderstanding the meaning of the sentence:

Excess parameters are ignored—since the subroutine never looks at $_[2]

What is meant by that is that in a perl subroutine (as in any language) if you don't use a parameter then it's not used.

In the particular example that the above sentence refers to, parameter 2, etc., are not used in the code so they are 'ignored'. They're available if you want to use them, they're just not used in that particular example.

However in YOUR code you are using them.

Solution 3:[3]

If that's what they said, and if that's the code they were talking about, then they are wrong. The sub clearly "looks at $_[2]".

3+4+5+6 is 18, and that's exactly what the code the outputs.

$ perl -e'
   sub privacy{
      $_[0]+$_[1]+$_[2]+$_[3];
   }

   $x=&privacy(3,4,5,6);
   print $x,"\n";
'
18

Note that the code has issues (& used on the sub call even though they are no prototypes to override, and $x isn't scoped), so you shouldn't be taking lessons from whomever wrote that code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rob Sweet
Solution 3