Perl - Add analytics snippet to batch of static html files

Sometimes it is necessary to measure hits on static html files. But having to add a small snippet of Javascript to a bunch of static files can be a real repetitive pain.

This is precisely the kind of thing that can be easily solved in a few lines of Perl. Here's one way to do it:

use strict; 
use warnings;
 
my $d = ".";
 
opendir(D, "$d") || die "Can't open dir $d: $!\n";
my @list = readdir(D);
closedir(D);
 my $analyticssnippet = '<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-1");
pageTracker._trackPageview();
} catch(err) {}</script>';
 
foreach my $f (@list) {
	print "$f\n";
	open OUT, "> output/".$f; 
	open (MYFILE, $f);
		while (<MYFILE>) {
			chomp;
			if($_ =~ /<\/\s*(body|BODY)>/){
				print OUT  $analyticssnippet . "\n$_\n";				
			}else{
				print OUT "$_\n";			
			}
		}
	close (MYFILE);
	close (OUT);
}
 
Reply:
 
 
 
 
rendered @ Thu May 23 7:16:04 CEST 2013