12Aug/090
String templates with Perl
Here is a nice thing with perl.
- You have a string template, like an e-mail, with fields to change.
- This fields are stored in a CVS file.
- 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";
}
Leave a comment