From ee654e937866115e8435fbfa4b7a2970c87a5cf0 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Tue, 28 Dec 2021 22:43:13 +0100 Subject: Fully implement the tied class for Binary Addition --- challenge-140/e-choroba/perl/ch-1.pl | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/challenge-140/e-choroba/perl/ch-1.pl b/challenge-140/e-choroba/perl/ch-1.pl index 214e130155..8657aec309 100755 --- a/challenge-140/e-choroba/perl/ch-1.pl +++ b/challenge-140/e-choroba/perl/ch-1.pl @@ -6,15 +6,21 @@ use strict; use Tie::Scalar; use parent -norequire => 'Tie::StdScalar'; + sub validate { + die 'Invalid format' if $_[0] =~ /[^01]/; + } + sub TIESCALAR { my ($class, $value) = @_; die 'Too many arguments' if @_ > 2; - die 'Invalid format' if $value =~ /[^01]/; + validate($value); bless \$value, $class } sub FETCH { $_[0] } + sub STORE { validate($_[1]); $_[0]->SUPER::STORE($_[1]) } + use overload '+' => sub { sprintf '%b', oct("0b${ $_[0] }") + oct("0b${ $_[1] }") @@ -41,7 +47,9 @@ use Test::Exception; is $A + $B, 110, "Example 2 ($A + $B)"; } -{ tie my $A, 'Binary', 100; - tie my $B, 'Binary', 11; +{ tie my $A, 'Binary', 0; + tie my $B, 'Binary', 0; + $A = 100; + $B = 11; is $A + $B, 111, "Example 3 ($A + $B)"; } -- cgit