ファイルの COPY

1.1. ファイルの COPY

1行ずつ読んで、1行ずつ書く

lesson001.pl

use strict;

print while(<STDIN>);

実行結果

C:\>perl "C:\study\SoftwareTools\1_1_ファイルのCOPY\lesson001.pl" < "C:\study\So
ftwareTools\1_1_ファイルのCOPY\test.txt"
1. 手はじめに

1.1. ファイルの COPY
1.2. 文字数を数える

1文字ずつ読んで、1文字ずつ書く

これでは、だめ

lesson002.pl

use strict;

my $char;
print $char, "\n" while($char = getc(STDIN));

実行結果

C:\>perl "C:\study\SoftwareTools\1_1_ファイルのCOPY\lesson002.pl" < "C:\study\So
ftwareTools\1_1_ファイルのCOPY\test.txt"

1
.














1
.
1
.


t

@

C



C
O
P
Y



1
.
2
.


















1文字ずつ読んで、1文字ずつ書く

lesson003.pl

use strict;

my $current_line = "";
my $pos = -1;
my $c = "";

while (<STDIN>)
{
# 1行ずつ読む
$current_line = $_;

# 改行コードを取り除く
chomp($current_line);

$pos = 0;
while ($pos < length($current_line))
{
# 半角 / 全角
if (substr($current_line, $pos, 1) =~ /^[\x80-\xff]/)
{
# 2バイト取得
$c = substr($current_line, $pos, 2);
$pos += 2;
}
else
{
# 1バイト取得
$c = substr($current_line, $pos, 1);
$pos++;
}

# 1文字表示
print $c, "\n";
}
}

実行結果

C:\>perl "C:\study\SoftwareTools\1_1_ファイルのCOPY\lesson003.pl" < "C:\study\So
ftwareTools\1_1_ファイルのCOPY\test.txt"

1
.





1
.
1
.





C
O
P
Y

1
.
2
.









1文字ずつ読んで、1文字ずつ書く

lesson004.pl

use strict;
#******************************************************************************
# 1文字ずつ読んで、1文字ずつ書く
#******************************************************************************
my $c = "";
my $EOF = "\0";

put_char($c) while (($c = get_char()) ne $EOF);

#==============================================================================
# 1文字 取得
#==============================================================================
my $current_line = "";
my $pos = -1;
my $NEWLINE = "\n";

sub get_char
{
my $char;

# まだ読んでなかったら
if ($current_line eq "")
{
# 1行読む
$current_line = <STDIN>;

# ファイルの終わりなら 終了
return $EOF if (!$current_line);

# 改行コードを取り除く
chomp($current_line);

# 現在位置 クリア
$pos = 0;
}

# 行の終わりに達したら
if ($pos >= length($current_line))
{
# 現在行 クリア
$current_line = "";

# 行の終わりを 知らせる
return $NEWLINE;
}

# 半角 / 全角
if (substr($current_line, $pos, 1) =~ /^[\x80-\xff]/)
{
# 2バイト取得
$char = substr($current_line, $pos, 2);
$pos += 2;
}
else
{
# 1バイト取得
$char = substr($current_line, $pos, 1);
$pos++;
}

return $char;
}

#==============================================================================
# 1文字 出力
#==============================================================================
my $buffer = "";

sub put_char
{
($_) = @_;

if ($_ eq $NEWLINE)
{
# 行の終わりなら 出力
print $buffer, "\n";
$buffer = "";
}
else
{
# 行の終わりでなければ、バッファにためる
$buffer .= $_;
}
}

実行結果

C:\>perl "C:\study\SoftwareTools\1_1_ファイルのCOPY\lesson004.pl" < "C:\study\So
ftwareTools\1_1_ファイルのCOPY\test.txt"
1. 手はじめに

1.1. ファイルの COPY
1.2. 文字数を数える