CJ7
CJ7

Reputation: 23275

How to have subroutine with required parameters?

Is it possible in Perl to declare a subroutine such that the script won't compile if parameters are not passed to it when it is called?

Upvotes: 3

Views: 324

Answers (2)

zdim
zdim

Reputation: 66873

Some of that can be achieved with prototypes (persub), to some extent

Perl supports a very limited kind of compile-time argument checking using function prototyping.
...
... intent of this feature is primarily to let you define subroutines that work like built-in functions

For example, subs declared as sub f1(\@) and sub f2($$) can only be called as f1(@ary) (array variable, with @) and f2(SCALAR, SCALAR) or there is a compile-time error.

But there is far more to it, with many subtle concerns; please read the docs and the links below. The prototypes are not like function signatures in compiled languages and are not intended to do that job, even though they may appear that way. Even a slight misuse can lead to subtle bugs. See

All that said, they can be useful if used appropriately. See ikegami's comments under OP.

Upvotes: 1

Ken Schumack
Ken Schumack

Reputation: 719

I think this type of thing is about the best you can currently do:

#!/usr/local/bin/perl -w
use strict;
require 5.020;
use warnings;
use feature qw( say signatures );
no warnings "experimental::signatures";

print "Enter your first name: ";
chomp(my $name1 = <STDIN>);

print "Enter your last name: ";
chomp(my $name2 = <STDIN>);

say "Calling takesOneOrTwoScalars with 2 args";
takesOneOrTwoScalars($name1, $name2);

say "Calling takesOneOrTwoScalars with 1 arg";
takesOneOrTwoScalars($name1);

say "Calling takesOneOrTwoScalars with 0 args";
takesOneOrTwoScalars();

sub takesOneOrTwoScalars($firstName, $lastName="")
{
    print "Hello, $firstName";
    if ($lastName)
    {
        say " $lastName";
    }
    else
    {
        say ", I see you didn't give your last name.";
    }
}

Upvotes: 2

Related Questions