eibwen has asked for the wisdom of the Perl Monks concerning the following question:
Recently one of my friends wrote a guess-the-word game in c, which prompted me to write a shorter one in perl, with more features. The coding was fine until I decided to support an option to use a random word from /usr/dict/words as the answer as opposed to one entered to <>.
Essentially the problem was that I passed the dict as $ARGV[0] and subsequently attempted to use <>, only to find that the behavior changed due to the presence of @ARGV as per perlop <EXPR>. While I was able to "fix" the code by clobbering @ARGV, equating it to the empty list, this brings me to the crux of my question:
When using both @ARGV and <STDIN>, what's the perlish implementation without clobbering @ARGV?
I would presume explicit use of <STDIN> or even readline(*STDIN) is better coding practice, but I'm at a loss as to a perlish impelementation.
UPDATE: By request, the guess-the-word game code:
#!/usr/bin/perl -w use strict; my ($answer, $guess, $guesses) = ("", "", 0); if (@ARGV) { open FILE, $ARGV[0] or die "No such dictionary..."; rand($.) < 1 && ($answer = (split(/[\r\n]+/,$_))[0]) while <FI +LE>; close FILE; @ARGV = (); } else { $answer = (split(/[\r\n]+/,<>))[0]; } system 'clear'; do { $guess = (split(/[\r\n]+/,<>))[0]; unless ($guess eq $answer) { if (length $guess != length $answer) { print "The answer is ", length $guess > length + $answer ? "shorter" : "longer", "\n"; } else { print "The $$_[0] letter ($$_[1]) is ", $$_[2] +? "" : "in", "correct\n" foreach map { [$_, (split //, $guess)[$_], ( +split //, $guess)[$_] eq (split //, $answer)[$_] ? 1 : 0 ] } (0..(len +gth $guess) - 1); } } $guesses++; } while ($answer ne $guess); print "You figured it out in a mere $guesses guesses\n";
Lastly, I should note that this was a question of style and practice, rather than a request for help with a particular code. After reading the reply by EvanCarroll, which concurs with my presumption that using <STDIN> is better programming practice, I re-read perlop and discovered several loops of the form:
while (<>) { ... }
When I read such passages while learning perl, I misunderstood <> for <STDIN>. While this misunderstanding has taken awhile to surface, I now know the distinction between <> and <STDIN>.
Thanks to everyone who helped out -- and feel free to try the game :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using <> in the presence of @ARGV
by pg (Canon) on Oct 04, 2005 at 02:33 UTC | |
|
Re: Using <> in the presence of @ARGV
by EvanCarroll (Chaplain) on Oct 04, 2005 at 01:47 UTC | |
by blokhead (Monsignor) on Oct 04, 2005 at 02:00 UTC | |
by sauoq (Abbot) on Oct 04, 2005 at 05:53 UTC | |
by EvanCarroll (Chaplain) on Oct 04, 2005 at 02:07 UTC | |
|
Re: Using <> in the presence of @ARGV
by GrandFather (Saint) on Oct 04, 2005 at 02:38 UTC | |
|
Re: Using <> in the presence of @ARGV
by GrandFather (Saint) on Oct 04, 2005 at 01:41 UTC |