mpapec
mpapec

Reputation: 50637

Explanation for 'uninitialized value' warning

Why perl -we '$c = $c+3' rises

Use of uninitialized value $c in addition (+) at -e line 1.

and perl -we '$c += 3' doesn't complain about uninitialized value?

UPDATE

Does documentation or some book like 'Perl best practices' mention such behavior?

Upvotes: 2

Views: 123

Answers (2)

cuonglm
cuonglm

Reputation: 2806

I think perldoc perlop has a little explanation:

Assignment Operators
       "=" is the ordinary assignment operator.

       Assignment operators work as in C.  That is,

           $a += 2;

       is equivalent to

           $a = $a + 2;

       although without duplicating any side effects that dereferencing the
       lvalue might trigger, such as from tie()

With B::Concise helper, we can see the trick:

$ perl -MO=Concise,-exec -e '$c += 3'
1  <0> enter 
2  <;> nextstate(main 1 -e:1) v:{
3  <#> gvsv[*c] s
4  <$> const[IV 3] s
5  <2> add[t2] vKS/2
6  <@> leave[1 ref] vKP/REFC
-e syntax OK

$ perl -MO=Concise,-exec -e '$c = $c + 3'
1  <0> enter 
2  <;> nextstate(main 1 -e:1) v:{
3  <#> gvsv[*c] s
4  <$> const[IV 3] s
5  <2> add[t3] sK/2
6  <#> gvsv[*c] s
7  <2> sassign vKS/2
8  <@> leave[1 ref] vKP/REFC
-e syntax OK

Update

After searching in perldoc, I saw that this problem had been documented in perlsyn:

Declarations
       The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines).  A variable
       holds the undefined value ("undef") until it has been assigned a defined value, which is anything other than "undef".  When used as a
       number, "undef" is treated as 0; when used as a string, it is treated as the empty string, ""; and when used as a reference that
       isn't being assigned to, it is treated as an error.  If you enable warnings, you'll be notified of an uninitialized value whenever
       you treat "undef" as a string or a number.  Well, usually.  Boolean contexts, such as:

           my $a;
           if ($a) {}

       are exempt from warnings (because they care about truth rather than definedness).  Operators such as "++", "--", "+=", "-=", and
       ".=", that operate on undefined left values such as:

           my $a;
           $a++;

       are also always exempt from such warnings.

Upvotes: 5

ikegami
ikegami

Reputation: 385506

Because it makes sense for addition to warn when adding things other than numbers, but it's very convenient for += not to warn for undefined values.

As Gnouc found, this is documented in perlsyn:

Operators such as ++ , -- , += , -= , and .= , that operate on undefined variables such as:

undef $a;
$a++;

are also always exempt from such warnings.

Upvotes: 4

Related Questions