in reply to Get excel column letter from number
Hi bulrush,
Here are a couple of tests, and just for fun my own (horribly inefficient, benchmark included) implementation using Perl's magic string increment:
#!/usr/bin/env perl use warnings; use strict; sub excelpos2ltr { # by bulrush, https://perlmonks.pair.com/?node_id=1 +168549 my($oldcol)=@_; # Col starts at 0='A' my($procname,$numeric,$ltr,$num2,$outs); $procname="excelpos2ltr"; # Alt method 4. $numeric = $oldcol % 26; $ltr = chr(65 + $numeric); #$num2 = intval($oldcol / 26); # old line $num2 = int($oldcol / 26); if ($num2 > 0) { $outs=excelpos2ltr($num2 - 1) . $ltr; } else { $outs=$ltr; } return $outs; } sub colname { my $n = "A"; $n++ for 1..shift; return $n; } my %tests = ( 0=>"A", 1=>"B", 25=>"Z", 26=>"AA", 27=>"AB", 99=>"CV", 420=>"PE", 479=>"RL", 14557=>"UMX", 285075=>"PERL", ); use Test::More; plan tests => 2 * scalar keys %tests; is excelpos2ltr($_), $tests{$_}, "excelpos2ltr $_ => $tests{$_}" for sort {$a<=>$b} keys %tests; is colname($_), $tests{$_}, "colname $_ => $tests{$_}" for sort {$a<=>$b} keys %tests; done_testing; use Benchmark 'cmpthese'; cmpthese(-5, { # not neccesarily a fair benchmark due to random test data excelpos2ltr => sub { excelpos2ltr(rand(10000)) }, colname => sub { colname(rand(10000)) }, });
Regards,
-- Hauke D
|
|---|