Dear PelrMonks,
All of your answers have been really helful. Your time is much appreciated. I think that my code now is better but still not accurate. My array is succesfully printed into a text file. I want my array though to be printed vertically (each line of the file to contain only one word of the array) and that's why I used the "$_\n". Now though, I am facing another problem. Each word needs one extra letter in the end. I used the chomp(); but maybe not correct. Any ideas? I created now this:
#!/usr/bin/perl -w
@words = qw( internet answers printer program );
@guesses=();
$wrong=0;
$line=0;
my @words = qw( internet answers printer program );
open my $fh, '>', "words.txt" or die "Cannot open words.txt: $!";
foreach (@words)
{
print $fh "$_\n"; #Because I want each word in a separate line
+.
chomp($fh); #maybe something wrong with chomp();?
}
close $fh;
srand;
open MYFILE, "<words.txt" or die "Could not open words.txt: $!\n";
rand($.)<1 and ($line=$_) while <MYFILE>;
close MYFILE;
$choice=$line;
$hangman="0-|--<";
@letters=split(//, $choice);
@hangman=split(//, $hangman);
@blankword=(0) x scalar(@letters);
OUTER:
while ($wrong<@hangman) {
foreach $i (0..$#letters) {
if ($blankword [$i]) {
print $blankword [$i];
} else {
print "-";
}
}
print "\n";
if ($wrong) {
print @hangman[0..$wrong-1]
}
print "\n Your Guess: ";
$guess=<STDIN>; chomp $guess;
foreach(@guesses) {
next OUTER if ($ _ eq $guess);
}
$guesses[@guesses]=$guess;
$right=0;
for ($i=0; $i<@letters; $i++) {
if ($letters[$i] eq $guess) {
$blankword[$i]=$guess;
$right=1;
}
}
$wrong++ if (not $right);
if (join('', @blankword) eq $choice) {
print "You got it right!\n";
exit;
}
}
print "$hangman\nSorry, the word was $choice.\n";
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.