1 Replies - 776 Views - Last Post: 24 July 2016 - 11:17 AM

#1 tonyal   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 85
  • Joined: 23-September 14

Problems printing multiple searches from file.

Posted 24 July 2016 - 11:01 AM

Hello. I'm wanting to do separate searches and print lines for information from a text file. I'm able to get both searches to print - but they're inter-mingled (I want each search to print separately from each other). I tried to do two separate while loops but results from only one will display. I've tried doing google searches, but only find basics about while loops, or how to do searches based on other search results.
Basically, I want to be able to go through the txt file once, and display all addresses that contain the word "Street". Then, in a separate search, go through the whole file again (not just the results of the first search) and print all names that start with a "B" (upper and lower case).
I tired to switch to switch statements, but with no luck.
Here is the code:
use warnings;

my ($name, $phone, $address, $birthday, $salary);

open (my $fh, "<", "sample.txt") or die "Can't open file!";
while (my $inputline=<$fh>) {
	($name, $phone, $address, $birthday, $salary) = split(":", $inputline);
	print $inputline if $address =~ /Street/;

while (my $inputline=<$fh>) {
    ($name, $phone, $address, $birthday, $salary) = split(":", $inputline);
	print $inputline if $name =~ /^B/i;
close $fh

Thank you in advanced!

Is This A Good Question/Topic? 0
  • +

Replies To: Problems printing multiple searches from file.

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6823
  • View blog
  • Posts: 28,271
  • Joined: 12-December 12

Re: Problems printing multiple searches from file.

Posted 24 July 2016 - 11:17 AM

I know nothing of this Perl of which you speak but suspect that you need to return the file pointer (the file position) to the beginning of the file using seek with SEEK_SET between each loop.

(I don't think that the results are intermingled, just that the second search picks up where the first one left off. Edited: In fact, I assume the first while loop iterates the whole file, so I'm not sure where the intermingling comes from.)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1