Perl 模块方法调用:无法调用方法“X"在 ${SOMEFILE} 行 ${SOMELINE} 处的未定义值 [英] Perl Module Method Calls: Can't call method "X" on an undefined value at ${SOMEFILE} line ${SOMELINE}

查看:18
本文介绍了Perl 模块方法调用:无法调用方法“X"在 ${SOMEFILE} 行 ${SOMELINE} 处的未定义值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到处都是,尤其是在 DBI 中,我一直看到这条消息出现.这很令人困惑,因为首先想到的是我传递给函数的参数被设置为 undef(或类似的东西),但显然不是这样.

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 passing the function are set to undef (or something similar), but it's clearly not the case.

给定一个模块和一个对应的脚本...

Given a module and a corresponding script...

模块:./lib/My/Module.pm

package My::Module;

use strict;
use warnings;

sub trim {
    my $str = shift;
    $str =~ s{ A s+ }{}xms; # remove space from front of string
    $str =~ s{ s+ z }{}xms; # remove space from end of string
    return $str;
}

脚本:./test.pl

#!/usr/bin/perl

use strict;
use warnings;
use My::Module qw(trim);

print $My::Module->trim( " 	 hello world	 	" );

我收到错误信息

无法对 ./text.pl 第 7 行的未定义值调用方法trim".

Can't call method "trim" on an undefined value at ./text.pl line 7.

事实上,如果我调用 $My::Module->notamemethod( "hello world" ); 它会给出类似的错误.

Infact, if I call $My::Module->notamethod( "hello world" ); it gives a similar error.

上面的脚本/模块有什么问题?

What's wrong with the above script/module?

Can't call method X" on an undefined value at ${SOMEFILE} line ${SOMELINE} 真正说的是什么错误?这是指方法调用的上下文(传递到这里打印),还是参数的上下文?

What is that error Can't call method "X" on an undefined value at ${SOMEFILE} line ${SOMELINE} really saying? Does this refer to the context of the method call (passed here to print), or the context of the arguments?

推荐答案

该语法在变量 $My::Module 中查找对象或类名并调用其修剪方法,但该变量未定义.

That syntax is looking for an object or classname in the variable $My::Module and calling its trim method, but that variable is undefined.

相反,您只想说 print My::Module::trim( " hello world " ); 来调用 My::Module::trim()功能.

Instead, you want to just say print My::Module::trim( " hello world " ); to call the My::Module::trim() function.

从 use 行看,您似乎正在尝试将 trim() 导入本地包,因此您可以在没有 My::Module:: 限定的情况下调用它,但您的模块没有看起来它不支持导出.

From the use line, it looks like you are trying to import trim() into the local package so you can just call it without the My::Module:: qualification, but your module doesn't look like it is set up to support exporting.

在您的正则表达式中,/s 和/m 标志没有任何作用 - 它们仅更改 .、^ 和 $ 匹配的内容,而您不使用其中任何一个.

In your regexes, the /s and /m flags don't have any effect - they only change what ., ^, and $ match, and you don't use any of those.

这篇关于Perl 模块方法调用:无法调用方法“X"在 ${SOMEFILE} 行 ${SOMELINE} 处的未定义值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