in reply to Re: Pick random item from list of unknown length?
in thread Pick random item from list of unknown length?

print "Say ", ( m!([^,]+)!g )[ scalar rand( tr!,!! ) ], "\n";

Counting the commas will give you one less than the numbers of elements in the list so you have to add one to it:

print "Say ", ( /[^,]+/g )[ rand 1 + tr/,// ], "\n";

Replies are listed 'Best First'.
Re^3: Pick random item from list of unknown length?
by Cody Fendant (Hermit) on Mar 01, 2010 at 06:03 UTC
    That works with the implicit regex on $_
    $_ = 'apple,banana,cherry'; print "Say ", (m!([^,]+)!g)[ scalar rand 1 + (tr!,!!) ], "\n";
    but for some reason, when I do this:
    $foo = 'apple,banana,cherry'; print "Say ", ($foo =~ m!([^,]+)!g)[ scalar rand 1 + (tr!,!!) ], "\n";

    I only ever get 'apple'.

      That works with the implicit regex on $_

      Nope, its implicit m//atch on $_, and you're forgetting about the implicit tr///ansliteration on $_

        Oh right. Slap-forehead and all that.
Re^3: Pick random item from list of unknown length?
by Anonymous Monk on Mar 01, 2010 at 05:13 UTC
    Yup, classic one-off error :) Should also probably count newlines :)