AshR
AshR

Reputation: 32

perl printing range of numbers with a newline at the end

I was trying to print 1 to 10 using perl.

print 1..10 #This works perfectly fine.

I am wondering if there is a way to add a new line after printing the last element.

print "1..10" . "\n" ; # it just  prints 1..10 (as expected) instead of 12345678910

print "{1..10} . "\n" ; # This doesn't work either :(

I know I could just store it in a list and then print the list :

my @test = 1..10 ;

print @test ;

I am just wondering if there is a trick with print to do it in 1 line. Thanks in advance !

Upvotes: 0

Views: 681

Answers (1)

ikegami
ikegami

Reputation: 385897

To pass the 10 numbers and a newline to print (which will print each in turn), you can use the following:

print 1..10, "\n";

If instead you want to build a string that consists of the numbers followed by a newline, you can use either of the following:

print join("", 1..10, "\n");

print join("", 1..10) . "\n";

Test:

$ perl -e'
   print 1..10, "\n";
   print join("", 1..10, "\n");
   print join("", 1..10) . "\n";
   print "done.\n";
'
12345678910
12345678910
12345678910
done.

Upvotes: 2

Related Questions