计入标量值

时间:2012-04-14 15:51:07

标签: perl for-loop foreach counting scalar

所以我有一个foreach循环:

foreach (1..10) {
    print "#", $t, "\n";
 }

但我也有一个标量:

$number = 5;

我可以从1计算到标量吗?

 foreach (1..$number) {
    print "#", $t, "\n";
 }

当我这样做时,程序根本不输出任何内容。我能做些什么才能做到这一点?

1 个答案:

答案 0 :(得分:2)

<强> 脚本:

#!/usr/bin/perl

use strict;
use warnings;

my $number = 5;

foreach (1..$number) {
  print "#$_\n";
}

#!/usr/bin/perl

use strict;
use warnings;

my $number = 5;

print "#$_\n" for 1..$number;

<强> 输出:

#1
#2
#3
#4
#5