bonar note

京都のエンジニア bonar の技術的なことや技術的でない日常のブログです。

[perl] 使えるPerlの特殊変数「$.」

会社の机を整理していたら、「Perlデスクトップリファレンス」が出てきました。
この本新卒で最初の会社に入ったときに買ったものでもう結構ボロボロなのですが、見返してみると結構知らないことがあるもんですね。仕事を止めて読みふけってしまいました。

とくに面白いなと思ったのが特殊変数の部分。よく使うものだと以下のようなものがありますよね。

$@ 最後の eval のエラーメッセージ
$0 そのスクリプトのファイル名
$$ そのプロセスのpid

等々。pid,uid,gidを取得したりとか色々できるわけですが、素直に English モジュールを使った方が良さそうですね。ただ、知らなかったけど使えそうだなというのがあって、それが「$.」です。$.は現在処理中のファイルハンドルにおいてカーソルがある(正確にはなんて言えばいいんだろう)行数が格納されています。行指向のデータファイルを処理していて途中でエラーを吐いて止まる、みたいなことは結構あって、そういう時は $line_count++ みたいにしていたのですが、以下のようにすっきり書けそうですね。

#!/usr/bin/perl

use strict;

my $file = $ARGV[0];
unless (open FH, '< ' . $file) {
    die "cannot open file [$file]";
}
while (<FH>) {
    printf("%d: %s", $., $_);
}
close(FH);

結果は以下になります。

bonar$ perl temp.pl temp
1: 
2: This is perl, v5.8.6 built for darwin-thread-multi-2level
3: (with 3 registered patches, see perl -V for more detail)
4: 
5: Copyright 1987-2004, Larry Wall
6: 
7: Perl may be copied only under the terms of either the Artistic License or the
8: GNU General Public License, which may be found in the Perl 5 source kit.
9: 
10: Complete documentation for Perl, including FAQ lists, should be found on
11: this system using `man perl' or `perldoc perl'.  If you have access to the
12: Internet, point your browser at http://www.perl.org/, the Perl Home Page.
13: 

普通に使えそうだけど読んだ人が困惑しそうなので微妙ですね。

これを書きながらまた30分くらい読んでしまった。。それにしてもラリーウォールは気の利いた序文を書くなあ。