The below code gives some strange output. Can any one explain the problem?
use warnings;
my $P = 10;
print "My Var: $P\n";
display();
my $P = 12;
display();
sub display()
{
print "My Var: $P\n";
}
output:
My Var: 10
My Var:
My Var: 12
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.