Search code examples
perlperl-module

Perl Module to convert numbers to letter notation


Is there a perl module that will convert a number to a letter and vice versa?

For instance

1 = A 
2 = B
3 = C
...
27 = AA
28 = AB
29 = AC
...
53 = BA
54 = BB
55 = BC

So on and so forth.


Solution

  • This code shows a function a2n that does what you need

    use strict;
    use warnings;
    
    printf "%2s = %d\n", $_, a2n($_) for qw/ A B C AA AB AC BA BB BC /;
    
    sub a2n {
      my $n = 0;
      $n = $n * 26 + $_ for map { ord($_) & 0x1F } split //, shift;
      $n;
    }
    

    output

     A = 1
     B = 2
     C = 3
    AA = 27
    AB = 28
    AC = 29
    BA = 53
    BB = 54
    BC = 55
    

    A corresponding n2a looks like this

    sub n2a {
      my ($n) = @_;
      my @a;
      while ($n > 0) {
        unshift @a, ($n-1) % 26;
        $n = int(($n-1)/26); #Edited for failing corner case
      }
      join '', map chr(ord('A') + $_), @a;
    }