http://www.perlmonks.org?node_id=270352

eduardo has asked for the wisdom of the Perl Monks concerning the following question:

Greetings!

So, I have a problem at my current contract that proved to be surprisingly annoying, and my solution looks remarkably inelegant to me. So, I thought to myself: "I'll ask the perlmonks, surely someone will give me a 8 character regexp that solves my problem elegantly!" :)

I have a series of "alphabet based base-26" numbers... what do I mean by this? Well how about some examples so you get the idea...

Base-26Base-10
a1
z26
aa27
az52
ba53
zz702
aaa703

So, basically each position is a power of 26. Pretty reasonable... I wanted a sub that I could easilly pass a string, and receive the base 10 equivalent. The following is my sub and test program...

#!/usr/bin/perl use warnings; use strict; use POSIX qw/ pow /; sub convert_from_base26 { my ($total, $exp); my ($val) = @_; $total += (ord($_) - (ord('a') - 1)) * pow(26, $exp++) for split('', lc(reverse($val))); return $total; } print "Enter a value: "; while (<>) { chomp; print convert_from_base26($_)."\n"; print "Enter a value: "; }

Although the code for the sub is relatively concise, it doesn't look like code I'd like to revisit (not to mention that I need to find a new sub name), as when I look at the code it's not "obvious" what is going on. I think the term I heard at one point that I loved was: "it has too many metasyntatic variables." So, monks... any ideas as to how I could write this to be a more elegant piece of code?