Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

sub BEGIN

by Anonymous Monk
on May 10, 2010 at 03:57 UTC ( #839160=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to understand below pm. urnmap is hash reference? But I don't understand how to access sub BEGIN(is this something like anonymous sub but gets applied before code is compiled?
#===================================================================== +====== # # /home/f5cm/cm/bigip10.1.0/85935/f5_build/iControl/sdk/dist_image/iCo +ntrol-10.1.0/sdk/samples/soap/perl/soaplite//iControlTypeCast.pm # #===================================================================== +====== # # The contents of this file are subject to the "END USER LICENSE AGREE +MENT FOR F5 # Software Development Kit for iControl"; you may not use this file ex +cept in # compliance with the License. The License is included in the iControl # Software Development Kit. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See # the License for the specific language governing rights and limitatio +ns # under the License. # # The Original Code is iControl Code and related documentation # distributed by F5. # # The Initial Developer of the Original Code is F5 Networks, # Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996 +-2004 F5 Networks, # Inc. All Rights Reserved. iControl (TM) is a registered trademark o +f F5 Networks, Inc. # # Alternatively, the contents of this file may be used under the terms # of the GNU General Public License (the "GPL"), in which case the # provisions of GPL are applicable instead of those above. If you wis +h # to allow use of your version of this file only under the terms of th +e # GPL and not to allow others to use your version of this file under t +he # License, indicate your decision by deleting the provisions above and # replace them with the notice and other provisions required by the GP +L. # If you do not delete the provisions above, a recipient may use your # version of this file under either the License or the GPL. # package iControlTypeCast; require SOAP::Lite; my $urnMap; sub BEGIN { $urnMap = { "{urn:iControl}ASM.ApplyLearningType" => 1, "{urn:iControl}ASM.DynamicSessionsInUrlType" => 1, "{urn:iControl}ASM.FlagState" => 1, "{urn:iControl}ASM.PolicyTemplate" => 1, "{urn:iControl}ASM.ProtocolType" => 1, "{urn:iControl}ASM.SeverityName" => 1, "{urn:iControl}ASM.ViolationName" => 1, "{urn:iControl}ASM.WebApplicationLanguage" => 1, "{urn:iControl}Common.ArmedState" => 1, "{urn:iControl}Common.AuthenticationMethod" => 1, "{urn:iControl}Common.AvailabilityStatus" => 1, "{urn:iControl}Common.DaemonStatus" => 1, "{urn:iControl}Common.EnabledState" => 1, "{urn:iControl}Common.EnabledStatus" => 1, "{urn:iControl}Common.FileChainType" => 1, "{urn:iControl}Common.HAAction" => 1, "{urn:iControl}Common.HAState" => 1, "{urn:iControl}Common.IPHostType" => 1, "{urn:iControl}Common.ProtocolType" => 1, "{urn:iControl}Common.SourcePortBehavior" => 1, "{urn:iControl}Common.StatisticType" => 1, "{urn:iControl}Common.TMOSModule" => 1, "{urn:iControl}GlobalLB.AddressType" => 1, "{urn:iControl}GlobalLB.AutoConfigurationState" => 1, "{urn:iControl}GlobalLB.AvailabilityDependency" => 1, "{urn:iControl}GlobalLB.LBMethod" => 1, "{urn:iControl}GlobalLB.LDNSProbeProtocol" => 1, "{urn:iControl}GlobalLB.LinkWeightType" => 1, "{urn:iControl}GlobalLB.MetricLimitType" => 1, "{urn:iControl}GlobalLB.MonitorAssociationRemovalRule" => 1, "{urn:iControl}GlobalLB.MonitorInstanceStateType" => 1, "{urn:iControl}GlobalLB.MonitorRuleType" => 1, "{urn:iControl}GlobalLB.RegionDBType" => 1, "{urn:iControl}GlobalLB.RegionType" => 1, "{urn:iControl}GlobalLB.ServerType" => 1, "{urn:iControl}GlobalLB.Application.ApplicationObjectType" => +1, "{urn:iControl}GlobalLB.DNSSECKey.KeyAlgorithm" => 1, "{urn:iControl}GlobalLB.DNSSECKey.KeyType" => 1, "{urn:iControl}GlobalLB.Monitor.IntPropertyType" => 1, "{urn:iControl}GlobalLB.Monitor.StrPropertyType" => 1, "{urn:iControl}GlobalLB.Monitor.TemplateType" => 1, "{urn:iControl}LocalLB.AddressType" => 1, "{urn:iControl}LocalLB.AuthenticationMethod" => 1, "{urn:iControl}LocalLB.AvailabilityStatus" => 1, "{urn:iControl}LocalLB.ClientSSLCertificateMode" => 1, "{urn:iControl}LocalLB.ClonePoolType" => 1, "{urn:iControl}LocalLB.CompressionMethod" => 1, "{urn:iControl}LocalLB.CookiePersistenceMethod" => 1, "{urn:iControl}LocalLB.CredentialSource" => 1, "{urn:iControl}LocalLB.EnabledStatus" => 1, "{urn:iControl}LocalLB.HardwareAccelerationMode" => 1, "{urn:iControl}LocalLB.HttpChunkMode" => 1, "{urn:iControl}LocalLB.HttpCompressionMode" => 1, "{urn:iControl}LocalLB.HttpRedirectRewriteMode" => 1, "{urn:iControl}LocalLB.LBMethod" => 1, "{urn:iControl}LocalLB.MonitorAssociationRemovalRule" => 1, "{urn:iControl}LocalLB.MonitorInstanceStateType" => 1, "{urn:iControl}LocalLB.MonitorRuleType" => 1, "{urn:iControl}LocalLB.MonitorStatus" => 1, "{urn:iControl}LocalLB.PersistenceMode" => 1, "{urn:iControl}LocalLB.ProfileContextType" => 1, "{urn:iControl}LocalLB.ProfileMode" => 1, "{urn:iControl}LocalLB.ProfileType" => 1, "{urn:iControl}LocalLB.RamCacheCacheControlMode" => 1, "{urn:iControl}LocalLB.RtspProxyType" => 1, "{urn:iControl}LocalLB.SSLOption" => 1, "{urn:iControl}LocalLB.ServerSSLCertificateMode" => 1, "{urn:iControl}LocalLB.ServiceDownAction" => 1, "{urn:iControl}LocalLB.SessionStatus" => 1, "{urn:iControl}LocalLB.SnatType" => 1, "{urn:iControl}LocalLB.TCPCongestionControlMode" => 1, "{urn:iControl}LocalLB.TCPOptionMode" => 1, "{urn:iControl}LocalLB.UncleanShutdownMode" => 1, "{urn:iControl}LocalLB.VirtualAddressStatusDependency" => 1, "{urn:iControl}LocalLB.Class.ClassType" => 1, "{urn:iControl}LocalLB.Class.FileFormatType" => 1, "{urn:iControl}LocalLB.Class.FileModeType" => 1, "{urn:iControl}LocalLB.Monitor.IntPropertyType" => 1, "{urn:iControl}LocalLB.Monitor.StrPropertyType" => 1, "{urn:iControl}LocalLB.Monitor.TemplateType" => 1, "{urn:iControl}LocalLB.ProfilePersistence.PersistenceHashMetho +d" => 1, "{urn:iControl}LocalLB.ProfileUserStatistic.UserStatisticKey" +=> 1, "{urn:iControl}LocalLB.RAMCacheInformation.RAMCacheVaryType" = +> 1, "{urn:iControl}LocalLB.RateClass.DirectionType" => 1, "{urn:iControl}LocalLB.RateClass.DropPolicyType" => 1, "{urn:iControl}LocalLB.RateClass.QueueType" => 1, "{urn:iControl}LocalLB.RateClass.UnitType" => 1, "{urn:iControl}LocalLB.VirtualServer.VirtualServerCMPEnableMod +e" => 1, "{urn:iControl}LocalLB.VirtualServer.VirtualServerType" => 1, "{urn:iControl}Management.DebugLevel" => 1, "{urn:iControl}Management.LDAPPasswordEncodingOption" => 1, "{urn:iControl}Management.LDAPSSLOption" => 1, "{urn:iControl}Management.LDAPSearchMethod" => 1, "{urn:iControl}Management.LDAPSearchScope" => 1, "{urn:iControl}Management.OCSPDigestMethod" => 1, "{urn:iControl}Management.ZoneType" => 1, "{urn:iControl}Management.EventNotification.EventDataType" => +1, "{urn:iControl}Management.EventSubscription.AuthenticationMode +" => 1, "{urn:iControl}Management.EventSubscription.EventType" => 1, "{urn:iControl}Management.EventSubscription.ObjectType" => 1, "{urn:iControl}Management.EventSubscription.SubscriptionStatus +Code" => 1, "{urn:iControl}Management.KeyCertificate.CertificateType" => 1 +, "{urn:iControl}Management.KeyCertificate.KeyType" => 1, "{urn:iControl}Management.KeyCertificate.ManagementModeType" = +> 1, "{urn:iControl}Management.KeyCertificate.SecurityType" => 1, "{urn:iControl}Management.KeyCertificate.ValidityType" => 1, "{urn:iControl}Management.Provision.ProvisionLevel" => 1, "{urn:iControl}Management.SNMPConfiguration.AuthType" => 1, "{urn:iControl}Management.SNMPConfiguration.DiskCheckType" => +1, "{urn:iControl}Management.SNMPConfiguration.LevelType" => 1, "{urn:iControl}Management.SNMPConfiguration.ModelType" => 1, "{urn:iControl}Management.SNMPConfiguration.PrefixType" => 1, "{urn:iControl}Management.SNMPConfiguration.PrivacyProtocolTyp +e" => 1, "{urn:iControl}Management.SNMPConfiguration.SinkType" => 1, "{urn:iControl}Management.SNMPConfiguration.TransportType" => +1, "{urn:iControl}Management.SNMPConfiguration.ViewType" => 1, "{urn:iControl}Management.UserManagement.UserRole" => 1, "{urn:iControl}Networking.FilterAction" => 1, "{urn:iControl}Networking.FlowControlType" => 1, "{urn:iControl}Networking.LearningMode" => 1, "{urn:iControl}Networking.MediaStatus" => 1, "{urn:iControl}Networking.MemberTagType" => 1, "{urn:iControl}Networking.MemberType" => 1, "{urn:iControl}Networking.PhyMasterSlaveMode" => 1, "{urn:iControl}Networking.RouteEntryType" => 1, "{urn:iControl}Networking.STPLinkType" => 1, "{urn:iControl}Networking.STPModeType" => 1, "{urn:iControl}Networking.STPRoleType" => 1, "{urn:iControl}Networking.STPStateType" => 1, "{urn:iControl}Networking.ARP.NDPState" => 1, "{urn:iControl}Networking.Interfaces.MediaType" => 1, "{urn:iControl}Networking.ProfileWCCPGRE.WCCPGREForwarding" => + 1, "{urn:iControl}Networking.STPInstance.PathCostType" => 1, "{urn:iControl}Networking.SelfIPPortLockdown.AllowMode" => 1, "{urn:iControl}Networking.Trunk.DistributionHashOption" => 1, "{urn:iControl}Networking.Trunk.LACPTimeoutOption" => 1, "{urn:iControl}Networking.Trunk.LinkSelectionPolicy" => 1, "{urn:iControl}Networking.Tunnel.TunnelDirection" => 1, "{urn:iControl}Networking.VLANGroup.VLANGroupTransparency" => +1, "{urn:iControl}Networking.iSessionLocalInterface.NatSourceAddr +ess" => 1, "{urn:iControl}Networking.iSessionPeerDiscovery.DiscoveryMode" + => 1, "{urn:iControl}Networking.iSessionPeerDiscovery.FilterMode" => + 1, "{urn:iControl}Networking.iSessionRemoteInterface.NatSourceAdd +ress" => 1, "{urn:iControl}Networking.iSessionRemoteInterface.OriginState" + => 1, "{urn:iControl}System.CPUMetricType" => 1, "{urn:iControl}System.FanMetricType" => 1, "{urn:iControl}System.HardwareType" => 1, "{urn:iControl}System.PSMetricType" => 1, "{urn:iControl}System.TemperatureMetricType" => 1, "{urn:iControl}System.ConfigSync.ConfigExcludeComponent" => 1, "{urn:iControl}System.ConfigSync.ConfigIncludeComponent" => 1, "{urn:iControl}System.ConfigSync.LoadMode" => 1, "{urn:iControl}System.ConfigSync.SaveMode" => 1, "{urn:iControl}System.ConfigSync.SyncMode" => 1, "{urn:iControl}System.Disk.RAIDStatus" => 1, "{urn:iControl}System.Failover.FailoverMode" => 1, "{urn:iControl}System.Failover.FailoverState" => 1, "{urn:iControl}System.Services.ServiceAction" => 1, "{urn:iControl}System.Services.ServiceStatusType" => 1, "{urn:iControl}System.Services.ServiceType" => 1, "{urn:iControl}System.Statistics.GtmIQueryState" => 1, "{urn:iControl}System.Statistics.GtmPathStatisticObjectType" = +> 1, } } sub END {} #Implement Typecast for iControl enumeration Elements sub SOAP::Deserializer::typecast { my ($self, $value, $name, $attrs, $children, $type) = @_; my $retval = undef; if ( 1 == $urnMap->{$type} ) { $retval = $value; } return $retval; } # End Of File

Comment on sub BEGIN
Download Code
Re: sub BEGIN
by NetWallah (Abbot) on May 10, 2010 at 04:37 UTC
    From perlmod:

    Five specially named code blocks are executed at the beginning and at the end of a running Perl program. These are the BEGIN , UNITCHECK , CHECK , INIT , and END blocks.

    These code blocks can be prefixed with sub to give the appearance of a subroutine (although this is not considered good style). One should note that these code blocks don't really exist as named subroutines (despite their appearance).

    So - you cannot access BEGIN.

         Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

Re: sub BEGIN
by BrowserUk (Pope) on May 10, 2010 at 04:41 UTC
    is this something like anonymous sub but gets applied before code is compiled?

    It is a (specially) named block, called by Perl before processing the rest of the module. See perlmod for details.

    But I don't understand how to access sub BEGIN

    What do you mean by "access sub BEGIN"?

    If you mean how do you call it? You don't.

    If you mean how do you use the package? I think the answer is that in the normal way of things you wouldn't. It appears to be a sub package of a larger suite that is intended to be called internally only. The one subroutine (method?!) it contains--that rather nastily, remotely insinuates itself in to a complete different package space--is a rather clumsy replication of exists.

    Basically, once the module is loaded, the hash has been constructed. But, the BEGIN block is probably unnecessary. The module would work just the same without it.

    And whenever anyone calls SOAP::Deserializer::typecast() passing ($self, $value, $name, $attrs, $children, $type), if $type exists in the hash, it returns $value, otherwise undef.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      so basically BEGIN and END is just bad styling.(or at least unnecessary). thank you so much guys!!
        Almost certainly unnecessary. It depends on when $urnMap is used. If that's your whole file, then it is indeed unnecessary. I wouldn't say bad style.

        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        

        From my perspective, BEGIN blocks are a form of code smell. In this case, a variation on 'Inappropriate intimacy'.

        Several possibilities for a fix stand out:

        1. Making that hash a constant.
        2. Using inheritance rather than poking stuff into remote namespaces.
        3. If the use of the BEGIN block is required to make the code work as need, then a better solution would be to move the require.
        4. If the BEGIN block is a precautionary prophylactic, you might as well use cling film, because it is full of holes.

          What if the required module calls the overridden method within its own BEGIN block?

          Once you start the arms race of every programmer putting the bits of their code they think are of paramount importance in BEGIN blocks, soon everybody will be putting everything in BEGIN blocks, and you're back to square one with no solution.

        But the most interesting question here I think would be: why are you poking around in there anyway?

        That is, what led you in there? What are you trying to do that you're failing to achieve? What error situation are you trying to avoid? What is it that you're really asking for help with?

        If this is just an academic exercise of trying to improve your Perl by reading and understanding the internals of some examples, on the basis of what you've posted in isolation, you'd better pick some better examples.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://839160]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2014-09-17 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (66 votes), past polls