Your method was almost there --- you just need to make the
following change:
# change this:
$defines{$_} =~ s/<(\w+)>/$defines{$1}/g;
# to this:
1 while $defines{$_} =~ s/<(\w+)>/$defines{$1}/g;
Doing just a single s///g can still leave you with unresolved
defines (when the substituted text contains unresolved defines).
Using the '1 while...' version continues to reapply the regex
until all of the defines are resolved (or forever in the case of
circular relationships). Here is an alternate version of your
routine that returns a reference to the resolved %defines hash
rather than a single option:
#!/usr/bin/perl -w
use strict;
sub parse_defines {
my $file = shift;
open(FILE, $file) || die "can't open $file: $!";
my %defines;
while(<FILE>){
next unless /^#DEFINE\s+<(\w+)>\s+(.*)/;
$defines{$1} = $2;
}
for (values %defines) {
1 while s/<(\w+)>/$defines{$1}/;
}
return \%defines;
}
my $opts = parse_defines('defs.txt');
my $file = $opts->{FILE};
print "$file\n";
Note: it also loops through and modifies the hash values in place
rather than accessing each one via a key --- IIRC, having values
return the actual values instead of copies is a 5.6ism, so you may
stick with your method of looping over the keys for portability.
-
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.
|