Apr 25, 2010

Teaching Perl - Week 2 ( part2 )

This part2 was prompted by Chromatic's post on state. I'd never heard of state before, and it's documentation is poor. Let's take a look at how state could affect our game.As you can see this allows us to make our $guess variable lexically scoped, meaning it's contained within the loop. This however generates some warnings: Use of uninitialized value $guess in numeric eq (==) at ./game.pl line 14. and if you enter non-numeric input Argument "l\n" isn't numeric in numeric eq (==) at ./game.pl line 14, line 1.. Both are completely fixable, but lets fix the uninitialized first.

So all we've had to change is adding parenthesis around state and assign it to a value. If we had used a my declaration it would reassign to 0 every time and we'd never match the $winning_num. But since state will only ever initialize once we don't have that problem. We still have our problem if we enter a character though, let's sanitize that input.
So in order to fix the 'not a numerical comparison' issue we check $guess to see if it's a digit with a regular expression. If it isn't a digit we set it to 0 which is an invalid guess anyways, but fixes the warning. This actually fixes two bugs. Before if you entered a letter it would tell you that it was too low (which I don't actually understand, because aren't characters > numbers? if someone on Iron Man could explain it in a comment.)

2 comments:

  1. Don't you think it's more natural to use loop with post-loop exit condition? Code will look much nicer and more natural.

    ReplyDelete
  2. @Ruslan it looks nicer... (playing with that now) but I can't seem to get $guess initialized within the loop. which is the only point of this newer version. I think if you use a do ... while loop $guess must be initialized outside the loop.

    I think maybe it might look a bit nicer if I broke the conditions up onto multiple lines too.

    ReplyDelete

No trolling, profanity, or flame wars :: My Blog, my rules! No crying or arguing about them.