Starting out with a value and modifying it piecemeal as you go through a list of something, which you do with $ret and the digits in both functions, is an ideal candidate for List::Util's reduce function.
use List::Util qw( reduce ); sub bin2dec { my ( $str ) = @_; reduce { mul2( $a, $b ) } "", split //, $str; }
Here, in the first iteration, $a is the empty string from the list passed to reduce, and $b is the first digit. The return value of the block is passed back to the block as $a in the next iteration, while $b goes through the all the remaining values from the list one by one.
$add_one_f I'd rename as $have_overflow, which documents intent rather than implementation. And if you only use it as a boolean, you don't need to initialize it either.
The for(;;) loop isn't necessary, you don't use the index anywhere, you just extract each corresponding character once. So you could rewrite that much more clearly as for( reverse split //, $str ). Then it could be turned into a reduce in the same way as above, but since you're just accumulating characters onto the front of a string, you are better served with a join reverse map.
sub mul2 { my ( $str, $have_overflow ) = @_; my $ret = join '', reverse map { my $c = $_ * 2 + ( $have_overflow ? 1 : 0 ); $have_overflow = ( $c >= 10 ); ( $c % 10 ); } reverse split //, $str; ( $have_overflow ? 1 : '' ) . $ret; }
You could even get rid of the out-of-band overflow check at the bottom if you rearrange things a little:
sub mul2 { my ( $str, $have_overflow ) = @_; join '', reverse map { my $c = $have_overflow ? 1 : 0; $c += $_ * 2 if length; $have_overflow = ( $c >= 10 ); # return a zero char only if not at top of string ( $c % 10 ) or ( length() ? 0 : '' ); } reverse '', split //, $str; }
But in this case I find it obfuscates more than it reduces redundancy.
Incidentally, the ( $have_overflow ? 1 : '' ) above is a no-op if $have_overflow is a boolean like in this case, since 1 and the empty string are what the boolean ops return in Perl for true and false respectively. So that could be written $have_overflow . $ret, though that lacks the the benefit of documented intent.
Makeshifts last the longest.
In reply to Re: bin2dec for big numbers
by Aristotle
in thread bin2dec for big numbers
by spurperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |