aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-002/john-barrett/perl5/ch-2.pl19
1 files changed, 16 insertions, 3 deletions
diff --git a/challenge-002/john-barrett/perl5/ch-2.pl b/challenge-002/john-barrett/perl5/ch-2.pl
index 3293529824..f18215e4f0 100755
--- a/challenge-002/john-barrett/perl5/ch-2.pl
+++ b/challenge-002/john-barrett/perl5/ch-2.pl
@@ -2,7 +2,7 @@
use strict;
use warnings;
-use feature 'say';
+use feature qw/ say /;
# Usage, e.g.
# ./ch-2.pl -to-base35 123
@@ -13,7 +13,21 @@ my @charset = ( 0..9, 'A'..'Y' );
my $base = @charset;
say to_base35( $args{'-to-base35'} ) if $args{'-to-base35'};
-#say to_base35( $args{'-to-base35'} ) if $args{'-to-base35'};
+say from_base35( $args{'-from-base35'} ) if $args{'-from-base35'};
+
+sub from_base35 {
+ my ( $base35 ) = @_;
+ my $sign = $base35 =~ s/-//g ? '-' : '';
+ my @digits = split '', $base35;
+ my $idx = join '', @charset;
+ my $pos = 0;
+ my $val;
+ while ( my $char = pop @digits ) {
+ $val += index( $idx, $char ) * ( $base ** $pos );
+ $pos++;
+ }
+ $sign . $val;
+}
sub to_base35 {
my ( $int ) = @_;
@@ -23,7 +37,6 @@ sub to_base35 {
do {
push @digits, $charset[ $int % $base ];
$int = int( $int / $base );
- say $int;
} while ( $int > 0 );
$sign . join '', reverse @digits;
}