tags:

views:

305

answers:

2

I'm trying to use the Net::OAuth module to authorise with the Yammer API and I have the following code snippet, pretty much taken from the Synopsis on CPAN.

$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
my $q = new CGI;

my $request = Net::OAuth->request("request token")->from_hash($q->Vars,
                request_url => $self->_request_token_url,
                request_method => $q->request_method,
                consumer_secret => $self->consumer_private,
            );

But if I try and run my test it throws an error as follows:

Expected a hash! at /Library/Perl/5.8.8/Net/OAuth/Message.pm line 241.

Have I made an obvious syntax error or am I going to have to look at the OAuth module itself?

+1  A: 

In the Net::OAuth::Message

sub from_hash {
    my $proto = shift;
    my $class = ref $proto || $proto;
    my $hash = shift;
    if (ref $hash ne 'HASH') {
        die 'Expected a hash!';
    }
    my %api_params = @_;

Maybe you can make sure that $q->Vars returns a hash ref

my $vars = $q->Vars;
print ref($vars);
ccheneson
+3  A: 

$q->Vars returns a hash reference in scalar context and a flattened hash in list context. Subroutine arguments create list context. Therefore, you should do:

my $request = Net::OAuth->request("request token")->from_hash(
      scalar $q->Vars,
      request_url => $self->_request_token_url,
      request_method => $q->request_method,
      consumer_secret => $self->consumer_private,
);

Thanks to Adam Bellaire for the comment that made me check this.

Sinan Ünür
I thought this at first too, but it isn't right. Look at the source linked by ccheneson, only the first argument is expected to be a hash reference, the rest are pulled from @_ into a separate hash.
Adam Bellaire
Besides, that's an odd number of elements in a hash constructor ;)
Adam Bellaire
It is not an odd number of elements because $q->Vars returns a flattened hash in list context. But that was the key to the solution. See my edited answer.
Sinan Ünür
Oh, I should have realized! Nicely done. :)
Adam Bellaire