A better title for the node would be: "...and then I realized that it wasn't so great."

I was reading over the various level powers, when I came across the "Categorized Questions and Answers". Though I haven't perused this section yet, I thought that I would do so, then add a deck-shuffling routine to it that I wrote a few days ago. The routine was magic to me, but simple enough that other newbs should be able to understand it.

But before I investigated further as to whether or not a question/answer like this had been posted, I decided to take a second look at my code.

I've tested it a few times, and it works just fine, but HOW it works is absolutely baffling to me, now (and I'm curious if it will continue to work or if it will get patched out of compiling in future versions of the language).

The code:

sub shuffle_Deck { my @deck; for (0 .. $#_) { my $rand = int(rand(@_)); push(@deck, splice(@_,$rand,1)); } return @deck; }

I would have expected the $_ in the for loop to take on the values between 0 and the passed arr's $# (as described in the for (LIST)). However, it appears to retain the value of the scalar within the passed array, rather than just a integer value...

This happens to be what I wanted anyways. :)

Is this an example of perl taking a Pretty Good Guess, or is the language actually supposed to do this?

Update: My above code was originally ...int(rand($#_))..., which left the bottom card at the bottom of the deck forever. :)

$scratchpad_public = 0 unless $scratchpad;


In reply to Unexpected value of $_ in a for loop. by David Caughell

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.