# _num_to_alpha - Returns a string of letters representing a positive integer.
# Arguments :
# number to convert
+# maximum number of letters
# returns undef if the number is negative
+# returns undef if the number of letters is greater than the maximum wanted
# _num_to_alpha( 0) eq 'A';
# _num_to_alpha( 1) eq 'B';
# Avoid ++ -- ranges split negative numbers
sub _num_to_alpha{
- my($num) = @_;
+ my($num,$max_char) = @_;
return unless $num >= 0;
my $alpha = '';
+ my $char_count = 0;
+ $max_char = 0 if $max_char < 0;
+
while( 1 ){
$alpha = $letters[ $num % 26 ] . $alpha;
$num = int( $num / 26 );
last if $num == 0;
$num = $num - 1;
+
+ # char limit
+ next unless $max_char;
+ $char_count = $char_count + 1;
+ return if $char_count == $max_char;
}
return $alpha;
}
BEGIN {
chdir 't' if -d 't';
- @INC = '../lib';
require './test.pl';
}
is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 ), 'AAAA');
is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 + 1 ), 'AAAB');
+is( _num_to_alpha(26 - 1 , 1), 'Z');
+is( _num_to_alpha(26 , 1), undef); # AA
+
+is( _num_to_alpha(26 ** 2 + 26 - 1 , 2 ), 'ZZ');
+is( _num_to_alpha(26 ** 2 + 26 , 2 ), undef); # AAA
+
+is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 - 1 , 3 ), 'ZZZ');
+is( _num_to_alpha(26 ** 3 + 26 ** 2 + 26 , 3 ), undef); # AAAA
+
done_testing();