G'day Tony,
Welcome to the Monastery.
Using a regex to parse markup like HTML and XML is a poor idea (see "Why a regex *really* isn't good enough for HTML and XML, even for "simple" tasks").
Having said that, here's how you might have gone about this, using your three posted h2 lines
(plus a couple more I added to test additional header levels):
#!/usr/bin/env perl
use 5.014;
use warnings;
my @html = (
'<h2>2.1. Match Literal Text</h2>',
'<h3>2.1.1 H3 Heading</h3>',
'<h4>2.1.1.1 H4 Heading</h4>',
'<h2>2.2. Match Nonprintable Characters</h2>',
'<h2>2.3. Match One of Many Characters</h2>',
);
my $re = qr{^(<h[1-6])(>[1-6. ]+)([^<]+)(</h[1-6]>)$};
for my $i (0 .. $#html) {
$html[$i] =~ s{$re}{$1 . ' id="' . lc($3) =~ y/ /_/r . "\"$2$3$4"}
+e;
}
say for @html;
Output:
<h2 id="match_literal_text">2.1. Match Literal Text</h2>
<h3 id="h3_heading">2.1.1 H3 Heading</h3>
<h4 id="h4_heading">2.1.1.1 H4 Heading</h4>
<h2 id="match_nonprintable_characters">2.2. Match Nonprintable Charact
+ers</h2>
<h2 id="match_one_of_many_characters">2.3. Match One of Many Character
+s</h2>
Note that requires Perl 5.14 or later for the '/r' modifier
(see "perl5140delta: Non-destructive substitution").
You can do something similar with older versions but it requires a bit more work.
And, just for completeness, say was introduced in Perl 5.10.
Also note that modifying elements of an array while you're looping through that array can have unforeseen problems.
See how I loop through the indices of the array instead.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.