ActivePerl Documentation
Table of Contents

(Usage Statistics)
(about this ver)

* Getting Started
    * Welcome To ActivePerl
    * Release Notes
    * Readme
    * ActivePerl Change Log
* Install Notes
    * Linux
    * Solaris
    * Windows
* ActivePerl Components
    * Overview
    * PPM
    * Windows Specifics
       * OLE Browser
       * PerlScript
       * Perl for ISAPI
       * PerlEZ
* ActivePerl FAQ
    * Introduction
    * Availability & Install
    * Using PPM
    * Docs & Support
    * Windows Specifics
       * Perl for ISAPI
       * Windows 9X/NT/2000
       * Quirks
       * Web Server Config
       * Web programming
       * Programming
       * Modules & Samples
       * Embedding & Extending
       * Using OLE with Perl
* Windows Scripting
    * Active Server Pages
    * Windows Script Host
    * Windows Script Components

Core Perl Documentation

* perl
* perlfaq
* perltoc
* perlbook

* perlsyn
* perldata
* perlop
* perlreftut
* perldsc
* perllol

* perllexwarn
* perldebug

* perlrun
* perlfunc
* perlopentut
* perlvar
* perlsub
* perlmod
* perlpod

* perlstyle
* perlmodlib
* perlmodinstall
* perltrap
* perlport
* perlsec

* perlref
* perlre
* perlform
* perllocale
* perlunicode

* perlboot
* perltoot
* perltootc
* perlobj
* perlbot
* perltie

* perlipc
* perlnumber
* perlfork
* perlthrtut

* perldiag
* perlfaq1
* perlfaq2
* perlfaq3
* perlfaq4
* perlfaq5
* perlfaq6
* perlfaq7
* perlfaq8
* perlfaq9

* perlcompile

* perlembed
* perlxstut
* perlxs
* perlguts
* perlcall
* perlfilter
* perldbmfilter
* perlapi
* perlintern
* perlapio
* perltodo
* perlhack

* perlhist
* perldelta
* perl5005delta
* perl5004delta

* perlamiga
* perlcygwin
* perldos
* perlhpux
* perlmachten
* perlos2
* perlos390
* perlvms
* perlwin32


* attributes
* attrs
* autouse
* base
* blib
* bytes
* charnames
* constant
* diagnostics
* fields
* filetest
* integer
* less
* lib
* locale
* lwpcook
* open
* ops
* overload
* perllocal
* re
* sigtrap
* strict
* subs
* utf8
* vars
* warnings


* ActivePerl
    * DocTools
        * TOC
            * RDF
* AnyDBM_File
* Archive
    * Tar
* AutoLoader
* AutoSplit
* B
    * Asmdata
    * Assembler
    * Bblock
    * Bytecode
    * C
    * CC
    * Debug
    * Deparse
    * Disassembler
    * Lint
    * Showlex
    * Stackobj
    * Terse
    * Xref
* Benchmark
* Bundle
    * LWP
* ByteLoader
* Carp
    * Heavy
    * Apache
    * Carp
    * Cookie
    * Fast
    * Pretty
    * Push
    * Switch
* Class
    * Struct
* Compress
    * Zlib
* Config
    * FirstTime
    * Nox
* Cwd
* Data
    * Dumper
* DB
* Devel
    * DProf
    * Peek
    * SelfStubber
* Digest
    * HMAC
    * HMAC_MD5
    * HMAC_SHA1
    * MD2
    * MD5
    * SHA1
* DirHandle
* Dumpvalue
* DynaLoader
* English
* Env
* Errno
* Exporter
    * Heavy
* ExtUtils
    * Command
    * Embed
    * Install
    * Installed
    * Liblist
    * MakeMaker
    * Manifest
    * Miniperl
    * Mkbootstrap
    * Mksymlists
    * MM_Cygwin
    * MM_OS2
    * MM_Unix
    * MM_VMS
    * MM_Win32
    * Packlist
    * testlib
* Fatal
* Fcntl
* File
    * Basename
    * CheckTree
    * Compare
    * Copy
    * CounterFile
    * DosGlob
    * Find
    * Glob
    * Listing
    * Path
    * Spec
        * Functions
        * Mac
        * OS2
        * Unix
        * VMS
        * Win32
    * stat
* FileCache
* FileHandle
* FindBin
* Font
    * AFM
