Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-19 22:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found