$mydata=; while(){ #Handle data file line by line splitting it at every new line \n my(@data)=split/\n/,$_; #Now lets go through the whole input data file line by line for($i=0;$i<@data;$i++){ $mydata=$data[$i]; if($mydata=~/^Blah$some_regex(\d+)$some_more_regex_perhaps/){ #Get the sector value which is listed in each matching line of data $DataSector=$1; #Output line of matching data to output file for the relevant sector print $fh[$dataSector] "$mydata\n"; } }