Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Confusion with Moo's builder attribute and a file handle

by tobyink (Canon)
on Jul 23, 2013 at 08:40 UTC ( [id://1045796]=note: print w/replies, xml ) Need Help??


in reply to Confusion with Moo's builder attribute and a file handle

OK; I think you're confused about what builders are supposed to do. Your builder will only be executed if you do NOT provide a value for the base_file attribute.

use v5.14; use Data::Dumper; package MyClass { use Moo; has base_file => ( is => 'rw', required => 1, init_arg => 'base', builder => sub { return 'bar' }, ); } # builder sub is *NOT* executed my $object1 = MyClass2->new(base => "foo"); print Dumper($object->base_file); # $VAR1 = 'foo' # builder sub *IS* executed my $object2 = MyClass->new(); print Dumper($object2->base_file); # $VAR1 = 'bar'

Further, you seem to be assuming that within the builder sub, $_[0] is some sort of file name. It's not; it's $self.

I think what you want is coercions...

use v5.14; use Data::Dumper; use IO::File; package MyClass { use Moo; has base_file => ( is => 'rw', required => 1, init_arg => 'base', coerce => sub { my $base_fh = IO::File->new( $_[0], '<' ) or die "$_[0]: $ +!"; $base_fh->binmode(":utf8"); return $base_fh; }, ); } my $object = MyClass->new(base => __FILE__); print Dumper($object->base_file);

In summary: use coercions to munge incoming values; use builders to provide a default value when there is no incoming value.

Here's another way you could have done it... provide a base attribute which is the filename as a string, and then build the base_file attribute from that:

use v5.14; use Data::Dumper; use IO::File; package MyClass { use Moo; has base => ( is => 'rw', required => 1, ); has base_file => ( is => 'rw', lazy => 1, builder => sub { my $base_fh = IO::File->new($_[0]->base, '<' ) or die($_[0 +]->base . ": $!"); $base_fh->binmode(":utf8"); return $base_fh; }, ); } my $object = MyClass->new(base => __FILE__); print Dumper($object->base_file);
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Confusion with Moo's builder attribute and a file handle
by mgatto (Novice) on Jul 23, 2013 at 14:45 UTC

    Thanks, tobyink. You're right: coerce was the right method to use. 20/20 in retrospect :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1045796]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-19 06:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found