I want to use Perl to loop through a file (or an array), start processing elements when a regular expression is matched and stopping processing when another regular expression is met.
One way to do it is to have a variable used as a flag (=1 when starting regex is met, and =0 when ending regex is met).
For example, the following works but is awfully ugly!!
use strict;
my @file = (
"<title>List of widgets</title>\n",
"<widgets>\n",
" <button>widget001.xml</button>\n",
" <textArea>widget002.xml</textArea>\n",
" <menu>widget002.xml</menu>\n",
"</widgets>\n",
"<footer>\n",
" This is the footer\n",
"</footer>\n",
);
my $in_list_widgets = 0;
for my $line (@file) {
if ($line=~m%<widgets%) {
$in_list_widgets = 1;
} elsif ($line=~m%</widgets>%) {
$in_list_widgets = 0;
} else {
if ($in_list_widgets == 1) {
&process_line($line);
} else {
#Do nothing
}
}
}
sub process_line {
my $line = shift;
print $line;
}
What would be a more elegant way to do it and still get the same result?
<button>widget001.xml</button>
<textArea>widget002.xml</textArea>
<menu>widget002.xml</menu>
Thanks