简体   繁体   中英

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 ie

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 ie:

$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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM