Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uninitialized value error in perl

Tags:

perl

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

like image 705
CiaranWelsh Avatar asked Apr 02 '26 13:04

CiaranWelsh


1 Answers

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".

like image 58
ikegami Avatar answered Apr 04 '26 13:04

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!