#!/usr/bin/perl use strict; use warnings; use DBD::mysql; use Getopt::Std; use File::Find::Rule; use HTML::Template; my %opt; get_args(\%opt); my @txt_file = File::Find::Rule->file()->name('*.txt')->in($opt{d}); my @happy_file; for my $file (@txt_file) { push @happy_file, $file if is_happy($file); } store_happy(\%opt, \@happy_file); gen_html(\%opt, \@happy_file); sub store_happy { my ($opt, $happy_file) = @_; my $dbh = DBI->connect( "DBI:mysql:database=$opt->{n}", # DSN connect string $opt->{u}, # User name $opt->{p}, # Password {RaiseError => 1} # Turn any DB exception into fatal ) or die $DBI::errstr; my $sth = $dbh->prepare("INSERT INTO Storage (path) VALUES (?)"); for my $file (@$happy_file) { $sth->execute($file); } } sub is_happy { my ($file) = @_; open(my $fh, '<', $file) or die "Unable to open '$file' for reading: $!"; while (<$fh>) { return 1 if /happy/; } return 0; } sub get_args { my ($opt) = @_; my $Usage = qq{Usage: $0 [options] -h : This help message -d : The base (d)irectory to start searching Default: . current working directory -u : The database (u)ser name Default: 'user' -p : The database (p)assword Default: 'password' -n : The (n)ame of the database -o : The (o)utput file (HTML) Default: 'index.html' } . "\n"; getopts('hd:u:p:n:o:', $opt) or die $Usage; die $Usage if $opt->{h}; die $Usage if ! defined $opt->{n}; $opt->{d} = '.' if ! defined $opt->{d}; $opt->{u} = 'user' if ! defined $opt->{u}; $opt->{p} = 'password' if ! defined $opt->{p}; $opt->{o} = 'index.html' if ! defined $opt->{o}; } sub gen_html { my ($opt, $happy_file) = @_; my $tmpl = HTML::Template->new(filehandle => *DATA); open(my $fh, '>', $opt->{o}) or die "Unable to open '$opt->{o}' for writing: $!"; $tmpl->param(FILE_LIST => [map {{FILE => $_}} @$happy_file]); print $fh $tmpl->output(); } __DATA__