Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Idiom to return 0 or random number of array elements

by LanX (Chancellor)
on Dec 07, 2012 at 05:48 UTC ( #1007690=note: print w/replies, xml ) Need Help??


in reply to Idiom to return 0 or random number of array elements

just include the possibility of @array[0..-1] which returns an empty list.

try something like: @array[0 .. (int rand (@array+1)) -1]

DB<130> @array=a..c => ("a", "b", "c") DB<131> @array[0 .. -1 + int rand 1+ @array] => () DB<132> @array[0 .. -1 + int rand 1+ @array] => ("a", "b") DB<133> @array[0 .. -1 + int rand 1+ @array] => ("a") DB<134> @array[0 .. -1 + int rand 1+ @array] => ("a", "b", "c") DB<135> @array[0 .. -1 + int rand 1+ @array] => ("a", "b")

Cheers Rolf

Replies are listed 'Best First'.
Re^2: Idiom to return 0 or random number of array elements
by Anonymous Monk on Dec 07, 2012 at 06:04 UTC
    Perfect, that's what I was looking for. Guess I was close, though. Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1007690]
help
Chatterbox?
[Discipulus]: with eskimo greeting is a little bit impressing, anyway
[Eily]: I actually used the eskimo greeting :P, I just wrote the "canonical" form of the oneliner here
[Discipulus]: next time you can add `SARGV-1` and if still not impressed pass a 'rm -f..' as last arg
[Eily]: :)
[Eily]: or I might be tempted to send him an Acme::EyeDropsed file next time
[Eily]: Acme::Bleach is tempting, but it will look like I'm just using the one module that does precisely exactly what he wants

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2017-04-26 15:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (482 votes). Check out past polls.