The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

MooseX::SingleArg - No-fuss instantiation of Moose objects using a single argument.

SYNOPSIS

Use this module in your class:

    package Person;
    use Moose;
    
    use MooseX::SingleArg;
    
    single_arg 'name';
    
    has name => ( is=>'ro', isa=>'Str' );

Then instantiate a new instance of your class with a single argument:

    my $john = Person->new( 'John Doe' );
    print $john->name();

DESCRIPTION

This module provides a role and declarative sugar for allowing Moose instances to be constructed with a single argument. Your class must use this module and then use the single_arg method to declare which of the class's attributes will be assigned the single argument value.

If the class is constructure using the typical argument list name/value pairs, or with a hashref, then things work as is usual. But, if the arguments are a single non-hashref value then that argument will be assigned to whatever attribute you have declared.

The reason for this module's existence is that when people want this feature they usually find Moose::Cookbook::Basics::Recipe10 which asks that something like the following be written:

    around BUILDARGS => sub{
        my $orig = shift;
        my $self = shift;
        
        if (@_==1 and ref($_[0]) ne 'HASH') {
            return $self->$orig( foo => $_[0] );
        }
        
        return $self->$orig( @_ );
    };

The above is complex boilerplate for a simple feature. This module aims to make it simple and fool-proof to support single-argument Moose object construction.

AUTHOR

Aran Clary Deltac <bluefeet@gmail.com>

LICENSE

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