A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

How to checkout hosted subversion project

Google code:

svn checkout https://example.googlecode.com/svn/trunk/ example_directory --username example@gmail.com

Assembla:

svn checkout https://subversion.assembla.com/svn/example/ example_directory --username your_username


Timing out a call to a remote service in Perl

#!/usr/bin/perl

use strict;
use warnings;

select STDERR; $| = 1;
select STDOUT; $| = 1;

my $server = 'remote server';

my $timeout = 3;
my $retries = 3;
my $retry = 1;
my $con = 0; # connection object
my $err; # error message
while (not $con and not $err and $retry <= $retries) {
    print "starting block...\n";

    eval {
        print "eval'ing\n";
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm $timeout;
        # make connection to server
        sleep $timeout + 1; # fake
        # if we reached here, the connection was successful
        alarm 0;
    };
    if ($@) {
        if ($@ eq "alarm\n") {
            # timed out
            print "Timed out $retry time(s) connecting to $server\n";
        }
        else {
            print "died unexpectedly\n";
            $err = $@;
            $err =~ s' at /[\w\./]+\.pm line \d+$'' if $err;
        }
    }
    else {
        print "No problem!!!\n";
        $con = 1;
    }
    $retry++;
}


print "ERROR: $err\n" if $err;

print "finished. connection = '$con'\n";

Parse XML in PHP

http://php.net/manual/en/function.file-get-contents.php - fetch URL
http://php.net/manual/en/simplexmlelement.xpath.php - parse XML
http://www.php.net/manual/en/simplexml.examples-basic.php - register namespaces, etc.

Example for Google calendar. Most important parts are the namespaces and (string) casting.

    $contents = file_get_contents($calendar_url); // should end with 'full', not 'basic'
    $xml = new SimpleXMLElement($contents);

    $namespaces = $xml->getDocNamespaces();
    $xml->registerXPathNamespace('__empty_ns', $namespaces['']);
    $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005'); # xmlns:gd='http://schemas.google.com/g/2005'

    $entries = $xml->xpath("//__empty_ns:entry");
    while(list( , $node) = each($entries)) {
        $time_nodes = $node->xpath("gd:when/@startTime");
        while ($time_node = each($time_nodes)) {
            # <gd:when endTime="2011-08-19T17:00:00.000+01:00" startTime="2011-08-19T14:00:00.000+01:00"></gd:when>

            $time_text = (string)$time_node[1]->startTime;

            die "time = $time_text\n";

Parse HTML with Ruby and Nokogiri


doc = Nokogiri::HTML(open(filename, 'r'))
puts doc.xpath('//title')[0].inner_html
puts doc.xpath('//h2')

Ruby: Read+write to database


require 'sqlite3'

db = SQLite3::Database.new( "db1" )
db.execute('INSERT INTO table_name (id, text) VALUES (1, "hello")')
db.execute( "SELECT* FROM table_name" ) do |row|
    puts row.inspect
end