Class::Struct - Core module that provides object orientation

Class::Struct is a classic module that provides Perl with object-oriented functionality. The constructor new can be automatically generated and the accessor can be automatically generated. An accessor is a method for setting and retrieving fields.

The Perl Primer will show you how to have a hash reference as the basic type of an object and provide a scalar accessor.

Create a Point class with fields x and y

Let's use Class::Struct to create a Point class with fields x and y.

package Point;

use Class::Struct __PACKAGE__, {
  x =>'$',
  y =>'$',
};

use allows you to pass arguments after the module name.

The first argument is the package name. This argument specifies for which package the constructor or accessor should be generated. __PACKAGE__ is a function that returns the current package name and returns Point.

The second argument is hash reference that defines the field. An accessor is automatically generated.

Use of Point class

Let's use the Point class. Following the code above, write the following.

package main;

# Create object
my $point = Point->new(x => 1, y => 2);

# Get the value of the field using an accessor
my $x = $point->x;
my $y = $point->y;
print "($x, $y)\n";

# Set field value using accessor
$point->x(5);
$point->y(10);
my $x2 = $point->x;
my $y2 = $point->y;
print "($x2, $y2)\n";

For the main package, refer to Package Declaration article.

Call constructor new

You can call the constructor new. You can also pass the value of the field.

# Create object
my $point = Point->new(x => 1, y => 2);

Call accessor

You can call the accessor to set/get the value.

# Get the value of the field using an accessor
my $x = $point->x;
my $y = $point->y;
print "($x, $y)\n";

# Set field value using accessor
$point->x(5);
$point->y(10);
my $x2 = $point->x;
my $y2 = $point->y;
print "($x2, $y2)\n";

Is it possible to inherit with Class::Struct?

It is possible to inherit the class created by Class::Strcut, but as a limitation, you cannot add fields. If you want to inherit, most of the time you want to add a field, so it's a good idea to think that you can't.

If you plan to inherit, use bless to create the object for Perl cores only. When using the CPAN module, use a module that supports adding field definitions by inheritance.

Is it possible to override the constructor?

Class::Strcut will generate a constructor for the target class, so you cannot override the constructor.

If you plan to customize the constructor, use bless to create the object for Perl cores only. If you want to use the CPAN module, use a module that supports constructor customization.

Related Informatrion