#!/usr/bin/perl -wl use strict; use Getopt::Long; use Pod::Usage; my ($IN,$OUT,$COUNT); GetOptions( 'help|?' => sub { pod2usage(-verbose => 2);exit } , 'in=s' => \$IN, 'out=s' => \$OUT, 'count=i' => \$COUNT ); die pod2usage {-verbose=>2} unless $IN; open IN, "< $IN" or die "Cannot open ($IN) for reading: $!"; chomp (my @items = ); close IN; $COUNT ||= scalar @items; my @permutes; push @permutes => \@items for 1 .. @items; my %results = map { join( '',@$_[0..($COUNT-1)]) => 1 } permute(@permutes); if ( $OUT ) { open OUT, "> $OUT" or die "Cannot open ($OUT) for writing: $!"; print OUT $_ foreach sort keys %results; close OUT; } else { print foreach sort keys %results; } sub permute { my $last = pop @_; return map [$_], @$last unless @_; return map { my $left = $_; map [@$left, $_], @$last } permute(@_); } __END__ =head1 NAME permutations.pl -- A simple tool to generate permutations of items =head1 SYNOPSIS B for more information perl permutations.pl [options] Options: --help Display help --? Same as --help --infile File with list of items (one on each line) --outfile File to write permutations to --count Number of items in permutation =head1 DESCRIPTION This program will generate a list of all possible permutations of data items listed in an infile. It will limit the number of items in the permutations to the number of items specified in the C<--count> option. For example, with the following items in an input file: .jpg .exe .com If you want to print all permutations with a limit of two items per permutation, you would use the following command (assuming that the input and output files are named C and C, respectively). perl permutations.pl --count 2 --in infile.txt --out outfile.txt You may use shortcuts, too: perl permutations.pl -c 2 -i infile.txt -o outfile.txt The above command will result in the following output: .com.com .com.exe .com.jpg .exe.com .exe.exe .exe.jpg .jpg.com .jpg.exe .jpg.jpg If C<--count> is omitted, the count will default to the number of items in the infile. If C<--out> is omitted, the results will be printed to C.