Perl Module Method Calls: Can't call method “X” on an undefined value at ${SOMEFILE} line ${SOMELINE}

前端 未结 3 2020
时光取名叫无心
时光取名叫无心 2020-12-16 06:34

All over the place, especially in DBI, I see this message come up all the time. It\'s confusing, because the first thing that comes to mind is that the arguments I\'m passin

3条回答
  •  忘掉有多难
    2020-12-16 06:46

    It is just how Perl does OO. The difference is in between the way you call the methods.

    This just calls the trim sub in the My::Module package:

     My::Module::trim('foo')
    

    On the other hand,

     My::Module->trim('foo)
    

    automatically becomes a call to the trim sub in the My::Module package with the string "My::Module" as the first argument. Objects work the same way:

     my $m = My::Module->new; # Corrected. Thanks for pointing this out.
     $m->trim('foo');
    

    Turns into a call to the same sub, but this time with a reference to the $m object as the first argument.

    What you are trying to do is:

    $My::Module->trim('foo');
    

    Which translates to a dereference of the variable $My::Module (which does not exist), thus the error message "Can't call method X on an undefined value". If $My::Module were an actual reference to an object, this would result in a call to trim() on that object, with the reference as an implicit first argument.

    Edit: Both commenters are correct. This answer was originally intended as a comment to the accepted answer. (Is there a way to fix that?)

    Sorry for the confusion. I've added a little more detail here so hopefully it becomes more clear how it relates to the original question (dereferencing an undefined variable).

提交回复
热议问题