I wanted a way to convert numbers into a different base (if thats the correct term - I'm no mathematician), where that base is determined by an array. The following works, but I'd like to know if it can be made shorter. It seems rather long for something so simple. Anyone feel like having a go?

I'll admit that this exercise is really nothing more than a silly vanity project for my website, to give me URLs somewhat similar to tinyurl.com, where numeric ids in a database will be converted to and from alphanumeric strings. Eg. http://mysite/?123 becomes http://mysite/?1Z or more interestingly http://mysite/?1000000 becomes http://mysite/?4c92

All efforts appreciated.
#!/usr/bin/perl -w use strict; my @alphanum = (0 .. 9, "a" .. "z", "A" .. "Z"); my $divisor = scalar @alphanum; #my $enc = &enc(1_000); #my $dec = &dec($enc); #print "$enc $dec\n"; for (my $x=0; $x<10_000; $x++) { print "$x -> " . &enc($x) . "\n"; } exit 0; sub dec { my $num = shift; # strip leading 0's $num =~ s/$0+//g; my ($y, $result) = (0, 0); foreach (split(//, reverse($num))) { my $found = 0; foreach my $item (@alphanum) { if ($item eq $_) { last; } $found++; } my $temp = $found * ($divisor ** $y); $result += $temp; $y++; } return $result; } sub reduce { return (int($_[0] / $divisor), $_[0] % $divisor); } sub enc { my $num = shift; my $end = ""; my ($a, $b) = reduce($num); $end = $alphanum[$b] . $end; until ($a < $divisor) { ($a, $b) = reduce($a); $end = $alphanum[$b] . $end; } $end = $alphanum[$a] . $end unless $a == 0; return $end; }

In reply to convert numbers to a different (arbitrary) base by hostyle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.