in reply to Regarding Declaring Variables

Each <STDIN> reads a line from stdin so if you have:

my $var = <STDIN>; while ($var = <STDIN>)

you read a line in the declaration (my $var), then replace the value in the while loop while ($var = <STDIN>).

The next;s inside the elsifs bypass the print "Enter ... at the end of the loop.

For fun consider this version:

use strict; my $target = 12; print "Guess my number.\n"; while ((print "Enter your guess: "), my $guess = <STDIN>) { (print "You guessed it!"), last if $guess == $target; (print "You guessed too low\n"), next if $guess < $target; (print "You guessed too high\n"), next if $guess > $target; }

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Regarding Declaring Variables
by Delusional (Beadle) on Nov 17, 2005 at 09:42 UTC
    Just a small alteration changing the hard coded 12 to something random:
    use strict; my $target = sprintf "%.$_[1]f", rand(10); print "Guess my number.\n"; while ((print "Enter your guess: "), my $guess = <STDIN>) { (print "You guessed it!"), last if $guess == $target; (print "You guessed too low\n"), next if $guess < $target; (print "You guessed too high\n"), next if $guess > $target; }
      my $target = 1 + int rand (20); # number 1 - 20

      would be more conventional for generating a random integer. Note that your version generates a number in the range 0 - 9 which may not be what some people would expect.


      DWIM is Perl's answer to Gödel
        No, %f rounds, so it generates a number in the range 0-10, but 0 and 10 have only half the chance of occuring that other numbers do.