Comment detail

法演算 (Nested Flatten)

overloadの格好の事例。

Dan the Perl Monger

 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
42
43
44
45
46
47
48
49
50
51
52
53
package modulo;
use strict;
use warnings;
our $VERSION = 0.01;

use overload
  '0+' => sub { $_[0]->[0] + 0 },
  '+'  => sub { __PACKAGE__->new( $_[0]->[0] + $_[1]->[0], $_[0]->[1] ) },
  '-'  => sub { __PACKAGE__->new( $_[0]->[0] - $_[1]->[0], $_[0]->[1] ) },
  '*'  => sub { __PACKAGE__->new( $_[0]->[0] * $_[1]->[0], $_[0]->[1] ) },
  ;

sub import {
    my ( $pkg, undef, $mod ) = @_;
    $mod >= 2 or die 'usage: use ', __PACKAGE__, ' mod => n;';
    overload::constant integer => sub { __PACKAGE__->new( shift, $mod ) };
}

sub new {
    my $pkg = shift;
    my ( $n, $m ) = @_;
    $n %= $m;
    bless [ $n, $m ], $pkg;
}

1;

#!/usr/local/bin/perl
use strict;
use warnings;
sub say { print @_, "\n" }
say "1 + 2 = ", 1 + 2;
say "3 - 4 = ", 3 - 4;
say "5 * 6 = ", 5 * 6;
{
    say "# mod = 2";
    use modulo mod => 2;
    say "1 + 2 = ", 1 + 2;
    say "3 - 4 = ", 3 - 4;
    say "5 * 6 = ", 5 * 6;
}
{
    say "# mod = 3";
    use modulo mod => 3;
    say "1 + 2 = ", 1 + 2;
    say "3 - 4 = ", 3 - 4;
    say "5 * 6 = ", 5 * 6;
}

say "# original scope";
say "1 + 2 = ", 1 + 2;
say "3 - 4 = ", 3 - 4;
say "5 * 6 = ", 5 * 6;

Index

Feed

Other

Link

Pathtraq

loading...