next up previous contents index
Next: TCL/TK (PGTCLSH/PGTKSH) Up: Programming Interfaces Previous: Scripting Languages

  
Perl

Figure [*] shows our state code application in Perl.  

        
        #!/usr/local/bin/perl
        #
        #   Perl sample program
        #
         
        use Pg;                                                 # load database routines
         
        $conn = Pg::connectdb("dbname=test");                   # connect to the database
                                                                # did the database connection fail?
        die $conn->errorMessage unless PGRES_CONNECTION_OK eq $conn->status;
         
        print "Enter a state code: ";                           # prompt user for a state code
        $state_code = <STDIN>;
        chomp $state_code;
         
        $result = $conn->exec(                                  # send the query
                "SELECT name \
                 FROM statename \
                 WHERE code = '$state_code'");
                                                                # did the query fail?
        die $conn->errorMessage unless PGRES_TUPLES_OK eq $result->resultStatus;
         
        while (@row = $result->fetchrow) {                      # loop through all rows returned
                print @row, "\n";                               # print the value returned
        }
        
 

Perl is a good choice for writing scripts and small applications. It is popular for processing text files and generating dynamic Web pages using CGI  (Common Gateway Interface). A Perl/DBI interface is also available. 


Bruce Momjian
2001-05-09