複製代碼 代碼如下:
#!/bin/perl
use strict;
use warnings;
#定義變數
my $count;
my $input;
my $number;
my $sentence;
my $story;
#定義四個數組
#定義了人物數組
my @nouns=
(
'Dad',
'TV',
'Mom',
'Groucho',
'Rebecca',
'Harpo',
'Robin Hood',
'Joe and Moe',
);
#定義了動作數組
my @verbs=
(
'ran to',
'giggled with',
'put hot sauce into the orange juice of',
'exploded',
'dissolved',
'dissolved',
'sang stupid songs with',
'jumped with',
);
#定義了地點數組
my @prepositions=
(
'at the store',
'over the rainbow',
'at the beach',
'before dinner',
'in New York City',
'in a dream',
'around the world',
);
do
{
#每次運行以前,清空$story的內容
$story='';
#以下是隨機組合產生故事
for ($count =0;$count<6;$count++)
{
#我們劃分一下結構,scalar @nouns 是擷取@nouns數組元素的個數,然後用rand總這幾個數中隨機產生幾個,最後int是將得到的數取整
$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>;
}
#這裡是利用Regex來匹配首字元是q的字串,如果有,那麼就退出,/^是匹配起始位置,/i是不區分大小寫
until ($input=~/^\s*q/i);
exit;