Question

I have a text file with a list of individual mnemonics (1000+) in it and a directory that also has page files in it. I want to see how many pages a given mnemonic is on.

below is my code so far..

use strict;
use warnings;
use File::Find ();

my $mnemonics = "path\\path\\mnemonics.txt";
my $pages = "path\\path\\pages\\";

open (INPUT_FILE, $names) or die "Cannot open file $mnemonics\n";
my @mnemonic_list = <INPUT_FILE>;
close (INPUT_FILE);

opendir (DH, $pages);
my @pages_dir = readdir DH;

foreach my $mnemonic (@mnemonic_list) {
    foreach my $page (@pages_dir) {
        if (-e $mnemonic) {
            print "$mnemonic is in the following page: $page";
        }  else {
            print "File does not exist \n";
        }
    }
}

Basically, where I know that a name exists in a page, it isn't showing me the correct output. I'm getting a lot of "File does not exists" when I know it does.

Also, instead of (-e) I tried using:

if ($name =~ $page) 

and that didn't work either..

Please help!

Was it helpful?

Solution

Assuming that you want to search a directory full of text files and print the names of files that contain words from the words in mnemonics.txt, try this:

use strict; use warnings;

my $mnemonics = "path/mnemonics.txt";
my $pages = "path/pages/";

open (INPUT_FILE, $mnemonics) or die "Cannot open file $mnemonics\n";
chomp(my @mnemonic_list = <INPUT_FILE>);
close (INPUT_FILE);

local($/, *FILE);          # set "slurp" mode
for my $filename (<$pages*>) {
  next if -d "$filename";  # ignore subdirectories
  open FILE, "$filename";
  binmode(FILE);
  $filename =~ s/.+\///;   # remove path from filename for output
  my $contents = <FILE>;   # "slurp" file contents
  for my $mnemonic (@mnemonic_list) {
    if ($contents =~ /$mnemonic/i) {
      print "'$mnemonic' found in file $filename\n";
    }
  }
  close FILE;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top