#!/usr/bin/perl use strict; my ($file); open(FILE, ") { chomp($_); if(/CITY/ ... /FLORIDA/) { if( ($file) = $_ =~ m/.+CITY:\s+(\w+)\s+/ ) { close(FH); $file .= '.txt'; open(FH, ">>$file"); } print FH "$_\n" unless $_ =~ m/FLORIDA/; } } close(FILE);