First of all, you'll want to replace that 'give me a' with a subroutine, since you call it X times.
Like so:
sub give_me_a
{
my ($part_of_speech) = @_;
print STDOUT "Give me a $part_of_speech: ";
my $word = <STDIN>;
chomp($word);
$word;
}
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:
The quick $adj1 fox ${verb1}ed over the lazy $noun1.
Better would be to put all of your nouns and adjectives
into arrays or hash tables. Something like this would do:
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;
}
I'm not sure at all if that's more elegant, but it's shorter.
The completed script is here:
"Mad Libs Rewrite" .
stephen
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.