tags:

views:

299

answers:

3

How might this block of code in Date/Manip.pm from the Date::Manip module:

#*Get rid of a problem with old versions of perl
no strict "vars";
# This sorts from longest to shortest element
sub sortByLength {

  return (length $b <=> length $a);
}

use strict "vars";

I get this warning:

Use of uninitialized value in length at /perl/lib/perl5.8/Date/Manip.pm line 244.
A: 

If warnings for uninitialized diagnostics were enabled (perhaps via blanket -w or use warnings;) and if sortByLength were somehow called as a normal subroutine, rather than as a sort {} function, you would likely see this error:

$ perl -Mwarnings=uninitialized -e 'sub sbl { (length $b <=> length $a) } sbl' 
Use of uninitialized value in length at -e line 1.
Use of uninitialized value in length at -e line 1.

Here I get two warnings, because both $a and $b are uninitialized. Hard to say without more context.

pilcrow
+2  A: 

The problem is not actually located there; the function is just being called with invalid (undef) parameters. To get a better trace of where it came from, try this:

$SIG{__WARN__} = sub {
  require Carp;
  Carp::confess("Warning: $_[0]");
};

This will print a stacktrace for all warnings.

bdonlan
+1  A: 

Either $a or $b are undef. Check the list you are feeding to the sort that uses this subroutine to see if you have an undefined value.

How are you using this code?

brian d foy

related questions