I wish to process a text file (a couple hundred lines long), which represents a category structure using leading tabs,
cat1 cat1,sub1 cat1,sub1,sub-sub1 cat1,sub2 cat2 cat3 cat3,sub1
and put it into a mysql table in the following format.
------------------------------------ | id | name | parent | ------------------------------------ | 1 | cat1 | 0 | | 2 | cat1,sub1 | 1 | | 3 | cat1,sub1,sub-sub1 | 2 | | 4 | cat1,sub2 | 1 | | 5 | cat2 | 0 | | 6 | cat3 | 0 | | 7 | cat3,sub1 | 6 | ------------------------------------
I know there's a maximum of 6 'tab's at the start of any line, so there's a maximum of 7 levels of categories.
I tried using seven variables $a = $b = $c = $d = $e = $f = $g = 0 and a nest of seven for loops... and ended up with something very messy.
I'm sure there must be a way to do this that doesn't rely on me knowing the max depth.
My thinking so far has been to get the data into an array-of-array's, such as
my @x = ('cat1', ['cat1,sub1', ['cat1,sub1,sub-sub1'], 'cat1,sub2'], 'cat2', 'cat3', ['cat3,sub1'], );
Then 'walk' it in some such way as,
$x[0] is SCALAR 1/0 (id/parent) $x[1] is ARRAY $x[1][0] is SCALAR 2/1 $x[1][1] is ARRAY $x[1][1][0] is SCALAR 3/2 $x[1][1][1] isn't defined $x[1][2] is SCALAR 4/1 $x[1][3] isn't defined $x[2] is SCALAR 5/0 $x[3] is SCALAR 6/0 $x[4] is ARRAY $x[4][0] is SCALAR 7/6 $x[4][1] isn't defined $x[5] isn't defined
and somehow assign those id/parent variables.
I just can't figure out how to do this and would appreciate any help or hints of how to approach it.

In reply to build mysql data structure from text file by fireartist

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.