Saturday, August 31, 2013

Use Perl to generate random project names

Combining /usr/share/dict/words or any word list file, taking advantage of a simple way to randomly pick two elements without replacement from a list, and File::Slurp, I no longer have to hit GitHub just to pick a new project name out of thin air:

#!/usr/bin/env perl

use 5.012;
use strict;
use warnings;
use warnings qw(FATAL utf8);
use open qw(:std :utf8);
use File::Slurp qw( read_file );

run(@ARGV);

sub run {
    @_ or die "Need path to word file\n";
    my $filename = shift;

    open my $words_fh, '<', $filename
        or die "Cannot open word file '$filename': $!";

    my $words = read_file(
        $words_fh,
        array_ref => 1,
        'chomp' => 1,
        blk_size => 4_000_000,
    );

    close $words_fh
        or die "Cannot close word file '$filename': $!";

    say join('-', pick($words));
    return;
}

sub pick {
    my $set = shift;

    my $j = int rand(@$set);
    my $k = int rand(@$set - 1);

    $k += ($k >= $j);

    return @{ $set }[$j, $k];
}

The first result I got seems appropriate for this particular script:

$ ./project-name-picker.pl /usr/share/dict/words
horopteric-unshavenness

Or, maybe not ;-)

A handful of tries later:

$ ./project-name-picker.pl /usr/share/dict/words
melodious-castlet

Yup.

That's good.

Of course, many refinements are possible. But, it was easier to keep re-executing the command than actually adding refinements.

And, I don't feel guilty about that slurp.

No comments:

Post a Comment