NAME
Farid::Model::Random provides a simple frontend to /dev/random
Webpage: https://farid.ps/random
SYNOPSIS
perl Random.pm [length]
use Farid::Model::Random;
print Farid::Model::Random->alnum([length]);
print Farid::Model::Random->hex([length]);
print Farid::Model::Random->num([length]);
LICENSE
Provided as-is under GPLv3. No warranties. Use at your own risk.
alnum: b8lSFFLW
hex: 101064a2
num: 45645948
#!/usr/bin/perl
package Farid::Model::Random;
=head1 NAME
Farid::Model::Random provides a simple frontend to /dev/random
Webpage: https://farid.ps/random
=head1 SYNOPSIS
perl Random.pm [length]
use Farid::Model::Random;
print Farid::Model::Random->alnum([length]);
print Farid::Model::Random->hex([length]);
print Farid::Model::Random->num([length]);
=head1 LICENSE
Provided as-is under GPLv3. No warranties. Use at your own risk.
=cut
use IO::File;
use Pod::Text;
use v5.20;
use feature 'signatures';
my @random;
my $pid = 0;
sub octet($self, $max = 256, $length = 32) {
unless ($pid == $$) {
@random = ();
$pid = $$;
}
my $limit = 256 - (256 % $max);
my $octet;
while (1) {
unless (@random) {
my $fh = IO::File->new('/dev/random', 'r');
die $! unless $fh;
my $random;
my $bytes_read = $fh->sysread($random, $length);
die unless $bytes_read == $length;
@random = unpack("C$length", $random);
}
$octet = shift @random;
last if $octet < $limit;
}
return $octet % $max;
}
sub string($self, $length, $chars) {
my $string = '';
my $char_count = scalar(@{$chars});
while (length($string) < $length) {
$string .= $chars->[$self->octet($char_count)];
}
return $string;
}
sub alnum($self, $length) {
return $self->string($length, ['0'..'9','a'..'z','A'..'Z']);
}
sub hex($self, $length) {
return $self->string($length, ['0'..'9','a'..'f']);
}
sub num($self, $length) {
return $self->string($length, ['0'..'9']);
}
sub pod($self) {
my $p2t = Pod::Text->new;
my $pod;
$p2t->output_string(\$pod);
$p2t->parse_file(__FILE__);
return $pod;
}
sub source($self) {
my $fh = IO::File->new(__FILE__, 'r');
die $! unless $fh;
return join('', <$fh>);
}
sub main($self, $length) {
print $self->pod;
printf "OUTPUT\n";
printf " alnum: %s\n", $self->alnum($length);
printf " hex: %s\n", $self->hex($length);
printf " num: %s\n", $self->num($length);
}
__PACKAGE__->main(shift(@ARGV) // 8) unless caller();
1;