raison.org.uk

Perl Tutorials

I have been learning the Perl scripting language recently, and thought it would be useful to have some tutorials here. Let's start with some basics.

MySQL Databases

To connect to a MySQL database, use this code:

use DBI;
my $dbh = DBI->connect("DBI:mysql:database=dbname;host=localhost","username", "password",{'RaiseError' => 1});


To do a query using prepared statements, use this code:

my $query = "insert into table1 (field1, field2, field3) values (?, ?, ?)";
my $statement = $dbh->prepare($query);
$statement->execute(value1,value2,value3);


To do a Select query and return the results, use this code:

my $sth = $dbh->prepare( "SELECT * FROM table1" );
$sth->execute();

my $row;
while ($row = $sth->fetchrow_hashref() ) {
      print "$row->{field1} $row->{field2} $row->{field3}\n";
}


And finally, to close the connection, use this code:

$dbh->disconnect();

JSON

JSON is used alot in accessing data from a remote server using API's. To decode the received JSON into something usable, we use the Perl JSON library. Some example code:

use JSON;
use Data::Dumper;

my $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

my $text = decode_json($json);
print Dumper($text);


This will create the following output:

$VAR1 = {
      'e' => 5,
      'c' => 3,
      'a' => 1,
      'b' => 2,
      'd' => 4
};


You can then access individual elements like this:

print $text->{b};