Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Friday, April 03, 2009

Trim a string in perl

problem:
I am a perl noob and i need trim a string.

solution:
1) if i can modify the actual string:
sub trim {$_[0] =~s/^\s+|\s+$//g}

2)if i don't want it to modify:
sub trim {my $s = $_[0]; $s=~s/^\s+|\s+$//g;return $s;}

Sunday, February 08, 2009

Using jQuery with NYT JSON API

New York Times recently made public a great API that lets you search all of their articles from 1981 to present, and get the data back in JSON format.
I decided to use this API to add some relevant news stories to a site i have been working on. I was going to use jQuery to pull the data using $.getJSON() and shove it into some divs on my site.

Problem:
I quickly ran into a problem. NYT is retuning plain JSON, not JSONP. JSONP is needed to do cross-domain JSON calls. jQuery will make a jsonp call if you add the following to the request url:
jsoncallback=?
In the background, what happens is that jQuery replaces the ? with a function is creates, for example jsonp1229009. jQuery is expecting a response of:

but new york times is returning:

When jQuery pulls that response into a script tag, and executes in, i get the following error in firefox: "Invalid Label".

Solution:
What i needed was a JSONP wrapper. Luckly, i have a friend who knows perl =) I asked him to write a service that will take 2 params: url and callback. Where URL is an encoded URL i am requesting, and callback is the param to wrap the response in. It worked out nicely, i can now use ANY JSON API and get JSONP back. This is the perl source:



Here is my crude and incomplete jQuery plugin that gets me a couple of articles with predefined fields and displays them on my site:



i call it like this:

Thursday, April 10, 2008

Escape cp-1252 chars in HTML

This is for when people paste crap from MS Word into html and add all those funky characters that looks horrible.

My friend gave me this perl one liner (ok, you can use it as a one liner if you wanted to) to escape the the evil CP-1252 characters in your HTML.

Notes for porting:
ord($1) converts capture group 1 to ASCII.
assumes $str has your html

Bonus!
the above regex replaces control chars!

Thursday, December 13, 2007

the most useful program in the world




clear&&perl -e'$|=1;@l=qw{| / - \\};while(){print
qq{$l[$_++%@l]\x0d};select($z,$z,$z,.2*(rand(2)**2))}'


i can think of like 9 uses for this already!