でばぐめ -IT技術メモ- -8ページ目

でばぐめ -IT技術メモ-

主にハードウェア/ソフトウェアのプログラミングに関するブログです。


Perlの書き方で、最初違和感があったのが、変数省略。
foreachの制御変数やprint文の引数は省略して書くことができます。

foreach (0..9) {
print;
}


0~9までループをまわすのは何となくわかるが、printって何をprintするの?

実行結果は

0123456789


foreachの制御変数を省略した場合や、print文の引数を省略した場合、
Perlはデフォルト変数 $_ を自動的に使用するようです。
つまり下と等価。

foreach $_ (0..9) {
print $_;
}


使いすぎると混乱しそうです。


「初めてのperl」の2章で-wオプションについて書かれています。
perl -h で helpを見ると推奨とのこと。
-wオプションを付けた場合と付けない場合との違いについて試してみました。

1. 演算結果が変
(1+2)*3を計算して表示するプログラムを書いてみました。

% cat my_prog1.pl
#!/usr/bin/perl
print (1+2)*3;
print "\n";

%my_prog1.pl
3


結果が"3"。予期せぬ結果が返ってきました。
-w オプションをつけて実行してみると、Warningを出力します。

% cat my_prog1-w.pl
#!/usr/bin/perl -w
print (1+2)*3;
print "\n";

% my_prog1-w.pl
print (...) interpreted as function at ./my_prog1-w.pl line 2.
Useless use of multiplication (*) in void context at ./my_prog1-w.pl line 2.
3


2.レキシカル変数の2重定義(?)
レキシカル変数(my変数)の2重定義も、Warningを出力してくれるようです。


% cat my_prog2-w.pl
#!/usr/bin/perl -w
my $a = 1;
my $a = 2;
print $a, "\n";

% my_prog2-w.pl
"my" variable $a masks earlier declaration in same scope at ./my_prog2-w.pl line 3.
2




1.の演算の場合、外側に()をつけるとうまくいきました。

#!/usr/bin/perl -w
print ((1+2)*3);
print "\n";


関連書籍

初めてのPerl 第5版/Randal L. Schwartz

¥3,780
Amazon.co.jp

初心者にもわかりやすく書かれていますが、
全くの初心者というより、少しPerlに慣れてきた時に威力を発揮する本です。
簡単なテキスト操作のためにPerlを使用するのであれば十分事足ると思います。


続・初めてのPerl 改訂版/Randal L. Schwartz

¥3,360
Amazon.co.jp

初めてのPerlの続編で、主にリファレンスについて書かれています。

Perl FAQを眺めてみました。

% perldoc perlfaq1


目次に気になるFAQが...

What’s the difference between "perl" and "Perl"?


違いってあるのかな?

One bit. Oh, you weren’t talking ASCII? :-)


......

One bit. Oh, you weren’t talking ASCII? :-) Larry now uses "Perl" to
signify the language proper and "perl" the implementation of it, i.e.
the current interpreter. Hence Tom’s quip that "Nothing but perl can
parse Perl." You may or may not choose to follow this usage. For
example, parallelism means "awk and perl" and "Python and Perl" look
OK, while "awk and Perl" and "Python and perl" do not. But never write
"PERL", because perl is not an acronym, apocryphal folklore and post-
facto expansions notwithstanding.


つまり、どっちでもいいってことみたいです。

最初に One bit... と中途半端なボケを入れたり、この質問自体がFAQになっていることがすごい。
日本人にこの感覚はないかな。少なくとも私にはない。