Posted By

engel on 02/21/08


Tagged

url shorten tinyurl xrl metamark


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

mzim
jonhenshaw


shortLink


 / Published in: Perl
 

Easily and quickly shorten URLs from the command line. Utilizes TinyURL and MetaMark APIs.

  1. #!/usr/bin/perl
  2.  
  3. package shortLink;
  4.  
  5. use Getopt::Std;
  6. use LWP::UserAgent;
  7. use strict;
  8. use Switch;
  9.  
  10. our($opt_s, $opt_u);
  11.  
  12. getopts('s:u:');
  13.  
  14. help_message() unless $opt_u;
  15. $opt_s = ( !$opt_s ) ? "tinyurl" : $opt_s;
  16.  
  17. switch ( $opt_s ) {
  18. case "tinyurl" {
  19. makeUA();
  20. my $r = $shortLink::ua->get('http://tinyurl.com/api-create.php?url=' . $opt_u);
  21. print errorCheck($r) . "\n";
  22. }
  23. case "metamark" {
  24. makeUA();
  25. my $r = $shortLink::ua->post('http://metamark.net/api/rest/simple', { long_url => $opt_u });
  26. print errorCheck($r) . "\n";
  27. }
  28. else {
  29. help_message();
  30. }
  31. }
  32.  
  33. sub errorCheck {
  34. my $response = shift;
  35. if ( $response->is_success ) {
  36. return $response->content;
  37. } else {
  38. return "There was an error: " . $response->status_line . "\n";
  39. }
  40. }
  41.  
  42. sub help_message {
  43. print "Usage: shortlink [ -s service ] -u url\n -s service\tSpecify URL shortener service to use. Possible values:\n\t\t\ttinyurl\n\t\t\tmetamark\n";
  44. }
  45.  
  46. sub makeUA {
  47. $shortLink::ua = LWP::UserAgent->new;
  48. }

Report this snippet  

You need to login to post a comment.