Ing. Branislav Gerzo wrote:
Hi pals,

Hello,

I'd like to code my own encode function, I have @list of allowed
characters, my input is number, and I'd like to 'convert' number to
characters. Here is script I coded, but I'm sure it could be really
better. This script should work, but there are too much conditions and
isn't so clear as I think it could be:

use strict;
use warnings;

my $a = 123456789; # $a >= 0
my @list = ( 'a' .. 'z', 'A' .. 'Z', 0 .. 9, '-', '_' );

print my $out = reverse(fn($a));

sub fn {
my $a = shift;
my $out = shift || '';
$out .= $list[$a % @list];
my $b = ($a/@list)-1;
if ( $b >= @list ) { $out .= fn($b) }
$out .= $list[$b] if $list[$b] and $b >= 0; return $out;
}
__END__


prints: gv7Zv

So if anyone helps me, how to clear it, I will be glad.

You could use the Math::BaseCalc module: http://search.cpan.org/~kwilliams/Math-BaseCalc-1.011/


$ perl -le'
use Math::BaseCalc;
my $calc = new Math::BaseCalc( digits => [ "a" .. "z", "A" .. "Z", 0 .. 9, "-", "_" ] );
my $num = 123456789;
my $out = $calc->to_base( $num );
print $out;
'
hw80v



Or if you really want to do it yourself:

$ perl -le'
my $num = 123456789;

{   my @digits = ( "a" .. "z", "A" .. "Z", 0 .. 9, "-", "_" );
    sub fn {
        my $in = shift;
        my $res = "";

        while ( $in ) {
            substr $res, 0, 0, $digits[ $in % @digits ];
            $in = int( $in / @digits );
            }
        return $res;
        }
    }

my $out = fn( $num );
print $out;
'
hw80v




John -- use Perl; program fulfillment

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to