http://qs321.pair.com?node_id=1224612


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.