That should read as follows:



use strict;
use warnings;

use Tie::File;
use File::Copy 'copy';
use File::Spec;

my $dir = '/path/to/my/directory';

opendir my ($dh), $dir;

# Find all files in the directory that match \d{6}\.htm
# Die if none or multiple files found
#
my @files = grep /\A\d{6}\.htm\z/i, readdir $dh;
die 'No matching files found' unless @files;
die 'Multiple matching files found' if @files > 1;
my $file = File::Spec->catfile($dir, $files[0]);

# Copy the file for safety
# Tie it to an array
#
(my $copy = $file) =~ s/(\.htm)\z/ - Copy$1/i;
copy $file, $copy;
tie my @lines, 'Tie::File', $copy;

my $index;

# Find the first line starting with <a class="nolinkunderline"
# Remove it and the following line
#
($index) = grep $lines[$_] =~ /\A<a class="nolinkunderline"/, 0 .. $#lines;
die 'No class="nolinkunderline" found' unless $index;
splice @lines, $index, 2;

# Find the first line equal to <pre>
# Append the contents of the file with the same name and a .txt type
#
($index) = grep $lines[$_] eq '<pre>', 0 .. $#lines;
die 'No <pre> found' unless $index;
(my $txtfile = $file) =~ s/\.htm/.txt/i;
my $text = do {
  open my $fh, '<', $txtfile or die qq{Unable to open "$txtfile": $!};
  local $/;
  <$fh>;
};
$lines[$index] .= $text;

# Find the first line equal to </div></body>
# Replace it with the contents of the DATA segment
#
($index) = grep $lines[$_] eq '</div></body>', 0 .. $#lines;
die 'No </div></body> found' unless $index;
chomp(my @replace = <DATA>);
splice @lines, $index, 1, @replace;

untie @lines;

__DATA__
</div>
<script type="text/javascript">
var sc_project=8607440;
var sc_invisible=1;
var sc_security="f3cd5e09";
var scJsHost = (("https:" == document.location.protocol) ?
"https://secure."; : "http://www.";);
document.write("<sc"+"ript type='text/javascript' src='" +
scJsHost+
"statcounter.com/counter/counter.js'></"+"script>");
</script>
<noscript><div class="statcounter"><a title="web analytics"
href="http://statcounter.com/"; target="_blank"><img
class="statcounter"
src="http://c.statcounter.com/8607440/0/f3cd5e09/1/";
alt="web analytics"></a></div></noscript>
</body>


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to