2016-05-31 5 views
3

私はPerlスクリプトを使用している間に何か変わったことがあります。異なる結果を与えるドットを使用することです。"print"ステートメントの先頭にドットがありますか?

perlop何かを上げなかったのか、それともそれを吹き飛ばしたのでしょうか。私は、私が欲しいものを得るために許容可能な回避策がある開始時に引用符を置くOperator Precedence and Associativity

print "I'd expect to see 11x twice, but I only see it once.\n"; 
print (1 . 1) . "3"; 
print "\n"; 
print "" . (1 . 1) . "3\n"; 
print "Pluses: I expect to see 14 in both cases, and not 113, because plus works on numbers.\n"; 
print (1 . 1) + "3"; 
print "\n"; 
print "" + (1 . 1) + "3\n"; 

を見ていたが、何を、私は欠けているの操作のために、ここで起こっているのでしょうか?学ぶべきルールはありますか?

+1

'はperldoc perlfunc':。(。構文の説明では、括弧を省略)「以下のリスト内のすべての機能を使用して、またはその引数の前後に括弧なしで使用することができるあなたは括弧を使用している場合は、単純だが、時折驚くべきルールこれは:それは機能のように見えるので、それは機能であり、優先順位は重要ではありません。 –

答えて

14

括弧でくくって最初の引数をprintにすると、Perlはそれを関数呼び出しの構文とみなします。

ので、この:

print(1 . 1) . "3"; 

または、等価的に:

print (1 . 1) . "3"; 

このように解析され

(print 1 . 1) . "3"; 

したがって、Perlの印刷 "11"、戻り値をとりますそのprintコール(成功した場合は1)のうち、3に、そして式全体がvoidコンテキストにあるので、結果として得られる13とはまったく何もしません。

あなたは(コマンドラインまたはuse warnings;プラグマに-w経由)を有効に警告を使用してコードを実行した場合、あなたはこれらの警告は、あなたのエラーを特定取得します:

$ perl -w foo.pl 
print (...) interpreted as function at foo.pl line 2. 
print (...) interpreted as function at foo.pl line 6. 
Useless use of concatenation (.) or string in void context at foo.pl line 2. 
Useless use of addition (+) in void context at foo.pl line 6. 

ボロディンは、以下のコメントで指摘しているように、 -w(またはコード内に相当する$^W)に頼るべきではありません。プロダクションコードは常にwarningsプラグマを使用する必要があります。好ましくはuse warnings qw(all);です。 5.11以上のPerlのバージョンのuseバージョン;経由で現代的な機能を要求することも自動的にstrictをオンにするが、それは、この特定のインスタンスでは問題、あなたはuse strict;もすべきではないだろうが。

+0

ありがとう!私は厳密に使う。警告を使う。大規模なプロジェクトではなく、10ライナー以下で私はちょうどハックします。ですから、この私の質問は、私の新しいperlファイルのサイズが大きいか小さいかにかかわらず、小さなテンプレートを持つための転換点です。ヘッダーコメントと厳密な使用を含む警告、このような問題をキャッチする警告を使用します。 – aschultz

4

名前付き演算子(またはサブ呼び出し)の後に括弧が続く場合、それらの括弧はオペランド(または引数)を区切ります。

print (1 . 1) . "3";  ≡ (print(1 . 1)) . "3"; 
print "" . (1 . 1) . "3"; ≡ print("" . (1 . 1) . "3"); 

Perlがあなたの問題をユーザーに警告していることに注意してくださいあなたが必要としてあなたが(use strict;と)use warnings qw(all);を使用してきました。

print (...) interpreted as function at a.pl line 2. 
print (...) interpreted as function at a.pl line 6. 
Useless use of concatenation (.) or string in void context at a.pl line 2. 
Useless use of addition (+) in void context at a.pl line 6. 
I'd expect to see 11x twice, but I only see it once. 
11 
113 
Pluses: I expect to see 14 in both cases, and not 113, because plus works on numbers. 
11 
Argument "" isn't numeric in addition (+) at a.pl line 8. 
14 
関連する問題