Search code examples
perlsubroutinefunction-parameter

Perl subroutines with exact signature / exact number of parameters


I have seen usage of $ in subroutine definition somewhere. To learn more about it, I created various cases with a simple subroutine, and came to know that it's used for defining subroutines with exact signatures.

Can anyone please confirm:

  1. Whether I'm right? I mean whether it's used for this purpose?
  2. Whether it has any other uses?
  3. Is there any other way to access those parameters inside subroutine, other than using my $param1 = shift; or my (@params) = @_?

use strict;
use warnings;

# just a testing function
sub show($$){
    print "Inside show";
}

show(1, 1);   # works fine
show(1);     # gives compilation error
# Not enough arguments for main::show at test.pl line 8, near "1)"
# Execution of test.pl aborted due to compilation errors.

show(1, 1, 1);   # gives compilation error
# Too many arguments for main::show at test.pl line 8, near "1)"
# Execution of test.pl aborted due to compilation errors.       

Solution

  • You are using subroutine prototypes. Don't. For more detail, see Why are Perl 5's function prototypes bad?

    A new, experimental feature introduced in 5.20 is subroutine signatures. Those do everything you wished subroutine prototypes could.

    For example:

    use strict;
    use warnings;
    
    use feature 'signatures';
    no warnings 'experimental::signatures';
    
    sub show ( $canvas, $actor ) {
        $actor->draw( $canvas, $COLOR{default});
    }
    

    etc