Perl数字变量

Cha*_*les 1 perl variable-types numeric

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

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

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

事实上,这是我在使用时可以看到的数字

my $string = "Downloaded: $MB MB\n";
Run Code Online (Sandbox Code Playgroud)

将字符串设置为Downloaded: 3.09680080413818 MB.

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

Pla*_*ure 9

你需要变量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
Run Code Online (Sandbox Code Playgroud)

  • 这就是为什么你应该总是`use strict;` (10认同)