my @colgroup1 = qw(foo bar baz); my @colgroup2 = qw(oop ack); # ... my %tables = ( table1 => { KEYS => [qw(colx coly)], DATA => [ @colgroup1 ], }, table2 => { KEYS => [ qw(cola colb) ], DATA => [ @colgroup2 ], }, # .... }; # ... foreach my $tabname (keys %tables) { my $buddy = $tabname . '_work'; my $tabref = $tables{$tabname}; $sql = qq{ delete $tabname from $tabname t where not exists( select 1 from $buddy where }; $sql .= join("\n and ", map { "t.$_ = w.$_" } @{$tabref->{KEYS}}; $sql .= "\n)"; # ...