Development
ALTer
Freshness Warning
This blog post is over 21 years old. It's possible that the information you read below isn't current and the links no longer work.
24 Sep 2003
I’m working on a site and realized that I had left off the alt text from some of my images. Going through several hundred pages looking for images that didn’t contain the alt text didn’t sound like much fun, so I whipped up a quick Perl script to add the text for me.
The program walks through a directory and opens every file ending with .html or .htm. Then it looks for image tags without alt attributes and adds them in. The alt text that it adds comes from a pipe-delimited data file containing image file names followed by the alt text. If the program comes across an image that doesn’t have an alt attribute and it isn’t listed in the data file, an empty alt attribute is inserted. Image tags that already have alt attributes are ignored.
To use the program, create a text file that looks like this:
someimage.jpg|Some Imagelogo.gif|Kalseyyomama.jpg|Your Mother
Then run the Perl app like so…
ALTer.pl /path/to/data_file.txt /path/to/search/inside/
Please note: This is provided with no warranty or tech support whatsoever. Make backups. If you come across a problem, I probably won’t be able to help you. The code is licensed under the MIT License, copyright 2003 Kalsey Consulting Group.
Here’s the contents of ALTer.pl
#!/usr/bin/perluse File::Find;use strict;my $directory = './';my $data_file;my @valid_extensions = ('\.html?');my %texts;$directory = $ARGV[1] if $ARGV[1];$data_file = $ARGV[0];open (DATA, $data_file) or die "Can’t open $data_file: $!";while (<DATA>) { chomp; my ($src, $alt) = split /\|/; $texts{$src} = $alt;}chomp($directory);$directory =~ s/\\/\//g;find(\&add_alt, $directory);sub add_alt() { my $file = $File::Find::name; my @html; my $blnValidType = 0; # skip directories return if(-d $file); # only insert alt text if this is an HTML file foreach(@valid_extensions) { if($file =~ m/$_$/) { $blnValidType = 1; last; } } return if($blnValidType == 0); chomp($file); open(IN, $file) || die "Cannot open $file for reading: $!"; @html = <IN>; close(IN); my $line = join("\n", @html); $line =~ s+<img([^>]*)?>+ my $orgtxt = $1; if($1 !~ /alt\=\"/) { my $alttxt = ''; if ($1 =~ m/src="([^"]*)/) { local $_ = $1; s/^.*(\\|\/)//; $alttxt = $texts{$_}; } "<img alt=\"$alttxt\" $orgtxt>"; } else { "<img$orgtxt>"; } +egs; open (OUT, ">$file"); print OUT $line; close OUT;}