I bashed up a quick mad-lib perl class for use in some future scripts. If you don’t know what mad-lib is it’s basically a function that when given an input such as us:we:i:them:she:he will select one. Given a whole block of text with multiple parts to be ‘mad-libbed’ it can crank out many chunks of readable, unique content.
#!/usr/bin/perl
package madlib;
use Moose;
## Fields for madlib objects
has 'phrase' => (isa => 'Str', is => 'rw');
has 'debug' => (isa => 'Bool', is => 'rw', default => '0');
## Function to select a random word from the phrase
sub madlib() {
my $self = shift;
if ($self->debug) { print "Phrase = ".$self->phrase."n"; }
my @words = split(/:/,$self->phrase);
my $length = @words;
if ($self->debug) { print "Length of @words = ".$length."n"; }
my $rand = int(rand($length));
return($words[$rand]);
}
return 1;
=head1 NAME
madlib - A class to perform 'madlib' function.
=head1 SYNOPSIS
use madlib;
my $object = madlib->new();
$object->phrase("some:phrase:to:madlib");
$object->debug(1) # to get some debugging output
print $object->madlib();
=head1 DESCRIPTION
This class provides the ability to 'madlib' a phrase/string to create unique content variations.
=head2 Methods
=over 12
=item C
Returns a new madlib object.
=item C
Returns a random word from the specified phrase.
=back
=head1 AUTHOR
Adam Taylor - http://www.adamjctaylor.com.
=cut
Won’t do much on its own but used within some other systems it could be quite useful. I’m thinking directory submission, social bookmarking etc..
(Yes it displays wonky; apologies…)
Related posts:
- Become a Perl rockstar… AKA Perl link dump
- Are Madlib Sites Whitehat?
- A little script for you
- Shwartzian Transform
- Perl Ain’t Dead…
Bookmarking
-
Stumble | Digg | del.icio.us | RSS


{ 1 trackback }
{ 3 comments… read them below or add one }
So lets say we are developing a database driven site using this snippet of code. A Recipe Database in MySql. How would I change the above madlib code to pull from this database? Examples would be great
Thanks in Advance
Brianjudo
Perl was good until. Gasp. Perl 6. Then it went downhill.
Haha, so true Perl 6 did suck.