http://qs321.pair.com?node_id=11119538


in reply to Calling sub-routine in regex

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

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.