Perl Code Sample
This Perl code will help you get started using OpenAmplify with Perl. Download and remove the .txt extension to use it as a Perl file.
File has been updated for use with OpenAmplify Version 2.0
Overview:
To access the OpenAmplify API from Perl, we'll use a URI object and HTTP Request. Parameters will be set as parameters of the URI.
Setting parameters:
For flexibility and ease of readability, we'll put the parameters in an array (%aryParams). They should then be written into the URI's query_param property.
# define a URL (including variables).
my $url = new URI("http://portaltnx20.openamplify.com/AmplifyWeb_v21/AmplifyThis");
my %aryParams = (
# If you don't have an API key, you can register here: http://www.openamplify.com/user/register
'apiKey' => '12345', # Insert your API key here.
'analysis' => 'all', # all (default), actions, topics, demographics, styles.
'outputFormat' => 'xml', # xml (default), json, dart.
# select either this option or the following... not both.
#'inputText' => 'I want to buy some sushi.'
'sourceURL' => 'http://www.openamplify.com'
);
foreach (keys %aryParams) {
$url->query_param($_, $aryParams{$_});
}Issue Request:
To send our request to the OpenAmplify API we'll use an HTTP Request object. For receiving the XML we'll use a UserAgent object.
# create UserAgent object.
my $ua = new LWP::UserAgent;
$ua->timeout(15);
# do it.
my $request = HTTP::Request->new('POST');
$request->url($url);
my $response = $ua->request($request);
# response code (like 200, 404, etc): you might want to check this.
my $code = $response->code;
# headers (Server: Apache, Content-Type: text/html, ...): you probably won't need this.
my $headers = $response->headers_as_string;
# HTML body: here's what you're looking for.
my $body = $response->content;
# print the website content.
# print $body . "\n\n";Parse XML
For a full discussion of the XML output, click that link back there. You know how the Internet works.
Once we have the content back, we can take advantage of Perl's XML object for navigating and parsing the data OpenAmplify provides:
# let's take apart the XML.
my $xp = XML::XPath->new($body);
print "Topics:\n";
foreach my $topics ($xp->find('//Topic')->get_nodelist){
print "\t" . $topics->find('Name')->string_value . "\n";
}
print "Actions:\n";
foreach my $actions ($xp->find('//Action')->get_nodelist){
print "\t" . $actions->find('Name')->string_value . "\n";
}
print "Demographics:\n";
foreach my $demographics ($xp->find('//Demographics')->get_nodelist){
print "\tAge: " . $demographics->find('Age//Name')->string_value . "\n";
print "\tGender: " . $demographics->find('Gender//Name')->string_value . "\n";
print "\tEducation: " . $demographics->find('Education//Name')->string_value . "\n";
}
print "Style:\n";
foreach my $styles ($xp->find('//Styles')->get_nodelist){
print "\tSlang: " . $styles->find('Slang//Name')->string_value . "\n";
print "\tFlamboyance: " . $styles->find('Flamboyance//Name')->string_value . "\n";
}