Rudra
Rudra

Reputation: 739

How to write a subroutine for forming an xml in perl

Suppose, I have 2 cases one is for sms and another for mail. I need to send a message in both cases. Now, for sending sms I use the following xml.

my $addxml="<tolist><to>";
$addxml=$addxml."<name>".$name."</name>";
$addxml=$addxml."<contactpersonname>".$name."</contactpersonname>";
$addxml=$addxml."<number>".$number."</number>";
$addxml=$addxml."</tolist></to>"

Now, for sending the email, I will be using the same xml except that instead of number I use email tag.

my $addxml="<tolist><to>";
$addxml=$addxml."<name>".$name."</name>";
$addxml=$addxml."<contactpersonname>".$name."</contactpersonname>";
$addxml=$addxml."<email>".$email."</email>";
$addxml=$addxml."</tolist></to>"

How can I write a subroutine in perl that is going to use the above xml once but change the tags (number and email) whenever necessary for sms or email.

Upvotes: 0

Views: 106

Answers (2)

mvp
mvp

Reputation: 116417

How about something like this:

my $sms_xml = xml_gen(
    name              => $name,
    contactpersonname => $contactpersonname,
    number            => $number,
);
my $mail_xml = xml_gen(
    name              => $name,
    contactpersonname => $contactpersonname,
    email             => $email,
);

sub xml_gen {
    my %params = @_;
    my $xml = qq{<tolist><to>};
    foreach my $key (keys %params) {
         $xml = qq{<$key>$params{$key}</$key>};
    }
    $xml .= qq{</to></tolist>};
    return $xml;
}

One advantage of this approach is that you can add as many fields to your XML as you wish.

If you want to completely abstract it away, you can create function like this:

sub xml_gen {
    my ($name, $number, $email) = @_;
    my $xml = qq{<tolist><to>}
            . qq{<name>$name</name>}
            . qq{<contactpersonname>$name</contactpersonname>;
    $xml .= qq{<number>$number</number>} if $number;
    $xml .= qq{<email>$email</email>}    if $email;
    $xml .= qq{</to></tolist>};
    return $xml;
}

Call it like:

xml_gen($name, $number, $email);

If $number or $email is undef, then it will be omitted from the output. This way you can set one, another or both.

Upvotes: 1

perreal
perreal

Reputation: 98108

use strict;
use warnings;

sub sendout {
  my ($type, $name, $addr) = (shift, shift, shift);
my $addxml =<<EID;
<tolist><to>
  <name>NAME</name>
  <contactpersonname>NAME</contactpersonname>
  <ADDR>@</ADDR> 
</tolist></to>
EID
  $addxml =~ s/NAME/$name/g;
  $addxml =~ s/@/$addr/g;
  $addxml =~ s/ADDR/number/g if ($type eq 'sms');
  $addxml =~ s/ADDR/email/g if ($type eq 'email');
  return $addxml;
}

print sendout('sms', "Fudo", "+1321123321"), "\n";
print sendout('email', "Fudo", "user\@fudo.com"), "\n";

Upvotes: 1

Related Questions