One way of doing it would be defining a hash whose keys are the keywords (the ones you want to provide links for) -- this will work with phrases too, BTW -- and whose values are URIs or URLs. Then just use s///g to do it (that's the quick n' dirty way).
#!/usr/bin/perl -w
use strict;
my %keywords = ( foo=>'/foo.html',
bar=>'bar.html',
cult=>'http://perlmonks.org'
);
my $textfile ="/file/to/link";
open TEXTFILE, $textfile or die "Yikes! $textfile won't open: $!\n";
my $data;
{
local $/; #sets input list separator to undef
#so we can 'slurp' the file in
$data = <TEXTFILE>;
}
close TEXTFILE;
foreach (keys %keywords) {
my $url = $keywords{$_};
# EDITED ... I'd forgotten to escape
# the / in front of the closing <a>
# credit to Albannach
$data =~ s/($_)/<a href="$url">$1<\/a>/g;
}
# now do something with $data
But that's *oh so quick* and *oh so dirty*, it probably raises a lot of problems and only works on very simple kinds of words (e.g. if you have phrases in your keywords hash, you could really mess things up).
UPDATE Implementing something like this site's linking mechanism wouldn't be so hard. just put delimiters around the words / phrases you want to link, and something like the above should work fairly well. E.g. [bob] would say 'put a link around "bob"' (what link, you could determine in a number of ways, but the hash idea seems to work well enough.)
Just alter the above substitution line to:
$data =~ s/\[($_)]<a href="$url">$1<\/a>/g;
Bonus: that takes care of phrases, too. (credit for this idea goes to whathisname
Seems like there must be a module that does something like this (I'll go to CPAN and give you an update)
Philosophy can be made out of anything. Or less -- Jerry A. Fodor |