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

I've been trying to match and extract information from a flat text file. (CGI). The script is as follows:
#!/usr/bin/perl -w use strict; #use CGI::Carp qw(fatalsToBrowser warningsToBrowser); use CGI ':standard'; my $data="/path/data.txt"; my $other_data="/path/other_data.txt"; my $checkfour = param('check'); my @other = (); open (OTHER, $other_data); while (my $line =<OTHER>) { my ($one,$two,$three,$four,$five) = split "\t",$line; if ($four eq $checkfour) { push (@other, $three); push (@other, $four); last; } } close (OTHER); my $checkthree = shift(@other); my $four = shift(@other); print header(), start_html(-title => ""); print "get $checkthree and $four then $checkfour<br>"; open (FILE, "$data"); while (my $line =<FILE>) { my ($one,$two,$three,$four,$five) = split "\t",$line; if ($three eq $checkthree) { print "<p>With matching parameters I should be able to see this </p>"; last; } else {print "<p>If I put the else statement in it ignores the fact t +hat the parameters match - and comes here! (But I don't know why).</ +p>"; last; } } close FILE; print end_html();
If the input in $checkfour matches the field $four then I can take out the information. If it doesn't match the 'else' kicks in.

Except.....when I use parameters that do match, it matches only if the else statement is not there - if take it out I get the match, if I put it in it ignores the match and goes to the else.

If someone could tell me why I'd be very grateful.

Replies are listed 'Best First'.
Re: data field extraction not as expected
by elusion (Curate) on Dec 06, 2002 at 22:21 UTC
    Your problem is here:
    while (my $line =<FILE>) { my ($one,$two,$three,$four,$five) = split "\t",$line; if ($three eq $checkthree) { print "<p>With matching parameters I should be able to see this + </p>"; last; } else { print "<p>If I put the else statement in it ignores the fact t +hat the parameters match - and comes here! (But I don't know why).</ +p>"; last; } }
    This is what's happening: You're getting to this while statement, and $line gets the first line from the file. You're finding that the first line of the file doesn't match $checkthree, so the else is executed, the line is printed, and the while is exited. To fix this, try some like the following.
    my $matched; while (my $line = <FILE>) { my ($one,$two,$three,$four,$five) = split "\t",$line; if ($three eq $checkthree) { print "<p>With matching parameters I should be able to see thi +s </p>"; $matched = 1; last; } } unless ($matched) { # this is like the else print "<p>If I put the else statement in it ignores the fact that +the parameters match - and comes here! (But I don't know why).</p>"; }

    elusion : http://matt.diephouse.com

      Thanks very much, elusion. The explanation was very clear and the solution works perfectly!