Perl Example 3 --- insert links

The following Perl script inserts html links for a list of key words in a html file. In the example used here, the link will be pointing to the Entrez PubMed of NCBI. Here is a web page before and after inserting linkes to PubMed.

#!perl
# This program adds PubMed links to selected keywords. 

#input name of the file to be read from command line
$infile = @ARGV[0];

#input name of the output file from command line
$outfile = @ARGV[1];

#remind user there is no input file
if(!$infile) {
  print "No input file.\nUsage: perl my_perl.pl infile outfile\n";
}

#the array of keywords, change to your own
@keywords = ('Alzheimer', 'statins', 'degenerative brain disorder');

# For each keyword, it will be replaced by
# <a href= "http://www3.ncbi.nlm.nih.gov/htbin-post/Entrez/query?db=0&form=1&term= keyword"> keyword </a>

# url for the Entrez PubMed page
$baseUrl = "http://www3.ncbi.nlm.nih.gov/htbin-post/Entrez/query?db=0&form=1&term=";

#read the input file if given
if($infile) {
  
  # open inputfile
  open(IN, $infile) or die "can not open $infile\n";

  #read the file
   while( $line = <IN> ) {
  
     # join all the lines in the file
     $content .= $line; 
   }

  close(IN) or die "can not close $infile\n";

  # remove extra blank spaces
  $content =~ s/\s+/ /g;

  # insert link for each keyword
  foreach $keyword (@keywords) {
    $linkcode  = "<a href=\"".$baseUrl.$keyword."\">".$keyword."</a>";
    $content =~ s/$keyword/$linkcode/g;
  }

  #if output file name provided
  if($outfile) {
    open(OUT, ">$outfile") or die "can not open $outfile";
    print OUT "$content\n";
    close(OUT) or die "can not close $outfile";
  } 
  # else print to screen
  else {
     print "$content\n"
  }

}