Tried Perl debugger on this code (Was Please help, my brain is fried)

Shay Harding mekla at
Thu Jan 27 22:20:48 CST 2000

> Hi, I'm mostly a lurker, being too busy shoveling myself out of debt,
> but this one got me thinking.
> It works fine for me with the below as the only alteration to the
> original (that someone else previously suggested):
>      $char = get_char() if ($char >= 91 && $char <= 96);
> You were correct earlier when you wrote that with the recursion you
> shouldn't need the 'while'; the 'if' becomes a 'while' via recursion.
> Are you sure you have the '$char = getchar()' rather than just the
> 'getchar()' in what you are executing, I only ask because I notice the
> code you last posted doesn't have it.  When I find myself circling a
> blind spot I give up and take a nap; pretend I'm giving up on it.  Thats
> when it hits ya; or at least you get your life back for awhile.
> Rgds,
> Marty

Yeah it works fine with that modification, but *why* does it matter? This is
what I truly want to know. Does it have to do with the 'if' block and
recursion. Basically here is what happens when I look at it via the debugger:

1:  get_char() is called
2:  $char gets an initial ASCII 93
3:  Hits the 'if' block and recurses
4:  $char is now undefined (at this point anyway)
5:  $char gets a value of 73
6:  Passes if block
7:  Is going to return $char
8:  $char is set back to 93 just before return

When it recurses, is this treated as another block of code so all variables
declared via 'my' exist outside the original block that triggered the
recursive call?

I guess the best way I can describe what I think is going on is by the
following code. This is basically what happens on this recursive call I believe.

sub get_char(){
# $char gets value of 93

   my $char = int(rand(57))+65;

   print $count, "  ", chr($char), "\n";

# evaluates to true, calls subroutine
# This block's $char = 93

    if ($char >= 91 && $char <= 96){

#73 returned but no var to 'catch' it


# returns 93 since other $char went out of scope

   return $char;

   sub get_char_next(){
# This block's $char = 73

       my $char = int(rand(57))+65;
       print $count, "  ", chr($char), "\n";
# Skips over this block

       $char = get_char_next() if ($char >= 91 && $char <= 96);

#returns 73

       return $char;


More information about the Phoenix-pm mailing list