Algorithm-Nhash
view release on metacpan or search on metacpan
lib/Algorithm/Nhash.pm view on Meta::CPAN
package Algorithm::Nhash;
BEGIN {
$Algorithm::Nhash::DIST = 'Algorithm-Nhash';
}
BEGIN {
$Algorithm::Nhash::VERSION = '0.002';
}
# ABSTRACT: Exim nhash algorithm
use warnings;
use strict;
use Carp;
use vars qw( @ISA @EXPORT_OK );
@ISA = qw( Exporter );
@EXPORT_OK = qw( nhash );
sub new {
my($class, @div) = @_;
return bless \@div, $class;
}
my @primes = qw( 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79
83 89 97 101 103 107 109 113);
sub nhash {
my($string, @div) = @_;
if (ref $string) { # called as a method
# $string is actually $self
($string, @div) = ($div[0], @$string);
}
#warn "'$string' @div";
my($sum, $i);
foreach my $val (split //, $string) {
$i += 28; $i %= 29;
$sum += $primes[$i] * ord($val);
}
return $sum unless @div;
my @ret;
while (my $div = pop @div) {
unshift @ret, $sum % $div;
$sum = int($sum / $div);
}
return wantarray ? @ret : join '/', @ret;
}
1;
__END__
=pod
=head1 NAME
Algorithm::Nhash - Exim nhash algorithm
=head1 VERSION
version 0.002
=head1 SYNOPSIS
Procedural usage:
use Algorithm::Nhash qw( nhash );
# prints 228769
print nhash('supercalifragilisticexpialidocious');
# prints 417 (which is 228769 % 512)
print nhash('supercalifragilisticexpialidocious', 512);
# prints '6/33' (6*64 + 3 == 417)
print nhash('supercalifragilisticexpialidocious', 8, 64);
# assigns (6, 33) to @nhash
my @nhash = nhash('supercalifragilisticexpialidocious', 8, 64);
OO usage:
( run in 2.850 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )