in reply to build mysql data structure from text file

This code seems to print out the data that you want. It's simple enough to change the code to insert the data into a database instead of printing it out.

#!/usr/local/bin/perl use strict; use warnings; my @parents = (0); my $prev_tabs = 0; while (<DATA>) { chomp; my $tabs = tr/\t//d; if ($tabs > $prev_tabs) { push @parents, $. - 1; } elsif ($tabs < $prev_tabs) { $#parents = $tabs; } print "$. : $_ : $parents[-1]\n"; $prev_tabs = $tabs; } __END__ cat1 cat1,sub1 cat1,sub1,sub-sub1 cat1,sub2 cat2 cat3 cat3,sub1
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: build mysql data structure from text file
by fireartist (Chaplain) on May 13, 2003 at 12:13 UTC
    Thanks davorg, this is just the approach that I was starting to think about. However, when I run your code (MacPerl 5.6.1), the 'parent' isn't assigned properly: I get the following output,
    1 : cat1 : 0 2 : cat1,sub1 : 0 3 : cat1,sub1,sub-sub1 : 0 4 : cat1,sub2 : 0 5 : cat2 : 0 6 : cat3 : 0 7 : cat3,sub1 : 0
    I'm going to have to look at my docs to figure this out though, as I've never used $. before.

      If you just cut and paste the code from my node, then it probably won't work as you'll need to replace the leading spaces with the appropriate number of tabs.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        I was just about to reply, saying that I'd figured out why it wasn't working!
        I checked the docs for tr///d and thought, 'why isn't it deleting the tabs?', then figured it out.
        Sorry for being so quick to claim error with your code sir.