in reply to HElp on program

First off, in your first line you're defining an array "@words" when what I think you want is a hash, "%words". Below, in the "$words{$name}" part, that wouldn't work as a lookup with the array @words, which is what you have now. Change the "@" to a "%" and your code should work.

I guess the thing to learn here is that problems aren't always obvious. If you start developing your scripts with use strict; and  perl -wT it will initially seem like a pain in the butt (but) problems like this will just pop out at you.

Good luck!

Here's your "llama" code, fixed.


#!/usr/bin/perl use strict; my(%words,$name,$secretword,$words,$guess); %words=qw( fred camel barney llama betty alpaca wilma alpaca ); print "What is your name?\n"; $name=<STDIN>; chomp ($name); if ($name eq "Randal") { print "Hello, Randal! Welcome!\n" } else { print "Hello $name.\n"; $secretword=$words{$name}; # use {} for hash if ($secretword eq ""){ # gives me an error around here $secretword="stupid"; #default secret word } print "What is the secret word?"; $guess =<STDIN>; chomp($guess); while ($guess ne $secretword){ print "Wrong, try again.\n"; $guess=<STDIN>; chomp ($guess); } }

Replies are listed 'Best First'.
Re: Re: HElp on program
by repson (Chaplain) on Mar 25, 2001 at 12:31 UTC
    That code, while it found the main code error, will still sometimes show the error message.

    $secretword=$words{$name}; if ($secretword eq ""){ $secretword="stupid"; }

    If $name is not found in the hash %words, then $secretword will be undefined and will produce the error mentioned when used as if defined. If you however test for the definedness of $secretword you will be closer to the original aim.

    if (defined $secretword) { $secretword = 'stupid'; }

    In perl style I'd probably write:

    $secretword = $words{$name} || 'stupid';

    But that is a matter of choice.