Alias Manipulation with Unix::AliasFile

While not a member of the Mail umbrella, Unix::AliasFile is an important module since it implements a complete interface to the Unix aliases text file that allows you to query, add, update, and delete aliases. In addition, it has a cleaner interface than Mail::Alias. Unix::AliasFile automatically handles file locking, comma and colon placement, and any other detail that’s related to manipulating your Unix mail alias file. For example:

use Unix::AliasFile;

my $aliasfile = '/etc/mail/aliases';
my $uaf = Unix::AliasFile->new($aliasfile);

foreach my $alias $uaf->aliases(  ) {
    chomp($alias);
    
    if($uaf->alias($alias) ne "$alias\@yourpopserver.your.domain") {
        # Doesn't exist, so add alias of the form:
        # alias: alias@yourpopserver.your.domain
        
        $uaf->alias($alias, ("$alias\@yourpopserver.your.domain"));
    } else {
        print "I already have $alias that way.\n";
    }
}

$uaf->commit(  );
undef $uaf;

Unix::AliasFile implements the following methods.

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.