プログラマでありたい

おっさんになっても、プログラマでありつづけたい

ミニマルPerl 2章 perlの起動オプション

オプション 意味
-e 'code' codeの実行
-w 警告
-n 読み込み(出力なし)
-p 読み込んで出力
-l 行末処理
-Odigits 入力レコードセパレータの設定

perl1行プログラミングの基本:-e

 -eの後に続く引数をプログラムとして指定します。

$perl -wl -e 'print 42/3;'
14

警告を有効にする:-w

 こちらは割と知っている人も多いんではないでしょうか?warningsオプションです。
ちなみに、strictオプションは-sではありません。

$perl -l -w 'print $HOME;' #シェル変数をPerlが認識していない?
(出力なし)
$perl -wl -e 'print $HOME;'
Name "main::HOME" used only once: possible typo at -e line 1.
Use of uninitialized value in print at -e line 1.

入力を処理する:-n

 入力処理の基本は、-nオプションです。入力ファイルの内容を1行ずつ読み込み、終了までループします。

以下、全て等価です。

$ cat seattleites 
Torbin Ulrch    98107
Yeshe Dolma     98117

$ sed 's/^/ /g' seattleites
 Torbin Ulrch   98107
 Yeshe Dolma    98117

$ perl -wnl -e 's/^/ /g; print;' seattleites 
 Torbin Ulrch   98107
 Yeshe Dolma    98117

自動出力処理付きで入力を処理する:-p

  • lオプションにprint機能を付けたのが、-pオプションとなります。よく使うことになるオプションだと思います。
$ perl -wpl -e 's/^/ /g;' seattleites
 Torbin Ulrch   98107
 Yeshe Dolma    98117

行末処理をする:-l

 先ほどからずっと出てきている-lオプション。自動的に改行処理をしてくれます。先ほどのファイルで行番号を出力するようにすると効果がよくわかります。基本、-lを付けていれば問題なしということも

$ perl -wn -e 'print $.;' seattleites 
12$

$ perl -wln -e 'print $.;' seattleites 
1
2
$

入力レコードセパレータを変更する:-0digits

 入力レコードの末尾を芦原す文字を8進数で定義します。
動きは解るのですが、どういった場合に使うのかがちょっと不明なので、もう少し勉強していきます。

$ perl -wpl -e 's/^/    /g;' memo   #デフォルトの行モード
        This is the file "memo", which has these
        lines spread out like so.
    
    
        And then it continues to a
        secound paragraph.

$ perl -00 -wpl -e 's/^/    /g;' memo  #段落モード
        This is the file "memo", which has these
    lines spread out like so.

        And then it continues to a
    secound paragraph.


$ perl -0777 -wpl -e 's/^/    /g;' memo  #ファイルモード
        This is the file "memo", which has these
    lines spread out like so.


    And then it continues to a
    secound paragraph.

#スペースは、4つ