Beefy Boxes and Bandwidth Generously Provided by pair Networks httptech
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Parse C-like define statements

by danger (Priest)
on May 29, 2002 at 18:29 UTC ( #170180=note: print w/ replies, xml ) Need Help??


in reply to Parse C-like define statements

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.


Comment on Re: Parse C-like define statements
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://170180]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2014-04-20 21:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (488 votes), past polls