CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
random element from array

 



ffranceschina
Deleted

Nov 27, 2000, 1:43 PM

Post #1 of 3 (194 views)
random element from array Can't Post

Hello everyone,

I need help with a small problem.
I have an array that I am trying to get a random element from.

Here is what I have...
*********************************
print "Name:\n";
$name = <>;
chomp ($name);
@list = ("Cat", "Dog");
$pick = rand @list;
while ( $pick eq $name ) {
$pick = rand @list;
}
$choice = $list[$pick];
print "Here is the element: $choice\n";
*****************************************
Even though I tell it to loop itself if the element equals the name it doesn't.
I am I missing something?


japhy
Enthusiast

Nov 27, 2000, 2:19 PM

Post #2 of 3 (194 views)
Re: random element from array [In reply to] Can't Post

You do:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


while ($pick eq $name)
</pre><HR></BLOCKQUOTE>

but $pick is an INDEX, not the actual element. Try

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


while ($list[$pick] eq $name)
</pre><HR></BLOCKQUOTE>

------------------
Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher



ffranceschina
Deleted

Nov 27, 2000, 8:32 PM

Post #3 of 3 (194 views)
Re: random element from array [In reply to] Can't Post

thanks!
That did the trick.
So the index is [0,1,2...] and so on depending on the amount of elements in the array!
I think I should stick to the beginner section!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives