Help-Site Computer Manuals
  Algorithms & Data Structures   Programming Languages   Revision Control
  Cameras   Computers   Displays   Keyboards & Mice   Motherboards   Networking   Printers & Scanners   Storage
  Windows   Linux & Unix   Mac

Pragma to implement constructor methods

Class::constr - Pragma to implement constructor methods


Class::constr - Pragma to implement constructor methods


Included in OOTools 2.21 distribution.

The latest versions changes are reported in the Changes file in this distribution.

The distribution includes:



    Perl version >= 5.6.1

    perl -MCPAN -e 'install OOTools'
Standard installation
From the directory where this file is located, type:

    perl Makefile.PL


    make test

    make install



    package MyClass ;


    # implement constructor without options

    use Class::constr ;


    # with all the possible options

    use Class::constr { name        => 'new_object' ,

                        pre_process => \&change_input,

                        default     => { propA => 'something' },

                        init        => [ qw( init1 init2 ) ] ,

                        copy        => 1

                        no_strict   => 1

                      } ;


    # init1 and init2 will be called at run-time


    # creates a new object and eventually validates

    # the properties if any validation property option is set

    my $object = MyClass->new(digits => '123');


This pragma easily implements constructor methods for your class, which are very efficient function templates that your modules may imports at compile time. ``This technique saves on both compile time and memory use, and is less error-prone as well, since syntax checks happen at compile time.'' (quoted from ``Function Templates'' in the perlref manpage).

Use it with Class::props and Object::props to automatically validate the input passed with new(), or use the no_strict option to accept unknown properties as well.

You can completely avoid to write the constructor mehtod by just using this pragma and eventually declaring the name and the init methods to call.


If you want to see some working example of this module, take a look at the source of my other distributions.


name => $name

The name of the constructor method. If you omit this option the 'new' name will be used by default.

no_strict => 0 | 1

With no_strict option set to a true value, the constructor method accepts and sets also unknown properties (i.e. not predeclared). You have to access the unknown properties without any accessor method. All the other options will work as expected. Without this option the constructor will croak if any property does not have an accessor method.

skip_autoload => 0 | 1

This option might be useful only if no_strict is true, and your package defines an AUTOLOAD sub. A true value will not try to set any unknown property by using the AUTOLOAD sub: it will just set the value ($$s{your_property} = $v) directly.

pre_process => \&$code

You can set a code reference to preprocess @_.

The original @_ is passed to the referenced pre_process CODE. Modify @_ in the CODE to change the actual input value.

    # This code will transform the @_ on input

    # if it's passed a ref to an ARRAY

    # [ qw|a b c| ] will become

    # ( a=>'a', b=>'b', c=>'c')


    use Class::constr

        { name       => 'new'

        , pre_process=> sub

                         { if ( ref $_[1] eq 'ARRAY' )

                            { $_[1] = { map { $_=>$_ } @{$_[1]} }




default => \%props | \&$method

Use this option to supply any default properties to the constructor. Setting a default is very similar to pass the properties/values pairs to the constructor, but properties passed as arguments will override defaults.

You can set the default to a HASH reference or to a method name or method reference. In case you use a method, it will be called at runtime with the blessed object passed in $_[0] and the other properties in the remaining @_; it must return a HASH reference.

init => $method | \@methods

Use this option if you want to call other methods in your class to further initialize the object. You can use methods names or method references.

After the assignation and validation of the properties (i.e. those passed to the constructor, the default properties and the copied properties), the initialization methods in the init option will be called. Each init method will receive the blessed object passed in $_[0] and the other properties in the remaining @_.

Any init method can cancel construction of the object by undefining $_[0]. This will cause the constructor to return undef. If you prefer, you can explicitly croak from your init method.


   use Class::constr

      { name       => 'new'

      , init       => 'too_many'



   sub too_many

      { if ( $MyClass::num_instances > $MyClass::max_instances)

         { $_[0] = undef # Do not allow new object to be returned



         { $MyClass::num_instances++



copy => 0 | 1

If this option is set to a true value, the constructor will be a ``copy constructor''. Copy constructors allow you to create a new object that inherits data from an existing object. Properties passed to the constructor will overwrite copied properties, that overwrite the default properties, and init methods will also have a chance to manipulate the values.

Warning: The copy constructor will only perform a shallow copy, which means that after a copy any references stored in properties will point to the same variable in both objects (the objects will share a single variable instead of each having its own private copy). If you don't want this behavior, you should reset these properties in your init method. Properties created by the Object::groups pragma are effected by this. Such properties should be explicitly set to undef in your init method for sane behavior.

Copy constructors may also be called as traditional class method constructors, but of course there will be no values to be copied into the new object. Generally, you will want to have a normal constructor to use when you don't need the copy functionality.

   package My::Class;

   use Class::constr

      ( { name       => 'new'

        , init       => '_init'


      , { name       => 'copy_me'

        , copy       => 1

        , init       => '_init_copy' # Special init undefs properties

                                     # containing shared references




   # Then in your program somewhere

   my $obj = My::Class->new( property => 1); 

   my $copy = $obj->copy_me(); # $copy->property == 1


If you need support or if you want just to send me some feedback or request, please use this link:


2004-2005 by Domizio Demichelis.

All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as perl itself.


Thanks to Juerd Waalboer ( that with its Attribute::Property inspired the creation of this distribution.

Thanks to Vince Veselosky (( for his patches and improvement.