1

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?

Community
  • 1
  • 1
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • The answer is right in the documentation you linked to: "[chomp] returns the total number of characters removed from all its arguments." Therefore, `$n = chomp($n);` sets `$n` to the total number of characters removed by `chomp` (in this case, 1). – ThisSuitIsBlackNot Apr 07 '15 at 20:11
  • I have an old book about perl from prosofttraining.com they were stated that chomp remove trailing new line from the input of `` @ThisSuitIsBlackNot – SaidbakR Apr 07 '15 at 20:14
  • 2
    `chomp` *does* remove the trailing newline. It also returns the number of newlines that were stripped. If you do `chomp($n);`, you will strip the trailing newline; if you do `$n = chomp($n);` you will strip the trailing newline, and then assign the return value of `chomp` (i.e. 1) to `$n`. – ThisSuitIsBlackNot Apr 07 '15 at 20:22
  • @ThisSuitIsBlackNot So, Perl deals with some subroutines in different way other than other language. i.e changes in variable's value should be assigned to a variable but in this case this subroutine changed it and assigned it automatically, does not it? – SaidbakR Apr 07 '15 at 20:29
  • 1
    Perl always [passes by reference](http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value). This means that subroutines can alter their parameters. See [`perldoc perlsub`](http://perldoc.perl.org/perlsub.html) and [Perl call-by-reference or call-by-value?](http://stackoverflow.com/q/5741042/176646) for details. – ThisSuitIsBlackNot Apr 07 '15 at 20:45

1 Answers1

6

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)

Zippers
  • 141
  • 6