Home: Perl Programming Help: Beginner:
Why do I get a Warning of Unitialized Value?



perldeveloer
New User

Oct 2, 2013, 12:57 AM


Views: 2229
Why do I get a Warning of Unitialized Value?

Hi everybody,

please see this short code snippet:

for( my $i = 0; $i <= $#new_file_face_; $i = $i + 1 )
{
my $j1 = $new_file_face_[ $i ];
my $j2 = $new_file_face_[ $i+1 ];
my $temp = $j2-$j1;
...

Why do I get a warning: Use of uninitialized value $j2 in subtraction (-)...? The array @new_file_face_ is initialized properly. Is there a problem with the call [$i+1]?

Thanks in advance.


2teez
Novice

Oct 2, 2013, 11:06 AM


Views: 2223
Re: [perldeveloer] Why do I get a Warning of Unitialized Value?

Use the output of the following codes below maybe you can see where the ERROR is. It's so obvious though.

Code
use warnings; 
use strict;

my @new_file_face_ = (1..5);

for( my $i = 0; $i <= $#new_file_face_; $i = $i + 1 )
{
my $j1 = $new_file_face_[ $i ];
my $j2 = $new_file_face_[ $i+1 ];
#my $temp = $j2-$j1;

print '$i = ',$i,', $#new_file_face_ = ',$#new_file_face_,
', $j1 = ',$j1,', $j2 = ',$j2,$/
}


But in case you don't get it remove the = in the

Code
..;$i <= $#new_file_face_

so that it becomes

Code
..;$i < $#new_file_face_

and see what you get.


(This post was edited by 2teez on Oct 2, 2013, 11:07 AM)


Laurent_R
Veteran / Moderator

Oct 3, 2013, 10:50 AM


Views: 2210
Re: [perldeveloer] Why do I get a Warning of Unitialized Value?

Consider what happens to:


Code
my $j2 = $new_file_face_[ $i+1 ];


in the last iteration, when $i is the subscript of the last element of your array (i.e. equal to $#new_file_face_).