MTn
MTn

Reputation: 103

Prevent perl script from new line

I have a Perl script:

 $i=0;

 while ( ($num = <STDIN>) =~ /\S/ ) {    
     push @lines, $num; $i++;
     print ("$num"x"$i")."\n";
 }

It prints this:

3
3
4
4
4
5
5
5
5

But I want it to print this:

3 
3
4
4 4
5
5 5 5

How can I prevent Perl from printing a new line after every print? I have tried this method, as you can see in the code snippet:

$num x $i

Upvotes: 1

Views: 322

Answers (1)

Kjetil S.
Kjetil S.

Reputation: 3787

You probably need chomp($num); which will remove your input newline at the end of $num.

my $i=0;
while ( (my $num = <STDIN>) =~ /\S/ ) {
  chomp($num);
  $i++;
  print "$num " x $i, "\n"
}

Or you could just:

print "$& " x ++$i, "\n" while <STDIN>=~/\d+/;

(Also, when asking code questions you should strip down your example to only contain what is relevant. Your push @lines, $num can only contribute to confuse potential answerers)

Upvotes: 2

Related Questions