[lug] Quick perl question

Chip Atkinson chip at rmpg.org
Wed Dec 11 23:28:38 MST 2002


Cool, thanks.  That got me started.  Here's what I ended up with:

#!/usr/bin/perl

use strict;

my ($slash, $file, $timestr);

$timestr = localtime();

my %substfields = (
  Lname => "Atkinson",
  Fname => "Chip",
  Addr1  => "123",
  Addr2  => "Main St.",
  Addr3  => "Erie",
  State => "CO",
  Zip   => "80516",
  Phone  => "(303)555-1212",
  Salut  => "Mr.",
  Date   => $timestr
);


$slash = $/;

$/ = undef;

$file = <>;

$/ = $slash;

$file =~s/<(\w+)>/$substfields{$1}/g;

print $file;

-------------------------
input file:
                                                     <Fname>
                                                     <Lname>
                                                     <Addr1>
                                                     <Addr2>
                                                     <Addr3><State>,<Zip>

<Date>

Dear <Salut> <Lname>,

Have we got a deal for you...

Sincerely,

Spa Mmer

----------------------------------
All the fields got substituted at once.  That was pretty darn cool.

Thanks again.

Chip




On Wed, 11 Dec 2002, Rob Nagler wrote:

> > I need to substitute some data values for some patterns in a text template
> > file and print it out.  There is only one template at a time, but multiple
> > sets of data values.
>
> This is novel. ;-)
>
> > I was thinking I could read the whole thing into a scalar and run a series
> > of pattern replacements on the scalar, but was wondering if there were
> > other methods that might be better, faster, and more powerful than ever
> > before.
>
> There are a zillion template languages.  I've written several. :)
> Template-Toolkit is quite popular.  However, depending on syntax, it
> may be faster to do:
>
>     $template =~ s/<(\$\w+)>/$1/eeg;
>
> (Yes, two e's) Where the variables are loaded in variables by name,
> e.g. $first_name, $last_name, etc.  Alternatively, you could:
>
>     $template =~ s/<\$(\w+)>/$some_hash->{$1}/g;
>
> where $some_hash is:
>
>     my($some_hash) = {
>     	first_name => "Rob",
> 	last_naem => "Nagler",
>     };
>
> or $some_hash could be "tied" to a dbm file or you could
>
> Rob
>
>
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: lug.boulder.co.us port=6667 channel=#colug
>




More information about the LUG mailing list