#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    71
    Rep Power
    3

    Moose Delegation


    I have a simple question about Moose's delegation feature. Is this a correct way to set up a delegation to the class Animal?

    Animal.pm
    Code:
    package Animal;
    
    use warnings;
    use strict;
    
    sub new
    {
    	my $class = shift(@_);
    	my $self = {@_};
    	return bless($self, $class);
    }
    
    sub get_name
    {
    	my $self = shift(@_);
    	return $self->{name};
    }
    
    sub set_name
    {
    	my $self = shift(@_);
    	my $n = shift(@_);
    	$self->{name} = $n;
    }
    
    1;
    Dog.pm
    Code:
    package Dog;
    
    use Moose;
    use namespace::autoclean;
    use Animal;
    
    has 'animal' => 	(
    			is => 'rw',
    			isa => 'Animal',
    			handles =>	{
    						get => 'get_name',
    						set => 'set_name',
    					},
    		);
    
    __PACKAGE__->meta->make_immutable;
    
    1;
    my.pl
    Code:
    #!/usr/bin/perl
    
    use warnings;
    use strict;
    use Dog;
    
    my $me = new Dog(animal=>new Animal(name=>"Rex"));
    
    print $me->get(), "\n";
    
    $me->set("Lassie");
    
    print $me->get(), "\n";
    
    __END__
    I'm new to Perl/Moose and I'm having problems understanding delegation and how it integrates into a Moose class. I think I got it in this simple example but I would really appreciate the opinion of the Perl/Moose experts.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    71
    Rep Power
    3
    I tried another program using WWW::Mechanize and I think I got it.

    Mech.pm
    Code:
    package Mech;
    
    use Moose;
    use namespace::autoclean;
    use WWW::Mechanize;
    
    has 'my_WWW' =>
    	(
    		is => 'rw',
    		isa => 'WWW::Mechanize',
    		handles =>	{
    						my_get => 'get',
    						my_links => 'links',
    					},
    	);
    
    1;
    my.pl
    Code:
    #!/usr/bin/perl
    
    use warnings;
    use strict;
    use feature qw/state/;
    use Mech;
    
    my $me = new Mech(my_WWW=>WWW::Mechanize->new);
    
    print "Enter starting URL->";
    chomp(my $str_url = <STDIN>);
    
    $me->my_get($str_url);
    my @ans = $me->my_links();
    
    foreach ( @ans )
    {
    	state $line_no;
    	print ++$line_no, ": ", $_->url, "\n";
    }
    
    __END__
    Unless someone can see and post some errors, I'll assume I understand Moose's delegation.

IMN logo majestic logo threadwatch logo seochat tools logo