SaidbakR
SaidbakR

Reputation: 13534

Perl chomp convert string into numerical values

I get a weird behavior for chomp. The <STDIN> adds trailing newline to the input, and I want to remove it, so I uses chomp like the following:

print("Enter Your Name:\n");
$n = <STDIN>;
$n = chomp($n); 
print("Your Name: $n");
$out = "";
for ($i =0; $i < 10; $i++)
{
  $out .= $n;
  print ($out);
  print("\n");
} 

When I enter any name value (string) such as "Fox" I expect output like:

Fox
FoxFox
FoxFoxFox
FoxFoxFoxFox
etc..

However, "Fox" is replaced by numerical value 1 i.e

1
11
111
1111

I tried to get assistance from the official manual of perl about chomp but I could not able to get any help there. Would any one explain why chomp do like that and how could solve this issue?

Edit

I reviewed the example on the book again, I found that they use chomp witout assign i.e:

$n = chomp($n);
# Is replaced by
chomp($n); 

And Indeed by this way the script printout as expected! Also I don't know how and why?

Upvotes: 1

Views: 235

Answers (1)

Zippers
Zippers

Reputation: 141

From the perldoc on chomp:

It returns the total number of characters removed from all its arguments

You're setting $n to the return value of chomp($n):

$n = chomp($n);

To do what you want, you can simply chomp($n)

Upvotes: 6

Related Questions