in reply to Reading an array with a single value (My 2nd completed script!)

ok... Here is my edit...
#!/usr/local/bin/perl -w use strict; srand; guess_routine(); #moved the print and rand into the routine # that way you don't have the code duplicated when user # says y for new game... sub guess_routine { my @guesses; print "I have a number between 1 and 19.\nTry to guess it.\n"; my $numb=int(rand(20)); my $in = input(); while ($in != $numb){ print($in > $numb ? 'Too high! ' : 'Too low! '); # moved to trinary operator, just shrinks up # code, if else isn't bad @guesses = sort{$a <=> $b} (@guesses,$in); # you were pushing onto the array, then sorting # simply sorting array and value together shoule # be more efficient $in = input(\@guesses); # created a subroutine for # this, since you had similar code in two places. } print "\nYes, $numb is the number!\n"; print "So you want another go?\n"; my $answer=<STDIN>; # no chomp, you check /^y/ chomp unecessary if ($answer =~/^y/i){ guess_routine(); } else { print "\nOK, bugger off then!\n"; exit 0; } } sub input { my $in; print "\nSo far you've guessed @{$_[0]}." if $_[0]; print "\nWhat is your guess?\n"; $in=<STDIN>; chomp ($in); $in }

                - Ant
                - Some of my best work - Fish Dinner

  • Comment on Re: Reading an array with a single value (My 2nd completed script!)
  • Download Code