1. ホーム
  2. スクリプト・コラム
  3. パール
  4. アプリケーションのヒント

perl で書かれた乱数話法プログラム (rand random function)

2022-01-29 22:45:21
コピーコード コードは以下の通りです。

#! /bin/perl
use strict; 
use warnings; 
#define variables 
my $count; 
my $input; 
my $number; 
my $sentence; 
my $story; 
#Define four arrays 
#Defines an array of characters 
my @nouns= 

   'Dad', 
   'TV', 
   'Mom', 
   'Groucho', 
   'Rebecca', 
   'Harpo', 
   'Robin Hood', 
   'Joe and Moe', 
); 
#defines the action array 
my @verbs= 

   'ran to', 
   'giggled with', 
   'put hot sauce into the orange juice of', 
   'exploded', 
   'dissolved', 
   'dissolved', 
   'sang stupid songs with', 
   'jumped with', 
 ); 
 #defines the location array 
 my @prepositions= 
 ( 
     'at the store', 
     'over the rainbow', 
     'at the beach', 
     'before dinner', 
     'in New York City', 
     'in a dream', 
     'around the world', 
 ); 
 do  
 { 
    # Clear the contents of $story before each run 
    $story=''; 
    # The following is a random combination of generated stories 
    for ($count =0;$count<6;$count++) 
    { 
       # We divide the structure, scalar @nouns is to get the number of elements of the @nouns array, then use rand to generate a few random numbers out of these numbers, and finally int is to round the resulting number 
       $sentence =$nouns[int(rand(scalar @nouns))] 
       . " " 
       . $verbs[int(rand(scalar @verbs))] 
       . " " 
       . $nouns[int(rand(scalar @nouns))] 
       . " " 
       . $prepositions[int(rand(scalar @prepositions))] 
       .' .' ; 
       $story . =$sentence; 
   } 
   print "\n",$story,"\n"; 
   print "\nType \"quit\"to quit, or press Enter to continue:"; 
   $input=<STDIN>; 

# Here is the use of regular expressions to match strings where the first character is q, if so, then exit, /^ is the start position of the match, /i is case insensitive 
until ($input=~/^\s*q/i); 
exit;