jpfarmer has asked for the wisdom of the Perl Monks concerning the following question:
I'm working on a script to produce player pairings for my little brother's chess club. I've written a subroutine produce a pairing.
What I don't understand is the way lexical scoping works for $black_player. I declare it with my at the beginning of the routine, fill it in the foreach loop, and then when I get the value I want, I use last to jump out to the return. However, the value at the return statement always has the initial value.
I've observed the same result when I declare the variable with our as well. It seems like the foreach loop is using local internally. Is that the case? and is there a way to get the behavior I'm looking for, short of using some kind of intermediate variable?
# This takes a player, then determines a valid game pairing. It #returns the opponent's name if there is one, otherwise # it returns undef. sub find_paring($white_player){ my $white_player = $_[0]; my $black_player = "none"; # Get a list of players still in the running my @possible_opponents = keys %{$matches_remaining{$white_player}}; # Shuffle the list to add some randomness, then find the first # avaliable opponent. &shuffle(\@possible_opponents); PAIRING: foreach $black_player (@possible_opponents){ # Once we have a valid match, we remove the entries from the # match hash, and return the pair. if (exists $matches_remaining{$black_player}{$white_player}){ delete $matches_remaining{$white_player}{$black_player}; delete $matches_remaining{$black_player}{$white_player}; last PAIRING; } } # Return the info we have return ($white_player, $black_player); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Question regarding variable scope
by Roger (Parson) on Oct 16, 2003 at 06:32 UTC | |
by Rhandom (Curate) on Oct 17, 2003 at 15:25 UTC | |
by Roger (Parson) on Oct 18, 2003 at 08:13 UTC | |
|
Re: Question regarding variable scope
by Enlil (Parson) on Oct 16, 2003 at 06:40 UTC | |
|
Re: Question regarding variable scope
by delirium (Chaplain) on Oct 16, 2003 at 11:41 UTC | |
|
Re: Question regarding variable scope
by chimni (Pilgrim) on Oct 16, 2003 at 06:49 UTC | |
by MarkM (Curate) on Oct 17, 2003 at 05:33 UTC | |
|
Re: Question regarding variable scope
by hanenkamp (Pilgrim) on Oct 17, 2003 at 02:34 UTC | |
by MarkM (Curate) on Oct 17, 2003 at 05:36 UTC |