Adam

Mad-Lib Perl Snippet

by Adam on June 19, 2008

in Code

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:

  1. Become a Perl rockstar… AKA Perl link dump
  2. Are Madlib Sites Whitehat?
  3. A little script for you
  4. Shwartzian Transform
  5. Perl Ain’t Dead…

{ 1 trackback }

Are Madlib Sites Whitehat? » Adam Taylor - Conversion Matters
September 17, 2008 at 1:43 am

{ 3 comments… read them below or add one }

brianjudo December 23, 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

Reply

Anonymous March 22, 2009 at 6:42 am

Perl was good until. Gasp. Perl 6. Then it went downhill.

Reply

Jason May 5, 2009 at 6:33 am

Haha, so true Perl 6 did suck.

Reply

Leave a Comment