gpt4 book ai didi

perl - 无论如何,字符串重载变量都被视为已定义

转载 作者:行者123 更新时间:2023-12-02 15:28:26 26 4
gpt4 key购买 nike

我的脚本中有以下几行:

my $spec = shift;
if (!defined $spec) {
return ("Invalid specification", undef);
}
$spec = "$spec" // '';

我自然希望在传递undef时,在数组中返回警告无效规范,第二项是undef 。相反,检查通过了,并且我收到一条控制台消息,警告我在下一行中Use of uninitialized value $spec in string

$spec 是一个具有字符串和数字重载的对象,不幸的是,它的编写方式是尝试测试此特定子例程中的真实性(通过 if ($spec) 例如)会导致深度递归和段错误。

虽然我对为什么会发生这种情况感兴趣,但我对如何让它停止发生感兴趣。我想消除控制台警告,最好没有 no warnings qw/uninitialized/。这可能吗?如果可以,我该怎么做?

最佳答案

你说 $spec 是一个带有 string overloading 的对象.

如果是这种情况,那么您需要在检查它是否被定义之前将其强制转换为字符串形式:

if (! defined overload::StrVal($spec)) {

每个周期的修正

正如 ysth 在 StrVal 中指出的那样,不会强制重载的字符串化:

overload::StrVal(arg)

Gives the string value of arg as in the absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using Scalar::Util::refaddr() , which is faster.

因此,要实现这一目标,请尝试他的其他建议:

"$spec" trapping warnings and detecting the uninitialized var warning. Better to add a method to the class to test for whatever case returns undef.

以下演示了这种方法:

#!/usr/bin/env perl

use strict;
use warnings;

use Test::More tests => 2;

my $obj_str_defined = StringOverloaded->new("has value");
my $obj_str_undef = StringOverloaded->new(undef);

ok( is_overloaded_string_defined($obj_str_defined), qq{\$obj_str_defined is defined} );
ok( !is_overloaded_string_defined($obj_str_undef), qq{\$obj_str_undef is undef} );

sub is_overloaded_string_defined {
my $obj = shift;

my $is_str_defined = 1;

local $SIG{__WARN__} = sub {
$is_str_defined = 0 if $_[0] =~ /Use of uninitialized value \$obj in string/;
};

my $throwaway_var = "$obj";

return $is_str_defined;
}

{
# Object with string overloading
package StringOverloaded;

use strict;
use warnings;

use overload (
'""' => sub {
my $self = shift;
return $$self; # Dereference
},
fallback => 1
);

sub new {
my $pkg = shift;
my $val = shift;
my $self = bless \$val, $pkg;

return $self;
}
}

输出:

1..2
ok 1 - $obj_str_defined is defined
ok 2 - $obj_str_undef is undef

关于perl - 无论如何,字符串重载变量都被视为已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40073283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com