Sha256: ad87c250a417f9ff547e938424d6b730ea6794b48cfa573259cb06764d87f1c0

Contents?: true

Size: 1.35 KB

Versions: 323

Compression:

Stored size: 1.35 KB

Contents

package Example;

use strict;
use warnings;
use overload
    "+"    => "add",
    "-"    => "subtract",
    "eq"   => "equals",
    '""'   => "to_string";

sub new {
    my ($class, $clock) = @_;
    my ($hour, $min) = @$clock;
    $min  = $min || "0";

    my $self = bless { hour => $hour, min => $min } => $class;
    $self->_normalize;

    return $self;
}

sub add {
    my ($self, $min) = @_;
    my $clock = $self->_copy;
    if ($min >= 60) {
        $clock->{hour} = ($clock->{hour} + int($min / 60)) % 24;
    }
    $clock->{min}  = $clock->{min} + $min % 60;
    $clock->_normalize;
    return $clock;
}

sub subtract {
    my ($self, $min) = @_;
    my $clock = $self->_copy;
    if ($min >= 60) {
        $clock->{hour} = $clock->{hour} - (int($min / 60) + 1);
        $clock->{hour} = 25 + $clock->{hour} if $clock->{hour} < 0;
    }
    $clock->{min} = abs $clock->{min} - $min % 60;
    $clock->_normalize;
    return $clock;
}

sub equals {
    my ($self, $other) = @_;
    return $self->to_string eq $other;
}

sub to_string {
    my $self = shift;
    return "$self->{hour}:$self->{min}";
}

sub _copy {
    my $self = shift;
    return Example->new( [$self->{hour}, $self->{min}] );
}

sub _normalize {
    my $self = shift;
    $self->{min}  = "0$self->{min}"   if $self->{min}  < 10;
    $self->{hour} = "0$self->{hour}"  if $self->{hour} < 10;
}

__PACKAGE__;

Version data entries

323 entries across 323 versions & 1 rubygems

Version Path
trackler-2.2.1.105 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.104 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.103 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.102 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.101 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.100 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.99 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.98 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.97 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.96 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.95 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.94 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.93 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.92 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.91 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.90 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.89 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.88 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.87 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.86 tracks/perl5/exercises/clock/Example.pm