in reply to Re: hangman question
in thread hangman question

Hey, thanks for your reply. Further questions on your explanation..
previsouly, "@blankword" was 0 0 0 (let's say for 3 letter words.. say like ---> n o w

so going through (0..$#letters), $i gets assigned n
o
w
now, how does $blankwordn equals element is zero or not?

Replies are listed 'Best First'.
Re^3: hangman question
by GrandFather (Saint) on Jul 16, 2007 at 01:46 UTC

    No. $i gets assigned 0, 1 and 2 - indexes into the two arrays, not the contents of the elements of @letters. 0 .. $#letters is the list context range operator and generates a list containing the integers from 0 to the index of the last element in @letters (0, 1 and 2 for this example).

    The code depends on elements of @blankwords being set to 0 until they are assigned a correct letter. The test could be rewritten if ($blankword[$n] eq $letters[$i]) { to make an explicit check that the correct letter has been guessed.


    DWIM is Perl's answer to Gödel
      I think now I am understanding the script. However, I ended up commenting out the @guesses portion (mainly because I think @guesses is useless part and script still works)..
      Was author wrong to put that code there(since it does nothing?).
      #!/usr/bin/perl -w @words = qw( hi no ); @guesses=(); $wrong=0; $choice=$words[rand @words]; $hangman="0-|--<"; @letters=split(//, $choice); print "\@letters is @letters\n"; @hangman=split(//, $hangman); @blankword=(0) x scalar(@letters); print "\@blankword is @blankword\n"; OUTER: while ($wrong<@hangman) { print "whielloop\n"; foreach $i (0..$#letters) { if ($blankword[$i]) { print $blankword[$i]; } else { print "-"; } } print "\n"; if ($wrong) { print @hangman[0..$wrong-1] } print "\n\n\n\n Your Guess: "; $guess=<STDIN>; chomp $guess; # foreach(@guesses) { # print "foreach loop\n"; # print "\$guess is $guess\n"; # print "\$\_ is $_\n"; # next OUTER if ($_ eq $guess); # } # print "\@guesses is @guesses\n"; # $guess_scalar = "@guesses"; # print "\$guess_scalar is $guess_scalar\n"; #$guesses[@guesses]=$guess; # push @guesses, $guess; $right=0; for ($i=0; $i<@letters; $i++) { print "\$i is $i\n"; print "in the forloop\n"; if ($letters[$i] eq $guess) { $blankword[$i]=$guess; print "\$blankword\[\$i\] is $blankword[$i] +\n"; $right=1; } } $wrong++ if (not $right); print "\$wrong is $wrong\n"; if (join('', @blankword) eq $choice) { print "IF loop\n"; print "You got it right!\n"; exit;
        @guesses and the next OUTER were making it ignore guesses that had already been given instead of counting them as right or wrong. It would have been better to use a %guesses hash for that:
        ... $guess=<STDIN>; chomp $guess; next if $guesses{$guess}++; $right=0; ...
        but this program seems blithely ignorant of the existence of hashes.

        If you feel daring, take a look at the severely undercommented word twist for a more hash-ridden implementation of a word game.