Perl array example - search replace in a Perl array

I was just modifying a Perl program so I could use a regular expression (regex) to search a Perl array for all less-than (<) and greater-than (>) symbols, and replace those with their HTML equivalents tags ("&lt;", and "&gt;", respectively).

Here's the source code I created to perform this Perl array search and replace operation (a Perl replace regex operation):

open(MY_FILE,$fileName);
my @fileContents = (<MY_FILE>);
close(MY_FILE);

for (@fileContents) 
{
  s/>/&gt\;/;
  s/</&lt\;/;
}

This Perl program does the following:

  1. Open a file, where the file is given by the variable $fileName.
  2. Read the contents of the file into the Perl array variable named @fileContents.
  3. Closes the file.
  4. Loops through each element in the @fileContents array, and does the desired Perl search and replace operations (using the regular expressions shown).

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.