my $data = qq`\nHTML1\n<% CODE1 %>\nHTML2\n<% CODE2 %>\nHTML3\n`; my $reader = get_reader( $data ); while (my $blob = $reader->()) { print "$blob->{'type'}: $blob->{'data'}\n";; } sub get_reader { my $input = shift; my $state = 'plain'; return sub { my $temp; return unless defined $input; if ($state eq 'plain') { if ($input =~ s/(.*?)<%//s) { $state = 'code'; return { type => 'plain', data => $1 }; } else { $temp = $input; undef $input; return { type => 'plain', data => $temp }; } } else { # state eq 'code' if ($input =~ s/(.*?)\%>//s) { $state = 'plain'; return { type => 'code', data => $1 }; } else { $temp = $input; undef $input; return { type => 'code', data => $temp }; } } } } __RETURNS__ plain: HTML1 code: CODE1 plain: HTML2 code: CODE2 plain: HTML3