我只是很好奇,– 甚至可以从标量变量创建一个V字符串而不需要使用eval?
I. e.,这有效,但使用eval:
my $var = 'v1.2.3'; my $conversion = to_vstring_1($var); # Prints "Version: 1.2.3,type: VSTRING" printf("Version: %vd,type: %s\n",$conversion,ref \$conversion); sub to_vstring_1 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg = 'v' . $arg; return eval $arg; }
这两个变体也有效,并且不使用eval,但它们打印“SCALAR”而不是“VSTRING”:
my $conversion_2 = to_vstring_2($var); # Prints "Version: 1.2.3,type: SCALAR" printf("Version: %vd,$conversion_2,ref \$conversion_2); my $conversion_3 = to_vstring_3($var); # Prints "Version: 1.2.3,$conversion_3,ref \$conversion_3); sub to_vstring_2 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg = pack('U*',split(/\./,$arg)); return $arg; } sub to_vstring_3 { my ($arg) = @_; $arg =~ tr/0-9.//cd; $arg =~ s/[._]?(\d+)/chr($1 & 0x0FFFF)/eg; return $arg; }
那么,还有第四种方法吗?