in reply to Auto linking to words in a text file

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

Replies are listed 'Best First'.
Re: Re: Auto linking to words in a text file
by marvell (Pilgrim) on Dec 01, 2000 at 22:28 UTC
    my $data; { local $/; #sets input list separator to undef #so we can 'slurp' the file in $data = <TEXTFILE>; } close TEXTFILE;

    Why didn't I think of that :)

    These are the sort of things I love about such forums as Perl Monks.

    --

    Brother Marvell

      If you like that then you'll probably like to know that it can be done w/ even less keystrokes:
      my $data = do { local $/; <TEXTFILE> };
      No, this isn't golf, but all the same it's a nice construct to know.
        Or even:
        { local $/=<TEXTFILE>; ## Do stuff with $/ directly }
Re: Re: Auto linking to words in a text file
by Fastolfe (Vicar) on Dec 02, 2000 at 06:20 UTC
    You probably want to take one additional step and sort each of the keys by length, doing the longest first. This would allow you to catch a link to "foo bar" as well as individual links to "foo" and "bar" without getting inconsistent results.
    foreach (sort { length($b) <=> length($a) } keys %keywords) { ... }