in reply to for loop to get the 3rd index

ok if i'm understanding you correctly.. you're reading from a file and wanting to find the third match? here's how
my $match_count = 0; my $third_match; while (<TMPFILE>) { chomp; if($_ =~ m/matchingStuffHere/) { $match_count++; if($match_count eq 3) { $third_match = $1; } last; } }
thats my solution .. hope it helps..

Replies are listed 'Best First'.
Re: Re: for loop to get the 3rd index
by cbro (Pilgrim) on Jun 06, 2003 at 14:02 UTC
    There are some problems with your solution.
    1. To get your match into $1, it should be m/(matchingStuff)/. That is, there needs to be parens.

    2. Your 'if' statement should be if ($match_count == 3). This is a numerical comparison.
    Try this:
    my @matches; open (F,"files.txt") || die ("Couldn't open file: $!\n"); while(<F>) { chomp; if (/matchingstffHere/) { push(@matches, $_); } } close(F); if (scalar(@matches) >= 3) { print "Needed = $matches[2].\n"; }
Re: Re: for loop to get the 3rd index
by Grygonos (Chaplain) on Jun 06, 2003 at 13:50 UTC
    oops.. drop that call to last; on the line after $third_match = $1; sorry... other wise it will drop the loop on first match.. sorry