I'm trying to search a large number of files (file1, file2, etc.). I want to search each file for a different name (Joe, Lee, etc.). I want to see if "Joe" appears in "file1" and "Lee" appears in "file2". I begin with a text file (array.txt) that contains the files and names and put this into an array.

array.txt: file1 Joe file2 Lee ... ...

Then, I use "foreach" to work through the items in the array. In the following code, the files "file1" and "file2" will open with each iteration of the "foreach" loop. However, the $name variable in the "if" statement doesn't seem to loop through the names (Joe, Lee) but rather stays on the first name (Joe). Therefore, both "file1" and "file2" are searched for "Joe". I only want to search "file1" for "Joe" then search "file2" for "Lee". Any help is much appreciated!

#!/usr/bin/perl -w use strict; use warnings; use diagnostics; my @filelist = (); my $file=''; my $name=''; open(FILE,"array.txt")||die "Can't open array.txt"; @filelist=<FILE>; close(FILE); foreach my $line (@filelist){ my $file=substr($line,0,5); chomp $file; my $name=substr($line,6,3); chomp $name; open (FILE2,"$file"); while ( <FILE2>) { if (/$name/ismo) { print ("$name found in $file\n"); } } close(FILE2); }

In reply to Passing variable to if statement by PeachCityDude

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.