Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Perl monks. I'm having a problem with a little program (actually, it's exercise for chapter 10 in the Llama book). Though I understand the book's solution to the excercise, I don't know what's going on with my solution. Here's part of it, which is a sort-of-working script (it runs).
$x = int (1 + rand 100); print "What is the secret random number? "; while (<STDIN>) { $guess = $_; if ($guess eq "quit") { last; } elsif ($guess == $x) { print "You got it, brother!\n"; last; } elsif ($guess > $x) { print $y; print "Too high! Try again!\n"; } elsif ($guess < $x) { print "Too low! Try again!\n"; } }
What I don't understand is why the "quit" comparison isn't working. When the user types in "quit", the program states that this is "Too low." Is it being converted to zero? I have it using an "eq" operator, so why doesn't it take the input as a string? Shouldn't the program be doing the conversion automatically, depending on the operator? Thanks, Barry

Replies are listed 'Best First'.
Re: conversion between numbers and strings?
by ysth (Canon) on Apr 22, 2004 at 04:24 UTC
    When they type quit, they actually type "enter" after the four letters; that becomes part of the string. When the string is converted to a number (for the == compares) the trailing newline (like all whitespace) is silently ignored, but eq is tripped up by it.

    Traditionally, one handles this by saying:

    while (my $guess = <STDIN>) { chomp($guess); ...
    See chomp.
Re: conversion between numbers and strings?
by Koosemose (Pilgrim) on Apr 22, 2004 at 04:19 UTC

    Your problem is that when things are read from STDIN, it includes the trailing newline, so that if you type quit, $guess ends up being "quit\n" which is, of course, not equal to "quit". The number comparison's work fine, because when it converts to a number any trailing non numerical characters are basically ignored. Just chomp $guess; before doing your comparisons

    Just Another Perl Alchemist
Re: conversion between numbers and strings?
by kvale (Monsignor) on Apr 22, 2004 at 04:20 UTC
    When you read in a line, it includes the newline "\n" at the end of the string and thus your string comparison does not work. By contrast, conversion to a number drops the newline, so your numerical comparison does work. To fix it, use chomp:
    chomp( $guess = $_);

    -Mark

Re: conversion between numbers and strings?
by Anonymous Monk on Apr 22, 2004 at 13:40 UTC
    Thank you very much for your quick response!

    I am at peace.

    Barry