All pastes #190435 Raw Edit

tinyurl module

public text v1 · immutable
·published 2006-10-03 23:55 UTC
rendered paste body
#!/usr/bin/perl

# Version 1.0
# written by modulus schmodulus
# 06/07/06

use strict;
my $no_tinyurl;
#my $target_url = $ARGV[0];

BEGIN {
    eval qq{
        use LWP::UserAgent;
        use HTTP::Request::Common qw(POST GET);
    };
    $no_tinyurl++ if($@);
}

sub tinyurl {
  my $url = $_[0];
  my $newurl;
  my $Converter = 'http://tinyurl.com/create.php';
  my $ua = new LWP::UserAgent;
    $ua->agent("Mozilla/4.5 " . $ua->agent);            # we are ie haters.
    $ua->timeout(10);

  return "tinyurl.pl: not configured. needs LWP::UserAgent and HTTP::Request::Common" if( $no_tinyurl );

  my $req = POST $Converter,
    [   name    => 'f',
        url     => $url,
        submit  => 'Make TinyURL!',
    ];

    my $res = $ua->request($req);                   # Submit request

    if ($res->is_success) {                         # Went through ok
        my $html = $res->as_string;
        # the line that i need to parse for the tinyurl:
        #<blockquote><b>http://tinyurl.com/6b5m</b><p><small>[<a href="http://tinyurl.com/6b5m" target="_blank">Open in new window</a>]</small></p></blockquote>
        if ($html =~ /\[<a href=\"(http\:\/\/tinyurl.com\/[^\"]+)\" target=\"_blank\">/ ){
          $newurl = $1;
        }
    } else {
      $newurl = "Oops. Something borked while trying to connect to http://www.tinyurl.com";
    }
    return $newurl;
}

1;