This is the kind of thing I wish everybody could write for themselves.
It automated a simple, repetitive task that Beatrice was spending a lot
of time on.  I wrote most of it in a few minutes, and then she finished
it.

#!/usr/bin/perl -w
use strict;
# script to help beatrice with her web pages
# comments for perl newbies

# ARGLEBARGLE marks the end of $stylelinks
# "my" creates a new variable
my $stylelinks = <<ARGLEBARGLE;
     <link href="../css/global.css" rel="stylesheet" type="text/css">
     <link rel="shortcut icon" href="../../paisley.ico">
ARGLEBARGLE

# similarly with SIMILARLY
my $sidebar = <<SIMILARLY;
<ul class="first"> 
        <li><a href="../animals/index.html"><h2 
localizable="true">Animals</h2></a></li>
        <li><a href="../architecture/index.html"><h2 
localizable="true">Architecture</h2></a></li>
        <li><a href="../light/index.html"><h2 
localizable="true">Light</h2></a></li>
        <li><a href="../macros/index.html"><h2 
localizable="true">Macros</h2></a></li>
        <li><a href="../performances/index.html"><h2 
localizable="true">Performances</h2></a></li>
        <li><a href="../plants/index.html"><h2 
localizable="true">Plants</h2></a></li>
        <li><a href="../../index.html"><h2 localizable="true">Home</h2></a></li>
SIMILARLY

sub mogrify_file {
  my ($input_filename, $output_file) = @_;
  # creates a variable $file, opens the file for input (<), and sticks
  # the open file in $file
  open my $file, "<", $input_filename or die "Can't open $input_filename: $!";

  # <$file> reads a line from the open file and sticks it in $_
  while (<$file>) {
    if (/<h2/) {              # /foo/ looks for "foo" in $_, returns true if 
found
      print $output_file $sidebar;
    } elsif (/rel="stylesheet"/) {
      print $output_file $stylelinks;
    } elsif (/CC-Attribution/) {
      print $output_file ' <p localizable="true"><a 
href="http://creativecommons.org/licenses/by-sa/3.0/";>CC-Attribution 3.0</a> 
Beatrice Murch</p>';
    } else {
      print $output_file $_;
    }
  }
}

sub dirname {
  my ($filename) = @_;
  # chop off slashes followed by zero or more (*) nonslashes ([^/]) at
  # the end ($)
  $filename =~ s|/[^/]*$||;
  return $filename;
}

die unless (dirname "fixed/foo/bar/baz.html") eq "fixed/foo/bar";

sub ensure_dir_exists {
  my ($filename) = @_;
  my $dirname = dirname($filename);
  # invoke shell command mkdir -p fixed/foo/bar
  system "mkdir", "-p", $dirname;
}

sub create_new_file_from {
  my ($filename) = @_;
  my $newfilename = "fixed/$filename";
  ensure_dir_exists($newfilename);
  open my $output, ">", $newfilename or die "Can't open $newfilename: $!";
  mogrify_file($filename, $output);
}

die "no files" unless @ARGV;
for my $file (@ARGV) {
  create_new_file_from($file);
}

Reply via email to