* Getopt
    * Long
    * Std
    * AsSubs
    * Element
    * Entities
    * Filter
    * Form
    * FormatPS
    * Formatter
    * FormatText
    * HeadParser
    * LinkExtor
    * Parse
    * Parser
    * TokeParser
    * TreeBuilder
    * Cookies
    * Daemon
    * Date
    * Headers
        * Util
    * Message
    * Negotiate
    * Request
        * Common
    * Response
    * Status
* I18N
    * Collate
* IO
    * Dir
    * File
    * Handle
    * Pipe
    * Poll
    * Seekable
    * Select
    * Socket
        * INET
        * UNIX
    * Msg
    * Open2
    * Open3
    * Semaphore
    * SysV
    * Debug
    * MediaTypes
    * MemberMixin
    * Protocol
    * RobotUA
    * Simple
    * UserAgent
* Math
    * BigFloat
    * BigInt
    * Complex
    * Trig
* MD5
    * Base64
    * QuotedPrint
* NDBM_File
* Net
    * Cmd
    * Config
    * Domain
    * DummyInetd
    * FTP
    * hostent
    * libnetFAQ
    * netent
    * Netrc
    * NNTP
    * PH
    * Ping
    * POP3
    * protoent
    * servent
    * SMTP
    * SNPP
    * Time
* O
* ODBM_File
* Opcode
* Pod
    * Checker
    * Find
    * Html
    * InputObjects
    * Man
    * Parser
    * ParseUtils
    * Plainer
    * Select
    * Text
        * Color
        * Termcap
    * Usage
    * SOAPClient
    * SOAPServer
* Safe
* SDBM_File
* Search
    * Dict
* SelectSaver
* SelfLoader
* Shell
    * Defs
    * Envelope
    * EnvelopeMaker
    * GenericHashSerializer
    * GenericInputStream
    * GenericScalarSerializer
    * Lite
    * OutputStream
    * Packager
    * Parser
    * Transport
        * HTTP
            * Apache
            * CGI
            * Client
            * Server
        * LOCAL
        * MAILTO
        * POP3
        * TCP
    * TypeMapper
* Socket
* Symbol
* Sys
    * Hostname
    * Syslog
* Term
    * ANSIColor
    * Cap
    * Complete
    * ReadLine
* Test
    * Harness
* Text
    * Abbrev
    * ParseWords
    * Soundex
    * Tabs
    * Wrap
* Thread
    * Queue
    * Semaphore
    * Signal
    * Specific
* Tie
    * Array
    * Handle
    * Hash
    * RefHash
    * Scalar
    * SubstrHash
* Time
    * gmtime
    * Local
    * localtime
    * tm
    * Lite
    * data
    * Escape
    * file
    * Heuristic
    * ldap
    * URL
    * WithBase
* User
    * grent
    * pwent
* Win32
    * AuthenticateUser
    * ChangeNotify
    * Clipboard
    * Console
    * Event
    * EventLog
    * File
    * FileSecurity
    * Internet
    * IPC
    * Mutex
    * NetAdmin
    * NetResource
    * ODBC
    * OLE
        * Const
        * Enum
        * NEWS
        * NLS
        * TPJ
        * Variant
    * PerfLib
    * Pipe
    * Process
    * Registry
    * Semaphore
    * Service
    * Sound
    * TieRegistry
* Win32API
    * File
    * Net
    * Registry
    * RobotRules
        * AnyDBM_File
    * Element
    * Parser
        * Expat
    * PPD
    * PPMConfig
    * ValidatingElement
* XSLoader

 WWW::Search - Virtual base class for WWW searches


WWW::Search - Virtual base class for WWW searches


  • Windows
This module is not included with the standard ActivePerl distribution. It is available as a separate download using PPM.


    require WWW::Search;
    $search_engine = "AltaVista";
    $search = new WWW::Search($search_engine);


This class is the parent for all access methods supported by the WWW::Search library. This library implements a Perl API to web-based search engines.

See README for a list of search engines currently supported.

Search results can be limited, and there is a pause between each request to avoid overloading either the client or the server.

Sample program

Using the library should be straightforward. Here is a sample program:

    my $search = new WWW::Search('AltaVista');
    while (my $result = $search->next_result()) 
      print $result->url, "\n";

Results are objects of type WWW::SearchResult (see the WWW::SearchResult manpage for details). Note that different backends support different result fields. All backends are required to support title and url.


For specific search engines, see the WWW::Search::TheEngineName manpage (replacing TheEngineName with a particular search engine).

For details about the results of a search, see the WWW::SearchResult manpage.



