-1

This could be a duplicate question. I know perl doesn't restrict users on no of arguments and their types. But what does $,$$ and ; stands for in below code.

sub run($$;$) {
    my ( $x, $y, $z ) = @_;
....
}
serenesat
  • 4,611
  • 10
  • 37
  • 53
Bharat Pahalwani
  • 1,404
  • 3
  • 25
  • 40

1 Answers1

4

It's a prototype. An advanced perl feature that is generally not a good idea to use. It allow you to specify constraints on arguments to the subroutine.

In the above example, it specifies this subroutine takes two mandatory scalar parameters, and one optional scalar.

E.g.:

use strict;
use warnings;

sub with_proto($$;$) {
    print @_;
}

with_proto("A");
with_proto("A","B");
with_proto("A","B","C");
with_proto("A","B","C","D");

Errors with:

Not enough arguments for main::with_proto, line 9, near ""A")"
Too many arguments for main::with_proto, line 12, near ""D")"

Note though - this also errors:

my @args = ( "A", "B", "C" );
with_proto(@args);

Because despite having 3 elements in the list, the prototype says 'scalars'.

with_proto(@args, "A", "B");

Will print:

3AB

Because the prototype says 'scalar' it takes @args in a scalar context. Where you might expect if you'd done it like this:

sub without_proto {
    print @_;
}

my @args = ( "A", "B", "C" );
without_proto (@args, "A", "B");

You would get "ABCAB".

So at best, it's a feature that's just not as clear as it might seem, and isn't particularly similar to "prototypes" as you might know them in other languages.

Sobrique
  • 52,974
  • 7
  • 60
  • 101