Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Show different text based on random number

by htmanning (Friar)
on Apr 22, 2016 at 04:14 UTC ( [id://1161175]=perlquestion: print w/replies, xml ) Need Help??

htmanning has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to show certain blocks of text randomly. I have used rand to generate a number, then determine if that number is odd or even, and based on that print a block of text. That only gives me two options. Can someone tell me how I should go about trying to incorporate 3 or 4 choices? I'm doing something insanely simple:
$rand = int(rand(10)); if (0 == $rand % 2) { &print_one; } else { &print_two; }

Replies are listed 'Best First'.
Re: Show different text based on random number
by kevbot (Vicar) on Apr 22, 2016 at 04:25 UTC
    You could put your text into an array, and then use the method shown in How do I pick a random element from an array?. For example,
    #!/usr/bin/env perl use strict; use warnings; my @choices = ( "Choice 1", "Choice 2", "Choice 3", "Choice 4" ); my $random_choice = $choices[rand @choices]; print "The text is: $random_choice\n"; exit;
      Thanks. I tried this but couldn't get it to work. The text is a rather large block so I put each of them in separate text files. I tried to open each file and assign it to a variable which I then stuff into the array, but it didn't work. I wonder if there is a better way since its such a large amount of text?
        If you have your text in individual files, you could do something like this (with the help of Path::Tiny):
        #!/usr/bin/env perl use strict; use warnings; use Path::Tiny; my @choices = ( path('c1.txt'), path('c2.txt'), path('c3.txt'), path('c4.txt'), ); my $random_path = $choices[rand scalar @choices]; my $text = $random_path->slurp; print "The text is: $text\n"; exit;
Re: Show different text based on random number
by Your Mother (Archbishop) on Apr 22, 2016 at 04:20 UTC
    my $rand = int(rand(4)); if ( 0 == $rand ) {} elsif ( 1 == $rand ) {} … etc

    Don’t use perl4 style unless you know why you’re doing it, c.f. &subname (carries @_ context) instead of subname(). Always use strict and warnings. This seems XY and maybe solved elsewhere: Data::Random.

      &sub is a perfectly valid Perl5 syntax. Is true that the author must be aware of side effects.

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

        I didn't say it was invalid, I said it was perl4 style with gotchas. I don't think I've ever seen a Seeker of Perl Wisdom who uses it and is aware of its side-effects. :P It whispers cargo-cult and cgi-lib.pl to me.

Re: Show different text based on random number
by golux (Chaplain) on Apr 22, 2016 at 04:36 UTC
    Hi htmanning,

    Even more generally, here's a subroutine that gives back a random integer in the range X to Y (inclusive):

    sub random_number_from_X_to_Y { my ($x, $y) = @_; my $random = $x + int(rand($y - $x + 1)); return $random; }
    say  substr+lc crypt(qw $i3 SI$),4,5
Re: Show different text based on random number
by Your Mother (Archbishop) on Apr 22, 2016 at 16:52 UTC

    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 }; }
      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: perlquestion [id://1161175]
Approved by kevbot
help
Chatterbox?
and the web crawler heard nothing...

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

      No recent polls found