Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Parsing by indentation

by atcroft (Abbot)
on Oct 24, 2018 at 20:18 UTC ( #1224612=note: print w/replies, xml ) Need Help??

in reply to Parsing by indentation

Some time back I had to do something similar. While I am not able to pull example code at the moment, what I did was basically the following:

    1. Read each line from the config into a file.
    2. Keep a count of the number of leading spaces on each line in a hash.
  1. Compute the greatest common factor (gcf) of the non-zero leading space counts.

I then processed the array of entries using the ( number of leading spaces / GCF ) value to determine indentation level.

For the example configuration you show, the indentation would show as the following:

%indentation = ( '0' => 1, '2' => 3, '4' => 2, );

Because I was potentially looking at multiple indentation levels, I believe I did something like the following to get the common indentation width:

# Yes, sometimes I write code in ways to make sure _I_ # remember what I was doing when I come back to it later. sub gcf { my ( $i, $j ) = sort { $b <=> $a} @_; return( abs( $j ) ) if ( $i == 0 ); return( abs( $i ) ) if ( $j == 0 ); return( abs( gcf( $j, $i % $j ) ); } my $common_indent_factor = 1; my @data = sort { $b <=> $a } keys %indentation; while ( scalar @data ) { my $f_1 = shift @data; my $f_2 = shift @data; my $f_temp = $common_indentation_factor = gcf( $f_1, $f_2 ); push @data, $f_temp; }

This resulted in a common indentation factor of 2, which agrees with the observed.

Hope that helps.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2021-01-25 02:29 GMT
Find Nodes?
    Voting Booth?