in reply to appending to html at beginning
Hi Limbomusic,
It appears you have found some very old example code - the code you are using to get the form parameters is outdated, and your script isn't doing use warnings; use strict; at the top (see Use strict and warnings).
If you are just learning Perl / CGI scripting, there are several modern web frameworks nowadays, whose use I'd strongly recommend. For example, a good starting point is Mojolicious::Guides::Tutorial. The "old" CGI module, which is the way a script like the one you've shown would handle form parameters, is no longer recommended for new developments.
Anyway, moving on to your question: Your open is using a mode of '>>', which is "append mode", that's why anything you write to the filehandle $fh is being inserted at the end of the file. If you wanted to insert lines at the top of a file, there are several ways to do so. However, simply inserting lines at the top of the file will break the HTML, so instead you'd need to insert the lines at the correct place instead. One way to do this would be to insert a marker comment at the proper place in the file, like <!-- INSERT HERE -->, and then one relatively easy way to insert lines in the middle of a file is Tie::File (see also the documentation of splice).
#!/usr/bin/env perl use warnings; use strict; my $filename = 'test.html'; my @to_insert = ( '<p>Hello,', 'World! It is '.gmtime(time).' UTC</p>' ); use Tie::File; tie my @lines, 'Tie::File', $filename or die "tie $filename: $!"; my $found; for (my $i=0; defined($lines[$i]); $i++) { if ($lines[$i]=~/<!--\s*INSERT\s+HERE\s*-->/i) { $found=1; splice @lines, $i+1, 0, @to_insert; last; } } die "Marker not found" unless $found; untie @lines;
Update: Code now inserts current time to make the order of updates to the file more clear.
Note that there are more "modern" ways to accomplish this instead of editing an HTML file. For example, you could store new "stories" in a file or a database on the server, and then when someone wants to see the list of stories, build the HTML page to display them dynamically. This has the advantages that you could allow for the user to select a range of stories, easily change the display format, etc. Even more advanced and "modern" techniques would be to provide the "stories" in JSON format, and then have JavaScript in the browser dynamically retrieve and display them. However, if you are just getting started, then the above is a good first step before going into these advanced techniques.
Hope this helps,
-- Hauke D
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: appending to html at beginning
by Limbomusic (Acolyte) on Feb 03, 2017 at 08:58 UTC | |
by hippo (Archbishop) on Feb 03, 2017 at 09:18 UTC | |
by haukex (Archbishop) on Feb 03, 2017 at 09:20 UTC | |
by Discipulus (Canon) on Feb 03, 2017 at 09:27 UTC | |
by haukex (Archbishop) on Feb 03, 2017 at 09:46 UTC |