Mohammad Jumah
Mohammad Jumah

Reputation: 435

Perl's length function

Why would perl's length function add an extra character in its result?

I have this simple code.

#!/usr/bin/perl
print "enter text ->";
my $variable;
my $variable = <>;
$length = length($variable);
print "$length\n";

But when I enter the text "hi" for example, the output of length is 3, while I'm expecting it to be 2.

Upvotes: 1

Views: 133

Answers (1)

choroba
choroba

Reputation: 241828

The newline at the end of the input is part of the value. Remove it with chomp:

my $variable = <>;
chomp $variable;
print length $variable;

Also, use warnings to be notified of duplicate declaration of $variable.

Upvotes: 9

Related Questions