我有一个Perl变量,该变量从从网页检索的值实例化。此变量用于实例化具有类型约束(例如,“ Int”类型)的Moose对象属性。如果我按原样使用变量(Validation failed for 'Int' with value "2" at constructor...
),则此类型约束将失败。我按照my $newvar = int($oldvar);
中的建议尝试了显式广播(my $newvar = sprintf("%d", $oldvar);
)和sprintf(How can I convert a string to a number in Perl?)。两者不一致并且经常导致0
。我尝试了诸如abs()
和+
中提到的算术运算(例如https://perldoc.perl.org/perlnumber.html)之类的建议,这些建议在将值转换为Moose的满意程度时也不可靠。由于无法获得Int
类型约束来成功地从网页获得不可预测的值,因此我没有将Moose类扩展为其他类型约束,例如float
或ArrayRef[Int]
作为union
约束。我在下面放了一个简化的代码。
UPDATE:当我尝试通过精简代码重现问题时,我发现JSON-> decode()添加了双引号。等效代码如下(注意:它可以在'2'或“ 2”上正常工作,但是当值是'“ 2”'时,它将失败。我只是将解码后的值传递给Moose类。在注意到JSON-> decode之后将值括在双引号中,即使它们已经被编码了,我还是想知道通过CGI将有多少额外的双引号;当然,正确地转义了。我认为我现在的任务是采用CGI-> param()并删除JSON可能添加的所有引号,以使其成为数字。
MyEvent.pm:
#!/usr/bin/perl
package MyEvent;
use strict;
use warnings;
use Moose;
use Moose::Util::TypeConstraints;
# MyEvent has identifier
has identifier => (
is => 'rw',
isa => 'Int',
predicate => 'has_identifier',
required => 1
);
no Moose;
__PACKAGE__->meta->make_immutable;
MyEventTest.pm
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Data::Dumper;
use MyEvent;
use lib '/home/user/tests/mooseTests';
my $id = '"2"'; # <<< Notice the double quoted string inside single quotes
my $myEvt = MyEvent->new("identifier" => $id);
print Dumper $myEvt;
这产生了:
Attribute (identifier) does not pass the type constraint because: Validation failed for 'Int' with value "2" at constructor MyEvent::new (defined at /home/user/tests/mooseTests/MyEvent.pm line 28) line 39
MyEvent::new('MyEvent', 'identifier', '"2"') called at MyEventTest.pl line 15
perl -e 'my $a = "2"; printf(%d, $a); '