Reputation: 229
I am trying to figure out why the chop function is not working for me when I try to take input from the user:
my $string = <STDIN>;
my $chr = chop($string);
print "String: $string\n";
print "Char: $chr\n";
output
perl chop.pl
hello
String: hello
Char:
But if I use a string, then it works!
my $string = "frong";
my $chr = chop($string);
print "String: $string\n";
print "Char: $chr\n";
output [583]
perl chop.pl
String: fron
Char: g
Upvotes: 2
Views: 852
Reputation: 1
If you're printing diagnostics to show variable contents, put some form of delimiter around them, then you'd see the newline in your $chr example.
eg.
print "String: \"$string\"\n";
print "Char: \"$chr\"\n";
Upvotes: 0
Reputation: 1
Checking the perl documentation for these two functions chop
and chomp
might just do.
chomp
chomp This safer version of "chop" removes any trailing string that corresponds to the current value of $/ (also known as $INPUT_RECORD_SEPARATOR in the "English" module.
chop
chop Chops off the last character of a string and returns the character chopped.
Hope this help
Upvotes: 0
Reputation: 3205
What you're chop()'ing is the newline at the end of the string. To remove the newline upon assignment from STDIN:
chomp(my $string = <STDIN>);
In other words, your program should look like this:
chomp(my $string = <STDIN>);
my $chr = chop($string);
print "String: $string\n";
print "Char: $chr\n";
Upvotes: 0
Reputation: 213351
When you pass input from console, chop
is chopping the newline
that is at the end of the string, which is present when you hit Enter
. While your string does not contain that.
Upvotes: 4