 |
|
Home:
Perl Programming Help:
Beginner:
Re: [Alain] Random Picture Loading [Golf]:
Edit Log
|
|

Jasmine
Administrator
/ Moderator
Feb 16, 2002, 11:55 AM
Views: 793
|
|
Re: [Alain] Random Picture Loading [Golf]
|
|
|
Sorry, I couldn't help it -- I really, really tried. And yes, I should be flogged for putting this in the beginners forum. 48 characters
map{$_->[rand@$_]}[grep{/\.(jpg|gif)$/i}glob"*"]; But if you really want to use it, you can keep it a little more flexible and legible: [perl] my $img = random_image( '/path/to/image/dir/' ); sub random_image{ my $dir = shift; return map { $_->[ rand @$_ ] } [ grep { /\.(jpg|gif)$/i } glob "$dir*" ]; } [/perl] If anyone's interested in knowing how this works, here is a simplified explanation: grep { /\.(jpg|gif)$/i } glob "$_[0]*"
[url=http://www.perldoc.com/perl5.6.1/pod/func/grep.html]grep is an operator that uses an expression to search a list. The expression in this case is { /\.(jpg|gif)$/i } (files that end jpg and gif files only). This expression needs to know what directory to look in, and [url=http://www.perldoc.com/perl5.6.1/pod/func/glob.html]glob takes care of that by using the wildcard * to look at all files that directory. The brackets around this entire expression create an anonymous array, which is passed to the [url=http://www.perldoc.com/perl5.6.1/pod/func/map.html]map line because map also works on a list. map { $_->[ rand @$_ ] }
So this line is now working on the results of the grep line (an anonymous array). All it's doing is selecting and returning a random element in the anonymous array. If you have any questions, or need more clarification, ask away.
(This post was edited by Jasmine on Feb 16, 2002, 12:42 PM)
|
|
|
Edit Log:
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 11:56 AM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 11:57 AM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 11:58 AM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 12:33 PM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 12:37 PM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 12:40 PM
|
|
Post edited by Jasmine
(Administrator) on Feb 16, 2002, 12:42 PM
|
|
|  |