On Tue, Dec 11, 2012 at 3:47 PM, Alex Ahn <[email protected]> wrote:
> I have a problem with a certain script, as a beginner.
>
#!/usr/bin/perl -w
#
# Cookie Monster
use strict;
print 'Give me a cookie (q to quit): ';
while ( my $cookie = <> ) {
chomp($cookie);
if ( $cookie eq 'cookie') {
print "Mmmm. Cookie.\n";
print 'Give me another cookie (q to quit): ';
}
else {
last if $cookie eq 'q';
print q(That's not a cookie, give me cookie (q to quit): );
}
}
So just a couple of points on what I added - use strict is a great idea,
esp. at learning stage. Any script over 5 lines? use strict. <> is pretty
much the same as <STDIN>, it's the "standard" <ahem> idiom. I used a temp
var as you had ("$cookie"), but in this case, using the default while usage
assings directly to $_:
while ( <> ) {
if ( $_ eq 'cookie') {
and that gets easier with regular expression matching:
while ( my $cookie = <> ) {
chomp($cookie);
if ( /cookie/ ) {
means "if $_ contains the word cookie" - we can limit that more if needed.
Using the temp var does let you use it in your code:
print "Mmmm. Cookie.\n";
becomes
print "Mmmm. $cookie.\n";
for example - again, more useful when there some variation allowed. The
line
last if $cookie eq 'q';
"last" breaks you out of the while loop - yes, it's akin to the much
reviled "goto" stmt but we don't talk about that. Actually we do - goto
isn't inherently bad, just too easy to misuse. Perl does have a goto stmt
even. Finally
print q(That's not a cookie, give me cookie (q to quit): );
the q( ... ) syntax is an alternative quoting process as I used a single
quote/apostrophe in the text. There is "q" and "qq" (double quotes) and
the next char will be the delimiter for the quoted string. If it is a
"paired" sort of char (parens, curly brackets etc), you use open an close
set. Otherwise any char will do; tildas are a common choice. Note, because
used the paired marker paren, Perl is smart enough to ignore the quoted
paren set around "q to quit".
HTH - sorry to be so pendantic, but I are one.
--
a
Andy Bach,
[email protected]
608 658-1890 cell
608 261-5738 wk