File Coverage

blib/lib/Number/Base/SpreadsheetColumn.pm
Criterion Covered Total %
statement 27 27 100.0
branch 2 4 50.0
condition 1 3 33.3
subroutine 6 6 100.0
pod 2 2 100.0
total 38 42 90.4


line stmt bran cond sub pod time code
1             package Number::Base::SpreadsheetColumn;
2              
3 2     2   407601 use 5.010001;
  2         8  
4 2     2   9 use strict;
  2         2  
  2         45  
5 2     2   6 use warnings;
  2         3  
  2         143  
6              
7 2     2   11 use Exporter qw(import);
  2         3  
  2         615  
8             our @EXPORT_OK = qw(
9             from_scbase
10             to_scbase
11             );
12              
13             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
14             our $DATE = '2026-02-02'; # DATE
15             our $DIST = 'Number-Base-SpreadsheetColumn'; # DIST
16             our $VERSION = '0.001'; # VERSION
17              
18             sub from_scbase {
19 7     7 1 269702 my $str = uc shift;
20              
21 7 50       27 die "Please only use letters A-Z" if $str =~ /[^A-Z]/;
22              
23 7         10 my $res = 0;
24 7         23 for my $char (split //, $str) {
25 13         21 $res = $res * 26 + (ord($char) - ord('A') + 1);
26             }
27 7         29 $res-1;
28             }
29              
30             sub to_scbase {
31 7     7 1 3102 my $num = shift;
32              
33 7 50 33     31 die "Currently can't handle fraction or negative number!"
34             if $num < 0 || $num != int($num);
35 7         8 $num = int($num);
36              
37 7         9 my $res = "";
38 7         13 while ($num >= 0) {
39 13         17 my $remainder = $num % 26;
40 13         20 my $letter = chr($remainder + ord('A'));
41             #say "D:num=<$num>, remainder=<$remainder>, letter=<$letter>";
42 13         16 $res = $letter . $res;
43 13         27 $num = int($num / 26) - 1;
44             #say "D:num=<$num>";
45             }
46 7         22 $res;
47             }
48              
49             1;
50              
51             # ABSTRACT: Convert spreadsheet column name (e.g. "A", "Z", "AA") to number (e.g. 0, 25, 26) and vice versa
52              
53             __END__