Created
November 4, 2011 01:47
-
-
Save syohex/1338481 to your computer and use it in GitHub Desktop.
Excel列名変換問題で第2回社内プログラミングコンテストを開催してみた(前編)を素直に書いてみた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl | |
use strict; | |
use warnings; | |
my $to_column = shift; | |
die "first argument is '0' or '1'" unless $to_column == 0 or $to_column == 1; | |
my $arg = shift or die "Usage: $0 to_column value"; | |
$arg = uc $arg; | |
my $a_ascii_code = ord 'A'; | |
if ($to_column == 0) { | |
my $num = 0; | |
for my $n (split //, $arg) { | |
my $char_var = ord($n) - $a_ascii_code + 1; | |
$num = (26 * $num + $char_var); | |
} | |
print "$arg => $num\n"; | |
} else { | |
my @remains; | |
my $num = $arg; | |
while ($num > 26) { | |
push @remains, ($num % 26); | |
$num = int($num / 26); | |
} | |
push @remains, $num; | |
my @chars; | |
for my $n (map { $_ - 1 } reverse @remains) { | |
push @chars, chr($n + $a_ascii_code); | |
} | |
printf "%s => %s\n", $arg, join '', @chars; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
perl excel_util.pl 0 A | |
A => 1 | |
perl excel_util.pl 0 Z | |
Z => 26 | |
perl excel_util.pl 0 AA | |
AA => 27 | |
perl excel_util.pl 0 XFD | |
XFD => 16384 | |
perl excel_util.pl 1 26 | |
26 => Z | |
perl excel_util.pl 1 27 | |
27 => AA | |
perl excel_util.pl 1 16384 | |
16384 => XFD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment