Perl 数值变量

发布于 2024-11-26 11:18:06 字数 452 浏览 2 评论 0原文

Perl 和我对于变量是否是数字存在分歧。我当然错了,但为什么呢?

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

给出参数“MB”在 foo.pl 第 200 行的 sprintf 中不是数字。

事实上,当我使用

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

它将字符串设置为 Downloaded: 3.09680080413818 MB 时可以看到,它是数字。

编辑:啊,愚蠢的错误,谢谢你发现它。

Perl and I disagree as to whether a variable is a number or not. I'm wrong, of course, but why?

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

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

It is, in fact, numeric as can be seen when I use

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

which sets the string to Downloaded: 3.09680080413818 MB.

Edit: Ah, silly mistake, thanks for catching it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裸钻 2024-12-03 11:18:06

您需要变量印记:

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

You need the variable 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
薯片软お妹 2024-12-03 11:18:06

看起来你的意思可能是:

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

除此之外,这应该可行。

Looks like you probably meant:

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

other than that this should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文