vnpenguin has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I would like to write a simple script to do a simple(?) template. I make a template file like:

Section %N1% Sub-section %N2%

By giving N1=1,2 and N2=1,3 I got:

Section 1 Sub-section 1 Sub-section 2 Sub-section 3 Section 2 Sub-section 1 Sub-section 2 Sub-section 3
This is my code:
#!/usr/bin/perl my ($file,$n1,$n2,$tpl); $file = shift; $n1 = shift; $n2 = shift; open(F,'<',$file) || die; while(<F>){ $tpl .= $_; } close(F); if ($n2){ for($i1=1;$i1<=$n1;$i1++){ for($i2=1;$i2<=$n2;$i2++){ $str = $tpl; $str =~ s/%N1%/$i1/gi; $str =~ s/%N2%/$i2/gi; print $str; } } } elsif($n1){ for($i1=1;$i1<=$n1;$i1++){ $str = $tpl; $str =~ s/%N1%/$i1/gi; print $str; } }
And I run:
./script.pl templatefile 2 3

I'm not Perl coder, just a Perl's fan "amateur". I think there is undoubtedly better way to do this. So I would like to learn from you :)

Thanks,

Replies are listed 'Best First'.
Re: simple template ?
by merlyn (Sage) on Sep 10, 2006 at 13:01 UTC
    use Template; my ($n1, $n2) = @ARGV; Template->new->process(\*DATA, { n1 => $n1, n2 => $n2 }) or die Templa +te->error; __END__ [% FOR i1 = [1 .. n1] -%] Section [% i1 %] [% FOR i2 = [1 .. n2] -%] Subsection [% i2 %] [% END -%] [% END -%]

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Thanks,

      I'll have a look at Template.

Re: simple template ?
by madbombX (Hermit) on Sep 10, 2006 at 16:16 UTC
    If your template is always the same layout. You can always consider using Perl formatting Perl6::Form. The formatting can fill in your data and produce a nice looking report.

    Eric

      For Perl 6 ? Oh, I have not yet release 6 of Perl on my systems (SuSE/FC5 linux and WinXP). I have only 5.8.x here.

      Thanks.

        It's a Perl 5 module that emulates a Perl 6 feature. It will work with 5.8.x.

Re: simple template ?
by gloryhack (Deacon) on Sep 11, 2006 at 00:33 UTC
    If you don't need anything so heavyweight as the Template Toolkit, you might give a look at CGI::FastTemplate. Don't let CGI in the name fool you: It doesn't actually have anything to do with CGI at all. It's fairly lightweight, easy enough to learn, and relatively fast, too.
Re: simple template ?
by mav3067 (Beadle) on Sep 10, 2006 at 20:19 UTC
    My comment is not so much on how to do what you want since the above posts give very good suggestions, but only on your coding style. I would suggest adding the lines
    use strict; use warnings;
    as well as I would look into using Getopt::Long for getting your command line input.
    cheers, mav