以下のコードは奇妙な出力を与えます。誰かが問題を説明できますか?
use warnings;
my $P = 10;
print "My Var: $P\n";
display();
my $P = 12;
display();
sub display()
{
print "My Var: $P\n";
}
出力:
My Var: 10
My Var:
My Var: 12
以下のコードは奇妙な出力を与えます。誰かが問題を説明できますか?
use warnings;
my $P = 10;
print "My Var: $P\n";
display();
my $P = 12;
display();
sub display()
{
print "My Var: $P\n";
}
出力:
My Var: 10
My Var:
My Var: 12
スクリプトの完全な出力を提供する必要があります。
"my" variable $P masks earlier declaration in same scope at P line 6.
main::display() called too early to check prototype at P line 4.
main::display() called too early to check prototype at P line 7.
My Var: 10
Use of uninitialized value in concatenation (.) or string at P line 11.
My Var:
My Var: 12
それを読んでください...答えは警告にあります...スクリプトの先頭に
追加すると、追加の警告が表示されます。use strict;
main::display() called too early to check prototype at P line 5.
main::display() called too early to check prototype at P line 8.
()
つまり、宣言する前にプロトタイプ (この場合は ) を指定してサブルーチンを呼び出すことを意味します...
最初にサブルーチンを宣言するか、プロトタイプを削除することをお勧めします。
コードを次のように変更します。
use strict;
use warnings;
my $P = 10;
print "My Var: $P\n";
display();
$P = 12;
display();
sub display
{
print "My Var: $P\n";
}
そして、期待どおりに機能します。
(ただし、サブルーチンの引数として $P を使用することをお勧めします...)
First of all, in Perl you are not required to define a subroutine before calling it; it would be a better practice to do so; hence the warning your code produces. However, there is nothing technically wrong in this regard; nor is this warning relevant to your problem.
I believe the answer is indeed in your two declarations of the same variable with "my", coupled with the specific behavior of the Perl interpreter. Here is the explanation of this warning from perldiag:
``my'' variable %s masks earlier declaration in same scope (S) A lexical variable has been redeclared in the same scope, effectively eliminating all access to the previous instance. This is almost always a typographical error. Note that the earlier variable will still exist until the end of the scope or until all closure referents to it are destroyed.
When your print statement happens, only the first declaration of $P has been processed by the interpreter, thus it prints 10, as you would expect.
However, when you call the sub, Perl goes to look for the subroutine definition. It also has to find all of the other variable declarations preceding it, so that the sub can have access to lexical variables; it finds the second declaration, and thus your first $P is overwritten with a new $P. However, since this new $P hasn't been set to anything yet in your program, it is undefined.
「my$P」は変数を宣言します。これを2回実行すると、エラーが発生するはずです。「my$P=12;」を変更します 「$P=12;」そして、あなたはあなたが望むものを手に入れるでしょう。
perlについて少し読んでおくことをお勧めします(「perldocperl」と「perldocperlintro」、またはhttp://www.perl.org/learn.htmlを参照してください) 。
my $P = 12;
上記で既に $P( my $P = 10;
) を宣言しており、これを再度行うべきではありません。my を削除し、
display();
次のようにサブルーチンを呼び出します。&display();