我制作了这个脚本来检查标量在意外使用'eq'而不是'=='时如何变化,反之亦然.在字符串上使用'=='只会改变,但在数字上使用'eq'会以某种方式改变标量.代码如下:
#!/usr/bin/perl
use strict;
use JSON;
my $str = "123";
my $num = 123;
print "BEFORE:\n";
print "str: ", \$str, " num: ", \$num, "\n";
print to_json({str => $str, num => $num}, {pretty => 1});
if ($str == 23) { }
if ($num eq "123") { }
print "AFTER:\n";
print "str: ", \$str, " num: ", \$num, "\n";
print to_json({str => $str, num => $num}, {pretty => 1});
print "\n";
Run Code Online (Sandbox Code Playgroud)
输出:
BEFORE:
str: SCALAR(0x8010f8) num: SCALAR(0x801050)
{
"num" : 123, …Run Code Online (Sandbox Code Playgroud) 我有一个带有模块名称的字符串,需要使用它来实例化一个对象.这怎么做得最好?我正在寻找类似的东西
foo.pl
#!/usr/bin/perl
use strict;
use Bar;
my $module = "Bar";
my $obj = {$module}->new(); # does not work
$obj->fun (123);
Run Code Online (Sandbox Code Playgroud)
Bar.pm
package Bar;
use strict;
sub new
{
my $self = {};
return bless $self;
}
sub fun
{
my ($self, $arg);
print "obj $self got arg $arg\n";
}
Run Code Online (Sandbox Code Playgroud)