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: Beginner: Re: [uatt] Random Picture Loading [Golf]: Edit Log



mhx
Enthusiast / Moderator

Feb 21, 2002, 8:30 AM


Views: 2093
Re: [uatt] Random Picture Loading [Golf]


Code
map { $_->[rand@$_] } ['red', 'green', 'blue', 'yellow'];


First of all, an anonymous array holding some color strings is created. The anonymous array constructor [ .. ] returns a reference to the newly created array. So this reference is the only item in the list that gets passed to map.

But why would you use map if you list would always consist of only one item? Because you can access that item with the $_ variable. Since the array reference isn't explicitly stored in another variable, this is the only way to access the anonymous array twice.

We need to access the anonymous array twice because we need its size for the rand function and we need to dereference a random element. To get the size of the anonymous array, we explicitly convert the array reference $_ into an array by prefixing the reference with an @. Since rand forces scalar context on its argument, @$_ will return the size of the anonymous array referenced by $_. The rand function will now return a random index into the array. Using the array dereference operator -> on the anonymous array reference $_ again, we can dereference that random item and return it. The random item will be the return value of the map function.

You could write the above more readable (but less golfy) as:


Code
$ref = ['red', 'green', 'blue', 'yellow']; 
$ref->[rand @$ref];


or even without an anonymous array:


Code
@ary = ('red', 'green', 'blue', 'yellow'); 
$ary[rand @ary];


Hope this makes things a little clearer. Smile

-- mhx

At last with an effort he spoke, and wondered to hear his own words, as if some other will was using his small voice. "I will take the Ring," he said, "though I do not know the way."

-- Frodo



(This post was edited by mhx on Feb 21, 2002, 9:27 AM)


Edit Log:
Post edited by mhx (Enthusiast) on Feb 21, 2002, 9:27 AM


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

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