Class::Std(3pm)
πΈ NAME πΈ
Class::Std β Support for creating standard "inside-out" classes π
β¨ VERSION β¨
This document describes Class::Std version 0.013. π
π SYNOPSIS π
package MyClass;
use Class::Std;
# Create storage for object attributes...
my %name : ATTR;
my %rank : ATTR;
my %snum : ATTR;
my %public_data : ATTR;
# Handle initialization of objects of this class...
sub BUILD {
my ($self, $obj_ID, $arg_ref) = @_;
$name{$obj_ID} = check_name( $arg_ref->{name} );
$rank{$obj_ID} = check_rank( $arg_ref->{rank} );
$snum{$obj_ID} = _gen_uniq_serial_num();
}
# Handle cleanup of objects of this class...
sub DEMOLISH {
my ($self, $obj_ID) = @_;
_recycle_serial_num( $snum{$obj_ID} );
}
# Handle unknown method calls...
sub AUTOMETHOD {
my ($self, $obj_ID, @other_args) = @_;
# Return any public data...
if ( m/\A get_(.*)/ ) { # Method name passed in $_
my $get_what = $1;
return sub {
return $public_data{$obj_ID}{$get_what};
}
}
warn "Can't call $method_name on ", ref $self, " object";
return; # The call is declined by not returning a sub ref
}
π DESCRIPTION π
This module provides tools that help to implement the "inside out object" class structure in a convenient and standard way. β¨
Portions of the following code and documentation from "Perl Best Practices" copyright (c) 2005 by O'Reilly Media, Inc. and reprinted with permission.
π¦ Introduction π¦
okay so bestie, most programmers who use Perl's object-oriented features construct their objects by blessing a hash. But lowkey that undermines the robustness of the OO approach. Hash-based objects are unencapsulated: their entries are open for the world to access and modify. π¬
Objects without effective encapsulation are vulnerable. Instead of politely respecting their public interface, some clever client coder inevitably will realize that it's marginally faster to interact directly with the underlying implementation, pulling out attribute values directly from the hash of an object:
for my $file ( get_file_objs() ) {
print $file->{name}, "\n";
}
instead of using the official interface:
for my $file ( get_file_objs() ) {
print $file->get_name(), "\n";
}
From the moment someone does that, your class is no longer cleanly decoupled from the code that uses it. You can't be sure that any bugs in your class are actually caused by the internals of your class, and not the result of some kind of monkeying by the client code. And to make matters worse, now you can't ever change those internals without the risk of breaking some other part of the system. π
There is a simple, convenient, and utterly secure way to prevent client code from accessing the internals of the objects you provide. Happily, that approach also guards against misspelling attribute names (a common error in hash-based classes), as well as being just as fast as--and often more memory-efficient than--ordinary hash-based objects. π
That approach is referred to by various names--flyweight scalars, warehoused attributes, inverted indices--but most commonly it's known as: inside-out objects. Consider the following class definitions:
package File::Hierarchy;
{
# Objects of this class have the following attributes...
my %root_of; # The root directory of the file hierarchy
my %files_of; # Array storing object for each file in root directory
# Constructor takes path of file system root directory...
sub new {
my ($class, $root) = @_;
# Bless a scalar to instantiate the new object...
my $new_object = bless \do{my $anon_scalar}, $class;
# Initialize the object's "root" attribute...
$root_of{ident $new_object} = $root;
return $new_object;
}
# Retrieve files from root directory...
sub get_files {
my ($self) = @_;
# Load up the "files" attribute, if necessary...
if (!exists $files_of{ident $self}) {
$files_of{ident $self}
= File::System->list_files($root_of{ident $self});
}
# Flatten the "files" attribute's array to produce a file list...
return @{ $files_of{ident $self} };
}
}
package File::Hierarchy::File;
{
# Objects of this class have the following attributes...
my %name_of; # the name of the file
# Constructor takes name of file...
sub new {
my ($class, $filename) = @_;
# Bless a scalar to instantiate the new object...
my $new_object = bless \do{my $anon_scalar}, $class;
# Initialize the object's "name" attribute...
$name_of{ident $new_object} = $filename;
return $new_object;
}
# Retrieve name of file...
sub get_name {
my ($self) = @_;
return $name_of{ident $self};
}
}
Unlike a hash-based class, each of these inside-out class is specified inside a surrounding code block:
package File::Hierarchy;
{
# [Class specification here]
}
package File::Hierarchy::File;
{
# [Class specification here]
}
That block is vital, because it creates a limited scope, to which any lexical variables that are declared as part of the class will automatically be restricted. π
The next difference between the two versions of the classes is that each attribute of all the objects in the class is now stored in a separate single hash:
# Objects of this class have the following attributes...
my %root_of; # The root directory of the file hierarchy
my %files_of; # Array storing object for each file in root directory
This is 90 degrees to the usual hash-based approach. In hash-based classes, all the attributes of one object are stored in a single hash; in inside-out classes, one attribute from all objects is stored in a single hash. Diagrammatically:
Hash-based:
Attribute 1 Attribute 2
Object A { attr1 => $valA1, attr2 => $val2 }
Object B { attr1 => $valB1, attr2 => $val2 }
Object C { attr1 => $valB1, attr2 => $val2 }
Inside-out:
Object A Object B Object C
Attribute 1 { 19817 => $valA1, 172616 => $valB1, 67142 => $valC1 }
Attribute 2 { 19817 => $valA2, 172616 => $valB2, 67142 => $valC3 }
Attribute 3 { 19817 => $valA3, 172616 => $valB3, 67142 => $valC3 }
So the attributes belonging to each object are distributed across a set of predeclared hashes, rather than being squashed together into one anonymous hash. ποΈ
This is a significant improvement. By telling Perl what attributes you expect to use, you enable the compiler to check--via use strict--that you do indeed use only those attributes. β
That's because of the third difference in the two approaches. Each attribute of a hash-based object is stored in an entry in the object's hash: $self->{name}. In other words, the name of a hash-based attribute is symbolic: specified by the string value of a hash key. In contrast, each attribute of an inside-out object is stored in an entry of the attribute's hash: $name_of{ident $self}. So the name of an inside-out attribute isn't symbolic; it's a hard-coded variable name. π
With hash-based objects, if an attribute name is accidentally misspelled in some method:
sub set_name {
my ($self, $new_name) = @_;
$self->{naem} = $new_name; # Oops!
return;
}
then the $self hash will obligingly--and silently!--create a new entry in the hash, with the key 'naem', then assign the new name to it. But since every other method in the class correctly refers to the attribute as $self->{name}, assigning the new value to $self->{naem} effectively makes that assigned value "vanish". π«
With inside-out objects, however, an object's "name" attribute is stored as an entry in the class's lexical %name_of hash. If the attribute name is misspelled then you're attempting to refer to an entirely different hash: %naem_of. Like so:
sub set_name {
my ($self, $new_name) = @_;
$naem_of{ident $self} = $new_name; # Kaboom!
return;
}
But, since there's no such hash declared in the scope, use strict will complain (with extreme prejudice):
Global symbol "%naem_of" requires explicit package name at Hierarchy.pm line 86
Not only is that consistency check now automatic, it's also performed at compile time. π΅οΈββοΈ
The next difference is even more important and beneficial. Instead of blessing an empty anonymous hash as the new object:
my $new_object = bless {}, $class;
the inside-out constructor blesses an empty anonymous scalar:
my $new_object = bless \do{my $anon_scalar}, $class;
That odd-looking "\do{my $anon_scalar}" construct is needed because there's no built-in syntax in Perl for creating a reference to an anonymous scalar; you have to roll-your-own. π²
The anonymous scalar is immediately passed to bless, which anoints it as an object of the appropriate class. The resulting object reference is then stored in $new_object.
Once the object exists, it's used to create a unique key ("ident $new_object") under which each attribute that belongs to the object will be stored (e.g. $root_of{ident $new_object} or $name_of{ident $self}). The "ident()" utility that produces this unique key is provided by the Class::Std module and is identical in effect to the "refaddr()" function in the standard Scalar::Util module. π
To recap: every inside-out object is a blessed scalar, and has--intrinsic to it--a unique identifying integer. That integer can be obtained from the object reference itself, and then used to access a unique entry for the object in each of the class's attribute hashes. π§
This means that every inside-out object is nothing more than an uninitialized scalar. When your constructor passes a new inside-out object back to the client code, all that comes back is an empty scalar, which makes it impossible for that client code to gain direct access to the object's internal state. π‘οΈ
okay so out of all the popular ways to reliably enforce encapsulation in Perl, inside-out objects are also, like, by far the cheapest. no contest, bestie. π
The run-time performance of inside-out classes is effectively identical to that of regular hash-based classes. and specifically? in both schemes, every single attribute access needs only one hash look-up. that's it. the only appreciable difference in speed happens when an inside-out object gets destroyed. that's the one moment it's different, periodt. π
Hash-based classes usually don't even have destructors. when the object's reference count decrements to zero, the hash gets automatically reclaimed, and any data structures stored inside the hash are likewise cleaned up. this works so well that a ton of OO Perl programmers find they never need to write a DESTROY() method β Perl's built-in garbage collection handles everything just fine. fr, the only time a destructor is actually needed is when objects have to manage resources outside that are not actually located inside the object, i.e. resources that need to be separately deallocated.
But. but. the whole entire point of an inside-out object is that its attributes are stored in allocated hashes that are not actually located inside the object. that's literally how it pulls off secure encapsulation: by not sending the attributes out into the client code. π
Unfortunately π that means when an inside-out object is eventually garbage collected, the only storage that gets reclaimed is the single blessed scalar implementing the object. the object's attributes are entirely unaffected by the object's deallocation, because the attributes aren't inside the object, and they're not referred to by it in any way either.
Instead, the attributes are referred to by the various attribute hashes they're stored in. and since those hashes will keep existing until the end of the program, the defunct object's orphaned attributes will likewise keep existing, safely nestled inside their respective hashes, but now untended by any object. in other words: when an inside-out object dies, its associated attribute hashes leak memory. π
The solution is simple. every inside-out class has to provide a destructor that "manually" cleans up the attributes of the object being destructed:
package File::Hierarchy;
{
# Objects of this class have the following attributes...
my %root_of; # The root directory of the file hierarchy
my %files_of; # Array storing object for each file in root directory
# Constructor takes path of file system root directory...
sub new {
# As before
}
# Retrieve files from root directory...
sub get_files {
# As before
}
# Clean up attributes when object is destroyed...
sub DESTROY {
my ($self) = @_;
delete $root_of{ident $self};
delete $files_of{ident $self};
}
}
The obligation to provide a destructor like this in every inside-out class can be mildly irritating, but it's still a very small price to pay for the considerable benefits that the inside-out approach otherwise provides for free. and honestly the irritation can easily be eliminated by using the appropriate class construction tools. see below. π
π¦ Automating Inside-Out Classes π¦
Perhaps the most annoying part about building classes in Perl (no matter how the objects are implemented) is that the basic structure of every class is more or less identical. for example, the implementation of the File::Hierarchy::File class used in File::Hierarchy looks like this:
package File::Hierarchy::File;
{
# Objects of this class have the following attributes...
my %name_of; # the name of the file
# Constructor takes name of file...
sub new {
my ($class, $filename) = @_;
# Bless a scalar to instantiate the new object...
my $new_object = bless \do{my $anon_scalar}, $class;
# Initialize the object's "name" attribute...
$name_of{ident $new_object} = $filename;
return $new_object;
}
# Retrieve name of file...
sub get_name {
my ($self) = @_;
return $name_of{ident $self};
}
# Clean up attributes when object is destroyed...
sub DESTROY {
my ($self) = @_;
delete $name_of{ident $self};
}
}
Apart from the actual names of the attributes, and their accessor methods, that's exactly the same structure, and even the same code, as in the File::Hierarchy class. wild, right?? π¦
Indeed, the standard infrastructure of every inside-out class looks exactly the same. so it makes sense not to have to rewrite that standard infrastructure code in every separate class. nobody has time for that. π
That's precisely what this module does: it implements the necessary infrastructure for inside-out objects. see below!
π INTERFACE π
π Exported subroutines π
ident()
Class::Std always exports a subroutine called ident(). this subroutine returns a unique integer ID for any object passed to it. that's the whole gig. π«Ά
πΈ Non-exported subroutines πΈ
Class::Std::initialize()
This subroutine sets up all the infrastructure to support your Class::Std-based class. it's usually called automatically in a CHECK block, or (if the CHECK block fails to run -- under mod_perl or require Class::Std or eval "...") during the first constructor call made to a Class::Std-based object. automatic. iconic. β¨
In rare circumstances, you may need to call this subroutine directly yourself. specifically: if you set up cumulative, restricted, private, or automethodical class methods (see below), and call any of them before you create any objects, then you need to call Class::Std::initialize() first. noted, bestie.
β¨ Methods created automatically β¨
The following subroutines are installed in any class that uses the Class::Std module. you get them for free. no cap. π
new()
Every class that loads the Class::Std module automatically has a new() constructor, which returns an inside-out object (i.e. a blessed scalar).
$obj = MyClass->new();
The constructor can be passed a single argument to initialize the object. this argument must be a hash reference.
$obj = MyClass->new({ name=>'Foo', location=>'bar' });
See the subsequent descriptions of the BUILD() and START() methods and :ATTR() trait, for an explanation of how the contents of this optional hash can be used to initialize the object.
β οΈ It is almost always an error to implement your ownnew()in any class that uses Class::Std. you almost certainly want to write aBUILD()orSTART()method instead. see below. π
DESTROY()
Every class that loads the Class::Std module automatically has a DESTROY() destructor, which automatically cleans up any attributes declared with the :ATTR() trait (see below). chef's kiss, it just handles it. π
β οΈ It is almost always an error to write your ownDESTROY()in any class that uses Class::Std. you almost certainly want to write your ownDEMOLISH()instead. see below.
AUTOLOAD()
Every class that loads the Class::Std module automatically has an AUTOLOAD() method, which implements the AUTOMETHOD() mechanism described below.
β οΈ It is almost always an error to write your ownAUTOLOAD()in any class that uses Class::Std. you almost certainly want to write your ownAUTOMETHOD()instead.
_DUMP()
This method returns a string that represents the internal state (i.e. the attribute values) of the object on which it's called. Only those attributes which are marked with an :ATTR (see below) are reported. Attribute names are reported only if they can be ascertained from an :init_arg, :get, or :set option within the :ATTR().
π‘ Note that _DUMP() is NOT designed to support full serialization/deserialization of objects. See the separate Class::Std::Storable module (on CPAN) for that. this one is giving "quick peek," not "whole archive." π«Ά
π Methods that can be supplied by the developer π
The following subroutines can be specified as standard methods of a Class::Std class. your turn to shine, bestie.
BUILD()
When the new() constructor of a Class::Std class is called, it automatically calls every method named BUILD() in all the classes in the new object's hierarchy. that is: when the constructor is called, it walks the class's inheritance tree (from base classes downwards) and calls every BUILD() method it finds along the way. so thorough of it. π
This means that, to initialize any class, you merely need to provide a BUILD() method for that class. you don't have to worry about ensuring that any ancestral BUILD() methods also get called β the constructor will take care of that. main character energy from the constructor, honestly. π
Each BUILD() method is called with three arguments: the invocant object, the identifier number of that object, and a reference to (a customized version of) the hash of arguments that was originally passed to the constructor:
sub BUILD {
my ($self, $ident, $args_ref) = @_;
...
}
The argument hash is a "customized version" because the module automatically does some fancy footwork to ensure that the arguments are the ones appropriate to the class itself. that's because there's a potential for collisions when Class::Std classes are used in a hierarchy. π§
One of the great advantages of using inside-out classes instead of hash-based classes is that an inside-out base class and an inside-out derived class can then each have an attribute of exactly the same name, which are stored in separate lexical hashes in separate scopes. in a hash-based object that's impossible, because the single hash can't have two attributes with the same key. no can do.
But that very advantage also presents something of a problem when constructor arguments are themselves passed by hash. if two or more classes in the name hierarchy do happen to have attributes of the same name, the constructor will need two or more initializers with the name key. which a single hash can't provide. π
The solution is to allow initializer values to be partitioned into distinct sets, each uniquely named, and which are then passed to the appropriate base class. the easiest way to accomplish that is to pass in a hash of hashes, where each top level key is the name of one of the base classes, and the corresponding value is a hash of initializers specifically for that base class.
For example:
...so the trick is: each class's BUILD() only fishes out the sub-hash that's keyed by its own class name. π
And because every class name is unique, the top-level keys of that multi-level initializer hash are guaranteed unique, no cap. And since no single class can have two attributes with the same name, the keys inside each second-level hash are unique too. So if two classes in the hierarchy both want an initializer literally called client_num, those two entries now live in separate sub-hashes and literally cannot clash. Clash-free. Iconic. β¨
package Client;
use Class::Std::Utils;
{
my %client_num_of :ATTR; # Every client has a basic ID number
my %name_of :ATTR;
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
$client_num_of{$ident} = $arg_ref->{'Client'}{client_num};
$name_of{$ident} = $arg_ref->{'Client'}{client_name};
}
}
package Client::Corporate;
use base qw( Client );
use Class::Std::Utils;
{
my %client_num_of; # Corporate clients have an additional ID number
my %corporation_of;
my %position_of;
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
$client_num_of{$ident}
= $arg_ref->{'Client::Corporate'}{client_num};
$corporation_of{$ident}
= $arg_ref->{'Client::Corporate'}{corp_name};
$position_of{$ident}
= $arg_ref->{'Client::Corporate'}{position};
}
}
# and later...
my $new_client
= Client::Corporate->new( {
'Client' => {
client_num => '124C1',
client_name => 'Humperdinck',
},
'Client::Corporate' => {
client_num => 'F_1692',
corp_name => 'Florin',
position => 'CEO',
},
});
Class::Std also does an even more sophisticated version of this glow-up, and honestly it's so much comfier for anyone actually using your classes. π«Ά Classes built on Class::Std infrastructure let you pass both general initializers and class-specific ones in the same initialization hash. You only have to name a class for those initializers whose names are genuinely ambiguous. Everything else just goes straight into the top-level hash:
my $new_client
= Client::Corporate->new( {
client_name => 'Humperdinck',
corp_name => 'Florin',
position => 'CEO',
'Client' => { client_num => '124C1' },
'Client::Corporate' => { client_num => 'F_1692' },
});
And Class::Std makes it stupid-easy for each class's BUILD() to actually reach those class-specific initializer values. Before every BUILD() gets invoked, the nested hash whose key matches the class name gets flattened right back into the initializer hash itself. So like, Client::BUILD() gets handed this hash:
{
client_name => 'Humperdinck',
corp_name => 'Florin',
position => 'CEO',
client_num => '124C1', # Flattened from 'Client' nested subhash
'Client' => { client_num => '124C1' },
'Client::Corporate' => { client_num => 'F_1692' },
}
whereas Client::Corporate::BUILD() gets handed this one:
{
client_name => 'Humperdinck',
corp_name => 'Florin',
position => 'CEO',
client_num => 'F_1692', # Flattened from 'Client::Corporate' subhash
'Client' => { client_num => '124C1' },
'Client::Corporate' => { client_num => 'F_1692' },
}
Which means each class's BUILD() can just assume the correct class-specific initializer values are sitting right there at the top level of the hash. Bestie, look:
sub Client::BUILD {
my ($self, $ident, $arg_ref) = @_;
$client_num_of{$ident} = $arg_ref->{client_num}; # '124C1'
$name_of{$ident} = $arg_ref->{client_name};
}
sub Client::Corporate::BUILD {
my ($self, $ident, $arg_ref) = @_;
$client_num_of{$ident} = $arg_ref->{client_num}; # 'F_1692'
$corporation_of{$ident} = $arg_ref->{corp_name};
$position_of{$ident} = $arg_ref->{position};
}
Both classes are reading the $arg_ref->{client_num} initializer value, but Class::Std automatically arranges for that value to be the right one for whichever class is asking. The way that it justβ¦ handles it. ππ
Also go peek at the :ATTR() marker (described further down, promise π) for a way simpler way of initializing attributes.
β¨ "START()" β¨
Once all of a class's BUILD() methods have been called, and any initialization values or defaults have been applied afterwards to whatever attributes were still uninitialized, Class::Std arranges for any START() methods in the class's hierarchy to be called before the constructor finishes. So picture it: after the build and default-init processes are done, the constructor walks down the class's inheritance tree a second time and calls every START() method it finds along the way. πΆββοΈπ³
Just like with BUILD(), every START() method gets called with three arguments: the invocant object, the identifier number of that object, and a reference to (a customized version of) the hash of arguments that was originally passed to the constructor.
The main difference between BUILD() and START() is timing, babes:
- A
BUILD()method runs before any attribute of the class is auto-initialized or default-initialized. - A
START()method runs after all the attributes of the class (including attributes from derived classes) have been initialized in some way.
So if you wanna pre-empt the initialization process β write a BUILD(). But if you wanna do something with the newly created, fully initialized object β write a START() instead. And obviously any class can define both a BUILD() and a START(), if that's what the situation calls for. π
β¨ "DEMOLISH()" β¨
The DESTROY() method that Class::Std automatically provides makes sure that all the marked attributes (that's the :ATTR() marker, more below πΈ) of an object β from every class in its inheritance hierarchy β get automatically cleaned up. Effortless. Gorgeous. She does it herself.
But if a class needs other destructor behaviours (closing filehandles, decrementing allocation counts, whatever else π«§), then you might need to specify those explicitly.
Whenever an object of a Class::Std class is destroyed, the DESTROY() method that Class::Std supplies automatically calls every method named DEMOLISH() in all the classes in the new object's hierarchy. So like, when the destructor fires, it walks the class's inheritance tree (from derived classes upwards π¦) and calls every DEMOLISH() it finds along the way.
That means to clean up any class, you literally only need to provide a DEMOLISH() method for that class. You don't gotta stress about making sure any ancestral DEMOLISH() methods also get called β the destructor handles all of that for you. Periodt.
Every DEMOLISH() method is called with two arguments: the invocant object, and the identifier number of that object. For example:
sub DEMOLISH {
my ($self, $ident) = @_;
$filehandle_of{$ident}->flush();
$filehandle_of{$ident}->close();
}
Heads up bestie π: the object's attributes are cleaned up after the DEMOLISH() method is complete, so you can absolutely still use them inside that method.
β¨ "AUTOMETHOD()" β¨
Okay so there's a pretty significant problem with Perl's built-in AUTOLOAD mechanism, and it's giving red flag π©: there's no way for a particular AUTOLOAD() to just say "no".
If two or more classes in a class hierarchy have separate AUTOLOAD() methods, then the one belonging to the left-most-depth-first class in the inheritance tree always gets invoked in preference to any of the others. And if it can't handle a particular call, that call will probably fail catastrophically. π Which means derived classes can't always be used in place of base classes β a feature known as "Liskov substitutability" β because their inherited autoloading behaviour might get pre-empted by some other, unrelated base class sitting to their left in the hierarchy. Not the vibe.
Class::Std provides a mechanism that solves this whole mess: the AUTOMETHOD method. An AUTOMETHOD() is expected to return either a handler subroutine that implements the requested method functionality, or an undef to indicate that it doesn't know how to handle the request. Class::Std then coordinates every AUTOMETHOD() in an object's hierarchy, trying each one in turn until one of them produces a suitable handler. Teamwork, honestly. π«Ά
The advantage of this approach is that the first AUTOMETHOD() invoked doesn't have to disenfranchise every other AUTOMETHOD() in the hierarchy. If the first one can't handle a particular method call, it just simply declines it and Class::Std tries the next candidate instead. No drama, no casualties. β¨
Using AUTOMETHOD() instead of AUTOLOAD() makes a class cleaner, more robust, and less disruptive in class hierarchies. For example:
package Phonebook;
use Class::Std;
{
my %entries_of : ATTR;
# Any method call is someone's name:
# so store their phone number or get it...
sub AUTOMETHOD {
my ($self, $ident, $number) = @_;
my $subname = $_; # Requested subroutine name is passed via $_
# Return failure if not a get_<name> or set_<name>
# (Next AUTOMETHOD() in hierarchy will then be tried instead)...
my ($mode, $name) = $subname =~ m/\A ([gs]et)_(.*) \z/xms
or return;
# If get_<name>, return a handler that just returns the old number...
return sub { return $entries_of{$ident}->{$name}; }
if $mode eq 'get';
# Otherwise, set_<name>, so return a handler that
# updates the entry and then returns the old number...
return sub {
$entries_of{$ident}->{$name} = $number;
return;
};
}
}
# and later...
my $lbb = Phonebook->new();
$lbb->set_Jenny(867_5309);
$lbb->set_Glenn(736_5000);
print $lbb->get_Jenny(), "\n";
print $lbb->get_Glenn(), "\n";
okay bestie pay attention to this one because it's lowkey the whole point π«Ά Unlike AUTOLOAD(), an AUTOMETHOD() gets called with both the invocant and the invocant's unique ident number, followed by the actual arguments that were passed to the method. So you're not out here guessing who you are, fr fr.
And also, the name of the method being called arrives as $_ instead of $AUTOLOAD, and it does NOT have the class name glued onto the front. So you don't have to strip that name off the front like almost everyone almost always does in their AUTOLOAD() β no cap. And if your AUTOMETHOD() also needs to peek at the $_ from the caller's scope? That's still right there as $CALLER::_. π
β¨ Variable traits that can be ascribed β¨
These are the markers you can drop into the definition of any hash used as attribute storage inside a Class::Std class:
":ATTR()"β this marker says "hey, this lexical hash is storing one particular attribute for all the objects of this class." Like so:
package File::Hierarchy;
{
my %root_of :ATTR;
my %files_of :ATTR;
# etc.
}
package File::Hierarchy::File;
{
my %name_of; :ATTR;
# etc.
}
Slapping the :ATTR marker on an attribute hash guarantees that the corresponding attribute belonging to each object of the class gets automatically cleaned up when the object is destroyed. π§Ήβ¨
The :ATTR marker can also take a bunch of options that automate other attribute-related behaviours. Each option is a key/value pair, and you can write it in either Perl 5 "fat comma" syntax (key => 'value') or in one of the Perl 6 option syntaxes (:key<value> or :key('value') or :keyXvalueX).
Heads up: due to a limitation in Perl itself, the complete :ATTR marker β including its options β must appear on a single line. interpolate variables into the option values
":ATTR( :init_arg<initializer_key> )"
This option tells Class::Std which key in the constructor's initializer hash holds the value that the marked attribute should be initialized with. So instead of writing this whole entire thing:
my %rank_of :ATTR;
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
$rank_of{$ident} = $arg_ref->{rank};
}
you get the exact same initialization by letting Class::Std automatically yank that entry out of the hash and stash it in the right attribute:
my %rank_of :ATTR( :init_arg<rank> );
# No BUILD() method required
no BUILD() required bestie, we love to see it ππ
":ATTR( :default<compile_time_default_value> )"
If a marked attribute never gets initialized (not directly inside a BUILD(), not automatically via an :init_arg option), the constructor that Class::Std hands you checks whether a default value was specified for that attribute. If it was β boom, that value gets assigned. β¨
So you could replace this:
my %seen_of :ATTR;
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
$seen_of{$ident} = 0; # Not seen yet
}
with:
my %seen_of :ATTR( :default(0) );
# No BUILD() required
Important: only literal strings and numbers can be used as default values. A very common mistake is writing:my %seen_of :ATTR( :default($some_variable) );But variables like that do NOT get interpolated into:ATTRmarkers (this is a limitation of Perl, not Class::Std, so don't blame the module π).
If your attribute needs something fancier, you'll have to default-initialize it in a START() method:
my %seen_of :ATTR;
sub START {
my ($self, $id, $args_ref) = @_;
if (!defined $seen_of{$id}) {
$seen_of{$id} = $some_variable;
}
}
":ATTR( :get<name> )"
Specify the :get option and a read accessor gets created for the corresponding attribute. The accessor's name is get_ followed by whatever name you passed as the value of the :get option. So instead of:
my %current_count_of :ATTR;
sub get_count {
my ($self) = @_;
return $current_count_of{ident($self)};
}
you can just write:
my %count_of :ATTR( :get<count> );
Heads up: there is no way to stop Class::Std from adding that initial get_ to every accessor name it creates. That's literally what "standard" means. π See Chapter 15 of Perl Best Practices (O'Reilly, 2005) for a full discussion on why accessors should be named this way.
":ATTR( :set<name> )"
Specify the :set option and a write accessor gets created for the corresponding attribute. The accessor's name is set_ followed by whatever name you passed as the value of the :set option. So instead of:
my %current_count_of :ATTR;
sub set_count {
my ($self, $new_value) = @_;
croak "Missing new value in call to 'set_count' method"
unless @_ == 2;
$current_count_of{ident($self)} = $new_value;
}
you can just write:
my %count_of :ATTR( :set<count> );
Heads up again: there is no way to stop Class::Std from adding that initial set_ to each accessor name it creates. And nor is there any way to create a combined "getter/setter" accessor. See Chapter 15 of Perl Best Practices (O'Reilly, 2005) for a full discussion on why accessors should be named and implemented this way. π
":ATTR( :name<name> )"
Specifying the :name option is just a convenient shorthand for specifying all three of :get, :set, and :init_arg at once. Slay. π
And you can, of course, specify two or more arguments in a single :ATTR() specification:
my %rank_of : ATTR( :init_arg<starting_rank> :get<rank> :set<rank> );
":ATTRS()"
This is just another name for the :ATTR marker (see above π). The plural form comes in clutch when you want to specify a whole series of attribute hashes in the same statement:
my (
%name_of,
%rank_of,
%snum_of,
%age_of,
%unit_of,
%assignment_of,
%medals_of,
) : ATTRS;
β¨ Method traits that can be ascribed β¨
These markers can be added to the definition of any subroutine used as a method inside a Class::Std class:
":RESTRICTED()" and ":PRIVATE()" π§
Sometimes it's genuinely useful to make subroutines that can only be reached from inside a class's own hierarchy β that is, by derived classes. And sometimes it's even more useful to make methods that can only be called from inside one specific class. π
Usually these are utility methods: little subroutines that do some internal service for a class, or for a whole class hierarchy. Class::Std supports making these by giving you two special markers: :RESTRICTED() and :PRIVATE().
Methods marked :RESTRICTED() get modified at the end of the compilation phase so that they throw an exception when called from outside a class's hierarchy. Methods marked :PRIVATE() get modified so that they throw an exception when called from outside the class in which they're declared. No sneaking in, bestie. π«
Check it:
package DogTag;
use Class::Std;
{
my %ID_of : ATTR;
my %rank_of : ATTR;
my $ID_num = 0;
sub _allocate_next_ID : RESTRICTED {
my ($self) = @_;
$ID_of{ident $self} = $ID_num++;
return;
}
sub _check_rank : PRIVATE {
my ($rank) = @_;
return $rank if $VALID_RANK{$rank};
croak "Unknown rank ($rank) specified";
}
sub BUILD {
my ($self, $ident, $arg_ref) = @_;
$self->_allocate_next_ID();
$rank_of{$ident} = _check_rank($arg_ref->{rank});
}
}
Obviously this code would run exactly the same without the :RESTRICTED() and :PRIVATE() markers β but the markers make sure that any attempt to call those two subroutines inappropriately:
package main;
my $dogtag = DogTag->new({ rank => 'PFC' });
$dogtag->_allocate_next_ID();
gets suitably punished π:
Can't call restricted method DogTag::_allocate_next_ID() from class main
":CUMULATIVE()"
One of the most iconic advantages of using the BUILD() and DEMOLISH() mechanisms that Class::Std supplies is that those methods don't require nested calls to their ancestral methods via the SUPER pseudo-class. The constructor and destructor that Class::Std provides take care of the necessary redispatching automatically. Every BUILD() method gets to focus solely on its own responsibilities β it doesn't have to also help orchestrate the cumulative constructor effects across the class hierarchy by remembering to call $self->SUPER::BUILD(). That's the dream, honestly. πβ¨
And also β calls via SUPER can only ever call the method of exactly one ancestral class, which is not sufficient under multiple inheritance. Yeah. π
So Class::Std hands you a different way of creating methods whose effects accumulate through a class hierarchy, the same way BUILD() and DEMOLISH() do. Specifically, the module lets you define your own cumulative methods. π
okay so bestie, pop quiz: what even is a cumulative method, and why is she giving main character energy? β¨
An ordinary non-cumulative method hides any method of the same name that was inherited from any base class. so when a non-cumulative method gets called, only the most-derived version of it is ever invoked. no sharing, no passing it down the family group chat. π€
A cumulative method, though?? she does NOT hide her ancestral methods of the same name. she assimilates them. π when a cumulative method is called, the most-derived version of it is invoked first, then any parental versions, then any grandparental versions, etc. etc., until every cumulative method of the same name throughout the entire hierarchy has been called. it's giving family reunion, and everyone showed up. π«Ά
For example, you could define a cumulative describe() method on the various classes in a simple class hierarchy like so:
package Wax::Floor;
use Class::Std;
{
my %name_of :ATTR( init_arg => 'name' );
my %patent_of :ATTR( init_arg => 'patent' );
sub describe :CUMULATIVE {
my ($self) = @_;
print "The floor wax $name_of{ident $self} ",
"(patent: $patent_of{ident $self})\n";
return;
}
}
package Topping::Dessert;
use Class::Std;
{
my %name_of :ATTR( init_arg => 'name' );
my %flavour_of :ATTR( init_arg => 'flavour' );
sub describe :CUMULATIVE {
my ($self) = @_;
print "The dessert topping $name_of{ident $self} ",
"with that great $flavour_of{ident $self} taste!\n";
return;
}
}
package Shimmer;
use base qw( Wax::Floor Topping::Dessert );
use Class::Std;
{
my %name_of :ATTR( init_arg => 'name' );
my %patent_of :ATTR( init_arg => 'patent' );
sub describe :CUMULATIVE {
my ($self) = @_;
print "New $name_of{ident $self} ",
"(patent: $patent_of{ident $self})\n",
"Combining...\n";
return;
}
}
Because the various describe() methods are marked as being cumulative, a subsequent call to:
my $product
= Shimmer->new({
name => 'Shimmer',
patent => 1562516251,
flavour => 'Vanilla',
});
$product->describe();
will work its way up through the classes of Shimmer's inheritance tree (in the same order as a destructor call would), calling each describe() method it finds along the way. So that single call to describe() invokes the corresponding method in each class, producing:
New Shimmer (patent: 1562516251)
Combining...
The floor wax Shimmer (patent: 1562516251)
The dessert topping Shimmer with that great Vanilla taste!
Note that the accumulation of describe() methods is hierarchical, and dynamic in nature. That is, each class only sees those cumulative methods that are defined in its own package or in one of its ancestors. So calling the same describe() on a base class object:
my $wax
= Wax::Floor->new({ name=>'Shimmer ', patent=>1562516251 });
$wax->describe();
only invokes the corresponding cumulative methods from that point on up the hierarchy, and hence only prints:
The floor wax Shimmer (patent: 1562516251)
Cumulative methods also accumulate their return values. In a list context, they return a (flattened) list that accumulates the lists returned by each individual method invoked. π
In a scalar context, a set of cumulative methods returns an object that, in a string context, concatenates individual scalar returns to produce a single string. When used as an array reference, that same scalar-context-return object acts like an array of the list context values. When used as a hash reference, the object acts like a hash whose keys are the classnames from the object's hierarchy, and whose corresponding values are the return values of the cumulative method from that class. she's multi-talented, she contains multitudes, she's literally everything. π
For example, if the classes each have a cumulative method that returns their list of sales features:
package Wax::Floor;
use Class::Std;
{
sub feature_list :CUMULATIVE {
return ('Long-lasting', 'Non-toxic', 'Polymer-based');
}
}
package Topping::Dessert;
use Class::Std;
{
sub feature_list :CUMULATIVE {
return ('Low-carb', 'Non-dairy', 'Sugar-free');
}
}
package Shimmer;
use Class::Std;
use base qw( Wax::Floor Topping::Dessert );
{
sub feature_list :CUMULATIVE {
return ('Multi-purpose', 'Time-saving', 'Easy-to-use');
}
}
then calling feature_list() in a list context:
my @features = Shimmer->feature_list();
print "Shimmer is the @features alternative!\n";
would produce a concatenated list of features, which could then be interpolated into a suitable sales-pitch:
Shimmer is the Multi-purpose Time-saving Easy-to-use
Long-lasting Non-toxic Polymer-based Low-carb Non-dairy
Sugar-free alternative!
It's also possible to specify a set of cumulative methods that start at the base class(es) of the hierarchy and work downwards, the way BUILD() does. To get that effect, you simply mark each method with :CUMULATIVE(BASE FIRST), instead of just :CUMULATIVE. For example:
package Wax::Floor;
use Class::Std;
{
sub active_ingredients :CUMULATIVE(BASE FIRST) {
return "\tparadichlorobenzene, cyanoacrylate, peanuts\n";
}
}
package Topping::Dessert;
use Class::Std;
{
sub active_ingredients :CUMULATIVE(BASE FIRST) {
return "\tsodium hypochlorite, isobutyl ketone, ethylene glycol\n";
}
}
package Shimmer;
use Class::Std;
use base qw( Wax::Floor Topping::Dessert );
{
sub active_ingredients :CUMULATIVE(BASE FIRST) {
return "\taromatic hydrocarbons, xylene, methyl mercaptan\n";
}
}
So a scalar-context call to active_ingredients():
my $ingredients = Shimmer->active_ingredients();
print "May contain trace amounts of:\n$ingredients";
would start in the base classes and work downwards, concatenating base-class ingredients before those of the derived class, to produce:
May contain trace amounts of:
paradichlorobenzene, cyanoacrylate, peanuts
sodium hypochlorite, isobutyl ketone, ethylene glycol
aromatic hydrocarbons, xylene, methyl mercaptan
Or, you could treat the return value as a hash:
print Data::Dumper::Dumper \%{$ingredients};
and see which ingredients came from where:
$VAR1 = {
'Shimmer'
=> 'aromatic hydrocarbons, xylene, methyl mercaptan',
'Topping::Dessert'
=> 'sodium hypochlorite, isobutyl ketone, ethylene glycol',
'Wax::Floor'
=> 'Wax: paradichlorobenzene, hydrogen peroxide, cyanoacrylate',
};
π¨ bestie, important!! you can't specify both:CUMULATIVEand:CUMULATIVE(BASE FIRST)on methods of the same name in the same hierarchy. The resulting set of methods would have no well-defined invocation order, soClass::Stdthrows a compile-time exception instead. she will not tolerate chaos in the group chat. π
:STRINGIFY β¨
If you define a method and add the :STRINGIFY marker, then that method is used whenever an object of the corresponding class needs to be coerced to a string. In other words, instead of:
# Convert object to a string...
sub as_str {
...
}
# Convert object to a string automatically in string contexts...
use overload (
q{""} => 'as_str',
fallback => 1,
);
you can just write:
# Convert object to a string (automatically in string contexts)...
sub as_str : STRINGIFY {
...
}
:NUMERIFY π’
If you define a method and add the :NUMERIFY marker, then that method is used whenever an object of the corresponding class needs to be coerced to a number. In other words, instead of:
# Convert object to a number...
sub as_num {
...
}
# Convert object to a string automatically in string contexts...
use overload (
q{0+} => 'as_num',
fallback => 1,
);
you can just write:
# Convert object to a number (automatically in numeric contexts)...
sub as_num : NUMERIFY {
...
}
:BOOLIFY π
If you define a method and add the :BOOLIFY marker, then that method is used whenever an object of the corresponding class needs to be coerced to a boolean value. In other words, instead of:
# Convert object to a boolean...
sub as_bool {
...
}
# Convert object to a boolean automatically in boolean contexts...
use overload (
q{bool} => 'as_bool',
fallback => 1,
);
you can just write:
# Convert object to a boolean (automatically in boolean contexts)...
sub as_bool : BOOLIFY {
...
}
:SCALARIFY π :ARRAYIFY πΈ :HASHIFY π¦ :GLOBIFY β :CODIFY π
If a method is defined with one of these markers, then it is automatically called whenever an object of that class is treated as a reference of the corresponding type. no manual overload wrangling, she just knows. β¨
For example, instead of:
sub as_hash {
my ($self) = @_;
return {
age => $age_of{ident $self},
shoesize => $shoe_of{ident $self},
};
}
use overload (
'%{}' => 'as_hash',
fallback => 1,
);
you can just write:
sub as_hash : HASHIFY {
my ($self) = @_;
return {
age => $age_of{ident $self},
shoesize => $shoe_of{ident $self},
};
}
And it's the SAME deal for the other reference-flavoured markers, bestie: methods that let an object cosplay as a scalar reference get :SCALARIFY, ones that go array reference get :ARRAYIFY, ones that serve subroutine reference realness get :CODIFY, and the ones doing typeglob reference energy get :GLOBIFY. β¨
π©Ί DIAGNOSTICS π©Ί
Class::Std is a talkative king and it WILL tell you exactly what went wrong. Here's the whole group chat of complaints, no cap:
Can't find class %sβ bestie you tried to run theClass::Std::new()constructor on a class that isn't even built with Class::Std. Classic move. Did you forget to writeuse Class::Stdright after thepackagedeclaration? Go check. πArgument to %s->new() must be hash referenceβ the constructors that Class::Std makes for you need ALL the initializer values handed over in a hash, and you handed over something that was NOT a hash. Put your constructor arguments in a hash. That's the whole vibe. πMissing initializer label for %s: %sβ you said one or more attributes had initializer values (that's theinitargument you put inside the attribute'sATTRmarker, iykyk), but then you never actually passed the matching initialization value in. Usually this happens because you DID pass the value but the key naming the attribute got misspelled. Spelling is not a suggestion, bestie. πCan't make anonymous subroutine cumulativeβ you tried to slap the:CUMULATIVEmarker on an anonymous subroutine, and nope, that marker only works on the named methods of a class. Either turn that anonymous sub into a named sub, or figure out some other way to make it play nice with the other methods. πConflicting definitions for cumulative method: %sβ you defined a:CUMULATIVEmethod AND a:CUMULATIVE(BASE FIRST)method with the same name in two classes inside the same hierarchy. And like... methods can only be called going strictly up the hierarchy or going strictly down it, so asking for both directions is objectively a mistake. Rename one of them, or decide: up or down? Pick one. No both. π₯Missing new value in call to 'set_%s' methodβ you called an attribute setter without giving it a new value for the attribute. Super common cause: you passed an array that happened to be empty. Please pass an actual value. An empty array is not a value, it's a cry for help. πCan't locate %s method "%s" via package %sβ you called a method on an object and like... that method doesn't exist ANYWHERE in the object's class hierarchy. Did you misspell the method name, or did you misunderstand which class the object actually belongs to? Vibe check the object first. π§%s method %s declared but not definedβ a method got declared with:RESTRICTEDor:PRIVATE, like this:
sub foo :RESTRICTED;
sub bar :PRIVATE;
...but the actual subroutine never got defined by the end of the compilation phase, which is when the module needed it so it could rewrite it to be restricted or privatized. Defining the thing is kind of the point. π
Can't call restricted method %s from class %sβ that method was declared with the:RESTRICTEDmarker and then you called it from outside its class hierarchy. Wrong method? Right method, wrong place? Either way, it's a no from the marker. βCan't call private method %s from class %sβ same energy, but with:PRIVATE: the method was declared private and then called from outside its own class. Did you call the wrong method, or the right method from the wrong place? Again. Be honest. πΈInternal error: %sβ okay first of all, your code is fine. π Your code is okay, but it uncovered a bug in the Class::Std module itself. Head to BUGS AND LIMITATIONS below, it explains how to report the problem.
βοΈ CONFIGURATION AND ENVIRONMENT βοΈ
The easiest section of your life: Class::Std requires no configuration files and no environment variables. Nothing to set. Nothing to export. Go touch grass. π
π¦ DEPENDENCIES π¦
Class::Std depends on the following modules, bestie, so make sure they're around:
versionScalar::UtilData::Dumper
π₯ INCOMPATIBILITIES π₯
Incompatible with the Attribute::Handlers module, since both of them define meta-attributes named :ATTR. It's giving two people showing up to the party in the same dress, except the party is your compile phase. Not compatible. Do not. π«Ά
π BUGS AND LIMITATIONS π
Real talk, the known limitations go like this:
- Does not handle threading (including
fork()under Windows). :ATTRdeclarations must all be on the same line (this one's a limitation in Perl itself, not us).:ATTRdeclarations cannot include variables, because those don't get interpolated into the declaration (again, a limitation in Perl itself β we're just the messenger).
Please report any bugs or feature requests to bug-class-std@rt.cpan.org, or through the web interface at http://rt.cpan.org. Spill the tea, we'll read it. π
π ALTERNATIVES π
Inside-out objects are gaining in popularity, and there are now MANY other modules out there implementing frameworks for building inside-out classes. The roster:
Object::InsideOutβ array-based objects, with support for threading. Many excellent features (especially thread-safety! π), but slightly less secure than Class::Std, because of non-encapsulation of attribute data addressing.Class::InsideOutβ a minimalist approach to building inside-out classes. Less is more, she's lowkey.Lexical::Attributesβ uses source filters to provide a near-Perl 6 approach to declaring inside-out classes. Time traveler core.Class::Std::Storableβ adds serialization/deserialization to Class::Std. Save and load, slay.
π AUTHOR π
Damian Conway <DCONWAY@cpan.org> β the icon, the legend, the moment. π
π LICENCE AND COPYRIGHT π
Copyright (c) 2005, Damian Conway <DCONWAY@cpan.org>. All rights reserved.
Portions of the documentation from Perl Best Practices copyright (c) 2005 by O'Reilly Media, Inc. and reprinted with permission.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
π¨ DISCLAIMER OF WARRANTY π¨
Okay bestie, this part is in ALL CAPS because it's the serious legal bit and we do not touch legal bits. Read it, it says what it says:
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
And that's the WHOLE page, bestie, we made it to the end and we ate. π The footer on this one is the standard perl core pages situation: it's perl v5.36.0, dated 2022-10-14, and the page itself is Class::Std(3pm). That's your receipt, keep it. π Go build some inside-out classes, you've got this. π¦
π¦ where this page comes from
- ubuntu noble: libclass-std-perl 0.013-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libclass-std-perl 0.013-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libclass-std-perl 0.013-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms