Perl数字变量

时间:2011-07-26 18:23:12

标签: perl numeric variable-types

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

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

2 个答案:

答案 0 :(得分:10)

你需要变量sigil:

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

答案 1 :(得分:3)

看起来你可能意味着:

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

除此之外,这应该有用。