The Foursquare gaming code challenge

Mayank Lahiri writes a Foursquare checkin tool in nine Perl statements, and Alex Ford says he has a two line solution, where line means statement, and statement. Part of the reason their solutions look so ugly is that they want to do it with the Standard Library. I was slightly interested in this because someone had asked Randal if he was checking in with Perl (he is not).

Larry Wall once said that he could program anything in one-line of Perl given a sufficiently long line. That is, in a language where lines aren't significant, line count is stupid. If you want to count lines, Python is probably your language.

Faking a Foursquare checking is not straightforward with LWP, which actually makes this problem a little more interesting. The Foursquare API uses either Basic or OAuth authorization, but it doesn't think about web browsers. It figures that your application doesn't need a prompt (i.e. a 403 response) for an authorization header, so there is no authorization realm. This means that LWP's credentials method is useless. However, I can use the add_handler method to fix up the request to force the Authorization header:

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;

# The Foursquare API doesn't have a 403 response, so it has
# no realm. This means I have to force the authorization
# header.
$ua->add_handler( 
    request_prepare => sub { 
        my( $request, $ua, $h ) = @_;
        $request->authorization_basic( @ENV{ qw(FOURSQUARE_USER FOURSQUARE_PASS) } );
        },
    );

$ua->post( 
    'http://api.foursquare.com/v1/checkin', 
    Content => {
        vid     => $ARGV[0] || 8212918,  # The Perl Review
        private => 0,
        geolat  => $ARGV[1] ||  42.01974,
        geolong => $ARGV[2] || -87.67446,
        }
    );

My script isn't exactly the same as theirs, though. I'll let cron handle the other details.

Leave a comment

About brian d foy

user-pic I'm the author of Mastering Perl, and the co-author of Learning Perl (6th Edition), Intermediate Perl, Programming Perl (4th Edition) and Effective Perl Programming (2nd Edition).