Anyway, this code works ...
An expression like $positions_ref->[ rand( $#{$positions_ref} ) ] will never evaluate to the last element of the array. Use $positions_ref->[ rand( @{$positions_ref} ) ] instead (unless you want to avoid the last element!).
>perl -wMstrict -le "my $n = shift || 1000; my $arrayref = [ qw{ a b c d e f g i j k l m n o p } ]; my $last_element = $arrayref->[-1]; my $n_max_i = 0; for (1 .. $n) { my $rand_element = $arrayref->[ rand $#$arrayref ]; ++$n_max_i if $rand_element eq $last_element; } printf 'last element picked randomly %f%% of %d times', $n_max_i/$n*100, $n; " last element picked randomly 0.000000% of 1000 times >perl -wMstrict -le "my $n = shift || 1000; my $arrayref = [ qw{ a b c d e f g i j k l m n o p } ]; my $last_element = $arrayref->[-1]; my $n_max_i = 0; for (1 .. $n) { my $rand_element = $arrayref->[ rand @$arrayref ]; ++$n_max_i if $rand_element eq $last_element; } printf 'last element picked randomly %f%% of %d times', $n_max_i/$n*100, $n; " last element picked randomly 6.700000% of 1000 times
Updates:
  1. Changed examples to use array references.
  2. Changed printf statements to correctly calculate percentage.

In reply to Re: Repeating an input prompt by AnomalousMonk
in thread Repeating an input prompt by zod

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.