I been trying to understand below program..
But I cannot get past the concept of couple areas,
1)
foreach $i (0..$#letters) {
if ($blankword[$i]) {
print $blankword[$i];
} else {
print "-";
}
Say @letters = n o w,
and iterating over 0..$#letters would assign i to
$letters[0]=n
$letters
1=o
$letters
2=w
and @blankword was 0 0 0,
how is $blankword\
$i\ is one of n o w ???
2)can someone please explain to me in plain english what
$guesses[@guesses]=$guess;
I guess @guesses=() was intially to empty array, now, how does
above mean? assigning $guess word to @guesses array, but not sure what putting array in square bracket means(never seen it before)
#!/usr/bin/perl -w
@words = qw( internet answers printer program );
@guesses=();
$wrong=0;
$choice=$words[rand @words];
$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.