MakeMe...xamples(3pm)
π NAME π
MakeMe...xamples(3pm) (from the User Contributed Perl Documentation shelf, bestie) β Class::MakeMethods::Docs::Examples β Sample Declarations and Usage β¨
β¨ EXAMPLES β¨
Okay bestie, these examples are here to show some of the capabilities of Class::MakeMethods. It's giving βlook what we can doβ in the best way π
π A Contrived Example π
Object-oriented Perl code is literally everywhere β you've probably seen code like this a million times:
my $obj = MyStruct->new( foo=>"Foozle", bar=>"Bozzle" );
if ( $obj->foo() =~ /foo/i ) {
$obj->bar("Barbados!");
}
Here's one possible implementation for the class whose interface is shown above:
package MyStruct;
sub new {
my $callee = shift;
my $self = bless { @_ }, (ref $callee || $callee);
return $self;
}
sub foo {
my $self = shift;
if ( scalar @_ ) {
$self->{'foo'} = shift();
} else {
$self->{'foo'}
}
}
sub bar {
my $self = shift;
if ( scalar @_ ) {
$self->{'bar'} = shift();
} else {
$self->{'bar'}
}
}
Class::MakeMethods lets you simply declare those methods to be of a predefined type, and it generates and installs the necessary methods in your package at compile-time. It's doing the repetitive stuff so you don't have to π
Here's the equivalent declaration for that same basic class:
package MyStruct;
use Class::MakeMethods::Standard::Hash (
'new' => 'new',
'scalar' => 'foo',
'scalar' => 'bar',
);
π A Typical Example π
The following example shows a common case of constructing a class with several types of accessor methods:
package MyObject;
use Class::MakeMethods::Standard::Hash (
new => 'new',
scalar => [ 'foo', 'bar' ],
array => 'my_list',
hash => 'my_index',
);
This class now has a constructor named new, two scalar accessors named foo and bar, and a pair of reference accessors named my_list and my_index. Typical usage of the class might include calls like the following:
my $obj = MyObject->new( foo => 'Foozle' );
print $obj->foo();
$obj->bar('Barbados');
print $obj->bar();
$obj->my_list(0 => 'Foozle', 1 => 'Bang!');
print $obj->my_list(1);
$obj->my_index('broccoli' => 'Blah!', 'foo' => 'Fiddle');
print $obj->my_index('foo');
π¦ Lvalue Accessors π¦
The Template subclasses support an optional --lvalue modifier that causes your accessors method to be marked as returning an lvalue which can be assigned to. Tiny important note, bestie: this feature is only available on Perl 5.6 or later.
package MyStruct;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'scalar --get --lvalue' => 'foo',
'array --get --lvalue' => 'bar',
);
$obj->foo = "Foozle";
print $obj->foo;
$obj->bar = ( 'baz', 'beep', 'boop' );
print $obj->bar->[1]; # beep
πΈ String and Numeric Accessors πΈ
In addition to the scalar accessor supported by the Standard::* classes, the Template subclasses also provide specialized accessors that can facilitate the use of specific types of data.
For example, we could declare the following class to hold information about available Perl packages:
package MyVersionInfo;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'string' => 'package',
'number' => 'version',
);
sub summary {
my $self = shift;
return $self->package() . " is at version " . $self->version()
}
You could use this class as follows:
package main;
use MyVersionInfo;
my $obj = MyVersionInfo->new( package=>"Class::MakeMethods");
$obj->version( 2.0 );
print $obj->summary();
Heads up: these accessors will provide a bit of diagnostic type checking β an attempt to call $obj->version("foo") will cause your program to croak. π
π String Concatenation Interface π
The following defines a get_concat method "i", and specifies a string to use when joining additional values when this method is called.
use Class::MakeMethods::Template::Hash
'string' => [ '--get_concat', 'i', { join => ' - ' } ];
For the tea on the string get_concat interface, peek at Class::MakeMethods::Template::Generic π
π₯ Access Control Example π₯
The following defines a secret_password method, which will croak if it is called from outside of the declaring package. Protective much? Iconic.
use Class::MakeMethods::Composite::Hash
'scalar' => [ 'secret_password' => { permit => 'pp' } ];
If you want the details on the permit modifier, see Class::MakeMethods::Composite.
For template classes, the same thing is accomplished with '--private':
use Class::MakeMethods::Template::Hash
'scalar' => [ '--private', 'secret_password' ];
The private modifier info lives in Class::MakeMethods::Template::Universal.
π Lazy-Init Interface π
Templapte scalar accessors declared with the init_and_get interface can be used for memoization or lazy-evaluation for object attributes. If the current accessor value is undefined, they will first call a user-provided init_* method and save its value.
package MyWidget;
use Class::MakeMethods::Template::Hash (
'new --with_values' => [ 'new' ],
'scalar --init_and_get' => [ 'foo', 'count', 'result' ],
);
sub init_foo {
return 'foofle';
}
sub init_count {
return '3';
}
sub init_result {
my $self = shift;
return $self->foo x $self->count;
}
...
my $widget = MyWidget->new();
print $widget->result; # output: fooflefooflefoofle
# if values are predefined, the init methods are not used
my $other_widget = MyWidget->new( foo => 'bar', count => 2 );
print $widget->result; # output: barbar
More on init_and_get lives in Class::MakeMethods::Template::Generic. This interface is also supported by all of Generic's subclasses, so you can add lazy-init methods for global data, class data, array objects, etc. Unfortunately, to date it is only supported for scalar-value accessors...
π Helper Methods π
Template methods often include similarly-named helper methods. For example, specifying the --with_clear interface for Template::*:scalar methods creates an extra method for each accessor x named clear_x.
package MyClass;
use Class::MakeMethods::Template::Hash('scalar --with_clear' => 'foo');
my $obj = MyClass->new;
$obj->foo(23);
$obj->clear_foo;
print $obj->foo();
π§ Reference Accessor and Helper Methods π§
For references to arrays and hashes, the Template subclasses provide accessors with extra helper methods to facilitate method-based interaction.
Here's a class whose instances each store a string and an array reference, along with a method to search the directories:
package MySearchPath;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'string' => 'name',
'array' => 'directories',
);
sub search {
my $self = shift;
my $target = shift;
foreach my $dir ( $self->directories ) {
my $candidate = $dir . '/' . $target;
return $candidate if ( -e $candidate );
}
return;
}
Note that the directories accessor returns the contents of the array when called in a list context, making it easier to loop over.
And here's a sample usage:
package main;
use MySearchPath;
my $libs = MySearchPath->new( name=>"libs", directories=>['/usr/lib'] );
$libs->push_directories( '/usr/local/lib' );
print "Searching in " . $libs->count_directories() . "directories.\n";
foreach ( 'libtiff', 'libjpeg' ) {
my $file = $libs->search("$_.so");
print "Checking $_: " . ( $file || 'not found' ) . "\n";
}
Note the use of the push_* and count_* helper accessor methods, which are defined by default for all 'Template::*:array' declarations.
Consult Class::MakeMethods::Template::Generic for more information about the available types of reference accessors, and the various methods they define.
β Object Accessors β
There's also a specialized accessor for object references:
package MyStruct;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'object' => [ 'widget' => {class=>'MyWidgetClass', delegate=>"twiddle"} ],
);
(Note that the class and delegate values specified above are method parameters, which provide additional information about the widget declaration; see "Standard Declaration Syntax" for more information.)
The above declaration creates methods equivalent to the following:
package MyStruct;
sub widget {
my $self = shift;
if ( scalar @_ ) {
if (ref $_[0] and UNIVERSAL::isa($_[0], 'MyWidgetClass')) {
$self->{widget} = shift;
} else {
$self->{widget} = MyWidgetClass->new(@_);
}
} else {
return $self->{widget};
}
}
sub clear_widget {
my $self = shift;
$self->{widget} = undef;
}
sub twiddle {
my $self = shift;
my $obj = $self->widget()
or Carp::croak("Can't forward twiddle because widget is empty");
$obj->twiddle(@_)
}
π Mixing Object and Global Methods π
Here's a package declaration using two of the included subclasses, Standard::Hash, for creating and accessing hash-based objects, and Basic::Global, for simple global-value accessors:
package MyQueueItem;
use Class::MakeMethods::Standard::Hash (
new => { name => 'new', defaults=>{ foo => 'Foozle' } },
scalar => [ 'foo', 'bar' ],
hash => 'history'
);
use Class::MakeMethods::Basic::Global (
scalar => 'Debug',
array => 'InQueue',
);
sub AddQueueItem {
my $class = shift;
my $instance = shift;
$instance->history('AddQueueItem' => time());
$class->InQueue([0, 0], $instance);
}
sub GetQueueItem {
my $class = shift;
$class->InQueue([0, 1], []) or $class->new
}
π Adding Custom Initialization to Constructors π
Frequently you'll want to provide some custom code to initialize new objects of your class. Most of the *:new constructor methods provides a way to ensure that this code is consistently called every time a new instance is created.
π§ Composite::Hash:new { post_rules => [] } π§
The Composite classes allow you to add pre- and post-operations to any method, so you can pass in a code-ref to be executed after the new() method.
package MyClass;
sub new_post_init {
my $self = ${(pop)->{result}}; # get result of original new()
length($self->foo) or $self->foo('FooBar'); # default value
warn "Initialized new object '$self'";
}
use Class::MakeMethods (
'Composite::Hash:new' => [
'new' => { post_rules=>[ \&new_post_init ] }
],
'Composite::Hash:scalar' => 'foo;,
);
...
package main;
my $self = MyClass->new( foo => 'Foozle' )
π Template::Hash:new --and_then_init
Use 'Template::Hash:new --and_then_init' when you want the object created and stuffed with the values you passed in first, and then have an init() method called on that shiny new object before it gets returned. It's giving "makeover before the reveal" β¨
package MyClass;
use Class::MakeMethods::Template::Hash (
'new --and_then_init' => 'new'
'string' => 'foo'
);
sub init {
my $self = shift;
length($self->foo) or $self->foo('FooBar'); # default value
warn "Initialized new object '$self'";
}
...
package main;
my $self = MyClass->new( foo => 'Foozle' )
πΈ Template::Hash:new --with_init
If you don't want your constructor to use the default hash-of-method-names style of initialization, use 'Template::Hash:new --with_init'. That one creates an empty object, passes its arguments to the init() method on the new object, and then returns it. Lowkey a different vibe, same slay π
package MyClass;
use Class::MakeMethods::Template::Hash (
'new --with_init' => 'new'
'string' => 'foo'
);
sub init {
my $self = shift;
$self->foo( shift || 'FooBar' ); # init with arg or default
warn "Initialized new object '$self'";
}
...
package main;
my $self = MyClass->new( 'Foozle' )
Some additional notes about these constructors, bestie π«Ά
- The
"Template::*:new"methods let you name your method something other than"init"by passing the"init_method"parameter:
use Class::MakeMethods::Template::Hash (
'new --and_then_init' => [
'new' => { init_method => 'my_init' }
],
);
- If you know you're not gonna have a complex class hierarchy, you can reduce resource consumption a bit by changing the above declarations from
"*::Hash"to"*::Array"so your objects end up as blessed arrays rather than blessed hashes. Tiny glow-up, real consequences π
π¦ Changing Method Names
The Template subclasses let you control the names assigned to the methods you generate by picking from several naming interfaces.
For example, the accessors declared above use a default, Perl-ish style interface, where one method can be called with no argument to retrieve the value, or with an argument to set it. But you can also choose a more Java-like syntax, with separate get* and set* methods, by including the '--java' template specification:
package MyStruct;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'scalar' => '--java Foo',
);
(Note that the declaration of Foo could also have been written as 'scalar --java' => 'Foo' or "'scalar' => ['--java', 'Foo']", or "'scalar' => [ 'foo' =" { 'interface'=>'java' } ], all of which are interpreted identically; see the Class::MakeMethods section on "Argument Normalization" for details.)
Usage of this accessor would then be as follows:
package main;
use MyStruct;
my $obj = MyStruct->new( setFoo => "Foozle" );
print $obj->getFoo();
$obj->setFoo("Bozzle");
π Selecting Specific Helper Methods
You can use the ability to specify interfaces to select specific helper methods rather than just accepting the default collection. No cap, it's very choose-your-own-adventure π§
For example, let's say you wanted to use a Template::Hash:array, but you only wanted two methods installed in your class: a foo() accessor and a shift_foo() mutator. Any of the below combinations of syntax should do the trick:
use Class::MakeMethods::Template::Hash
'array' => [
'foo' => { interface=>{'foo'=>'get_set', 'shift_foo'=>'shift'} },
];
If you're gonna have a lot of methods with the same interface, you could pre-declare a named interface once and use it repeatedly:
BEGIN {
require Class::MakeMethods::Template::Hash;
Class::MakeMethods::Template::Hash->named_method('array')->
{'interface'}->{'my_get_set_shift'} =
{ '*'=>'get_set', 'shift_*'=>'shift' };
}
use Class::MakeMethods::Template::Hash
'array --my_get_set_shift' => [ 'foo', 'bar' ];
π Tree Structure Example
In this example we're gonna create a pair of classes that hold references to other objects. Iconic little object family tree π³
The first class is a single-value data object implemented as a reference to a scalar.
package MyTreeData;
use Class::MakeMethods::Template::Scalar (
'new' => 'new',
'string' => 'value',
);
The second class defines a node in a tree, with a constructor, an accessor for a data object from the class above, and accessors for a list of child nodes.
package MyTreeNode;
use Class::MakeMethods::Template::Hash (
'new' => 'new',
'object -class MyTreeData' => 'data',
'array_of_objects -class MyTreeNode' => 'children',
);
sub depth_first_data {
my $self = shift;
return $self->data, map { $_->depth_first_data() } $self->children;
}
Here's a sample of how the above classes could be used in a program.
package main;
use MyTreeData;
use MyTreeNode;
my $node = MyTreeNode->new(
data => { value=>'data1' },
children => [ { value=>'data3' } ]
);
$node->push_children( MyTreeNode->new( data => { value=>'data2' } ) );
foreach my $data ( $node->depth_first_data ) {
print $data->value();
}
π SEE ALSO
See Class::MakeMethods for general information about this distribution.
π Annotated Tutorials
Ron Savage has posted a pair of annotated examples, linked to below. Each demonstrates building a class with MakeMethods, and each includes scads of comments that walk you through the logic and demonstrate how the various methods work together. Obsessed with the thoroughness fr fr π₯
http://savage.net.au/Perl-tutorials.html
http://savage.net.au/Perl-tutorials/tut-33.tgz
http://savage.net.au/Perl-tutorials/tut-34.tgz
That's a wrap, bestie π«Ά the source/version footer says perl v5.36.0, dated 2022-10-13, on the MakeMe...xamples(3pm) page. Mwah π
π¦ where this page comes from
- ubuntu noble: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libclass-makemethods-perl 1.01-7 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms