A short program that asks users for parts of speech and substitutes values.
%word_list = (); @story = split(/\n/, <<End_Story); Once upon a time there was a [adj1] [noun1] named Bob, who had a [adj2] [noun2]. He used it to [verb1] his [adj3] [noun3]. End_Story foreach my $part_of_speech ( 'noun', 'verb', 'adj' ) { for (my $word_idx = 1; $word_idx <= 3; $word_idx++) { $word_list{$part_of_speech}{$word_idx} = give_me_a($part_of_sp +eech); } } foreach my $line (@story) { $line =~ s/\[(noun|verb|adj)([1-3])\]/$word_list{$1}{$2}/g; print STDOUT $line, "\n"; } sub give_me_a { my ($part_of_speech) = @_; print STDOUT "Give me a $part_of_speech: "; my $word = <STDIN>; chomp($word); $word; }

Replies are listed 'Best First'.
RE: Mad Libs Rewrite
by btrott (Parson) on Apr 13, 2000 at 22:36 UTC
    Nice. Here's mine:
    #!/usr/local/bin/perl -w use strict; die "usage: $0 <madlib>" unless @ARGV; use Text::Template; # read in the story my @story = <>; my $hash = { }; # these are the word types that you're # going to prompt for and include in your madlib; # the key is what you call the type in the madlib ("adj") # and the value is what you want to prompt for my %types = ( noun => 'noun', verb => 'verb', adj => 'adjective' ); # read in the values from STDIN; # you may want to change this around. # 3 means read 3 words of each type (3 nouns, 3 verbs, etc.) for my $type (keys %types) { for my $i (1..3) { print "give me a $types{$type}: "; chomp($hash->{$type . $i} = <STDIN>); } } # set up a new template object: # get template from array @story where template # variables are in [] (DELIMITERS) my $t = new Text::Template(TYPE => 'ARRAY', SOURCE => [ @story ], DELIMITERS => ['[', ']']); # fill in the template with the values you read into $hash; # so in the template, [$noun1] => $hash->{'noun1'} my $story = $t->fill_in(HASH => $hash); # then just print it out print $story;