To create a new WWW::Search, call

    $search = new WWW::Search('SearchEngineName');

where SearchEngineName is replaced with a particular search engine. For example:

    $search = new WWW::Search('Google');

If no search engine is specified a default (currently 'AltaVista') will be chosen for you. The next step is usually:


reset_search (PRIVATE)

Resets internal data structures to start over with a new search.


Returns the value of the $VERSION variable of the backend engine, or $WWW::Search::VERSION if the backend does not contain $VERSION.


Returns the value of the $MAINTAINER variable of the backend engine, or $WWW::Search::MAINTAINER if the backend does not contain $MAINTAINER.


Specify a query to the current search object; the query will be performed with the engine's default options, as if it were typed by a user in a browser window.

The query must be escaped; call escape_query in the WWW::Search manpage to escape a plain query. See native_query below for more information.

Currently, this feature is supported by only a few backends; consult the documentation for each backend to see if it is implemented.


Specify a query (and optional options) to the current search object. Previous query (if any) and its cached results (if any) will be thrown away. The option values and the query must be escaped; call the WWW::Search::escape_query() manpage to escape a string. The search process is not actually begun until results or next_result is called (lazy!), so native_query does not return anything.


                        { option1 => 'able', option2 => 'baker' } );

The hash of options following the query string is optional. The query string is backend-specific. There are two kinds of options: options specific to the backend, and generic options applicable to multiple backends.

Generic options all begin with 'search_'. Currently a few are supported:

Specifies the base URL for the search engine.

Enables backend debugging. The default is 0 (no debugging).

Enables backend parser debugging. The default is 0 (no debugging).

Specifies the HTTP method (GET or POST) for HTTP-based queries. The default is GET

search_to_file FILE
Causes the search results to be saved in a set of files prefixed by FILE. (Used internally by the test-suite, not intended for general use.)

search_from_file FILE
Reads a search from a set of files prefixed by FILE. (Used internally by the test-suite, not intended for general use.)

Some backends may not implement these generic options, but any which do implement them must provide these semantics.

Backend-specific options are described in the documentation for each backend. In most cases the options and their values are packed together to create the query portion of the final URL.

Details about how the search string and option hash are interpreted might be found in the search-engine-specific manual pages (WWW::Search::SearchEngineName).

