Mad-Lib Perl Snippet
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.conversion-matters.co.uk.
=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
- About Adam Taylor and Converison Matters
- Dominating the SERPs
- Are Madlib Sites Whitehat?
- When is a blog not a blog?













September 17th, 2008 at 1:43 am
[…] you could fire this through your madlib function and you have a load of unique titles for a small amount of […]
December 23rd, 2008 at 5:55 pm
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
March 22nd, 2009 at 6:42 am
Perl was good until. Gasp. Perl 6. Then it went downhill.
May 5th, 2009 at 6:33 am
Haha, so true Perl 6 did suck.