in reply to Re^2: Too many arguments for subroutine
in thread Too many arguments for subroutine
The one place where Prototypes are useful* is if you want to write a replacement for a built-in function that has its arguments parsed in the same way as the builtin. For example, prototype("CORE::lc") is "_", and let's say we want to write a replacement:
use warnings; use strict; use feature 'say'; use Data::Dump 'pp'; sub mylc (_) { print "in=", pp @_; return lc $_[0] } sub mylc2 { # no prototype for comparison print "in=", pp @_; return lc $_[0] }
The prototype does three things:
There is only one argument. If lc or its hypothetical replacement didn't have a prototype, then lc "x", "y" would be the same as lc("x", "y"), but because of the prototype, the former is the equivalent of lc("x"), "y". See also Named Unary Operators.
say "lc: out=", pp( lc "A","B" ); print "mylc: "; say " out=", pp( mylc "A","B" ); print "mylc2: "; say " out=", pp( mylc2 "A","B" ); # lc: out=("a", "B") # mylc: in="A" out=("a", "B") # mylc2: in=("A", "B") out="a"
Like the '$' prototype, the argument is forced into scalar context. If lc didn't have a prototype, if you said lc(@x), its arguments @_ would be the elements of @x. But because of the prototype, the former is actually equivalent to lc(scalar(@x)), meaning it gets only one argument, the number of elements in @x.
my @x=qw/ X Y Z /; say "lc: out=", pp( lc @x,"B" ); print "mylc: "; say " out=", pp( mylc @x,"B" ); print "mylc2: "; say " out=", pp( mylc2 @x,"B" ); # lc: out=(3, "B") # mylc: in=3 out=(3, "B") # mylc2: in=("X", "Y", "Z", "B") out="x"
It automagically uses $_ when no argument is passed to the function.
$_ = 'Z'; say "lc: out=", pp( lc,"B" ); print "mylc: "; say " out=", pp( mylc,"B" ); print "mylc2: "; say " out=", pp( mylc2,"B" ); # lc: out=("z", "B") # mylc: in="Z" out=("z", "B") # Use of uninitialized value $_[0] in lc at example.pl line 12. # mylc2: in=() out=("", "B")
* However:
therefore, they are firmly in the "only use this if you know what you are doing and can explain exactly why" category, or, rephrasing that for non-experts, "Don't use subroutine prototypes"...
Update: Switched code from oneliners to a script.
|
---|