selfjungle Just another WordPress weblog

12Aug/090

String templates with Perl

Here is a nice thing with perl.

  1. You have a string template, like an e-mail, with fields to change.
  2. This fields are stored in a CVS file.
  3. Perl changes this fields with hashes and regular expressions in no time.

Note: the field names are the keys in the hash, lines of the CVS are an array with hash refs.

#!/usr/bin/perl

use warnings;
use strict;

my @data = ();

# data.csv:
# bela,fired
# julcsi,killed
# jani,promoted

my $string_template = <<EOF;
Dear <name>,
   You have been <action>.
Br: Someone.
EOF

# CSV to hash
open FILE, "data.csv" or die $!;
while (my $line = ) {
    my %temp_hash = ();
    ($temp_hash{"name"}, $temp_hash{"action"}) = split (",", $line);
    chomp $temp_hash{"action"};
    push @data, \%temp_hash;
}
close FILE;

# replace & print
foreach (@data) {
    my $s = $string_template;
    $s=~s/<(.*?)>/$$_{$1}/g;
    print "$s\n";
}
Tagged as: Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

 

No trackbacks yet.