You seem to misunderstand both BEGIN and prototypes.

Let's look at BEGIN first. It causes the enclosed code to be executed as soon as it is compiled.

For the following code:

print "a"; BEGIN { print "b"; } print "c";

the following happens:

BEGIN is completely useless around a sub definition because a sub definition doesn't produce any runnable code.

Now, let's look at prototypes. Prototypes affect how sub calls are parsed and they affect the code into which a sub call is compiled. Obviously, that means the prototype of a sub must be known at the time a call to the sub is encountered.

For the following code:

foo('bar'); sub foo($) { print "foo called: @_\n"; }
the following happens:

You need to declare the sub before any calls to the sub are compiled. It's the only way the sub call can be affected by the prototype.

sob foo($); foo('bar'); sub foo($) { print "foo called: @_\n"; }

By the way, prototypes are by and large discouraged in Perl. They are not a good way to check the validity of arguments.


In reply to Re: BEGIN block and prototyped subroutines by ikegami
in thread BEGIN block and prototyped subroutines by hangon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.