please tell us what the function filter does. with a short codechange for the checkbox the addition should reduce to merely add the names to @fields.
and try to write subroutines in such a way that they do not rely on variables that are elsewhere defined.
for example, you could just pass $database as actual argument to add_record, as with the array @fields.