use Test::More q(no_plan); # ngram2number # # Convert an ngram into a number given a # hashref containing the alphabet conversion, # and the ngram to convert. # # An area for improvement would be to cache the # $base ** ( $position++ ) results. # # Untested (ok, now it is), no warranty, blah blah blah # # Update: error in code - added reverse to correct # Update: Multiply current digit, not add; scalar keys %alphabet # Update: Added testing commands # sub ngram2number { my ( $alphabet, $ngram ) = @_; my $results = 0; my $position = 0; my $base = scalar( keys %$alphabet ); for my $c ( reverse split( //, $ngram ) ) { $results += ( $base ** ( $position++ ) ) * $alphabet->{ $c }; } $results; } $hex = { map { ( $_ => hex( $_ ) ) } ( '0'..'9', 'a'..'f' ) }; is( ngram2number( $hex, $_ ), hex( $_ ), "$_ in hex matches" ) for ( '0'..'9', 'a'..'f' ); is( ngram2number( $hex, $_ ), hex( $_ ), "$_ in hex matches" ) for ( glob '{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f}'x2 );