LanX got to the @slice[ 0 .. -1 ] solution ahead of me, but I'm thinking you might still be missing something.
In your first example, "$element = $array[int rand @array];", you're selecting a random element. In your second example, "@elements = @array[0 .. int rand @array];" you're selecting a random number of elements, but the elements being selected are not random except for the quantity. If your array contains "a, b, c, d, e", you'll get "a", or "a,b", or "a,b,c", etc. Even after dealing with the ability to get no elements at all, you're still not actually getting random elements.
Maybe that's what you want. Or maybe you want a random number of random elements (with no duplicates). If that's the case, you might just shuffle:
use List::Util 'shuffle';
use List::MoreUtils 'minmax';
my @array = 'a' .. 'z';
my @quantities;
for( 1 .. 100 ) {
# --------------------This is the solution line: -------------------
+----------
my @selected = @{ [ shuffle @array ] }[ 0 .. int( rand @array + 1 )
+- 1 ];
# ------------------------------------------------------------------
+------
push @quantities, my $quantity = @selected;
print "@selected => ($quantity)\n";
}
print "\nMin/Max elements: (", join( ',', minmax @quantities ), ")\n";
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.