Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Show different text based on random number

by Your Mother (Archbishop)
on Apr 22, 2016 at 16:52 UTC ( [id://1161241]=note: print w/replies, xml ) Need Help??


in reply to Show different text based on random number

Everyone's problems are more interesting than mine. As long as I can write idiopathically. Idiomatically, I mean. I meant idiomatically.

use strict; # DO NOT OMIT. use warnings; # DITTO. my $dir = shift || die "Gimme a dir full of text files!\n"; my $random_texter = build_texter(dir => $dir); print $random_texter->(); exit; sub build_texter { require List::Util; require Path::Tiny; require Carp; my %arg = ( dir => "YOU FORGOT TO SET THE DIR!", suffix => "", # e.g., .txt @_ ); my $dir = Path::Tiny::path($arg{dir}); -d $dir && -r _ || Carp::croak("$dir is not a readable directory") +; my @files = grep /\Q$arg{suffix}\E\z/, grep -f, $dir->children; Carp::croak("There are no matching files in $dir") unless @files; sub { [ List::Util::shuffle( @files ) ]->[0]->slurp }; }

Replies are listed 'Best First'.
Re^2: Show different text based on random number
by kevbot (Vicar) on Apr 23, 2016 at 05:03 UTC
    I like your version, since you don't have to list the text files in the script...and you can add a choice simply by adding a file to the directory. It inspired me to update my version:
    #!/usr/bin/env perl use strict; use warnings; use Path::Tiny; my $dir_path = path('text_files'); my @choices = $dir_path->children; unless( scalar @choices > 0 ){ die "No text files found in $dir_path"; } my $random_path = $choices[rand scalar @choices]; my $text = $random_path->slurp; print "The text is: $text\n"; exit;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1161241]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2024-04-18 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found