use strict; my $info = "I am a brown icecube"; (my $unknown = $info) =~ tr[a-zA-Z][*]; until($info eq $unknown) { print "guess a char: "; chomp(my $input = <STDIN>); my $c = substr $input => 0, 1; next if $c !~ /[a-z]/i or index($info => $c) == -1; substr($unknown => pos($info) - 1, 1) = $c while $info =~ /$c/g; print $unknown, $/; }
So we setup $unknown by assigning $info then replacing all alphabetic characters with asteriks. Then we loop until $info is equal to $unknown i.e when all the characters have been guessed. On every iteration the user is prompted to enter a character, which is read as a line from STDIN and the first character is used. If the given character is not in the alphabet or found in the string, then we reiterate, otherwise we loop through $info looking for $c and replacing the appropriate position in $unknown with $c, then print $unknown.

For more info on the operators and functions used above see. tr, substr, s///, index and pos. If the => is a little confusing it's just the comma in disguise, aka that 'fat comma'.
HTH

_________
broquaint


In reply to Re: string matching/replacing by broquaint
in thread string matching/replacing by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.