After native_query, the next step is usually:

    @results = $search->results();


    while ($result = $search->next_result()) {
        # do_something;


Some backends indicate how many hits they have found. Typically this is an approximate value.


Return all the results of a query as a reference to array of SearchResult objects. Example:

    @results = $search->results();
    foreach $result (@results) {
        print $result->url(), "\n";

On error, results() will return undef and set response() to the HTTP response code.


Call this method repeatedly to return each result of a query as a SearchResult object. Example:

    while ($result = $search->next_result()) 
      print $result->url(), "\n";

On error, next_result() will return undef and set response() to the HTTP response code.


Return the HTTP Response code for the last query (see the HTTP::Response manpage). If the query returns undef, errors could be reported like this:

    my $response = $search->response();
    if ($response->is_success) {
        print "normal end of result list\n";
    } else {
        print "error:  " . $response->as_string() . "\n";

Note: even if the backend does not involve the web it should return HTTP::Response-style codes.


Set which result next_result should return (like lseek in Unix). Results are zero-indexed.

The only guaranteed valid offset is 0, which will replay the results from the beginning. In particular, seeking past the end of the current cached results probably will not do what you might think it should.

Results are cached, so this does not re-issue the query or cause IO (unless you go off the end of the results). To re-do the query, create a new search object.




The maximum number of hits to return. Queries resulting in more than this many hits will return the first hits, up to this limit. Although this specifies a maximum limit, search engines might return less than this number.

Defaults to 500.

Example: $max = $search->maximum_to_retrieve(100);


The maximum length of time any portion of the query should take, in seconds.

Defaults to 60.

Example: $search->timeout(120);


This function provides an application a place to store one opaque data element (or many via a Perl reference). This facility is useful to (for example), maintain client-specific information in each active query when you have multiple concurrent queries.


Escape a query. Before queries are made special characters must be escaped so that a proper URL can be formed. This is like escaping a URL, but all non-alphanumeric characters are escaped and and spaces are converted to ``+''s.

Example: $escaped = WWW::Search::escape_query('+hi +mom');

    (Returns "%2Bhi+%2Bmom").

See also unescape_query. NOTE that this is not a method, it is a plain function.


Unescape a query. See escape_query for details.

Example: $unescaped = WWW::Search::unescape_query('%22hi+mom%22');

    (Returns '"hi mom"').

NOTE that this is not a method, it is a plain function.


Given a string, returns a copy of that string with HTML tags removed. This should be used by each backend as they insert the title and description values into the SearchResults.

hash_to_cgi_string (PRIVATE)

Given a reference to a hash of string => string, constructs a CGI parameter string that looks like 'key1=value1&key2=value2'.

Backends should use this function rather than piecing the URL together by hand, to ensure that URLs are identical across platforms and software versions.


    $self->{_options} = {
                         'opt3' => 'val3',
                         'search_url' => '',
                         'opt1' => 'val1',
                         'QRY' => $native_query,
                         'opt2' => 'val2',
    $self->{_next_url} = $self->{_options}{'search_url'} .'?'. 


Set-up an HTTP proxy (for connections from behind a firewall).

This routine should be called before the first retrieval is attempted.



user_agent($NON_ROBOT) (PRIVATE)

This internal routine creates a user-agent for derived classes that query the web. If $NON_ROBOT, a normal user-agent (rather than a robot-style user-agent) is used.

Backends should use robot-style user-agents whereever possible. Also, backends should call user_agent_delay between every page retrieval to avoid swamping search-engines.

http_request($method, $url)

Return the response from an http request, handling debugging. Requires that user_agent already be set up. For POST methods, query is split off of the URL and passed in the request body.

split_lines (PRIVATE)

This internal routine splits data (typically the result of the web page retrieval) into lines in a way that is OS independent.

generic_option (PRIVATE)

This internal routine checks if an option is generic or backend specific. Currently all generic options begin with 'search_'. This routine is not a method.

setup_search (PRIVATE)

This internal routine does generic Search setup. It calls native_setup_search to do backend specific setup.

user_agent_delay (PRIVATE)

Derived classes should call this between requests to remote servers to avoid overloading them with many, fast back-to-back requests.

absurl (PRIVATE)

An internal routine to convert a relative URL into a absolute URL. It takes two arguments, the 'base' url (usually the search engine CGI URL) and the URL to be converted. Returns a URI::URL object.

retrieve_some (PRIVATE)

An internal routine to interface with native_retrieve_some. Checks for overflow.


Returns the value of the $TEST_CASES variable of the backend engine. All backends should set $TEST_CASES to a string containing perl code which will be eval-ed during 'make test'. See for an example.


WWW::Search supports backends to separate search engines. Each backend is implemented as a subclass of WWW::Search. the WWW::Search::AltaVista manpage provides a good sample backend.

A backend must have the two routines native_retrieve_some and native_setup_search.

native_retrieve_some is the core of a backend. It will be called periodically to fetch URLs. It should retrieve several hits from the search service and add them to the cache. It should return the number of hits found, or undef when there are no more hits.

Internally, native_retrieve_some typically sends an HTTP request to the search service, parse the HTML, extract the links and descriptions, then save the URL for the next page of results. See the code for the AltaVista implementation for an example.

native_setup_search is invoked before the search. It is passed a single argument: the escaped, native version of the query.

The front- and backends share a single object (a hash). The backend can change any hash element beginning with underscore, and {response} (an HTTP::Response code) and {cache} (the array of WWW::SearchResult objects caching all results). Again, look at one of the existing web search backends as an example.

If you implement a new backend, please let the authors know.


The bugs are there for you to find (some people call them Easter Eggs).

Desired features:

A portable query language.
A portable language would easily allow you to move queries easily between different search engines. A query abstraction is non-trivial and unfortunately will not be done anytime soon by the current maintainers. If you want to take a shot at it, please let me know.


WWW::Search was written by John Heidemann, <>. WWW::Search is currently maintained by Martin Thurn, <>.

backends and applications for WWW::Search were originally written by John Heidemann, Wm. L. Scheding, Cesare Feroldi de Rosa, and GLen Pringle.


Copyright (c) 1996 University of Southern California. All rights reserved.

Redistribution and use in source and binary forms are permitted
provided that the above copyright notice and this paragraph are
duplicated in all such forms and that any documentation, advertising
materials, and other materials related to such distribution and use
acknowledge that the software was developed by the University of
Southern California, Information Sciences Institute.  The name of the
University may not be used to endorse or promote products derived from
this software without specific prior written permission.


 WWW::Search - Virtual base class for WWW searches