in reply to Small Code Snippet from PHP to Perl

After looking past what I thing was probably a bug, the steps for solving this using DBI are:

  1. Start your script with use strict; use warnings; use autodie; use DBI;
  2. Ask DBI to connect to the database using the DBD::mysql driver, obtaining a database handle.
  3. With the database handle, use DBI's "do()" method to perform your query, obtaining a statement handle.
  4. Open your output file using the three-arg open.
  5. With the statement handle, within the conditional of a while(){} loop, invoke DBI's fetchrow_hashref() method, obtaining a hashref for one query row.
  6. Inside the while loop's block, write your output using print in its print FILEHANDLE LIST; format. Use the filehandle obtained by open.
  7. After the end of the while loop (outside/after the main block), close the output filehandle using close.

If there is any possibility that this script might be run concurrently with another process that also touches the same output file, be sure to properly flock your output file.

Additional reading: perlintro, open, perlsyn (for a discussion of while loops), perlsub (for a discussion of lexical variables), DBI, perlopentut, print, close, flock.

Each of the seven steps above is a small amount of code. With the exception of step one, we're talking about a single statement or line of code per step. It would take fewer keystrokes for me to just write it for you than it does for me to explain it, but that's not what PerlMonks is here for. This site is for educational, and arguably recreational purposes. Let me know which step you get stuck on, and provide the code you've written so far, and I'll gladly help you get past the tricky part.


Dave