Perlで文字列操作を学ぶための自作ドリル(英大文字/英小文字)

研修生に教えるための問題と解答例を作ってみた。

問題

英小文字→英大文字(キー入力→画面出力)

実行結果

$ perl uppercase.pl
abcde(改行)
ABCDE
This is perl program.(改行)
THIS IS PERL PROGRAM.
12345xyz ZYX67890(改行)
12345XYZ ZYX67890
(Ctrl+Dで終了)$
英大文字→英小文字(キー入力→画面出力)

実行結果

$ perl lowercase.pl
ABCDE(改行)
abcde
This is Perl Program.(改行)
this is perl program.
12345xyz ZYX67890(改行)
12345xyz zyx67890
(Ctrl+Dで終了)$
単語頭文字のみ大文字(キー入力→画面出力)

実行結果

$ perl upperfirstcase.pl
abcde(改行)
Abcde
ABCDE(改行)
Abcde
This is perl program.(改行)
This Is Perl Program.
THIS IS PERL PROGRAM.(改行)
This Is Perl Program.
12345xyz ZYX67890(改行)
12345xyz Zyx67890
(Ctrl+Dで終了)$
単語頭文字のみ大文字(ファイル入出力)

実行結果

$ perl uppercasefirst_textconv.pl source.txt result.txt

変換元ファイル(source.txt)

abcde fghij klmno pqrst uvwxy
zABCD EFGHI JKLMN OPQRS TUVWX
YZ123 45678 90+-* /^\%=

変換結果ファイル(result.txt)

Abcde Fghij Klmno Pqrst Uvwxy
Zabcd Efghi Jklmn Opqrs Tuvwx
Yz123 45678 90+-* /^\%=

解答例

英小文字→英大文字(キー入力→画面出力)
while (my $line = <STDIN>) {
  $line = uc($line);
  print $line;
}
英大文字→英小文字(キー入力→画面出力)
while (my $line = <STDIN>) {
  $line = lc($line);
  print $line;
}
単語頭文字のみ大文字(キー入力→画面出力)
while (my $line = <STDIN>) {
  my @words = split / /, $line;
  foreach my $word (@words) {
    $word = lc($word);
    $word = ucfirst($word);
  }
  $line = join ' ', @words;
  print $line;
}
単語頭文字のみ大文字(ファイル入出力)
use strict;
use warnings;
if (@ARGV < 2) {
  print STDERR "ERROR: 引数が足りません(2個必要です。)\n";
  exit;
}
my $finame = $ARGV[0]; # 読み込みファイル名
my $foname = $ARGV[1]; # 書き出し先ファイル名
unless (-e $finame) {
  print STDERR "ERROR: 読み込みファイルが存在しません。\n";
  exit;
}
if (-e $foname) {
  print STDERR "ERROR: 書き出し先のファイルが既にあります。\n";
  exit;
}
open my $fi, '<', $finame or die;
open my $fo, '>', $foname or die;
while (my $line = <$fi>) {
  my @words = split /[ ]/, $line;
  foreach my $word (@words) {
    $word = lc($word);
    $word = ucfirst($word);
  }
  $line = join ' ', @words;
  print $fo $line;
}
close $fi;
close $fo;
exit;