diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-12-28 22:26:21 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-12-28 22:26:21 +0000 |
| commit | cc72a2ea325ac4a00b6a84dd29c5b0c94990f37c (patch) | |
| tree | 2b92639ed3c7f618cc7fad135f3142a486baef0c | |
| parent | c524a3754a9f0a685a84c2dfdeea58b36e85f512 (diff) | |
| parent | ee654e937866115e8435fbfa4b7a2970c87a5cf0 (diff) | |
| download | perlweeklychallenge-club-cc72a2ea325ac4a00b6a84dd29c5b0c94990f37c.tar.gz perlweeklychallenge-club-cc72a2ea325ac4a00b6a84dd29c5b0c94990f37c.tar.bz2 perlweeklychallenge-club-cc72a2ea325ac4a00b6a84dd29c5b0c94990f37c.zip | |
Merge pull request #5434 from choroba/ech140r
Fully implement the tied class for Binary Addition
| -rwxr-xr-x | challenge-140/e-choroba/perl/ch-1.pl | 14 |
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)"; } |
