Perl Notes/Perl Templating Example: Difference between revisions

From Federal Burro of Information
Jump to navigationJump to search
(Created page with "Template: <pre> <VirtualHost *:80> ServerName OLDHOST DocumentRoot /var/www/html <Directory "/var/www/html"> Order allow,deny ...")
 
No edit summary
Line 38: Line 38:
                 print $host;
                 print $host;
         }
         }
}
</pre>
also (from http://matetelki.com/blog/?p=71 ):
<pre>
#!/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";
}
}
</pre>
</pre>

Revision as of 15:24, 23 April 2014

Template:

<VirtualHost *:80>
        ServerName OLDHOST
        DocumentRoot /var/www/html
        <Directory "/var/www/html">
                Order allow,deny
                Allow from all
        </Directory>
        ProxyPass /     http://NEWHOST/
</VirtualHost>

Script:


#!/usr/bin/perl -w

use strict;

my $template ;
{
  local $/=undef;
  open FILE, "virtualtemplate.tmpl" or die "Couldn't open virtualtemplate.tmpl: $!";
  # binmode FILE;
  $template = <FILE>;
  close FILE;
}

while (<>){
        if ( /(\S+):(\d+) (\S+)/ ) {
                my $old = $1;
                my $port = $2;
                my $new = $3;
                my $host = $template;
                $host =~ s/OLDHOST/$old/g;
                $host =~ s/NEWHOST/$new/g;
                print $host;
        }
}

also (from http://matetelki.com/blog/?p=71 ):

#!/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";
}