Skip to content

Instantly share code, notes, and snippets.

@deris
Created January 5, 2020 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deris/8caa84def8cc263ad72bdd12efa735c4 to your computer and use it in GitHub Desktop.
Save deris/8caa84def8cc263ad72bdd12efa735c4 to your computer and use it in GitHub Desktop.
ファイルの行ごとの幅チェック
use strict;
use warnings;
use Encode;
use constant MAX_WIDTH => 90;
use constant TAB_WIDTH => 4;
# ディレクトリ走査
sub traverse {
my $dir = shift;
my $func = shift;
my $result = shift;
opendir my $dh, $dir
or die "Can't open directory $dir: $!";
while (my $file = readdir $dh) {
if (-d $file and $file !~ /^\.{1,2}$/) {
&traverse($file, $func, $result);
} elsif (-e $file) {
&$func($file, $result);
}
}
}
# ファイルを1行ずつ読み込み、表示幅がMAX_WIDTHより大きい行を標準出力に出力
my $func = sub {
my $file = shift;
my $result = shift;
open my $fh, '<', $file
or die "Can't open file $file $!";
while (my $line = <$fh>) {
chomp $line;
utf8::decode($line);
my @chars = split //, $line;
# ASCIIだったら幅:1 ASCII以外だったら幅:2 タブ文字だったらタブ幅考慮して計算
my $width = 0;
foreach my $char ( @chars ) {
utf8::encode($char); # フラグ落とし
if ($char eq "\t") {
if (($width % TAB_WIDTH) == 0) {
$width += TAB_WIDTH;
} else {
$width += TAB_WIDTH - ($width % TAB_WIDTH);
}
} elsif ($char =~ /^\p{ascii}$/) {
$width += 1;
} else {
$width += 2;
}
}
print $width, ':', $line, "\n" if $width > MAX_WIDTH;
}
};
die "1 argument required!" if @ARGV != 1;
my $dir_path = shift;
my @result = ();
&traverse($dir_path, $func, \@result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment