in reply to Search and store solution?
#!/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 f +atal ) 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 readin +g: $!"; 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}' fo +r writing: $!"; $tmpl->param(FILE_LIST => [map {{FILE => $_}} @$happy_file]); print $fh $tmpl->output(); } __DATA__ <html> <head><title>Happy Files</title></head> <body> <center> <h2>The following files are happy</h2> <p> <TMPL_LOOP NAME=FILE_LIST> File: <TMPL_VAR NAME=WORD> <br /> </TMPL_LOOP> </p> </center> </body> </html>
The reason I have given you a 97% solution is to illustrate a point. It took me less than 20 minutes to code but it will probably take you more than 2 hours to fine tune the remaining 3%. This is a moderately complex problem and you have very little experience under your belt. It is unrealistic to expect to start running 10K (about 6 miles) races after a week of training - this is no different.
Good luck and welcome to the monastery.
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Search and store solution?
by nukeboy (Initiate) on Jul 11, 2008 at 15:18 UTC | |
by Limbic~Region (Chancellor) on Jul 12, 2008 at 20:31 UTC | |
by YYCseismic (Beadle) on Jul 14, 2008 at 17:40 UTC | |
by Anonymous Monk on Jul 11, 2008 at 16:15 UTC |