2011-07-26 118 views
1

Perl和我不同意变量是否是数字。我错了,当然,但是为什么?Perl数值变量

my $bytes = 0; 
# . . . 
$bytes = $bytes + length($text); 
# . . . 
my $MB = $bytes/1048576; 
my $string = sprintf("Downloaded: %.1f MB\n", MB); 

给出Argument "MB" isn't numeric in sprintf at foo.pl line 200.

它,其实,数字为可当我使用

my $string = "Downloaded: $MB MB\n"; 

其设置字符串Downloaded: 3.09680080413818 MB看到。

编辑:啊,愚蠢的错误,感谢你抓住它。

+4

正如@Wooble指出的那样,你可以在将来用'strict strict;'来捕获其中的一些('我会补充说你还应该'使用警告'')。 –

+0

@Platinum Azure:绝对。我总是会使用它们......感谢提醒。 – Charles

回答

10

您需要的变量印记:

my $bytes = 0; 
# . . . 
$bytes = $bytes + length($text); 
# . . . 
my $MB = $bytes/1048576; 
my $string = sprintf("Downloaded: %.1f MB\n", $MB); # <--- note the $MB at the end 
+10

这就是为什么你总是应该严格使用'' – geoffspear

3

看起来你可能是指:

my $string = sprintf("Downloaded: %.1f MB\n", $MB); 

等这应该工作。