MooX::Struct(3pm)

๐Ÿ“ฆ
version 0.020 ยท 5 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu questing

๐ŸŒธ MooX::Struct ๐Ÿ’… โ€” the MooX::Struct(3pm) page, but make it a group chat

User Contributed Perl Documentation ยท MooX::Struct(3pm)


โœจ NAME โœจ

MooX::Struct โ€” makes simple lightweight record-like structures that make sounds like cows ๐Ÿฎ๐ŸŽ€


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

use MooX::Struct
   Point   => [ 'x', 'y' ],
   Point3D => [ -extends => ['Point'], 'z' ],
;

my $origin = Point3D->new( x => 0, y => 0, z => 0 );

# or...
my $origin = Point3D[ 0, 0, 0 ];

๐Ÿ’– DESCRIPTION ๐Ÿ’–

So bestie, MooX::Struct lets you spin up cheap little struct-ish classes for your data, and it does it all with Moo. No cap. ๐Ÿ’…

Spiritually it's cousins with MooseX::Struct and Class::Struct, but the usage pattern is different, lowkey. Instead of handing you a struct keyword you'd call to define structs, you define all the structs right there inside the use statement. Which means โ€” and this is the moment โ€” they happen at compile time. โœจ

A struct is just an "anonymous" Moo class. MooX::Struct makes that class for you and installs a lexical alias for it in your namespace. So your module can have a Point3D struct, and some other module can have one too, and they will not fight. Periodt. Every struct class inherits from MooX::Struct.

Arguments to MooX::Struct are key-value pairs: keys are the struct names, values are arrayrefs. ๐Ÿซถ

use MooX::Struct
   Person   => [qw/ name address /],
   Company  => [qw/ name address registration_number /];

The elements in that array are the attributes for the struct โ€” they get created as read-only attributes โ€” but some array elements get โœจspecial treatmentโœจ:

  • Per the example in the SYNOPSIS, -extends introduces a list of parent classes for the struct. If you don't specify it, the class just inherits from MooX::Struct itself.

Structs can inherit from other structs, or from normal classes. If you're inheriting from another struct, you must define both of them in the same use statement. Inheriting from a non-struct class is discouraged, ngl. ๐Ÿ™ˆ

# Not like this.
use MooX::Struct Point   => [ 'x', 'y' ];
use MooX::Struct Point3D => [ -extends => ['Point'], 'z' ];

# Like this.
use MooX::Struct
   Point   => [ 'x', 'y' ],
   Point3D => [ -extends => ['Point'], 'z' ],
;
  • Similarly, -with consumes a list of roles. ๐Ÿ‘‘
  • If an attribute name is followed by a coderef, that coderef gets installed as a method instead. ๐Ÿ”ฅ
use MooX::Struct
   Person => [
      qw( name age sex ),
      greet => sub {
         my $self = shift;
         CORE::say "Hello ", $self->name;
      },
   ];

But bestieโ€ฆ if you're out here defining methods for your structs, you've possibly missed the whole point of them. ๐Ÿ˜ญ

  • If an attribute name is followed by an arrayref, those get used to set the options for that attribute. Like:
use MooX::Struct
   Person  => [ name => [ is => 'ro', required => 1 ] ];

Using the init_arg option would probably break stuff. Don't do that. ๐Ÿ’€

  • Attribute names may be "decorated" with prefix and postfix sigils. The prefix sigils @ and % say the attribute isa arrayref or hashref respectively. (Blessed arrayrefs and hashrefs are accepted; so are objects which overload @{} and %{}.) The prefix sigil $ says the attribute value must not be an unblessed arrayref or hashref. The prefix sigil + indicates the attribute is a number, and gives it a default value of 0, unless the attribute is required. The postfix sigil ! says the attribute is required. ๐ŸŒˆ
use MooX::Struct
   Person  => [qw( $name! @children )];

Person->new();         # dies, name is required
Person->new(           # dies, children should be arrayref
   name     => 'Bob',
   children => 2,
);

Before the key-value list, you can drop in some extra flags. These begin with hyphens. The flag -rw means attributes should be read-write instead of read-only. โœ๏ธ

use MooX::Struct -rw,
   Person => [
      qw( name age sex ),
      greet => sub {
         my $self = shift;
         CORE::say "Hello ", $self->name;
      },
   ];

The -retain flag says MooX::Struct should not use namespace::clean to enforce lexicalness on your struct class aliases.

Flags -trace and -deparse may be of use debugging. ๐Ÿ”

๐Ÿงš Instantiating Structs ๐Ÿงš

There are two supported methods of instantiating structs. One: the traditional class-like constructor with named parameters:

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

Two: the abbreviated syntax with positional parameters:

my $point = Point[ 1, 2 ];

If you know about Moo and you go peeking around in the source code for this module, I'm sure you can figure out additional ways to instantiate them โ€” but the above are the only supported two, okay? ๐Ÿ’…

When inheritance or roles have been used, it might not always be clear what order the positional parameters come in (though see the documentation for the FIELDS below), so the traditional class-like style may be preferred.

๐Ÿ’œ Methods ๐Ÿ’œ

Structs are objects and thus have methods. You can define your own methods as described above. MooX::Struct's built-in methods will always obey the convention of being in ALL CAPS (except in the case of _data_printer). So by using lower-case letters to name your own methods, you can avoid naming collisions. ๐ŸŽ€

The following methods are currently defined. Additionally, all the standard Perl (isa, can, etc) and Moo (new, does, etc) methods are available.

  • OBJECT_ID โ€” Returns a unique identifier for the object.

