frenchface has asked for the wisdom of the Perl Monks concerning the following question:

So I currently have the below script which I can search 1 txt file. However I have 168 text files in the directory that I need it to look at. In the directory I have files that look like this 0-Mon.txt 1-Mon.txt 0-Tues.txt and etc. What I would like it to do is look at all the ones starting with 0, then 1 etc.
#!/usr/bin/perl use strict; use warnings; use CGI ':standard'; print header, start_html('Player Point Tracker'), h1('Point Tracker'), start_form, body(''), p, 'Players Name: ', textfield('name'), br, submit('Search!'), end_form, p, hr; my $search_term =param('name'); my $file = '18.txt'; open (my $FILE_HANDLE, '<', $file) || die "Can't open $file: $! \n"; while (<$FILE_HANDLE>) { chomp; my ($word, $count) = split / /, $_; if ($word =~ /^$search_term$/) { print "At 18:00 server time $word had $count p +oints.",p; } } close ($FILE_HANDLE);

Replies are listed 'Best First'.
Re: cgi search all txt files in a directory
by perlpie (Beadle) on Sep 23, 2010 at 00:55 UTC

    Before you put this on a user-facing server, consider all the creative ways folks could abuse your server by putting clever things in your regex. You might want to look into quotemeta.

Re: cgi search all txt files in a directory
by perlpie (Beadle) on Sep 23, 2010 at 00:52 UTC

    You could throw in a couple of for loops...

    #!/usr/bin/perl use strict; use warnings; use CGI ':standard'; print header, start_html('Player Point Tracker'), h1('Point Tracker'), start_form, body(''), p, 'Players Name: ', textfield('name'), br, submit('Search!'), end_form, p, hr; my $search_term =param('name'); for my $digit (0 .. 9) { for my $file (<$digit*>) { open (my $FILE_HANDLE, '<', $file) || die "Can't open $file: $ +! \n"; while (<$FILE_HANDLE>) { chomp; my ($word, $count) = split / /, $_; if ($word =~ /^$search_term$/) { print "At 18:00 server time $word had $count points.", +p; } } close ($FILE_HANDLE); } }
      Thanks for you reply, My question though are where do I specify the path to the file and also it looks like that is only going to open files with the name "0" or "1" and I need it to open "1-Mon.txt" or "22-Fri.txt" Thanks!

        It will open files that start with $digit. The star after $digit is a glob. For example, when $digit is 1, then you'll get all files starting with 1. If you need to put some more path around that, go ahead. For example:

        </path/to/some/directory/$digit*>