Create Postfix virtual table from ldap attributes

The following Perl script will create a Postfix virtual table with mailaddress and uid, so you don't have a ldap query for every incoming email.

#!/usr/bin/perl 

use Net::LDAP; 

# Enter the FQDN of your ldap server
$dc="example.com"; 

# User search base
$hqbase="ou=people,dc=example,dc=com"; 

#Bind user & password
$user="cn=admin,dc=example,dc=com";
$passwd="secret"; 

#connecting to ldap server
$ldap = Net::LDAP->new($dc); 

$mesg = $ldap->bind ( dn => $user, password => $passwd);
if ( $mesg->code()) {
die ("error:", $mesg->code(),"n");

$searchbase = $hqbase; 

# Searching for uid and mailaddress that are mail-enabled 

 $mesg = $ldap->search (base => $searchbase,
filter => "(&(uid=*)(mail=*))",
attrs => "uid", "mail" ); 

$entries = $mesg->count; 

if ($entries lt 1) {
die;

#print ($mesg->entries); 

$outfile = $ARGV[0];
open OUTFILE, "> $outfile" || die "Can't open $outfile for outputn"; 

print OUTFILE "#This virtual file is generated from the importldap script.\n"; 

foreach my $entry ( $mesg->entries ) {
    foreach my $mail ( $entry->get_value( "mail" ) ) {
  foreach my $uid ($entry->get_value( "uid" ) ) {
  if ( ($mail =~ !($mail =~ m/^*/) ) ) {
   print OUTFILE "$mail\t $uid\n";
  }
  } 
    }

system("mv virtual /etc/postfix/virtual"); 

#Generate new Postfix virtual file
system("postmap /etc/postfix/virtual");