Perl の特殊変数 $# は使うな
結論から先に言うと、
$#
は使うなuse warnings;
を書いておきましょう
ということになる。
$#
を使ってはいけない
変数 $#
は、Perl が数値を print
するときに使うフォーマットを指定するのに使う変数。別名 $OFMT
。
perldoc perlvar
すると出てくるドキュメントには deprecated だって書いてある。また、perl-5.10 では削除されている。
ちなみに私の環境は perl-5.8.9 です。
#! /usr/bin/perl print 10/3, "\n"; # 通常の表示で $# = '%.6g'; # 有効桁を 6 桁に print 10/3, "\n"; $# = '%e'; # 指数形式 print 10/3, "\n";
実行結果:
3.33333333333333 3.33333 3.333333e+00
これが、配列の最後の要素への添字を返す $#array
という書き方とまざると、おかしなことになる。
#! /usr/bin/perl @array = (0, 1, 2); print "the last index is ", $#array, "\n"; # 配列の最後の要素への添字 print 10/3, "\n"; $# = '%.6g'; print 10/3, "\n"; $# = '%e'; print 10/3, "\n"; print "the last index is ", $#array, "\n"; # もう一度
実行結果:
the last index is 2 3.33333333333333 3.33333 3.333333e+00 the last index is 0.000000e+00
さすがにゼロは無いだろうよw
use warnings;
しましょう
-w
をつけるか use warnings;
して $#
に触ると、ちゃんと教えてくれます。
Use of $# is deprecated at ./dollar_sharp.pl line 9. the last index is 2 3.33333333333333 3.33333 3.333333e+00 the last index is 0.000000e+00
perl 5.10 で実行すると、「もう $#
はサポートしてませんよ」というメッセージ。
$# is no longer supported at ./dollar_sharp.pl line 9. the last index is 2 3.33333333333333 3.33333333333333 3.33333333333333 the last index is 2
そして、数値の表示の仕方にも、なんら影響が出ていない。
参考
- perl5100delta - perldoc.perl.org
- http://perldoc.perl.org/perl5100delta.html#The-%27%24*%27-and-%27%24%23%27-variables-have-been-removed
- perldelta - perl 5.10.0 の新機能 - perldoc きまぐれ訳
- http://fleur.hio.jp/perldoc/modules/perl/perl-5.10.0/pod/perl5100delta.mix.html#The_$*_and_$#_variables_have_been_removed