learningMatlab
learningMatlab

Reputation: 229

Why does 'chop' not work with <STDIN>?

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

Answers (4)

scm
scm

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

2teez
2teez

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

Jarmund
Jarmund

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

Rohit Jain
Rohit Jain

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

Related Questions