fritz1968 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I am lazy. That is why I code in Perl. And if a loop of some sort can set/define most of my variables, then I will use that and get the 'one-offs' later. Which brings me to my problem. I have the following code:
package LDAPclient; use Moose; my @ldap_attrs = qw( ssl host port retry timeout version loginID loginPW logging ); for my $name (@ldap_attrs) { my $reader = 'get_' . $name; my $writer = 'set_' . $name; has $name => ( is => 'rw', reader => $reader, writer => $writer, required => 0 ); }

I want to set default values for ssl, port, retry, timeout, version and logging... but I don't want to have 5 different "has" lines with each having the is, reader, writer, required and default parts. Is there a way to set a default for a value outside of the above loop? If so, I would appreciate an example.

thanks, frank

Replies are listed 'Best First'.
Re: Moose and OOP in Perl
by moritz (Cardinal) on May 09, 2013 at 20:00 UTC
    my %defaults = ( ssl => 1, port => 12345, timeout => 42, ); for my $name (@ldap_attrs) { my $reader = 'get_' . $name; my $writer = 'set_' . $name; my @default; if (exists $defaults{$name}) { @default = (default => $defaults{$name}); } has $name => ( is => 'rw', reader => $reader, writer => $writer, required => 0, @default, ); }

    Untested, but something along those lines should work.

Re: Moose and OOP in Perl
by tobyink (Canon) on May 09, 2013 at 21:35 UTC

    moritz' answer is perfectly good. Here's another in the spirit of TIMTOWTDI. It uses builders instead of defaults. (Slightly slower object construction, but generally considered a cleaner way of doing things in terms of making it easier for subclassing.)

    my @ldap_attrs = qw( ssl host port retry timeout version loginID loginPW logging ); use constant { _build_ssl => 1, _build_port => 12345, _build_timeout => 42, }; has $_ => ( is => "rw", reader => "get_$_", writer => "set_$_", required => 0, __PACKAGE__->can("_build_$_") ? (builder => "_build_$_") : (), ) for @ldap_attrs;
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name