#!/usr/bin/perl -w sub q { \$; = 1; # \$; stores how many tries you've had; start at 1 for (0..3) { \$;[\$_] = int(rand(9)) # @; stores the correct four numbers; set it up here } } sub _ { print @_ } &q; for (;;) { \$: = \$~ = 0; # set \$: (right number in the right spot) and \$~ (right number) to 0 _ "\$/\$; "; # prints a newline then the number of tries you've had \$_ = <>; # read a line into \$_ if (/^\d{4}\$/) { # if the line is exactly 4 digits... @q = split //; # @q holds the 4 digits --\$#q; # set \$#q = 3, ignoring the newline at \$q[4] \$@ = -1; # set \$@ to -1 # This loops through the input digits and checks for correctness for (@q) { # set \$_ to each of the 4 input digits \$a = \$_; # set \$a to the current digit (why not leave it \$_?) (\$a == \$;[++\$@]) && ++\$: # increment \$: if you have a right number in the right spot || (grep /\$a/, @;) && ++\$~ # else increment \$~ if you have a right number in the wrong spot } _ "\$~W\$:B "; # print out the total of right/wrong (\$~W) and right/right (\$:B) ++\$;; # increment number of tries \$: == 4 # if we have four right numbers all in the right spots | \$; > 10 # or we have already had 10 tries && _ (@;) # print out the correct answer && &q # and start the game over } }