Question

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!

Was it helpful?

Solution

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";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top