Connecting Tech Pros Worldwide Help | Site Map

splitting a file by a character

Newbie
 
Join Date: Jan 2009
Posts: 3
#1: May 2 '09
I got a multiline SQL file that I would like to split by ; and read into an array. However when I try to do
Expand|Select|Wrap|Line Numbers
  1. my @array = split(";", <FH>);
  2.  
and iterate over each element I get just the first line of the SQL file.

Does anyone know how they would get the array of sql statements (and no new lines)?
Icecrack's Avatar
Expert
 
Join Date: Sep 2008
Location: Sydney, Australia
Posts: 173
#2: May 4 '09

re: splitting a file by a character


so far what is all your code or at least how are you reading the next line of the sql file?

have you tried a while loop?
Newbie
 
Join Date: Jan 2009
Posts: 3
#3: May 4 '09

re: splitting a file by a character


I've solved this problem since I last posted here. Thanks for the response though. Here's what I used:
Expand|Select|Wrap|Line Numbers
  1. my $line = "";
  2. my $currentCommand = "";
  3. while(defined($line = <SCHEMA>)) {
  4.     $line =~ s/[\t\n]*//g;
  5.     # append to the current sql command
  6.     $currentCommand = $currentCommand . $line;
  7.     if($line =~ /;/) {
  8.         # this line ends an sql command, execute
  9.         $sth = $dbh->prepare($currentCommand);
  10.         $sth->execute();
  11.         # reset the current line
  12.         $currentCommand = "";
  13.     }
  14. }
  15. close(SCHEMA);
  16.  
numberwhun's Avatar
Site Moderator
 
Join Date: May 2007
Location: New Hampshire
Posts: 2,565
#4: May 13 '09

re: splitting a file by a character


Your code, upon issuing the execute statement, will fetch the first row from sql, but what about each subsequent row? To do that, you will have to incorporate the fetchrow_array method in a loop.
Newbie
 
Join Date: Jan 2009
Posts: 3
#5: May 14 '09

re: splitting a file by a character


Quote:

Originally Posted by numberwhun View Post

Your code, upon issuing the execute statement, will fetch the first row from sql, but what about each subsequent row? To do that, you will have to incorporate the fetchrow_array method in a loop.

I'm sorry I forgot to mention in the title what those sql statements were. I'm not fetching anything from the database using this code. I'm issuing statements to create sql tables and such to postgresql using the DBI.
Reply

Tags
file, perl, split