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

Is there a way to do it more succinctly without creating that temporary array?

Pass a list, not a string ?:)

$_ = <<'__DERP__'; apple apple,banana,cherry banana,cherry apple,cherry banana cherry __DERP__ print "Say ", ( m!([^,]+)!g )[ scalar rand( tr!,!! ) ], "\n"; __END__ Say banana

Replies are listed 'Best First'.
Re^2: Pick random item from list of unknown length?
by jwkrahn (Abbot) on Mar 01, 2010 at 05:10 UTC
    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";
      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 $_

      Yup, classic one-off error :) Should also probably count newlines :)