Reputation: 163
I can't seem to figure out how to print just some of the return values such as: title
, url
, content
#!/usr/bin/perl
print "Content-type: text/html\n\n";
use REST::Google;
# set service to use
REST::Google->service('http://ajax.googleapis.com/ajax/services/search/web');
# provide a valid http referer
REST::Google->http_referer('http://www.example.com');
my $res = REST::Google->new(
q => 'ice cream',
);
die "response status failure" if $res->responseStatus != 200;
my $data = $res->responseData;
use Data::Dumper;
print Dumper( $data );
my @results = $data->results;
# CANT MAKE THIS WORK
foreach my $r (@result) {
print "\n";
print $r->title;
print $r->url;
print $r->content;
}
Upvotes: 0
Views: 327
Reputation: 5279
#!/usr/bin/perl
use strict;
print "content-type: text/html\n\n";
use REST::Google;
# set service to use
REST::Google->service(
'http://ajax.googleapis.com/ajax/services/search/web' );
# provide a valid http referer
REST::Google->http_referer( 'http://www.example.com' );
my $res = REST::Google->new( q => 'ice cream', );
die "response status failure" if $res->responseStatus != 200;
my $data = $res->responseData;
my @results = @{ $data->{results} };
foreach my $r ( @results ) {
print "\n";
print $r->{title};
print $r->{url};
print $r->{content};
}
A couple of problems here:
1) $data is not an object, so you can't treat it like an object.
$data->results would be the correct syntax if you're calling a method on an object. In this case $data is just a regular HASHREF, so the syntax is:
$data->{results}
2) $data->{results} is an ARRAYREF and not an ARRAY. So, you need to de-reference it in order to get at the values.
Now, my @results = $data->{results} becomes:
my @results = @{ $data->{results} };
@{ ARRAYREF } is how you dereference the array.
3) As you're iterating over @results, you're once again using the object syntax. However, the values of @results are also just plain HASHREFs. So, $r->title becomes:
$r->{title}
Using a tool like Data::Dumper to inspect return values can be key in sorting this kind of thing out. You may also want to look at Data::Printer, which is even sexier than Data::Dumper
Upvotes: 0
Reputation: 561
Try:
foreach my $r (@results) {
note the "s" -- if you put at the top of your script:
use strict;
use warnings;
you will catch these things
Upvotes: 2