in reply to An Elegance Question
More importantly, there're a number of ways you can make the replace more efficient. First, there're a billion text templating modules on CPAN. Text::Template is the most commonly used; that would allow you to do variable substitution directly into the templates, like so:sub give_me_a { my ($part_of_speech) = @_; print STDOUT "Give me a $part_of_speech: "; my $word = <STDIN>; chomp($word); $word; }
Better would be to put all of your nouns and adjectives into arrays or hash tables. Something like this would do:The quick $adj1 fox ${verb1}ed over the lazy $noun1.
I'm not sure at all if that's more elegant, but it's shorter. The completed script is here: "Mad Libs Rewrite" .my %word_list = (); 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_spe +ech); } } foreach my $line (@story) { $line =~ s/\[(noun|verb|adj)([1-3])\]/$word_list{$1}{$2}/g; print STDOUT $line; }
stephen
|
---|