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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.