perlwww-mechanizelwp-useragent

Extracting cookies from cookie_jar by cookie name


What I'm struggling with is why LWP::UserAgent doesn't provide an accessor so that I can just get everything I want to know about a cookie in the cookie_jar by providing the cookie's name. I realize there is the scan() method on cookie_jar, but it seems like a lot of overhead to provide a callback for something so basic. This is what I have right now:

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dump qw (dump);
use WWW::Mechanize;

my $mech = WWW::Mechanize->new;
$mech->get( 'http://www.nytimes.com' );

my %cookies = (); 
$mech->cookie_jar->scan( \&check_cookies );

dump \%cookies;

sub check_cookies {
    my @args = @_; 
    $cookies{ $args[1] } = { 
        version   => $args[0],
        val       => $args[2],
        path      => $args[3],
        domain    => $args[4],
        port      => $args[5],
        path_spec => $args[6],
        secure    => $args[7],
        expires   => $args[8],
        discard   => $args[9],
        hash      => $args[10],
    };  
} 

The output of the script is something like this:

{   adxcs => {
        discard   => 1,
        domain    => ".nytimes.com",
        expires   => undef,
        hash      => {},
        path      => "/", 
        path_spec => 1,
        port      => undef,
        secure    => undef,
        val       => "-", 
        version   => 0,
    },       
    RMID => {
        discard   => undef,
        domain    => ".nytimes.com",
        expires   => 1374340257,
        hash      => {},
        path      => "/", 
        path_spec => 1,
        port      => undef,
        secure    => undef,
        val       => "02b4bc821c00500991212ba2",
        version   => 0,
    },       
}

So, that gives me easy access to a cookie by name, but I was wondering if there's an easier way to do this or if there's a helpful module I just don't know about.


Solution

  • $cookies->scan(sub  
    { 
      if ($_[1] eq $name) 
      { 
        print "$_[1] @ $_[4] = $_[2]\n"; 
      }; 
    }); 
    

    Output would be for example:

    sessionID @ www.nytimes.com = 1234567890
    

    Edit: >>

    sub getCookieValue
    {
      my $cookies = $_[0];
      my $name = $_[1];
      my $result = null;
      $cookies->scan(sub  
      {  
        if ($_[1] eq $name) 
        { 
          $result = $_[2];
        }; 
      });
      return $result;
    }
    

    and use it like so:

    print getCookieValue($cokies, 'sessionID');