in reply to Tricky Parsing Ko'an

This was quite a bit shorter before I threw in all the comments.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %vars; my $data = do{ local $/; <DATA> }; # first, get the items that have a set of UI elements while ( $data =~ s/ (\S+) # non-spaces -- the type \s+ # spaces (\S+) # non-spaces -- the name \s+ # spaces (including newlines) \< # opening angle thingy \s+ # spaces (including newlines) ( # start capturing the UI stuff (?: # grouping UI lines \S+ # non-spaces -- the UI stuff type \s+ # spaces UI\S+ # UI name \s*=\s* # equal sign, maybe spaces .* # anything except a newline \;\s* # traling semicolon, optional spaces (including new +line) )+ # UI lines repeat ) # capture all the UI lines \s* # optional spaces (including newline) \> # ending angle thingy \s*=\s* # equal sign, maybe spaces (.*) # the main variable value \; # trailing semicolon //mx ) { my ( $main_type, $main_varname, $ui_stuff, $main_value ) = ( $1, $2, $3, $4 ); my $ui_ref = {}; # pull out the individual UI elements while ( $ui_stuff =~ s/ \S+ # non-spaces -- the ui element type \s+ # spaces UI(\S+) # UI element name \s*=\s* # equal sign, maybe spaces (.*) # UI element value \; # trailing semicolon //mx ) { my ( $name, $value ) = ( $1, $2 ); # lowercase the name $name =~ tr/A-Z/a-z/; $ui_ref->{$name} = $value; } $vars{ $main_varname }{ type } = $main_type; $vars{ $main_varname }{ value } = $main_value; $vars{ $main_varname }{ ui } = $ui_ref; } # get the rest of the stuff that doesn't have UI thingies while ( $data =~ s/ (\S+) # type \s+ # spaces (\S+) # name \s*=\s* # equal, maybe spaces (.*) # value \; # trailing semicolon //mx ) { my ( $type, $name, $value ) = ( $1, $2, $3 ); $vars{$name}{value} = $value; $vars{$name}{type} = $type; } print Dumper( \%vars ); __DATA__ float myVarA < float UIMin = 1; float UIMax = 0; float UIStep = .001; string UIWidget = "slider"; > = 0.5f; float myVarB = 1.0; float4 myVarC = {1,0,0,1};

Output:

$VAR1 = { 'myVarA' => { 'ui' => { 'step' => '.001', 'min' => '1', 'max' => '0', 'widget' => '"slider"' }, 'value' => '0.5f', 'type' => 'float' }, 'myVarC' => { 'value' => '{1,0,0,1}', 'type' => 'float4' }, 'myVarB' => { 'value' => '1.0', 'type' => 'float' } };

There are a few loose ends still (the trailing "f" on the float value, for instance), but those should be easy to clean up.

Replies are listed 'Best First'.
Re^2: Tricky Parsing Ko'an
by jmmistrot (Sexton) on Jan 25, 2007 at 06:29 UTC
    Awesome thanks!