in reply to Re^2: Parsing a file line by line until a certain indice in array
in thread Parsing a file line by line until a certain indice in array
Your first example of pars0r immediately above has a subtle bug in it -- you have my $counter++ instead of $counter++. This has the effect of creating a new instance of $counter, which is why you'll be printing "$vol_to_parse got got\n" every time you get a match:
sub pars0r{ foreach my $volume (@raw_data) { if ($volume =~ /$vol_to_parse/) { my $counter++; # Create new $counter, set it to + 1 if($counter <= 1){ # This will always be true print "$vol_to_parse got got \n"; } elsif ($counter > 1 ) { # Block will never be executed next; # or break; ? } } } }
If you take out the $my it should function correctly.
Your second example of pars0r immediately above has a different bug; even if you change the if ($counter >= 1) to if ($counter <= 1) as I think you meant, once you've found the first match, and until you find a second one, you will always print "$vol_to_parse got got\n":
sub pars0r{ foreach my $volume (@raw_data) { if ($volume =~ /$vol_to_parse/){ $counter++; # Set counter to one the first time } if ($counter <= 1){ # Changed ">= 1" to "<= 1" # This block executes after the first match, and up to # the next non-match, which is NOT what you want! ## print "$vol_to_parse got got \n"; } elsif( $counter > 1){ next; } } }
Why not just do something like this:
sub pars0r{ my $b_got_match = 0; # Initialize boolean to FALSE foreach my $volume (@raw_data) { if ($volume =~ /$vol_to_parse/){ if (!$b_got_match) { # Only print the match once, as $b_got_match gets # set once we print it, and then this conditional # will never again get executed. ## print "$vol_to_parse got got\n"; $b_got_match = 1; } # We can still track the total number of matches ++$counter; } } }
|
|---|