3

I have the following Perl script that generates a string based on a number:

my @chars;
push @chars, map(chr, 48..57), map(chr, 97..122);
my $c = $#chars+1;

for (0..50) {
    my $string;
    my $l = $_ / $c;
    my $i = int $l;
    my $r = ($l - $i) * $c;
    $string .= $chars[$r];
    while ($i > 0) {
        $l = $i / $c;
        $i = int $l;
        $r = ($l - $i) * $c;
        $string .= $chars[$r];
    }
    print "$string\n";
}

When I run this I get the following output:

0
1
2
3
4
...
z
01
01
21
21
41
41
61
61
81
91
91
b1
b1
d1
d1

What am I missing? Thankful for any help!

tbjers
  • 564
  • 3
  • 13
  • What are you trying to get it to do? What exactly are you asking? Are you asking how you convert radix or are you asking for an analysis of that perl code? – D. Patrick May 15 '09 at 14:52
  • I am trying to create something similar to Base64 but with the base of 36 in this case, using the character range given in @chars. – tbjers May 15 '09 at 14:54

2 Answers2

3

Try this instead, it's a little clearer than the script you have and properly converts to an arbitrary base:

my @chars;
push @chars, map(chr, 48..57), map(chr, 97..122);

my $base = @chars;

for my $num (0..100) {
    my $string = '';

    while ($num >= $base) {
        my $r = $num % $base;
        $string .= $chars[$r];

        $num = int($num / $base);
    }
    $string .= $chars[$num];
    print reverse($string) . "\n";
}
kbosak
  • 2,132
  • 1
  • 13
  • 16
  • 2
    I'd probably write `my @chars = map chr, 48..57, 97..122;` or `my @chars = (0..9, 'a'..'z');`, but to each their own :) – ephemient May 15 '09 at 15:40
1

See also http://www.rosettacode.org/wiki/Number_base_conversion#Perl

glenn jackman
  • 238,783
  • 38
  • 220
  • 352