Passing parameters by name with perl, plus easier emailing.

Posted by Chris on July 30th, 2009 filed in programming

One of the advantages of python et al is that instead of taking parameters in order, you can pass them by name.  In python, this is done using (by convention) the following notation:

def myfunction(self,*args,**kwargs):

param1 = kwargs['param1']
param2 = kwargs['param2']

mything=myfunction(param1=something, param2=something2)

I can do the same thing in perl with just a tiny bit of extra work. – This is how I actually usually send emails in a program, for example.

package include;
use MIME::Lite;
sub send_email()

my $ref = shift || return;
my %pass = %$ref; #this converts it to a hash - broken out for clarity
#from here out, we can just:
my $subj=$pass{'subject'};
my $body=$pass{'body'};
my $file=$pass{'file'};
my $to =$pass{'to'};
my $from=$pass{'from'};
my $debug = $pass{'debug'} || 0;

my $msg=MIME::Lite->new(

To => $to,
From => $from,
Subject => $subj,
Type => 'multipart/mixed'

) or die ("Couldn't create multipart email: $!\n");

Type => 'TEXT',
Data => $body

) or die("Couldn't attach the text part: $!\n");
my @filelist=();
@filelist=split(",",$file) if $file;
foreach my $filename(@filelist)

print "Attaching file $filename\n" if $debug;
my $suffix=( split(/\./,$filename) )[-1];
if($suffix eq 'png' or $suffix eq 'jpg' or $suffix eq 'gif' or $suffix eq 'jpeg')

Type => $suffix,
Path => $filename,
Filename=> $filename,

) or die("Couldn't attach file attachment: $!\n");


or die("Couldn't send message: $!\n");



subject =>"My email",
to =>$mailto,
from =>'[email protected]',
body => $msg_body,
file => join(",",@attachments),


So, this is in my include module (as seen in the usage) that other programs import. From then on it’s just a matter of a few lines to send emails, and no remembering the position of the arguments either. This is very similar to how I like to pass paramters to a program using CGI.

The other nice part of this is it’s guaranteed.  No importing another module, having to use an object, etc.

Leave a Comment