Why do I get “uninitialized value” warnings when I use Date::Manip's sortByLength?

◇◆丶佛笑我妖孽 提交于 2019-12-25 04:39:10

问题


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.

回答1:


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.




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/1263943/why-do-i-get-uninitialized-value-warnings-when-i-use-datemanips-sortbylengt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!