It seems likely (functionally) unnecessary in this specific case. But some prefer not to analyze each specific case to try to convince themselves that it is actually foolproofly unnecessary and so just include BEGIN for such initializations as a "best practice". (The END block is likely just a visual reminder for "this is where you put clean-up code" and "I didn't forget the clean-up code, we just don't need any for this module at this time" -- as such, I might comment it out for the sake of clarity.)

The flow of the above code w/o the BEGIN goes like:

Compile: package iControlTypeCast; Compile: require SOAP::Lite; # nothing happens Compile: my $urnMap; # declares the variable Compile: $urnMap = ...; # nothing happens Compile: sub SOAP::Deserializer::typecast # makes it possible to cal +l this Run: require SOAP::Lite; # compiles and then runs S +OAP/Lite.pm # During the loading of SOAP::Lite, a whole ton # of stuff can happen and is likely to happen Run: my $urnMap = ...; # the variable is /finally +/ initialized

In this particular case, it seems unlikely that anything that happens during the loading of SOAP::Lite would lead to SOAP::Deserializer::typecast() being called. But I'd actually have to study the SOAP modules quite a bit more before I was fully convinced of that. It would certainly be bad style for that order of execution, IMHO. But I see no reason to just rely on such an order of execution never arising.

So it seems wise to avoid the window of time where SOAP::Deserializer::typecast() can be called while $urnMap is still not initialized. The BEGIN block avoids exactly that. So, I consider it good style/practice.

- tye        


In reply to Re^3: sub BEGIN (wise) by tye
in thread sub BEGIN by Anonymous Monk

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.