in reply to Considering Prototypes

it did appear that passing reference to data-structures (e.g. sub foo(\%) {}) wasn't too problematic: mainly coming down to issues of "semantic sugar" rather than unexpected behaviour. Is that a misconception?

I think it is, at least somewhat. Some of it comes down to who is doing the expecting, of course. I think it might help to show an example.

sub foo { my $array_reference = shift; print "foo: ", $array_reference->[0], "\n"; } sub bar (\@) { my $array_reference = shift; print "bar: ", $array_reference->[0], "\n"; } my @a1 = ( 1 ); my @a2 = ( \@a1 ); my $a3 = [ 3 ]; foo(@a1); foo(@a2); foo($a3); bar(@a1); bar(@a2); # bar($a3); # Can't do that because it would be a runtime error. bar(@$a3);

The first thing to notice is that both subs expect an array reference, right? Well, yes and no. They both want to receive an array reference, but the prototype'd sub forces the programmer to pass an array, not a reference to one. That's why bar($a3) errors out. It forces you to write bar(@$a3) instead. But that seems unnatural for a sub which is expecting a reference.

The second issue is that, with prototypes, the normal array flattening behavior that we've come to expect doesn't work any more. We can't stuff the arguments into an array and pass them to the prototyped sub. See the difference between foo(@a2) and bar(@a2)? It's worse when there is more than one argument. A function like sub baz (\@\@) { ... } expects to be called as baz(@qux, @quux) but without the prototype, those two arrays would be flattened into one. All of this might not be so bad if it weren't for issue three...

Where prototypes really fail is that they aren't enforced. Remember bar($a3)? Runtime error. That is, unless you call it as &bar($a3) in which case the prototype is circumvented. Same problem if you want to work with a reference to the bar sub.

my $subref = \&bar; $subref->(@a1); # Doesn't act like bar(@a1)...
And it won't work if bar() is a method call either. And again, these problems are even stickier when the sub in question is prototyped to take more than one argument like baz() above. Prototypes are circumvented, argument lists are flattened, and weird bugs appear without any nice error or warning messages to help you find them.

Basically, Perl's prototypes foster inconsistency when used as if they were real prototypes. There are a few good reasons to use them. Three that I know of:

  1. An empty prototype on a sub hints that a sub is a candidate for inlining.
  2. Creating subroutines that act like builtins.
  3. Extending the language syntax. (By writing subs that take a BLOCK.)

-sauoq
"My two cents aren't worth a dime.";