in reply to Mixed-up output

It looks like you forgot to seek back to the beginning of the file before you read into @index. As is, @index only holds the lines after <!-- ENDMAIN -->, so when you think you're printing the start of the file you're actually printing the end.

This isn't the best way to write the program, though. Instead of reading in the entire template, then printing out the pieces, it's simpler to loop for each section, and exit a loop when the next section starts:

#!E:/perl/bin/perl use CGI qw(:all); use strict; print header; open (TEMPLATE, "index.shtml") || die "cannot find index.shtml: $!"; while (<TEMPLATE>) { print; last if /^\s*<!-- MAIN -->.*$/; } while (<TEMPLATE>) { print, last if /^\s*<!-- ENDMAIN -->.*$/; } open (FORMTEMPLATE, 'form.txt') || die "cannot find form.txt: $!"; while (<FORMTEMPLATE>) { print; } while (<TEMPLATE>) { print; }

Replies are listed 'Best First'.
Re: Re: Mixed-up output
by Nimster (Sexton) on Jan 16, 2001 at 01:34 UTC
    OMG, Chipmunk, ovid, eg, you're all right... :~(
    I can't believe I was sitting on that silly thing for 4 hours without noticing. However, chipmunk, can you explain your solution? I see how you integrated my code better inside itself so it won't run over the same thing twice - but what you did is:
    Print template up until <!-- MAIN --> Print template from <!-- ENDMAIN --> to end. Print the contents of form.txt then print template again?
    and it will appear in that order? Am I missing something, or did you just misunderstand my initial intention of placing one within the other?

    -Nimster
      I think the second step is the one that's not clear. Here's how my solution works:
      Read and print from TEMPLATE until <!-- MAIN -->. Read but don't print from TEMPLATE until <!-- ENDMAIN -->. Read and print everything from FORMTEMPLATE. Read and print everything that's left from TEMPLATE.
      I figured that <!-- MAIN --> and <!-- ENDMAIN --> may contain some text that should be replaced by the form. The second loop just skips over all of that.
Re: Re: Mixed-up output
by repson (Chaplain) on Jan 16, 2001 at 09:14 UTC
    Speaks for itself, isn't perfect tho.
    my $printed; while (<TEMPLATE>) { if (/<!-- MAIN -->/ .. /<!-- ENDMAIN -->/) { unless ($printed) { open FORMTEMPLATE, 'form.txt' or die "cannot find form.txt: $!"; local $_; print while (<FORMTEMPLATE>) close FORMTEMPLATE; $printed++; } } else { print; } }