2014-03-26

Perl Moose notes

Learn about constructors. Non-obvious gotchas


  • Do not define new() for your classes. Moose provides it. 
  • Attributes are initialized by themselves, or set from parameters that match their name when calling new
  • There are hooks in the methods BUILDARGS and BUILD that you can implenent to override pre- and post-construction. 
  • BUILDARGS receives as args the args passed to new.
  • BUILD is called after an object is instantiated. Used mostly to do assertions, logging

Learn about Moose is how Attributes work. Non-obvious gotchas:
  • If you want to provide a reference as a default, this has to be returned from an anonymous sub, so that each instance has ist own reference, and not all are sharing one and the same
  • You can provide an anonymous sub to initialize the default, or you can define the name of of a builder subroutine. Builder can be composed in by role or subclassed, preferable for anything but trivial cases
  • Make attributes with a builder lazy. Your subroutine to intialize the attribute may depend on values of other attributes, and these may not yet have been set. You must define the attribute as lazy to avoid issues. (What about circular refs?) 
  • Lazy builders are ony called when the value is accessed. This can happen anywhere, including inside a map or grep. $_ may have strange values at those times. Make it local $_; if you use it
  • has really is just a function call

No comments:

Post a Comment