use strict; use warnings; #-- hash that will be keyed by Latex element my %in = (); while ( ) { if ( /\\begin\{(\S+?)\}/ ) { #-- tell that we're in a block $in{$1}->{Status} = "in"; #-- add a new element to the anon array containing this info push @{$in{$1}->{Text}}, ""; } if ( /\\end\{(\S+?)\}/ ) { $in{$1}->{Status} = "pending"; } #-- now loop on all keys, see we are in that element. foreach my $key ( keys %in ) { my $status = $in{$key}->{Status}; if ( $status eq "in" || $status eq "pending" ) { #-- add text to last element of the array $in{$key}->{Text}->[$#{$in{$key}->{Text}}] .= $_; } $in{$key}->{Status} = "out" if $status eq "pending"; } } #-- write it out. Here loop over all possible keys. Could be restricted to # 'exertext', 'answers', 'soln' foreach my $key ( keys %in ) { my $file = $key . ".tex"; print "Creating file '$file'\n"; open( FILE, '>', $file) or die "Cannot open file '$file' for writing: $!\n"; #-- write each element of array my $i = 1; foreach my $text ( @{$in{$key}->{Text}} ) { print FILE "%% Starting Element $i\n"; print FILE $text; $i++; } close FILE; }