shaileshsp has asked for the wisdom of the Perl Monks concerning the following question:

Hi all the gurus,
i am really new to perl(4days only),i have a problem of reading a text file and inserting the data into my SQL database table the file looks somthing like below:
[1] 01:01:14:13 01:01:16:20 [GP=1][GP0:L=2;P=0;J=0;SNG=0;STY=0;X=0;Y=0] Forced OUR APPRECIATION [2] 01:01:16:22 01:01:20:12 [GP=1][GP0:L=2;P=0;J=0;SNG=0;STY=0;X=0;Y=0] Forced OF THE STATE OF NEW MEXICO, [3] ..... ..
i have to read each block, and each block contains 7 lines only and this pattern is followed throughout the text file. Does anybody have a sample code that i could follow or know any links to good reference material

anytype of feedback will be highly appreciated..

thanks,
shailesh

Edit by tye

Replies are listed 'Best First'.
(ar0n) Re: reading from txt file and inserting into database tables
by ar0n (Priest) on Jun 12, 2001 at 01:51 UTC
    Well, for starters, I'd suggest you take a look at open, split, strict and DBI.

    You may also want to read perlre, in case you need regular expressions for matching your data.

    The following is similiar to what you may be trying to achieve:
    # enable strict syntax use strict; # load the DBI module (for database connectivity) use DBI; # open connection to database. when you use strict, you # need to declare your variables with 'my'. this a good # thing. trust me. my $dbh = DBI->connect("DBI:mysql:databasename", "user", "password", { +RaiseError => 1}); # create a statement handle. the question marks a # placeholders, which simply denote the place you'll # put your data my $sth = $dbh->prepare("INSERT INTO table (column1, column2) VALUES ( +?, ?)"); open FH, "myfile.txt" or die "Can't open myfile.txt: $!\n"; until ( eof FH ) { my @data; for (1..7) { my $line = <FH>; # slurp in new line chomp; # remove trailing newline character push @data, $line; # add current line to data array } # # do stuff with @data # # actually the data insert into the database $sth->execute( $var1, $var2 ); } close FH; $dbh->disconnect();
    It's a sketch. It won't work, but it'll get you started. And buy a book! Programming Perl's pretty good :)

    ar0n ]


    update: you're right; i forgot to add $dbh->disconnect(). too used to apache::dbi, i guess ;)
      ar0n, I'm also learning DBI.
      Since the die comes after the "DBI->connect" I was wondering whether the DBI needs any special handling to close the database connections?

      Or does that get handled in the wash?

      I know your code was not intended to be complete. But this looked like a good place to ask for a little clarificaion. I have the Programming with DBI book coming from Amazon. It should be here early next week.

      Thanks
      Claude

        DBI is clever enough to disconnect from the database when the program finishes, though it might complain about it.

        Good you get that book, it's great!