May only be called as an instance method.

  • FIELDS โ€” Returns a list of fields associated with the object. For the Point3D struct in the SYNOPSIS, this would be 'x', 'y', 'z'.

The order the fields are returned in is equal to the order they must be supplied for the positional constructor.

Attributes inherited from roles, or from non-struct base classes, are not included in FIELDS, and thus cannot be used in the positional constructor. ๐Ÿ˜ค

May be called as an instance or class method.

  • TYPE โ€” Returns the type name of the struct, e.g. 'Point3D'.

May be called as an instance or class method.

  • CLASSNAME โ€” Returns the internally used package name for the struct, e.g. 'MooX::Struct::__ANON__::0007'. Pretty rare you'd want to see this.

May be called as an instance or class method.

  • TYPE_TINY โ€” Returns a Type::Tiny type constraint corresponding to the CLASSNAME, suitable for a Moose/Moo isa. โญ
package Foo {
  use Moo;
  use MooX::Struct Bar => [qw( $name )];

  has left_bar  => (is => 'rw', isa => Bar->TYPE_TINY, coerce => 1);
  has right_bar => (is => 'rw', isa => Bar->TYPE_TINY, coerce => 1);

  ...;
}

May be called as an instance or class method.

  • TO_HASH โ€” Returns a reference to an unblessed hash where the object's fields are the keys and the object's values are the hash values.

May only be called as an instance method.

  • TO_ARRAY โ€” Returns a reference to an unblessed array where the object's values are the array items, in the same order as listed by FIELDS.

May only be called as an instance method.

  • TO_STRING โ€” Joins TO_ARRAY with whitespace. This is not necessarily a brilliant stringification, but it's easy enough to overload:
use MooX::Struct
   Point => [
      qw( x y ),
      TO_STRING => sub {
         sprintf "(%d, %d)"), $_[0]->x, $_[0]->y;
      },
   ]
;

May only be called as an instance method.

  • CLONE โ€” Creates a shallow clone of the object.

May only be called as an instance method.

  • EXTEND โ€” An experimental feature. ๐Ÿงช

Extend a class or object with additional attributes, methods, etc. This method takes almost all the same arguments as use MooX::Struct, albeit with some slight differences.

use MooX::Struct Point => [qw/ +x +y /];
my $point = Point[2, 3];
$point->EXTEND(-rw, q/+z/);  # extend an object
$point->can('z');   # true

my $new_class = Point->EXTEND('+z');  # extend a class
my $point_3d  = $new_class->new( x => 1, y => 2, z => 3 );
$point_3d->TYPE;  # Point !

my $point_4d = $new_class->EXTEND(\"Point4D", '+t');
$point_4d->TYPE;  # Point4D

my $origin = Point[]->EXTEND(-with => [qw/ Math::Role::Origin /]);

This feature has been included mostly because it's easy to implement on top of the existing code for processing use MooX::Struct. Some subsets of this functionality are sane, such as the ability to add traits to an object. Others (like the ability to add a new uninitialized, read-only attribute to an existing object) are less sensible. ๐Ÿ™ˆ

May be called as an instance or class method.

  • BUILDARGS โ€” Moo internal fu.
  • _data_printer โ€” Automatic pretty printing with Data::Printer.
use Data::Printer;
use MooX::Struct Point => [qw/ +x +y /];
my $origin = Point[];
p $origin;

Use Data::Printer 0.36 or above please. ๐Ÿ™

With the exception of FIELDS and TYPE, any of these can be overridden using the standard way of specifying methods for structs. ๐Ÿ‘‘

๐ŸŒˆ Overloading ๐ŸŒˆ

MooX::Struct overloads stringification and array dereferencing. Objects always evaluate to true in a boolean context. (Even if they stringify to the empty string.) ๐Ÿ’–


๐Ÿ’€ CAVEATS ๐Ÿ’€

Because you only get an alias for the struct class, you need to be careful with some idioms:

my $point = Point3D->new(x => 1, y => 2, z => 3);
$point->isa("Point3D");   # false!
$point->isa( Point3D );   # true

my %args  = (...);
my $class = exists $args{z} ? "Point3D" : "Point";  # wrong!
$class->new(%args);

my $class = exists $args{z} ?  Point3D  :  Point ;  # right
$class->new(%args);

๐Ÿ› BUGS ๐Ÿ›

Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=MooX-Struct>.


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

Moo, MooX::Struct::Util, MooseX::Struct, Class::Struct.


๐Ÿซถ AUTHOR ๐Ÿซถ

Toby Inkster <tobyink@cpan.org>.


This software is copyright (c) 2012-2013, 2017-2018 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

๐Ÿšจ DISCLAIMER OF WARRANTIES ๐Ÿšจ

okay bestie, real talk, no jokes for one sec ๐Ÿ’… this is the part every manpage has and nobody reads until something breaks. here it is, in all its all-caps glory:

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.

that's it. that's the whole vibe. as is, no promises, no take-backs, and if you were about to sue because your struct did a struct thing โ€” the page said it first. ๐Ÿซถ

(and yes, MERCHANTIBILITY is spelled exactly like that up there. not me fixing it. it's iconic, it stays. ๐Ÿ˜ญ)


and that's the entire page, bestie, you made it to the end ๐ŸŽ€ go forth and MooX::Struct responsibly. this one comes to you from MooX::Struct(3pm) as shipped with perl v5.36.0, dated 2022-12-12 โ€” so if the version you're on is different, check your own local copy, fr fr. ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from