カウントアップ

Perlでタブを使った階層を表したテキストを箇条書きメモにする - tittea blogを見てやってみた。

list.pl

file1.txtを読み込んで、加工して$resultに格納し、それをfile2.txtに出力する。

use strict;
use warnings;
my $depth = 0;
my $before = 0;
my $max_depth = 3; # ネストを何段階まで許すか。0から数える。
my %head = (
	0=>[map { '*' } ( 1..100 )],
	1=>[(1..100)],
	2=>[map { '('.$_.')' } (1..100)],
	3=>[map { '('.$_.')' } 'a'..'z']
);
my %count = ();
my $result = '';
open ( IN, 'file1.txt' );
while ( my $line = <IN> ) {
	$depth = 0;
	while ( $line =~ s/^\s// ) { ++ $depth; } # 行の先頭の空白文字の数を調べる。
	$depth > $max_depth and $depth = $max_depth; # ネストの深さを制限する。
	$result .=  ' ' x $depth; # 行の先頭に空白文字を補う。
	exists $count{$depth} or $count{$depth} = 0; # これ消すと警告が出るので。
	# 浅くなった場合の処理
	$depth < $before and map { $count{$_} = 0 } ( ($depth+1)..$max_depth ); 
	# 本文を作る。
	$result .= $head{$depth}->[$count{$depth}];
	$result .= $line;
	++ $count{$depth}; # カウントアップ
	$before = $depth;
}
close ( IN );
# 結果を出力する。
open ( OUT, '>file2.txt' );
print OUT $result;
close ( OUT );

file1.txt

	議題1
		ほげほげ
			うひひ
			いひひ
		いひ
	あはは
		うふふ
		ふふ
	えへ
		ああー

file2.txt

 1議題1
  (1)ほげほげ
   (a)うひひ
   (b)いひひ
  (2)いひ
 2あはは
  (1)うふふ
  (2)ふふ
 3えへ
  (1)ああー

まとめ

回帰使わなくてもなんとかなりそう。