aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2021-12-28 22:43:13 +0100
committerE. Choroba <choroba@matfyz.cz>2021-12-28 22:43:13 +0100
commitee654e937866115e8435fbfa4b7a2970c87a5cf0 (patch)
tree2b92639ed3c7f618cc7fad135f3142a486baef0c
parentc524a3754a9f0a685a84c2dfdeea58b36e85f512 (diff)
downloadperlweeklychallenge-club-ee654e937866115e8435fbfa4b7a2970c87a5cf0.tar.gz
perlweeklychallenge-club-ee654e937866115e8435fbfa4b7a2970c87a5cf0.tar.bz2
perlweeklychallenge-club-ee654e937866115e8435fbfa4b7a2970c87a5cf0.zip
Fully implement the tied class for Binary Addition
-rwxr-xr-xchallenge-140/e-choroba/perl/ch-1.pl14
1 files 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)";
}