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.

— Ken


In reply to Re: Calling sub-routine in regex by kcott
in thread Calling sub-routine in regex by tonydunn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.