Why does my output go to next line when there is no next line character in the script

I am learning & writing a very basic Perl script as follows:-

print "Please enter your name dear: ";
$name = <STDIN>;
print "${name} you are learning Perl";

For some reason, output is displayed as:-

Please enter your name dear: saas
saas
 you are learning Perl

Why does the text after input name go to next line character when there isn't \n mentioned anywhere?

Upvotes: 1

Views: 275

Answers (2)

ikegami
ikegami

Reputation: 386621

There's a newline output where the contents of $name is output! Could it be that it's in $name? Think about what you typed. Did you type saas? No. You typed saas + Enter.

Use chomp to remove the trailing newline from $name.

Upvotes: 5

twhughes
twhughes

Reputation: 534

print "Please enter your name dear: ";
$name = <STDIN>;
chomp $name;
print "${name} you are learning Perl";

Notice line 3. When you send "saas" to you must press enter to send it. Newline is appended to your name variable. Chomp will remove this for you

Upvotes: 1

Related Questions