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.85 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.84 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.83 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.82 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.81 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.80 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.79 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.78 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.77 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.76 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.75 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.74 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.73 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.72 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.71 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.70 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.69 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.68 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.67 tracks/perl5/exercises/clock/Example.pm
trackler-2.2.1.66 tracks/perl5/exercises/clock/Example.pm