ミニマルPerl のメモ
catと同様の動作をする
$ perl -w -e 'while(<>) { print; }' file file2
abc
def
$ perl -wnl -e 'print;' file file2
abc
def
$ perl -wpl -e '' file file2
abc
def
#---
perlの重要な起動オプション(P16)
- e
- w
- n
- p
- l
- 0
#---
perlの起動のオプション詳細
- n: 入力を処理する
$ sed 's/^/ /g' file
123
456
perlで表すと以下
$ perl -wnl -e 's/^/ /g; print;' file
123
456
- p: 自動出力
$ perl -wpl -e 's/^/ /g;' file
123
456
- l: 行末を処理
$ perl -wn -e 'print $.;' three_line_file
123
- lオプションを省略すると、改行が付与されない
$ perl -wnl -e 'print $.;' three_line_file
1
2
3
- lオプションを使わないで同じことを実行
$ perl -wn -e 'print $., "\n";' three_line_file
1
2
3
#---
入力レコードセパレータの変更
デフォルト
レコードが行単位
$ perl -wpl -e 's/^/ /g;' memo
This is the file "memo", which has these
lines spread out like so.
And then if continues to a
second paragraph.
ファイル全体が1つのレコード
$ perl -0777 -wpl -e 's/^/ /g;' memo
This is the file "memo", which has these
lines spread out like so.
And then if continues to a
second paragraph.
本当は、段落がレコード?
$ perl -00 -wpl -e 's/^/ /g;' memo
This is the file "memo", which has these
lines spread out like so.
And then if continues to a
second paragraph.
入力レコードセパレータの特殊文字:$/
#---
特殊変数
$_
最後に読み込んだ入力レコード
$.
現在の行番号
$ perl -wnl -e 'printf "$.: "; print;' file
1: 123
2: 456
1つのprintだけを使う場合
$ perl -wnl -e 'print "$.: $_";' file
1: 123
2: 456
#---
モジュールをロードする
$ perl -M'Text::Autoformat' -00 -wn -e 'print autoformat "$.: $_", { right => 60 };' memo
#---
ワンライナーバージョンをPerlスクリプトで記述
$ perl -wnl -e 'print;' file
123
456
$ ./perl_cat file
123
456
$ cat perl_cat
#!/usr/bin/perl -wnl
print;
#---
バックスラッシュ
$ perl test.pl
Spendy's restaurant saves you $$$
Haru@Haru-PC ~/perl
$ cat test.pl
#!/usr/bin/perl
print 'Spendy\'s restaurant saves you $$$';
→ネストしたシングルクォートをリテラル文字として扱う
#---