if ($array[$line] =~ /0?.*?(RECORD .*)/){ $record = trim($1); # works correctly $array[$line+1] =~ /(\d+)(.*)/; $id = trim($1); # works correctly $name = trim($2); # works correctly # still looking at the "a" lines, sometimes there's a date, sometimes no date $array[$line+2] =~ /.*?(\d{2}\/\d{2}\/\d{4})?(.*)/; $date = trim($1); # when no date it's using the previous $1 that goes into $id $address = trim($2); # when no date it's using the previous $2 that goes into $name ... code continues ...