-1

So I have a foreach loop:

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

But I also have a scalar:

$number = 5;

Can I count from 1 to the scalar like so?

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

When I do this, the program simply outputs nothing. What can I do to make this work?

Dynamic
  • 921
  • 1
  • 12
  • 31
  • 3
    You are using the variable `$t` in the loop body, but do not define it. [`use strict; use warnings;`](http://stackoverflow.com/questions/8023959/why-use-strict-and-warnings) would have alerted you to your mistake. - `foreach my $t (1..$number) {` works as intended. – daxim Apr 14 '12 at 16:45
  • @daxim In the full code, I did define $v... sorry about that. – Dynamic Apr 19 '12 at 00:56

1 Answers1

2

Script:

#!/usr/bin/perl

use strict;
use warnings;

my $number = 5;

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

or

#!/usr/bin/perl

use strict;
use warnings;

my $number = 5;

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

Output:

#1
#2
#3
#4
#5
Ωmega
  • 42,614
  • 34
  • 134
  • 203