my %react_to = ( a => sub { shift->{b} = sub { print "A before B\n" } }, b => sub { shift->{a} = sub { print "B before A\n" } }, ); my $text = "b is the first word, but a is not the last."; for ($text =~ /(\w+)/g) { print "Read word: $_\n"; if (my $reaction = $react_to{$_}) { $reaction->(\%react_to); } }