Perl – Where is the error “Use of uninitialized value in string ne” coming from

perl

Where is the uninitialised value in the below code?

#!/usr/bin/perl
use warnings;

my @sites = (undef, "a", "b");
my $sitecount = 1;
my $url;

while (($url = $sites[$sitecount]) ne undef) {
   $sitecount++;
}

Output:

Use of uninitialized value in string ne at t.pl line 6.
Use of uninitialized value in string ne at t.pl line 6.
Use of uninitialized value in string ne at t.pl line 6.
Use of uninitialized value in string ne at t.pl line 6.

Best Solution

You can't use undef in a string comparison without a warning.

if ("a" ne undef) { ... }

will raise a warning. If you want to test if a variable is defined or not, use:

if (defined $var) { ... }

Comments about the original question:

That's a strange way to iterate over an array. The more usual way of doing this would be:

foreach my $url (@sites) { ... }

and drop the $sitecount variable completely, and don't overwrite $url in the loop body. Also drop the undef value in that array. If you don't want to remove that undef for some reason (or expect undefined values to be inserted in there), you could do:

foreach my $url (@sites) {
  next unless defined $url;
  ...
}

If you do want to test for undefined with your form of loop construct, you'd need:

while (defined $sites[$sitecount]) {
  my $url = $sites[$sitecount];
  ...
  $sitecount++;
}

to avoid the warnings, but beware of autovivification, and that loop would stop short if you have undefs mixed in between other live values.

Related Question