3

I'm pretty new to perl (and programming in general but I'm used to Python).

use strict;
use warnings;
use diagnostics;

my $simple_variable = "string";
print my $simple_variable;

Basically I want to know why this script returns an uninitialized value error, since the variable is clearly defined.

Thanks

2
  • 2
    You have learned about scoping!! The classic online references for learning more are Coping with Scoping and the oft read PerlMonks node on Variable Scoping in Perl. I found that the node id number was easily memorizable :-) Commented Jun 18, 2014 at 13:19
  • You want print "$simple_variable\n"; You must put that \n on the end because print doesn't do that automatically for you. Commented Jun 18, 2014 at 18:58

1 Answer 1

3

my creates a variable and initializes it to undef (scalars) or empty (arrays and hashes). It also returns the variable it creates.

As such,

print my $simple_variable;

is the same thing as

my $simple_variable = undef;
print $simple_variable;

You meant to do

my $simple_variable = "string";
print $simple_variable;

I'm not sure why you are asking this because Perl already told you as much. Your program outputs the following:

"my" variable $simple_variable masks earlier declaration in same scope at a.pl
        line 6 (#1)
    (W misc) A "my", "our" or "state" variable has been redeclared in the
    current scope or statement, 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.

Note how the new declaration has the effect of "effectively eliminating all access to the previous instance".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.