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); }
In reply to Question regarding variable scope by jpfarmer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |