File: moo_attributes.pl

package info (click to toggle)
liblist-objects-withutils-perl 2.028003-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,292 kB
  • sloc: perl: 1,957; makefile: 17; sh: 6
file content (41 lines) | stat: -rw-r--r-- 946 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use strict; use warnings FATAL => 'all';

# A very simple example of how List::Objects::WithUtils can make for prettier
# OO syntax using Moo(se); see List::Objects::Types for more useful bits like
# coercions.

my $widget_id = 0;

{ package Widget;
  use Moo;
  has id => ( is => 'ro', default => sub { ++$widget_id } );
  sub execute { 
    my $self = shift;
    print "Widget ".$self->id." present!\n"
  }
}

{ package Machine;

  use List::Objects::WithUtils;
  use Types::Standard -types;

  use Moo;

  has widgets => (
    is      => 'ro',
    # You could skip the Types::Standard import and just use an 'array':
    default => sub { array_of InstanceOf['Widget'] },
    handles => +{
      add_widgets  => 'push',
      list_widgets => 'all',
      each_widget  => 'visit',
    },
  );
}

my $machine = Machine->new;
my @widgets = map {; Widget->new } 1 .. 4;

$machine->add_widgets(@widgets);
$machine->each_widget(sub { $_->execute });