in reply to Converting "IV" from base 26
In any case, I think the better way to fix the original problem is like this:
That is, your v() sub should return the correct index value for a given letter (between 1 and 26), so that it doesn't have to be fixed by the caller.sub v{ ord($_[0])-ord("A")+1 }
UPDATE: I wondered about your comment regarding "weight 1" vs. "weight 0"... are you sure about that? If we are talking about the column labels in a spreadsheet, "A" is col. 1, "Z" is 26, "AA" is 27, etc. That is, each letter "digit" has a "weight" of 1 (if I understand you terminology correctly).
In any case, an even better solution is to let the v() sub split the string and handle the power multiplication:
prints "28", as it should, IMO.sub v { my (@letters) = split //, $_[0]; my $sum = 0; my $pwr = 1; while ( @letters ) { my $digit = ord( pop( @letters )) - ord("A") + 1; $sum += $digit * $pwr; $pwr *= 26; } return $sum; } print v("AB"),"\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Converting "IV" from base 26
by Eimi Metamorphoumai (Deacon) on Jul 01, 2008 at 14:29 UTC | |
|
Re^2: Converting "IV" from base 26
by ikegami (Patriarch) on Feb 09, 2009 at 19:27 UTC |