http://www.perlmonks.org?node_id=1125321


in reply to processing a list of events

If I understood correctly, you want the indices of the first EVENT A and the first EVENT B after the EVENT A. It would be helpful if you provided an example of desired output for your data.

As for the solution, how about a simple dispatch table?

use strict; use warnings; use feature 'say'; # Sample data my @events = ( 'EVENT A', 'EVENT A', 'EVENT B', 'EVENT A', 'EVENT A', 'EVENT A', 'EVENT B', 'EVENT A', 'EVENT B' ); my ($first_A, $first_B); my $state = 'find_A'; my %parse = ( find_A => sub { my ($event, $index) = @_; if ($event eq 'EVENT A') { $first_A = $index; $state = 'find_B'; } }, find_B => sub { my ($event, $index) = @_; if ($event eq 'EVENT B') { $first_B = $index; $state = 'finished'; } } ); while (my ($index, $event) = each @events and $state ne 'finished') { $parse{$state}->($event, $index); } say 'First occurrence of A: ', $first_A // 'none'; say 'First occurrence of B: ', $first_B // 'none';

The script is going to execute one of the functions from the %parse hash, according to the search state. If an EVENT A still hasn't been found, it will check for 'EVENT A' and save the index if it's found, then it will switch to the second state, searching for 'EVENT B'. After an EVENT B is found, the loop will terminate.