Jeffrey Ray
Jeffrey Ray

Reputation: 1264

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.

Upvotes: 5

Views: 3775

Answers (4)

Borodin
Borodin

Reputation: 126742

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;
}

Upvotes: 9

TLP
TLP

Reputation: 67900

Well, Perl can handle letters in ranges, which might suit your needs:

my @letters = 'A' .. 'BC'; # A B C ... Z AA AB AC etc.

Then you can simply do:

my $letter = $letter[$foo - 1];   # 1 -> A, 2 -> B ...

Upvotes: 6

drquicksilver
drquicksilver

Reputation: 1635

There is a cute trick with the .. operator. Try:

print join ",",("A".."ZZ"),"\n"

or

my @a = ("A".."ZZ");
print $a[56],"\n";

This is not really a good way if you're going to go up into the 100s of thousands of elements, though. Then you're better of doing the maths (very simple maths) for base-26 yourself.

Upvotes: 3

choroba
choroba

Reputation: 241968

Do you really need a module for this?

my $n = 55;
my $s = 'A';
$s++ while --$n;
print "$s\n";

Upvotes: -1

Related Questions