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

Newbie question here:

How can I end this loop so it reads "Sorry, your query was not found."? A then statement?
#for each line while ($line = <EMPLOYEES>) { #remove the carriage return chomp $line; #splits the line between tabs and get the different elements ($name, $city, $language) = split /\t/, $line; next unless $language =~ /$search/; print "$name can speak " . ($search) . " and lives in " . ($city) . " +.\n";

Thank you all,
Mox

Replies are listed 'Best First'.
Re: Ending a 'next unless' loop...
by jasonk (Parson) on Oct 04, 2006 at 00:34 UTC

    The easiest way would be to keep track of whether you have produced any output or not...

    my $found = 0; #for each line while ($line = <EMPLOYEES>) { #remove the carriage return chomp $line; #splits the line between tabs and get the different elements ($name, $city, $language) = split /\t/, $line; next unless $language =~ /$search/; $found++; print "$name can speak " . ($search) . " and lives in " . ($city) + . ".\n"; } print "Found $found results.\n";

    We're not surrounded, we're in a target-rich environment!
Re: Ending a 'next unless' loop...
by blueberryCoffee (Scribe) on Oct 04, 2006 at 05:39 UTC
    sub query { my $search = shift; while(my $line = <EMPLOYEES>) { if($line =~ /(.*?)\t(.*?)\t.*$search/) { return "$1 speaks $search and lives in $2"; } } return "Sorry, nothin for ya"; } print query("Norse");
Re: Ending a 'next unless' loop...
by ikegami (Patriarch) on Oct 04, 2006 at 04:49 UTC
    If you're reading from a file (well, anything except a terminal), then you could use eof.
    if (eof(EMPLOYEES)) { print "Sorry, your query produced no results.\n"; } else { while (my $line = <EMPLOYEES>) { #remove the carriage return chomp $line; #splits the line between tabs and get the different elements ($name, $city, $language) = split /\t/, $line; next unless $language =~ /$search/; print "$name can speak " . ($search) . " and lives in " . ($city) . ".\n"; } }
      There is one problem I see with this approach.

      Unless I'm missing something I think you meant

      open(EMPLOYEES,'test.txt') or die; while (my $line = <EMPLOYEES>) { #remove the carriage return chomp $line; #splits the line between tabs and get the different elements my ($name, $city, $language) = split /\t/, $line; next unless $language =~ /$search/; print "$name can speak " . ($search) . " and lives in " . ($city) . ".\n"; } print "Sorry, your query produced no results.\n" if (eof(EMPLOYEES)) +;

      But the bigger problem using the eof approach is that if the match is last line of the file - you'll get the match printed and the 'Sorry' message.



      grep
      One dead unjugged rabbit fish later

        Unless I'm missing something I think you meant

        For some odd reason, I thought <EMPLOYEES> contained the query results. Don't try to make sense of it for I was completely wrong.