Re: marine subroutine



"Chas Owens" schreef:
Martin Barth:
Andrew Curry:

That's rubbish,

but you get a warning like:

main::a() called too early to check prototype at -e line 1.

Use Prototypes at the beginning of your file if you want to write the
subs at the end.
snip

This would be a good point but for the fact that prototypes are
fundamentally broken* in Perl 5 and should not be used except in very
specific cases.

Here is a few things to consider before using prototypes:

#!/usr/bin/perl

use strict;
use warnings;

sub foo ($) {
my $s = shift;
print "$s\n";
}

my @a = qw<a b c d e>;

print "with a prototype\n";
#this not an error
#do you know why?
foo(@a);

my $sub = \&foo;

#this isn't an error either,
#but it gets different results
#do you know why?
$sub->(@a);

#this won't error
#for the same reason
&foo($a[0], $a[1], $a[2]);

#this is also not an error
#but it produces yet another result
#do you know why?
foo(@a[0 .. $#a]);

#lets see what happens without prototypes
print "without a prototype\n";
bar(@a);
$sub = \&bar;
$sub->(@a);
&bar($a[0], $a[1], $a[2]);
bar(@a[0 .. $#a]);

sub bar {
my $s = shift;
print "$s\n";
}


* well, this is a bit harsh, they just don't do what most people
expect them to do.

This is nice content, but not presented well, so I wonder how many
people take the time to read and grok it.

Maybe you can transform it into an article, maybe both on this list and
on PerlMonks?

(and please give away the answers :)

--
Affijn, Ruud

"Gewoon is een tijger."

.



Relevant Pages

  • Re: kanjidic parser in Perl?
    ... they give programmers a false sense of security, because they only catch argument type and number errors under some circumstances and not others. ... that he make a point of including prototyped sub declarations ... I myself have found prototypes to be extremely valuable, ... John Chew http://www.poslfit.com ...
    (sci.lang.japan)
  • Re: Sweetest Accessor?
    ... care for mixing shift and @_ in the same sub -- visually. ... That isn't tied to shifting. ... You can't throw prototypes into an OO design. ...
    (comp.lang.perl.misc)
  • Re: marine subroutine
    ... but you get a warning like: ... Use Prototypes at the beginning of your file if you want to write the ... sub foo { ... my $s = shift; ...
    (perl.beginners)
  • Re: How to define a sub on the fly?
    ... > Anno Siegel wrote: ... They are the exception with sub definitions, ... use prototypes routinely with all subs. ...
    (comp.lang.perl.misc)
  • Re: why doesnt this argument list need a comma after the 1st argument?
    ... I'm reading this very interesting book on Perl (Effective Perl Programming ... that the anonymous subroutine does not require the "sub" keyword, ... Prototypes were introduced to allow you to write ... block (without a comma) like this, and treat it as an anon sub. ...
    (comp.lang.perl.misc)