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.


In reply to Re: Parsing by indentation by atcroft
in thread Parsing by indentation by llarochelle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.