Programming, using and understanding

Pike

by Fredrik Hübinette

Preface

This book was written with the intention of making anybody with a little programming experience able to use Pike. It should also be possible to gain a deep understanding of how Pike works and to some extent why it works the way does from this book. It will teach you how to write your own extensions to Pike. I have been trying for years to get someone else to write this book, but since it seems impossible without paying a fortune for it I will have to do it myself. A big thanks goes to
Ian Carr-de Avelon and Henrik Wallin for helping me iron out some of the rough spots. The book assumes that you have programmed some other programming language before and that you have some experience of UNIX.

Table of contents

Preface
Table of contents
Introduction
Overview
The history of Pike
A comparison with other languages
What is Pike
How to read this manual
1 Getting started
1.1 Your first Pike program
1.2 Improving hello_world.pike
1.3 Further improvements
1.4 Control structures
1.5 Functions
1.6 True and false
1.7 Data Types
2 A more elaborate example
2.1 Taking care of input
2.1.1 add_record()
2.1.2 main()
2.2 Communicating with files
2.2.1 save()
2.2.2 load()
2.2.3 main() revisited
2.3 Completing the program
2.3.1 delete()
2.3.2 search()
2.3.3 main() again
2.4 Then what?
2.5 Simple exercises
3 Control Structures
3.1 Conditions
3.1.1 if
3.1.2 Switch
3.2 Loops
3.2.1 while
3.2.2 for
3.2.3 do-while
3.2.4 foreach
3.3 Breaking out of loops
3.3.1 break
3.3.2 continue
3.3.3 return
3.4 Exercises
4 Data types
4.1 Basic types
4.1.1 int
4.1.2 float
4.1.3 string
4.2 Pointer types
4.2.1 array
4.2.2 mapping
4.2.3 multiset
4.2.4 program
4.2.5 object
4.2.6 function
4.3 Sharing data
4.4 Writing data types
5 Operators
5.1 Arithmetic operators
5.2 Comparison operators
5.3 Logical operators
5.4 Bitwise/set operators
5.5 Indexing
5.6 The assignment operators
5.7 The rest of the operators
5.8 Operator precedence
5.9 Operator functions
6 Object orientation
6.1 Terminology
6.2 The approach
6.3 How does this help?
6.4 Pike and Object Orientation
6.5 Inherit
6.6 Multiple inherit
6.7 Pike Inherit compared to other languages
6.8 Modifiers
6.9 Operator Overloading
6.10 Simple exercises
7 Miscellaneous functions
7.1 sscanf
7.2 catch & throw
7.3 gauge
7.4 typeof
8 Modules
8.1 How to use modules
8.2 Where do modules come from?
8.3 The . operator
8.4 How to write a module
8.5 Simple exercises
9 File I/O
9.1 Stdio.File
9.2 Stdio.FILE
9.3 Standard streams
9.4 Other Stdio functions
9.5 Listening to sockets
9.6 A more complex example - a simple WWW server
10 Threads
10.1 Starting a thread
10.2 Threads reference section
10.3 Threads example
11 Modules for specific data types
11.1 String
11.2 Array
12 Image
12.1 Image.colortable
12.2 Image.font
12.3 Image.image
12.4 Image.GIF
12.5 Image.PNM
13 Other modules
13.1 System
13.2 Process
13.3 Regexp
13.4 Gmp
13.5 Gdbm
13.6 Getopt
13.7 Gz
13.8 Yp
13.9 MIME
13.9.1 Global functions
13.9.2 The MIME.Message class
13.9.2.1 Public fields
13.9.2.2 Public methods
13.10 Simulate
14 The preprocessor
15 All the builtin functions
Appendix A Terms and jargon
Appendix B Register program
Appendix C Reserved words
Appendix D BNF for Pike
Appendix E How to install Pike
Index

Introduction

This introduction will give you some background about Pike and this book and also compare Pike with other languages. If you want to start learning Pike immediately you can skip this chapter.

Overview

This book is designed for people who want to learn Pike fast. Since Pike is a simple language to learn, especially if you have some prior programming experience, this should benefit most people.

Chapter one is devoted to background information about Pike and this book. It is not really necessary to read this chapter to learn how to use and program Pike, but it might help explain why some things work the way they do. It might be more interesting to re-read the chapter after you have learned the basics of Pike programming. Chapter two is where the action starts. It is a crash course in Pike with examples and explanations of some of the basics. It explains the fundamentals of the Pike data types and control structures. The systematic documentation of all Pike capabilities starts in chapter three with a description of all control structures in Pike. It then continues with all the data types in chapter four and operators in chapter five. Chapter six deals with object orientation in Pike, which is slightly different than what you might be used to.

The history of Pike

In the beginning, there was Zork. Then a bunch of people decided to make multi-player adventure games. One of those people was Lars Pensjö at the Chalmers university in Gothenburg, Sweden. For his game he needed a simple, memory-efficient language, and thus LPC (Lars Pensjö C) was born. About a year later I started playing one of these games and found that the language was the most easy-to-use language I had ever encountered. I liked the language so much that I started improving it and before long I had made my own LPC dialect called LPC4. LPC4 was still geared towards writing adventure games, but was quite useful for writing other things with as well. A major problem with LPC4 was the copyright. Since it was based on Lars Pensjö's code, it came with a license that did not allow it to be used for commercial gain. So, in 1994 I started writing µLPC, which was a new but similar LPC interpreter. I got financial backing from Signum Support AB for writing µLPC. Signum is a company dedicated to supporting GNU and GPL software and they wanted to create more GPL software.

When µLPC became usable, InformationsVävarna AB started using it for their web-server. Before then, Roxen (then called Spinner) was non-commercial and written in LPC4. Then in 1996 I started working for InformationsVävarna developing µLPC for them. We also changed the name of µLPC to Pike to get a more commercially viable name.

A comparison with other languages

Python
Python is probably the language that is most like Pike. Pike is faster and has better object orientation. It also has a syntax similar to C++, which makes it more familiar for people who know C++. Python on the other hand, has a lot more libraries available.
C++
Pike's syntax is almost the same as for C++. A huge difference is that Pike is interpreted. This makes the code slower, but reduces compile times to almost nothing. For those few applications which require the speed of C or C++, it is often easier to write a Pike extension than to write the whole thing in C or C++.
Lisp and Scheme
Internally Pike has a lot in common with Lisp and Scheme. They are both stack based, byte-compiled, interpreted languages. Pike is also a 'one-cell' language, just like Scheme.
Pascal
Pike has nothing in common with Pascal.
Tcl/Tk
Pike is similar to Tcl/Tk in intent and they both have good string handling. Pike has better data types and is much faster however. On the other hand Tcl/Tk has X windows system support.

What is Pike

Pike is: Pike has:

How to read this manual

This manual uses a couple of different typefaces to describe different things:
italics
Italics is used as a placeholder for other things. If it says a word in the text it means that you should put your own word there.
bold
Bold is just used to emphasize that this word is not merely what it sounds like. It is actually a term.
fixed size
Fixed size is used to for examples and text directly from the computer.
Also, please beware that the word program is also a builtin Pike data type.

Chapter 1, Getting started

First you need to have Pike installed on your computer. See appendix E "How to install Pike" if this is not already done. It is also vital for the first of the following examples that the Pike binary is in your UNIX search path. If you have problems with this, consult the manual for your shell or go buy a beginners book about UNIX.

1.1 Your first Pike program

int main()
{
    write("hello world\n");
    return 0;
}
Let's call this file hello_world.pike, and then we try to run it:

	$ pike hello_world.pike
	hello world
	$ 
Pretty simple, Let's see what everything means:
int main()
This begins the function main. Before the function name the type of value it returns is declared, in this case int which is the name of the integer number type in Pike. The empty space between the parenthesis indicates that this function takes no arguments. A Pike program has to contain at least one function, the main function. This function is where program execution starts and thus the function from which every other function is called, directly or indirectly. We can say that this function is called by the operating system. Pike is, as many other programming languages, built upon the concept of functions, i.e. what the program does is separated into small portions, or functions, each performing one (perhaps very complex) task. A function declaration consists of certain essential components; the type of the value it will return, the name of the function, the parameters, if any, it takes and the body of the function. A function is also a part of something greater; an object. You can program in Pike without caring about objects, but the programs you write will in fact be objects themselves anyway. Now let's examine the body of main;

{
    write("hello world\n");
    return 0;
}
Within the function body, programming instructions, statements, are grouped together in blocks. A block is a series of statements placed between curly brackets. Every statement has to end in a semicolon. This group of statements will be executed every time the function is called.

write("hello world\n");
The first statement is a call to the builtin function write. This will execute the code in the function write with the arguments as input data. In this case, the constant string hello world\n is sent. Well, not quite. The \n combination corresponds to the newline character. write then writes this string to stdout when executed. Stdout is the standard Unix output channel, usually the screen.

return 0;
This statement exits the function and returns the value zero. Any statements following the return statements will not be executed.

1.2 Improving hello_world.pike

Typing pike hello_world.pike to run our program may seem a bit unpractical. Fortunately, Unix provides us with a way of automating this somewhat. If we modify hello_world.pike to look like this:

#!/usr/local/bin/pike

int main()
{
    write("hello world\n");
    return 0;
}
And then we tell UNIX that hello_world.pike is executable so we can run hello_world.pike without having to bother with running Pike:

	$ chmod +x hello_world.pike
	$ ./hello_world.pike
	hello world
	$ 
N.B.: The hash bang (#!) must be first in the file, not even whitespace is allowed to precede it! The file name after the hash bang must also be the complete file name to the Pike binary, and it may not exceed 30 characters.

1.3 Further improvements

Now, wouldn't it be nice if it said Hello world! instead of hello world ? But of course we don't want to make our program "incompatible" with the old version. Someone might need the program to work like it used to. Therefore we'll add a command line option that will make it type the old hello world. We also have to give the program the ability to choose what it should output based on the command line option. This is what it could look like:

#!/usr/local/bin/pike

int main(int argc, string *argv)
{
    if(argc > 1 && argv[1]=="--traditional")
    {
        write("hello world\n"); // old style
    }else{
        write("Hello world!\n"); // new style
    }
    return 0;
}
Let's run it:

	$ chmod +x hello_world.pike
	$ ./hello_world.pike
	Hello world!
	$ ./hello_world.pike --traditional
	hello world
	$ 
What is new in this version, then?
int main(int argc, string *argv)
In this version the space between the parenthesis has been filled. What it means is that main now takes two arguments. One is called argc, and is of the type int. The other is called argv and is a an array of strings. A perhaps better way to represent an array of strings would be array(string) which is exactly the same as string * and probably easier to understand. The syntax string * is more like the syntax in C/C++ however.

The arguments to main are taken from the command line when the Pike program is executed. The first argument, argc, is how many words were written on the command line (including the command itself) and argv is an array formed by these words.

    if(argc > 1 && argv[1] == "--traditional")
    {
        write("hello world\n"); // old style
    }else{
        write("Hello world!\n"); // new style
    }
This is an if-else statement, it will execute what's between the first set of brackets if the expression between the parenthesis evaluate to something other than zero. Otherwise what's between the second set of brackets will be executed. Let's look at that expression:

argc > 1 && argv[1] == "--traditional"
Loosely translated, this means: argc is greater than one, and the second element in the array argv is equal to the string --traditional. Since argc is the number of words on the command line the first part is true only if there was anything after the program invocation.

Also note the comments:

        write("hello world\n"); // old style
The // begins a comment which continues to the end of the line. Comments will be ignore by the computer when it reads the code. This allows to inform whoever might read your code (like yourself) of what the program does to make it easier to understand. Comments are also allowed to look like C-style comments, ie. /* ... */, which can extend over several lines. The // comment only extends to the end of the line.

1.4 Control structures

The first thing to understand about Pike is that just like any other programming language it executes one piece of code at a time. Most of the time it simply executes code line by line working its way downwards. Just executing a long list of instructions is not enough to make an interesting program however. Therefore we have control structures to make Pike execute pieces of code in more interesting orders than from top to bottom.

We have already seen an example of the if statement:

if( expression )
     statement1;
else
     statement2;
if simply evaluates the expression and if the result is true it executes statement1, otherwise it executes statement2. If you have no need for statement2 you can leave out the whole else part like this:
if( expression )
    statement1;
In this case statement1 is evaluated if expression is true, otherwise nothing is evaluated.

Note for beginners: go back to our first example and make sure you understand what if does.

Another very simple control structure is the while statement:

while( expression )
    statement;
This statement evaluates expression and if it is found to be true it evaluates statement. After that it starts over and evaluates expression again. This continues until expression is no longer true. This type of control structure is called a loop and is fundamental to all interesting programming.

1.5 Functions

Another control structure we have already seen is the function. A function is simply a block of Pike code that can be executed with different arguments from different places in the program. A function is declared like this:
modifiers type name(type name1, type name2, ...)
{
    statements
}
The modifiers are optional. See
section 6.8 "Modifiers" for more details about modifiers. The type specifies what kind of data the function returns. For example, the word int would signify that the function returns an integer number. The name is used to identify the function when calling it. The names between the parenthesis are the arguments to the function. They will be defined as local variables inside the function. Each variable will be declared to contain values of the preceding type. The three dots signifies that you can have anything from zero to 256 arguments to a function. The statements between the brackets are the function body. Those statements will be executed whenever the function is called.

Example:

int sqr(int x) { return x*x; }
This line defines a function called sqr to take one argument of the type int and also returns an int. The code itself returns the argument multiplied by itself. To call this function from somewhere in the code you could simply put: sqr(17) and that would return the integer value 289.

As the example above shows, return is used to specify the return value of a function. The value after return must be of the type specified before the function name. If the function is specified to return void, nothing at all should be written after return. Note that when a return statement is executed, the function will finish immediately. Any statements following the return will be ignored.

There are many more control structures, they will all be described in a later chapter devoted only to control structures.

1.6 True and false

Throughout this chapter the words true and false have been used without any explanation to what they mean. Pike has a fairly simple way of looking at this. The number 0 is false and everything else is true. (Except when using operator overloading as I will discuss in a later chapter.)

1.7 Data Types

As you saw in our first examples we have to indicate the type of value returned by a functions or contained in a variable. We used integers (int.), strings (string), and arrays (with the * notation). The others are mapping, mixed, void, float, multiset, function, object and program. Neither mixed nor void are really types, void signifies that no value should be returned and mixed that the return value can be of any type, or that the variable can contain any type of value. Function, object and program are all types related to object orientation. We will not discuss the last three in any great detail here,
Int
The integer type stores an integer.
Float
This variable type stores a floating point number.
Array
Arrays are basically a place to store a number of other values. Arrays in Pike are allocated blocks of values. They are dynamically allocated and do not need to be declared as in C. The values in the array can be set when creating the array like this:
arr=({1,2,3});
Or, if you have already created an array, you can change the values in the array like this:
This sets entry number ind in the array arr to data. ind must be an integer. The first index of an array is 0 (zero). A negative index will count from the end of the array rather than from the beginning, -1 being the last element. To declare that a variable is an array we simply type array in front of the variable name we want:
array i;
We can also declare several array variables on the same line:
string i, j;
If we want to specify that the variable should hold an array of strings, we would write:
array (string) i;
String
A string contains a sequence of characters, a text, i.e. a word, a sentence or a book. Note that this is not simply the letters A to Z; special characters, null characters, newlines and so on can all be stored in a string. Any 8-bit character is allowed. String is a basic type in Pike, it is not an array of char like it is in C. This means that you cannot assign new values to individual characters in a string. Also, all strings are "shared", i.e. if the same string is used in several places, it will be stored in memory only once. When writing a string in a program, you enclose it in double quotes. To write special characters you need to use the following syntax:
  • \n
  • newline
  • \r
  • carriage return
  • \t
  • tab
  • \b
  • backspace
  • \"
  • " (quotation character)
  • \\
  • \ (literal backslash)
    Mapping
    A mapping is basically an array that can be indexed on any type, not just integers. It can also be seen as a way of linking data (usually strings) together. It consists of a lot of index-data pairs which are linked together in such a way that map[index1] returns data1. A mapping can be created in a way similar to arrays:
    map=([five:good, ten:excellent]);
    You can also set that data by writing map[five]=good. If you try to set an index in a mapping that isn't already present in the mapping it will be added as well.
    Multiset
    A multiset is basically a mapping without data values. When referring to an index in the multiset a 1 (one) will be returned if the index is present and 0 (zero) otherwise.

    Chapter 2, A more elaborate example

    To illustrate several of the fundamental points of Pike we will now introduce an example program, that will be extended as we go. We will build a database program that keeps track of a record collection and the songs on the records. In the first version we hard-code our "database" into the program. The database is a mapping where the index is the record name and the data is an array of strings. The strings are of course the song names. The default register consists of one record.
    #!/usr/local/bin/pike

    mapping (string:array(string)) records =
    ([
        "Star Wars Trilogy" : ({
            "Fox Fanfare",
            "Main Title",
            "Princess Leia's Theme",
            "Here They Come",
            "The Asteroid Field",
            "Yoda's Theme",
            "The Imperial March",
            "Parade of the Ewoks",
            "Luke and Leia",
            "Fight with Tie Fighters",
            "Jabba the Hut",
            "Darth Vader's Death",
            "The Forest Battle",
            "Finale"
        })
    ]);
    We want to be able to get a simple list of the records in our database. The function list_records just goes through the mapping records and puts the indices, i.e. the record names, in an array of strings, record_names. By using the builtin function sort we put the record names into the array in alphabetical order which might be a nice touch. For the printout we just print a header, "Records:", followed by a newline. Then we use the loop control structure for to traverse the array and print every item in it, including the number of the record, by counting up from zero to the last item of the array. The builtin function sizeof gives the number of items in an array. The printout is formatted through the use of sprintf which works more or less like the C function of the same name.
    void list_records()
    {
        int i;
        array (string) record_names=sort(indices(records));

        write("Records:\n");
        for(i=0;i<sizeof(record_names);i++)
            write(sprintf("%3d: %s\n", i+1, record_names[i]));
    }
    If the command line contained a number our program will find the record of that number and print its name along with the songs of this record. First we create the same array of record names as in the previous function, then we find the name of the record whose number (num) we gave as an argument to this function. Next we put the songs of this record in the array songs and print the record name followed by the songs, each song on a separate line.
    void show_record(int num)
    {
        int i;
        array (string) record_names = sort(indices (records));
        string name=record_names[num-1];
        array (string) songs=records[name];
        
        write(sprintf("Record %d, %s\n",num,name));
        for(i=0;i<sizeof(songs);i++)
            write(sprintf("%3d: %s\n", i+1, songs[i]));
    }
    The main function doesn't do much; it checks whether there was anything on the command line after the invocation. If this is not the case it calls the list_records function, otherwise it sends the given argument to the show_record function. When the called function is done the program just quits.
    int main(int argc, array (string) argv)
    {
        if(argc <= 1)
        {
            list_records();
        } else {
            show_record((int) argv[1]);
        }
    }

    2.1 Taking care of input

    Now, it would be better and more general if we could enter more records into our database. Let's add such a function and modify the main() function to accept "commands".

    2.1.1 add_record()

    Using the builtin function readline() we wait for input which will be put into the variable record_name. The argument to readline() is printed as a prompt in front of the user's input. Readline takes everything up to a newline character. Now we use the control structure while to check whether we should continue inputting songs. The while(1) means "loop forever", because 1 is always true. This program does not in fact loop forever, because it uses return to exit the function from within the loop when you type a period. When something has been read into the variable song it is checked. If it is a "." we return a null value that will be used in the while statement to indicate that it is not ok to continue asking for song names. If it is not a dot, the string will be added to the array of songs for this record, unless it's an empty string. Note the += operator. It is the same as saying records[record_name]=records[record_name]+({song}).
    void add_record()
    {
        string record_name=readline("Record name: ");
        records[record_name]=({});
        write("Input song names, one per line. End with '.' on its own line.\n");
        while(1)
        {
            string song;
            song=readline(sprintf("Song %2d: ",
                                                        sizeof(records[record_name])+1));
            if(song==".")
                 return;
            if (strlen(song))
                records[record_name]+=({song});
        }
    }

    2.1.2 main()

    The main function now does not care about any command line arguments. Instead we use readline() to prompt the user for instructions and arguments. The available instructions are "add", "list" and "quit". What you enter into the variables cmd and args is checked in the switch() block. If you enter something that is not covered in any of the case statements the program just silently ignores it and asks for a new command. In a switch() the argument (in this case cmd) is checked in the case statements. The first case where the expression equals cmd (the argument) then executes the statement after the colon. If no expression is equal, we just fall through without any action. The only command that takes an argument is "list" which works like the first version of the program. If "list" receives an argument that record is shown along with all the songs on it. If there is no argument it shows a list of the records in the database. When the program returns from either of the listing functions, the break instruction tells the program to jump out of the switch() block. "Add" of course turns control over to the function described above. If the command given is "quit" the exit(0) statement stops the execution of the program and returns 0 (zero) to the operating systems, telling it that everything was ok.
    int main(int argc, array(string) argv)
    {
        string cmd;
        while(cmd=readline("Command: "))
        {
            string args;
            sscanf(cmd,"%s %s",cmd,args);

            switch(cmd)
            {
            case "list":
                if((int)args)
                {
                    show_record((int)args);
                } else {
                    list_records();
                }
                break;

            case "quit":
                exit(0);

            case "add":
                add_record();
                break;
            }
        }
    }

    2.2 Communicating with files

    Now if we want to save the database and also be able to retrieve previously stored data we have to communicate with the environment, i.e. with files on disk. Now we will introduce you to programming with objects. To open a file for reading or writing we will use one of the programs which is builtin in Pike called Stdio.File. To Pike, a program is a data type which contains code, functions and variables. A program can be cloned which means that Pike creates a data area in memory for the program, place a reference to the program in the data area, and initialize it to act on the data file in question. The methods (ie. functions in the object) and variables in the object Stdio.File enables us to perform actions on the associated data file. The methods we need to use are open, read, write and close. See
    chapter 9 "File I/O" for more details.

    2.2.1 save()

    First we clone a Stdio.File program to the object o. Then we use it to open the file whose name is given in the string file_name for writing. We use the fact that if there is an error during opening, open() will return a false value which we can detect and act upon by exiting. The arrow operator (->) is what you use to access methods and variables in an object. If there is no error we use yet another control structure, foreach, to go through the mapping records one record at a time. We precede record names with the string "Record: " and song names with "Song: ". We also put every entry, be it song or record, on its own line by adding a newline to everything we write to the file.
    Finally, remember to close the file.
    void save(string file_name)
    {
        string name, song;
        object o;
        o=Stdio.File();

        if(!o->open(file_name,"wct"))
        {
            write("Failed to open file.\n");
            return;
        }

        foreach(indices(records),name)
        {
             o->write("Record: "+name+"\n");
             foreach(records[name],song)
                 o->write("Song: "+song+"\n");
        }

        o->close();
    }

    2.2.2 load()

    The load function begins much the same, except we open the file named file for reading instead. When receiving data from the file we put it in the string file_contents. The absence of arguments to the method o->read means that the reading should not end until the end of the file. After having closed the file we initialize our database, i.e. the mapping records. Then we have to put file_contents into the mapping and we do this by splitting the string on newlines (cf. the split operator in Perl) using the division operator. Yes, that's right: by dividing one string with another we can obtain an array consisting of parts from the first. And by using a foreach statement we can take the string file_contents apart piece by piece, putting each piece back in its proper place in the mapping records.
    void load(string file_name)
    {
        object o;
        string name="ERROR";
        string file_contents,line;

        o=Stdio.File();
        if(!o->open(file_name,"r"))
        {
            write("Failed to open file.\n");
            return;
        }

        file_contents=o->read();
        o->close();

        records=([]);

        foreach(file_contents/"\n",line)
        {
            string cmd, arg;
            if(sscanf(line,"%s: %s",cmd,arg))
            {
                switch(lower_case(cmd))
                {
                case "record":
                    name=arg;
                    records[name]=({});
                    break;

                 case "song":
                     records[name]+=({arg});
                     break;
                }
            }
        }
    }

    2.2.3 main() revisited

    main() remains almost unchanged, except for the addition of two case statements with which we now can call the load and save functions. Note that you must provide a filename to load and save, respectively, otherwise they will return an error which will crash the program.
    case "save":
        save(args);
        break;

    case "load":
        load(args);
        break;

    2.3 Completing the program

    Now let's add the last functions we need to make this program useful: the ability to delete entries and search for songs.

    2.3.1 delete()

    If you sell one of your records it might be nice to able to delete that entry from the database. The delete function is quite simple. First we set up an array of record names (cf. the list_records function). Then we find the name of the record of the number num and use the builtin function m_delete() to remove that entry from records.
    void delete_record(int num)
    {
        array(string) record_names=sort(indices(records));
        string name=record_names[num-1];

        m_delete(records,name);
    }

    2.3.2 search()

    Searching for songs is quite easy too. To count the number of hits we declare the variable hits. Note that it's not necessary to initialize variables, that is done automatically when the variable is declared if you do not do it explicitly. To be able to use the builtin function search(), which searches for the presence of a given string inside another, we put the search string in lowercase and compare it with the lowercase version of every song. The use of search() enables us to search for partial song titles as well. When a match is found it is immediately written to standard output with the record name followed by the name of the song where the search string was found and a newline. If there were no hits at all, the function prints out a message saying just that.
    void find_song(string title)
    {
        string name, song;
        int hits;

        title=lower_case(title);

        foreach(indices(records),name)
        {
            foreach(records[name],song)
            {
                if(search(lower_case(song), title) != -1)
                {
                    write(name+"; "+song+"\n");
                    hits++;
                }
            }
        }

        if(!hits) write("Not found.\n");
    }

    2.3.3 main() again

    Once again main() is left unchanged, except for yet another two case statements used to call the search() and delete functions, respectively. Note that you must provide an argument to delete or it will not work properly.
    case "delete":
        delete_record((int)args);
        break;

    case "search":
        find_song(args);
        break;

    2.4 Then what?

    Well that's it! The example is now a complete working example of a Pike program. But of course there are plenty of details that we haven't attended to. Error checking is for example extremely sparse in our program. This is left for you to do as you continue to read this book. The complete listing of this example can be found in
    appendix B "Register program". Read it, study it and enjoy!

    2.5 Simple exercises

    • Make a program which writes hello world 10 times.
    • Modify hello_world.pike to write the first argument to the program.
    • Make a program that writes a hello_world program to stdout when executed.
    • Modify the register program to store data about programs and diskettes instead of songs and records.
    • Add code to the register program that checks that the user typed an argument when required. The program should notify the user and wait to receive more commands instead of exiting with an error message.
    • Add code to the register program to check that the arguments to show_record and delete_records are numbers. Also make sure that the number isn't less than one or bigger than the available number of records.
    • Rewrite the register program and put all the code in main().

    Chapter 3, Control Structures

    In this chapter all the control structures in Pike will be explained. As mentioned earlier, control structures are used to control the flow of the program execution. Note that functions that make the program pause and simple function calls are not qualified as control structures.

    3.1 Conditions

    Pike only has two major condition control structures. We have already seen examples of both of them in Chapter two. But for completeness they will be described again in this chapter.

    3.1.1 if

    The simplest one is called the if statement. It can be written anywhere where a statement is expected and it looks like this:
    if( expression ) statement1; else statement2;
    Please note that there is no semicolon after the parenthesis or after the else. Step by step, if does the following:
    1. First it evaluates expression.
    2. If the result was false go to point 5.
    3. Execute statement1.
    4. Jump to point 6.
    5. Execute statement2.
    6. Done.
    This is actually more or less how the interpreter executes the if statement. In short, statement1 is executed if expression is true otherwise statement2 is executed. If you are not interested in having something executed if the expression is false you can drop the whole else part like this:
    if( expression )
        statement1;
    If on the other hand you are not interested in evaluating something if the expression is false you should use the not operator to negate the true/false value of the expression. See chapter 5 for more information about the not operator. It would look like this:
    if( ! expression )
        statement2 ;
    Any of the statements here and in the rest of this chapter can also be a block of statements. A block is a list of statements, separated by semicolons and enclosed by brackets. Note that you should never put a semicolon after a block of statements. The example above would look like this;
    if ( ! expression )
    {
        statement;
        statement;
        statement;
    }

    3.1.2 Switch

    A more sophisticated condition control structure is the switch statement. A switch lets you select one of many choices depending on the value of an expression and it can look something like this:
    switch ( expression )
    {
        case constant1:
            expressions1;
            break;

        case constant2:
            expressions2;
            break;

        case constant3 .. constant4:
            expressions3;
            break;

        default:
            expressions5;
    }
    As you can see, a switch statement is a bit more complicated than an if statement. It is still fairly simple however. It starts by evaluating the expression it then searches all the case statements in the following block. If one is found to be equal to the value returned by the expression, Pike will continue executing the code directly following that case statement. When a break is encountered Pike will skip the rest of the code in the switch block and continue executing after the block. Note that it is not strictly necessary to have a break before the next case statement. If there is no break before the next case statement Pike will simply continue executing and execute the code after that case statement as well.

    One of the case statements in the above example differs in that it is a range. In this case, any value between constant3 and constant4 will cause Pike to jump to expressions3. Note that the ranges are inclusive, so the values constant3 and constant4 are also valid.

    3.2 Loops

    Loops are used to execute a piece of code more than once. Since this can be done in quite a few different ways there are four different loop control structures. They may all seem very similar, but using the right one at the right time makes the code a lot shorter and simpler.

    3.2.1 while

    While is the simplest of the loop control structures. It looks just like an if statement without the else part:
    while ( expression )
        statement;
    The difference in how it works isn't that big either, the statement is executed if the expression is true. Then the expression is evaluated again, and if it is true the statement is executed again. Then it evaluates the expression again and so forth... Here is an example of how it could be used:
    int e=1;
    while(e<5)
    {
        show_record(e);
        e=e+1;
    }
    This would call show_record with the values 1, 2, 3 and 4.

    3.2.2 for

    For is simply an extension of while. It provides an even shorter and more compact way of writing loops. The syntax looks like this:
    for ( initializer_statement ; expression ; incrementor_expression )
        statement ;
    For does the following steps:
    1. Executes the the initializer_statement. The initializer statement is executed only once and is most commonly used to initialize the loop variable.
    2. Evaluates expression
    3. If the result was false it exits the loop and continues with the program after the loop.
    4. Executes statement.
    5. Executes the increment_expression.
    6. Starts over from 2.
    This means that the example in the while section can be written like this:
    for(int e=1; e<5; e=e+1)
        show_record(e);

    3.2.3 do-while

    Sometimes it is unpractical that the expression is always evaluated before the first time the loop is executed. Quite often you want to execute something, and then do it over and over until some condition is satisfied. This is exactly when you should use the do-while statement.
    do
        statement;
    while ( expression );
    As usual, the statement can also be a block of statements, and then you do not need a semicolon after it. To clarify, this statement executes statement first, and then evaluates the expression. If the expression is true it executes the loop again. For instance, if you want to make a program that lets your modem dial your Internet provider, it could look something like this:
    do {
        modem->write("ATDT441-9109\n"); // Dial 441-9109
                    } while(modem->gets()[..6]] != "CONNECT");
    This example assumes you have written something that can communicate with the modem by using the functions write and gets.

    3.2.4 foreach

    Foreach is unique in that it does not have an explicit test expression evaluated for each iteration in the loop. Instead, foreach executes the statement once for each element in an array. Foreach looks like this:
    foreach ( array_expression, variable )
        statement ;
    We have already seen an example of foreach in the find_song function in chapter 2. What foreach does is:
    1. It evaluates the array_expression which must return an array.
    2. If the array is empty, exit the loop.
    3. It then assigns the first element from the array to the variable.
    4. Then it executes the statement.
    5. If there are more elements in the array, the next one is assigned to the variable, otherwise exit the loop.
    6. Go to point 4.
    Foreach is not really necessary, but it is faster and clearer than doing the same thing with a for loop, as shown here:
    array tmp1= array_expression;
    for ( tmp2 = 0; tmp2 < sizeof(tmp1); tmp2++ )
    {
        variable = tmp1 [ tmp2 ];
        statement;
    }

    3.3 Breaking out of loops

    The loop control structures above are enough to solve any problem, but they are not enough to provide an easy solution to all problems. One thing that is still missing is the ability to exit a loop in the middle of it. There are three ways to do this:

    3.3.1 break

    Break exits a loop or switch statement immediately and continues executing after the loop. Break can not be used outside of a loop or switch. It is quite useful in conjunction with while(1) to construct command parsing loops for instance:
    while(1)
    {
        string command=readline("> ");
        if(command=="quit") break;
        do_command(command);
    }

    3.3.2 continue

    Continue does almost the same thing as break, except instead of breaking out of the loop it only breaks out of the loop body. It then continues to execute the next iteration in the loop. For a while loop, this means it jumps up to the top again. For a for loop, it jumps to the incrementor expression. For a do-while loop it jumps down to the expression at the end. To continue our example above, continue can be used like this:
    while(1)
    {
        string command=readline("> ");
        if(strlen(command) == 0) continue;
        if(command=="quit") break;
        do_command(command);
    }
    This way, do_command will never be called with an empty string as argument.

    3.3.3 return

    Return doesn't just exit the loop, it exits the whole function. We have seen several examples how to use it chapter 2. None of the functions in chapter two returned anything in particular however. To do that you just put the return value right after return. Of course the type of the return value must match the type in the function declaration. If your function declaration is int main() the value after return must be an int. For instance, if we wanted to make a program that always returns an error code to the system, just like the UNIX command false this is how it would be done:
    #!/usr/local/bin/pike

    int main()
    {
        return 1;
    }
    This would return the error code 1 to the system when the program is run.

    3.4 Exercises

    • End all functions in the examples in chapter two with a return statement.
    • Change all foreach loops to for or while loops.
    • Make the find_song function in chapter 2 return when the first matching song is found.
    • Make the find_song function write the number of the record the song is on.
    • If you failed to get the program to work properly in the last exercise of chapter 2, try it again now.
    • Make a program that writes all the numbers from 1 to 1000.
    • Modify the program in the previous exercise to NOT write numbers dividable by 3, 7 or 17.
    • Make a program that writes all the prime numbers between 1 to 1000.

    Chapter 4, Data types

    In this chapter we will discuss all the different ways to store data in Pike in detail. We have seen examples of many of these, but we haven't really gone into how they work. In this chapter we will also see which operators and functions work with the different types. There are two categories of data types in Pike: basic types, and pointer types. The difference is that basic types are copied when assigned to variable. With pointer types, merely the pointer is copied, that way you get two variables pointing to the same thing.

    4.1 Basic types

    The basic types are int, float and string. For you who are accustomed to C or C++, it may seem odd that a string is a basic type as opposed to an array of char, but it is surprisingly easy to get used to.

    4.1.1 int

    Int is short for integer, or integer number. They are normally 32 bit integers, which means that they are in the range -2147483648 to 2147483647. Note that on some machines an int might be larger than 32 bits. Since they are integers, no decimals are allowed. An integer constant can be written in several ways:
    	78	// decimal number
    	0116	// octal number
    	0x4e	// hexadecimal number
    	'N'	// Ascii character
    
    All of the above represent the number 78. Octal notation means that each digit is worth 8 times as much as the one after. Hexadecimal notation means that each digit is worth 16 times as much as the one after. Hexadecimal notation uses the letters a, b, c, d, e and f to represent the numbers 10, 11, 12, 13, 14 and 15. The ASCII notation gives the ASCII value of the character between the single quotes. In this case the character is N which just happen to be 78 in ASCII.

    Integers are coded in 2-complement and overflows are silently ignored by Pike. This means that if your integers are 32-bit and you add 1 to the number 2147483647 you get the number -2147483648. This works exactly as in C or C++.

    All the arithmetic, bitwise and comparison operators can be used on integers. Also note these functions:

    int intp(mixed x)
    This function returns 1 if x is an int, 0 otherwise.
    int random(int x)
    This function returns a random number greater or equal to zero and smaller than x.
    int reverse(int x)
    This function reverses the order of the bits in x and returns the new number. It is not very useful.
    int sqrt(int x)
    This computes the square root of x. The value is always rounded down.

    4.1.2 float

    Although most programs only use integers, they are unpractical when doing trigonometric calculations, transformations or anything else where you need decimals. For this purpose you use float. Floats are normally 32 bit floating point numbers, which means that they can represent very large and very small numbers, but only with 9 accurate digits. To write a floating point constant, you just put in the decimals or write it in the exponential form:
    3.14159265358979323846264338327950288419716939937510 // Pi
    1.0e9 // A billion
    1.0e-9 // A billionth
    Of course you do not need this many decimals, but it doesn't hurt either. Usually digits after the ninth digit are ignored, but on some architectures float might have higher accuracy than that. In the exponential form, e means "times 10 to the power of", so 1.0e9 is equal to "1.0 times 10 to the power of 9".

    All the arithmetic and comparison operators can be used on floats. Also, these functions operates on floats:

    trigonometric functions
    The trigonometric functions are: sin, asin, cos, acos, tan and atan. If you do not know what these functions do you probably don't need them. Asin, acos and atan are of course short for arc sine, arc cosine and arc tangent. On a calculator they are often known as inverse sine, inverse cosine and inverse tangent.
    float log(float x)
    This function computes the natural logarithm of x,
    float exp(float x)
    This function computes e raised to the power of x.
    float pow(float x, float y)
    This function computes x raised to the power of y.
    float sqrt(float x)
    This computes the square root of x.
    float floor(float x)
    This function computes the highest integer value lower or equal to x. Note that the value is returned as a float, not an int.
    float ceil(float x),
    This function computes the lowest integer value higher or equal to x and returns it as a float.

    4.1.3 string

    A string can be seen as an array of values from 0 to 255. Usually a string contains text such as a word, a sentence, a page or even a whole book. But it can also contain parts of a binary file, compressed data or other binary data. Strings in Pike are shared, which means that identical strings share the same memory space. This reduces memory usage very much for most applications and also speeds up string comparisons. We have already seen how to write a constant string:
    	"hello world" // hello world
    	"he" "llo"    // hello
    	"\116"        // N (116 is the octal ASCII value for N)
    	"\t"          // A tab character
    	"\n"          // A newline character
    	"\r"          // A carriage return character
    	"\b"          // A backspace character
    	"\0"          // A null character
    	"\""          // A double quote character
    	"\\"          // A singe backslash
    	"hello world\116\t\n\r\b\0\"\\" // All of the above
    
    As you can see, any sequence of characters within double quotes is a string. The backslash character is used to escape characters that are not allowed or impossible to type. As you can see, \t is the sequence to produce a tab character, \\ is used when you want one backslash and \" is used when you want a double quote to be a part of the string instead of ending it. Also, \XXX where XXX is an octal number from 000 to 377 lets you write any character you want in the string, even null characters. If you write two constant strings after each other, they will be concatenated into one string.

    Although a string is an array, you can not change the individual characters in the string. Instead you have to construct a new string, here is an example of how:

    string s = "hello torld";
    s=s[..5]+"w"+s[7..];

    All the comparison operators plus the operators listed here can be used on strings:

    Summation
    Adding strings together will simply concatenate them. "foo"+"bar" becomes "foobar".
    Subtraction
    Subtracting one string from another will remove all occurrences of the second string from the first one. So "foobarfoogazonk" - "foo" results in "bargazonk".
    Indexing
    Indexing will let you get the ascii value of any character in a string. The first character is index zero.
    Range
    The range operator will let you copy any part of the string into a new string. Example: "foobar"[2..4] will return "oba".
    Division
    Division will let you divide a string at every occurrence of a word or character. For instance if you do "foobargazonk" / "o" the result would be ({"f","","bargaz","nk"}).
    Multiplication
    The reverse of the division operator can be accomplished by multiplying an array with a string. So if you evaluate ({"f","","bargaz","nk"}) * "o" the result would be "foobargazonk".

    Also, these functions operates on strings:

    string String.capitalize(string s)
    Returns s with the first character converted to upper case.
    string lower_case(string s)
    Returns s with all the upper case characters converted to lower case.
    string replace(string s, string from, string to)
    This function replaces all occurrences of the string from in s with to and returns the new string.
    string reverse(string s)
    This function returns a copy of s with the last byte from s first, the second last in second place and so on.
    string search(string haystack, string needle)
    This function finds the first occurrence of needle in haystack.
    string sizeof(string s)
    Same as strlen(s), returns the length of the string.
    int stringp(mixed s)
    This function returns 1 if s is a string, 0 otherwise.
    string strlen(string s)
    Returns the length of the string s.
    string upper_case(string s)
    This function returns s with all lower case characters converted to upper case.

    4.2 Pointer types

    The basic types are, as the name implies, very basic. They are foundation, most of the pointer types are merely interesting ways to store the basic types. The pointer types are array, mapping, multiset, program, object and function. They are all pointers which means that they point to something in memory. This "something" is freed when there are no more pointers to it. Assigning a variable with a value of a pointer type will not copy this "something" instead it will only generate a new reference to it. Special care sometimes has to be taken when giving one of these types as arguments to a function; the function can in fact modify the "something". If this effect is not wanted you have to explicitly copy the value. More about this will be explained later in this chapter.

    4.2.1 array

    Arrays are the simplest of the pointer types. An array is merely a block of memory with a fixed size containing a number of slots which can hold any type of value. These slots are called elements and are accessible through the index operator. To write a constant array you enclose the values you want in the array with ({ }) like this:
    	({ })      // Empty array
    	({ 1 })    // Array containing one element of type int
    	({ "" })   // Array containing a string
    	({ "", 1, 3.0 }) // Array of three elements, each of different type
    
    As you can see, each element in the array can contain any type of value. Indexing and ranges on arrays works just like on strings, except with arrays you can change values inside the array with the index operator. However, there is no way to change the size of the array, so if you want to append values to the end you still have to add it to another array which creates a new array. Figure 4.1 shows how the schematics of an array. As you can see, it is a very simple memory structure.


    fig 4.1

    Operators and functions usable with arrays:

    indexing ( arr [ c ] )
    Indexing an array retrieves or sets a given element in the array. The index c has to be an integer. To set an index, simply put the whole thing on the left side of an assignment, like this: arr [ c ] = new_value
    range ( arr [ from .. to ] )
    The range copies the elements from, from+1, , from+2 ... to into a new array. The new array will have the size to-from+1.
    comparing (a == b and a != b)
    The equal operator returns 1 if a and b are the same arrays. It is not enough that they have the same size and same data. They must be the same array. For example: ({1}) == ({1}) would return 0, while array(int) a=({1}); return a==a; would return 1. Note that you cannot use the operators >, >=, < or <= on arrays.
    Summation (a + b)
    As with strings, summation concatenates arrays. ({1})+({2}) returns ({1,2}).
    Subtractions (a - b)
    Subtracting one array from another returns a copy of a with all the elements that are also present in b removed. So ({1,3,8,3,2}) - ({3,1}) returns ({8,2}).
    Intersection (a & b)
    Intersection returns an array with all values that are present in both a and b. The order of the elements will be the same as the the order of the elements in a. Example: ({1,3,7,9,11,12}) & ({4,11,8,9,1}) will return: ({1,9,11}).
    Union (a | b)
    Union works almost as summation, but it only concatenates elements not already present in a. So, ({1,2,3}) | ({1,3,5}) will return ({1,2,3,5}).
    Xor (a ^ b)
    This is also called symmetric difference. It returns an array with all elements present in a or b but the element must NOT be present in both. Example: ({1,3,5,6}) ^ ({4,5,6,7}) will return ({1,3,4,7}).
    array aggregate(mixed ... elems)
    This function does the same as the ({ }) operator; it creates an array from all arguments given to it. In fact, writing ({1,2,3}) is the same as writing aggregate(1,2,3).
    array allocate(int size)
    This function allocates a new array of size size. All the elements in the new array will be zeroes.
    int arrayp(mixed a)
    This function returns 1 if a is an array, 0 otherwise.
    array column(array(mixed) a, mixed ind)
    This function goes through the array a and indexes every element in it on ind and builds an array of the results. So if you have an array a in which each element is a also an array. This function will take a cross section, by picking out element ind from each of the arrays in a. Example: column( ({ ({1,2,3}), ({4,5,6}), ({7,8,9}) }), 2) will return ({3,6,9}).
    int equal(mixed a, mixed b)
    This function returns 1 if if a and b look the same. They do not have to be pointers to the same array, as long as they are the same size and contain equal data.
    array Array.filter(array a, mixed func, mixed ... args)
    filter returns every element in a for which func returns true when called with that element as first argument, and args for the second, third, etc. arguments.
    array Array.map(array a, mixed func, mixed ... args)
    This function works similar to Array.filter but returns the results of the function func instead of returning the elements from a for which func returns true.
    array replace(array a, mixed from, mixed to)
    This function will create a copy of a with all elements equal to from replaced by to.
    array reverse(array a)
    Reverse will create a copy of a with the last element first, the last but one second, and so on.
    array rows(array a, array indexes)
    This function is similar to column. It indexes a with each element from indexes and returns the results in an array. For example: rows( ({"a","b","c"}), ({ 2,1,2,0}) ) will return ({"c","b","c","a"}).
    int search(array haystack, mixed needle)
    This function returns the index of the first occurrence of an element equal (tested with ==) to needle in the array haystack.
    int sizeof(mixed arr)
    This function returns the number of elements in the array arr
    array sort(array arr, array ... rest)
    This function sorts arr in smaller-to-larger order. Numbers, floats and strings can be sorted. If there are any additional arguments, they will be permutated in the same manner as arr. See chapter 15 "All the builtin functions" for more details.
    array uniq(array a)
    This function returns a copy of the array a with all duplicate elements removed. Note that that this function can return the elements in any order.

    4.2.2 mapping

    Mappings are are really just more generic arrays. However, they are slower and use more memory than arrays, so they cannot replace arrays completely. What makes mappings special is that they can be indexed on other things than integers. We can imagine that a mapping looks like this:


    fig 4.2

    Each index-value pair is floating around freely inside the mapping. There is exactly one value for each index. We also have a (magical) lookup function. This lookup function can find any index in the mapping very quickly. Now, if the mapping is called m and we index it like this: m [ i ] the lookup function will quickly find the index i in the mapping and return the corresponding value. If the index is not found, zero is returned instead. If we on the other hand assign an index in the mapping the value will instead be overwritten with the new value. If the index is not found when assigning, a new index-value pair will be added to the mapping. Writing a constant mapping is easy:

    	([ ])       // Empty mapping
    	([ 1:2 ])   // Mapping with one index-value pair, the 1 is the index
    	([ "one":1, "two":2 ]) // Mapping which maps words to numbers
    	([ 1:({2.0}), "":([]), ]) // Mapping with lots of different types
    

    As with arrays, mappings can contain any type. The main difference is that the index can be any type too. Also note that the index-value pairs in a mapping are not stored in a specific order. You can not refer to the fourteenth key-index pair, since there is no way of telling which one is the fourteenth. Because of this, you cannot use the range operator on mappings.

    The following operators and functions are important to use mappings:

    indexing ( m [ ind ] )
    As discussed above, indexing is used to retrieve, store and add values to the mapping.
    addition, subtraction, union, intersection and xor
    All these operators works exactly as on arrays, with the difference that they operate on the indexes. In those cases when the value can come from either mapping, it will be taken from the right side of the operator. This is to make it easier to add new values to a mapping with +=. Some examples:
    ([1:3, 3:1]) + ([2:5, 3:7]) returns ([1:3, 2:5, 3:7 ])
    ([1:3, 3:1]) - ([2:5, 3:7]) returns ([1:3])
    ([1:3, 3:1]) | ([2:5, 3:7]) returns ([1:3, 2:5, 3:7 ])
    ([1:3, 3:1]) & ([2:5, 3:7]) returns ([3:7])
    ([1:3, 3:1]) ^ ([2:5, 3:7]) returns ([1:3, 2:5])
    same ( a == b )
    Returns 1 if a is the same mapping as b, 0 otherwise.
    not same a != b )
    Returns 0 if a is the same mapping as b, 1 otherwise.
    array indices(mapping m)
    Indices returns an array containing all the indexes in the mapping m.
    void m_delete(mapping m, mixed ind)
    This function removes the index-value pair with the index ind from the mapping m.
    int mappingp(mixed m)
    This function returns 1 if m is a mapping, 0 otherwise.
    mapping mkmapping(array ind, array val)
    This function constructs a mapping from the two arrays ind and val. Element 0 in ind and element 0 in val becomes one index-value pair. Element 1 in ind and element 1 in val becomes another index-value pair, and so on..
    mapping replace(mapping m, mixed from, mixed to)
    This function creates a copy of the mapping m with all values equal to from replaced by to.
    mixed search(mapping m, mixed val)
    This function returns the index of the 'first' index-value pair which has the value val.
    int sizeof(mapping m)
    Sizeof returns how many index-value pairs there are in the mapping.
    array values(mapping m)
    This function does the same as indices, but returns an array with all the values instead. If indices and values are called on the same mapping after each other, without any other mapping operations in between, the returned arrays will be in the same order. They can in turn be used as arguments to mkmapping to rebuild the mapping m again.
    int zero_type(mixed t)
    When indexing a mapping and the index is not found, zero is returned. However, problems can arise if you have also stored zeroes in the mapping. This function allows you to see the difference between the two cases. If zero_type(m [ ind ]) returns 1, it means that the value was not present in the mapping. If the value was present in the mapping, zero_type will return something else than 1.

    4.2.3 multiset

    A multiset is almost the same thing as a mapping. The difference is that there are no values:


    fig 4.3

    Instead, the index operator will return 1 if the value was found in the multiset and 0 if it was not. When assigning an index to a multiset like this: mset[ ind ] = val the index ind will be added to the multiset mset if val is true. Otherwise ind will be removed from the multiset instead.

    Writing a constant multiset is similar to writing an array:

    	(< >)      // Empty multiset
    	(< 17 >)  // Multiset with one index: 17
    	(< "", 1, 3.0, 1 >) // Multiset with 3 indexes
    
    Note that you can actually have two of the same index in a multiset. This is normally not used, but can be practical at times.

    4.2.4 program

    Normally, when we say program we mean something we can execute from a shell prompt. However, Pike has another meaning for the same word. In Pike a program is the same as a class in C++. A program holds a table of what functions and variables are defined in that program. It also holds the code itself, debug information and references to other programs in the form of inherits. A program does not hold space to store any data however. All the information in a program is gathered when a file or string is run through the Pike compiler. The variable space needed to execute the code in the program is stored in an object which is the next data type we will discuss.


    fig 4.4
    Writing a program is easy, in fact, every example we have tried so far has been a program. To load such a program into memory, we can use compile_file which takes a file name, compiles the file and returns the compiled program. It could look something like this:
    program p = compile_file("hello_world.pike");
    You can also use the cast operator like this:
    program p = (program) "hello_world";
    This will also load the program hello_world.pike, the only difference is that it will cache the result so that next time you do (program)"hello_world" you will receive the _same_ program. If you call compile_file("hello_world.pike") repeatedly you will get a new program for each time.

    There is also a way to write programs inside programs with the help of the class keyword:

    	class class_name {
    	  inherits, variables and functions 
    	}
    
    The class keyword can be written as a separate entity outside of all functions, but it is also an expression which returns the program written between the brackets. The class_name is optional. If used you can later refer to that program by the name class_name. This is very similar to how classes are written in C++ and can be used in much the same way. It can also be used to create structs (or records if you program Pascal). Let's look at an example:
    class record {
        string title;
        string artist;
        array(string) songs;
    }

    array(object(record)) records = ({});

    void add_empty_record()
    {
        records+=({ record() });
    }

    void show_record(object(record) rec)
    {
        write("Record name: "+rec->title+"\n");
        write("Artist: "+rec->artist+"\n");
        write("Songs:\n");
        foreach(rec->songs, string song)
            write(" "+song+"\n");
    }
    This could be a small part of a better record register program. It is not a complete executable program in itself. In this example we create a program called record which has three identifiers. In add_empty_record a new object is created by calling record. This is called cloning and it allocates space to store the variables defined in the class record. Show_record takes one of the records created in add_empty_record and shows the contents of it. As you can see, the arrow operator is used to access the data allocated in add_empty_record. If you do not understand this section I suggest you go on and read the next section about objects and then come back and read this section again.

    cloning
    To create a data area for a program you need to instantiate or clone the program. This is accomplished by using a pointer to the program as if it was a function and call it. That creates a new object and calls the function create in the new object with the arguments. It is also possible to use the functions new() and clone() which do exactly the same thing except you can use a string to specify what program you want to clone.
    compiling
    All programs are generated by compiling a file or a string. For this purpose there are two functions:
    program compile_file(string filename);
    program compile_string(string p, string filename);
    Compile_file simply reads the file given as argument, compiles it and returns the resulting program. Compile_string instead compiles whatever is in the string p. The second argument, filename, is only used in debug printouts when an error occurs in the newly made program.
    casting
    Another way of compiling files to program is to use the cast operator. Casting a string to the type program calls a function in the master object which will compile the program in question for you. The master also keeps the program in a cache, so if you later need the same program again it will not be re-compiled.
    int programp(mixed p)
    This function returns 1 if p is a program, 0 otherwise.
    comparisons
    As with all data types == and != can be used to see if two programs are the same or not.

    4.2.5 object

    Although programs are absolutely necessary for any application you might want to write, they are not enough. A program doesn't have anywhere to store data, it just merely outlines how to store data. To actually store the data you need an object. Objects are basically a chunk of memory with a reference to the program from which it was cloned. Many objects can be made from one program. The program outlines where in the object different variables are stored.

    fig 4.5
    Each object has its own set of variables, and when calling a function in that object, that function will operate on those variables. If we take a look at the short example in the section about programs, we see that it would be better to write it like this:
    class record {
        string title;
        string artist;
        array(string) songs;

        void show()
        {
            write("Record name: "+title+"\n");
            write("Artist: "+artist+"\n");
                            write("Songs:\n");
                            foreach(songs, string song)
                write(" "+song+"\n");
        }
    }

    array(object(record)) records = ({});

    void add_empty_record()
    {
        records+=({ record() });
    }

    void show_record(object rec)
    {
        rec->show();
    }
    Here we can clearly see how the function show prints the contents of the variables in that object. In essence, instead of accessing the data in the object with the -> operator, we call a function in the object and have it write the information itself. This type of programming is very flexible, since we can later change how record stores its data, but we do not have to change anything outside of the record program.

    Functions and operators relevant to objects:

    indexing
    Objects can be indexed on strings to access identifiers. If the identifier is a variable, the value can also be set using indexing. If the identifier is a function, a pointer to that function will be returned. If the identifier is a constant, the value of that constant will be returned. Note that the -> operator is actually the same as indexing. This means that o->foo is the same as o["foo"]
    cloning
    As discussed in the section about programs, cloning a program can be done in two different ways:
    1. Use a pointer to the program as a function and call it.
    2. Use the functions new or clone. (They are the same function.)
    Whenever you clone an object, all the global variables will be initialized. After that the function create will be called with any arguments you call the program with.
    void destruct(object o)
    This function invalidates all references to the object o and frees all variables in that object. This function is also called when o runs out of references. If there is a function named destroy in the object, it will be called before the actual destruction of the object.
    array(string) indices(object o)
    This function returns a list of all identifiers in the object o.
    program object_program(object o)
    This function returns the program from which o was cloned.
    int objectp(mixed o)
    This function returns 1 if o is an object, 0 otherwise. Note that if o has been destructed, this function will return 0.
    object this_object()
    This function returns the object in which the interpreter is currently executing.
    array values(object o)
    This function returns the same as rows(o,indices(o)). That means it returns all the values of the identifiers in the object o.
    comparing
    As with all data types == and != can be used to check if two objects are the same or not.

    4.2.6 function

    When indexing an object on a string, and that string is the name of a function in the object a function is returned. Despite its name, a function is really a function pointer.

    fig 4.6
    When the function pointer is called, the interpreter sets this_object() to the object in which the function is located and proceeds to execute the function it points to. Also note that function pointers can be passed around just like any other data type:
    int foo() { return 1; }
    function bar() { return foo; }
    int gazonk() { return foo(); }
    int teleledningsanka() { return bar()(); }
    In this example, the function bar returns a pointer to the function foo. No indexing is necessary since the function foo is located in the same object. The function gazonk simply calls foo. However, note that the word foo in that function is an expression returning a function pointer that is then called. To further illustrate this, foo has been replaced by bar() in the function teleledningsanka.

    For convenience, there is also a simple way to write a function inside another function. To do this you use the lambda keyword. The syntax is the same as for a normal function, except you write lambda instead of the function name:

    lambda ( types ) { statements }
    The major difference is that this is an expression that can be used inside other function. Example:
    function bar() { return lambda() { return 1; }; )
    This is the same as the first two lines in the previous example, the keyword lambda allows you to write the function inside bar.

    Note that unlike C++ and Java you can not use function overloading in Pike. This means that you cannot have one function called 'foo' which takes an integer argument and another function 'foo' which takes a float argument.

    This is what you can do with a function pointer.

    calling ( f ( mixed ... args ) )
    As mentioned earlier, all function pointers can be called. In this example the function f is called with the arguments args.
    string function_name(function f)
    This function returns the name of the function f is pointing at.
    object function_object(function f)
    This function returns the object the function f is located in.
    int functionp(mixed f)
    This function returns 1 if f is a function, 0 otherwise. If f is located in a destructed object, 0 is returned.
    function this_function()
    This function returns a pointer to the function it is called from. This is normally only used with lambda functions because they do not have a name.

    4.3 Sharing data

    As mention in the beginning of this chapter, the assignment operator (=) does not copy anything when you use it on a pointer type. Instead it just creates another reference to the memory object. In most situations this does not present a problem, and it speeds up Pike's performance. However, you must be aware of this when programming. This can be illustrated with an example:
    int main(int argc, array(string) argv)
    {
        array(string) tmp;
        tmp=argv;
        argv[0]="Hello world.\n";
        write(tmp[0]);
    }
    This program will of course write Hello world.

    Sometimes you want to create a copy of a mapping, array or object. To do so you simply call copy_value with whatever you want to copy as argument. Copy_value is recursive, which means that if you have an array containing arrays, copies will be made of all those arrays.

    If you don't want to copy recursively, or you know you don't have to copy recursively, you can use the plus operator instead. For instance, to create a copy of an array you simply add an empty array to it, like this: copy_of_arr = arr + ({}); If you need to copy a mapping you use an empty mapping, and for a multiset you use an empty multiset.

    4.4 Writing data types

    When declaring a variable, you also have to specify what type of variable it is. For most types, such as int and string this is very easy. But there are much more interesting ways to declare variables than that, let's look at a few examples:
    	int x; // x is an integer
    	int|string x; // x is a string or an integer
    	array(string) x; // x is an array of strings
    	array x; // x is an array of mixed
    	mixed x; // x can be any type
    	string *x; // x is an array of strings
    
    	 // x is a mapping mapping from int to string
    	mapping(string:int) x;
    
    	// x is a clone of Stdio.File
    	object(Stdio.File) x;
    
    	// x is a function that takes two integer
    	// arguments and returns a string
    	function(int,int:string) x;
    
    	// x is a function taking any amount of
    	// integer arguments and returns nothing.
    	function(int...:void) x;
    
    	// x is ... complicated
    	mapping(string:function(string|int...:mapping(string:string*))) x;
    
    As you can see there are some interesting ways to specify types. Here is a list of what is possible:
    mixed
    This means that the variable can contain any type, or the function return any value
    array( type )
    This means an array of type.
    type *
    This also means an array of type.
    mapping( key type : value type )
    This is a mapping where the keys are of type key type and the values of value type.
    multiset ( type )
    This means a multiset containing values of type type.
    object ( program )
    This means an object cloned from the specified program. The program can be a class, a constant, or a string. If the program is a string it will be casted to a program first. See the documentation for inherit for more information about this casting.
    function( argument types : return type )
    This is a function taking the specified arguments and returning return type. The argument types is a comma separated list of types that specify the arguments. The argument list can also end with ... to signify that there can be any amount of the last type.
    type1 | type2
    This means either type1 or type2
    void
    Void can only be used in certain places, if used as return type for a function it means that the function does not return a value. If used in the argument list for a function it means that that argument can be omitted. Example: function(int|void:void) this means a function that may or may not take an integer argument and does not return a value.

    Chapter 5, Operators

    To make it easier to write Pike, and to make the code somewhat shorter, some functions can be called with just one or two characters in the code. These functions are called operators and we have already seen how they work in plenty of examples. In this chapter I will describe in detail what they do. The operators are divided into categories depending on their function, but beware that some operators have meanings that go way beyond the scope of the category they are in.

    5.1 Arithmetic operators

    The arithmetic operators are the simplest ones, since they work just like you remember from math in school. The arithmetic operators are:

    Function Syntax Identifier Returns
    Addition a + b `+ the sum of a and b
    Subtractiona - b `- b subtracted from a
    Negation - a `- minus a
    Multiplicationa * b`* a multiplied by b
    Division a / b `/ a divided by b
    Modulo a % b `% the remainder of a division between a and b

    The third column, "Identifier" is the name of the function that actually evaluates the operation. For instance, a + b can also be written as `+(a, b). I will show you how useful this can be at the end of this chapter.

    When applied to integers or floats these operators do exactly what they are supposed to do. The only operator in the list not known from basic math is the modulo operator. The modulo operator returns the rest of an integer division. It is the same as calculating a - floor(a / b) * b. floor rounds the value down to closest lower integer value. Note that the call to floor isn't needed when operating on integers, since dividing two integers will return the result as an integer and it is always rounded down. For instance, 8 / 3 would return 2.

    If all arguments to the operator are integers, the result will also be an integer. If one is a float and the other is an integer, the result will be a float. If both arguments are float, the result will of course be a float.

    However, there are more types in Pike than integers and floats. Here is the complete list of combinations of types you can use with these operators:

    OperationReturned typeReturned value
    int + intintthe sum of the two values
    float + int
    int + float
    float + float
    floatthe sum of the two values
    string + string
    int + string
    float + string
    string + int
    string + float
    stringIn this case, any int or float is first converted to a string. Then the two strings are concatenated and the resulting string is returned.
    array + arrayarrayThe two arrays are concatenated into a new array and that new array is returned.
    mapping + mappingmappingA mapping with all the index-value pairs from both mappings is returned. If an index is present in both mappings the index-value pair from the right mapping will be used.
    multiset + multisetmultisetA multiset with all the indices from both muiltisets is returned.
    int - intintThe right value subtracted from the left.
    float - int
    int - float
    float - float
    floatThe right value subtracted from the left.
    string - stringstringA copy of the left string with all occurrences of the right string removed.
    array - arrayarrayA copy of the right array with all elements present in the right array removed. Example: ({2,1,4,5,3,6,7}) - ({3,5,1}) will return ({2,4,6,7}).
    mapping - mappingmappingA new mapping with all index-value pairs from the left mapping, except those indexes that are also present in the right mapping.
    multiset - multisetmultisetA copy of the left multiset without any index present in the left multiset.
    intintSame as 0 - int.
    floatfloatSame as 0 - float.
    int * intintthe product of the two values
    float * int
    int * float
    float * float
    floatthe product of the two values
    array(string) * stringstringAll the strings in the array are concatenated with the string on the right in between each string. Example: ({"foo,"bar})*"-" will return "foo-bar".
    int / intintThe right integer divided by the left integer rounded towards minus infinity.
    float / int
    int / float
    float / float
    floatThe right value divided by the left value.
    string / stringarray(string)In symmetry with the multiplication operator, the division operator can split a string into pieces. The right string will be split at every occurrence of the right string and an array containing the results will be returned. Example: "foo-bar"/"-" will return ({"foo","bar"})
    int % intintThe rest of a division. If a and b are integers, a%b is the same as a-(a/b)*b
    float % float
    int % float
    float % int
    floatThe rest of a division. If a and b are floats, a%b is the same as a-floor(a/b)*b

    5.2 Comparison operators

    The arithmetic operators would be hard to use for something interesting without the ability to compare the results to each other. For this purpose there are six comparison operators:

    Function Syntax Identifier Returns
    Same a == b `== 1 if a is the same value as b, 0 otherwise
    Not same a != b `!= 0 if a is the same value as b, 1 otherwise
    Greater than a > b `> 1 if a is greater than b, 0 otherwise
    Greater than or equal toa >= b`>=1 if a is greater to or equal to b, 0 otherwise
    Lesser than a < b `< 1 if a is lesser than b, 0 otherwise
    Lesser than or equal to a <= b`<=1 if a is lesser than or equal to b, 0 otherwise

    The == and != operators can be used on any type. For two values to be same they must be the same type. Therefor 1 and 1.0 are not same. Also, for two values of pointer types to be the same the two values must be pointers to the same object. It is not enough that the two objects are of the same size and contain the same data.

    The other operators in the table above can only be used with integers, floats and strings. If you compare an integer with a float, the int will be promoted to a float before the comparison. When comparing strings, lexical order is used and the value of the environment variables LC_CTYPE and LC_LANG is respected.

    5.3 Logical operators

    Logical operators are operators that operate with truth values. In Pike any value except zero is considered true. Logical operators are a very basic part of Pike. They can also decide which arguments to evaluate and which not to evaluate. Because of this the logical operators do not have any identifiers and can not be called as normal functions. There are four logical operators:

    Function Syntax Returns
    And a && b If a is false, a is returned and b is not evaluated. Otherwise, b is returned.
    Or a || b If a is true, a is returned and b is not evaluated. Otherwise, b is returned.
    Not ! a Returns 0 if a is true, 1 otherwise.
    If-else a ? b : c If a is true, b is returned and c is not evaluated. Otherwise c is returned and b is not evaluated.

    5.4 Bitwise/set operators

    These operators are used to manipulate bits as members in sets. They can also manipulate arrays, multisets and mappings as sets.

    Function Syntax Identifier Returns
    Shift left a << b `<< Multiplies a by 2 b times.
    Shift right a >> b `>> Divides a by 2 b times.
    Inverse (not) ~ a `~ Returns -1-a.
    Intersection (and) a & b `& All elements present in both a and b.
    Union (or) a | b `| All elements present in a or b.
    Symmetric difference (xor)a ^ b `^ All elements present in a or b, but not present in both.

    The first three operators can only be used with integers and should be pretty obvious. The other three, intersection, union and symmetric difference, can be used with integers, arrays, multisets and mappings. When used with integers, these operators considers each bit in the integer a separate element. If you do not know about how bits in integers I suggest you go look it up in some other programming book or just don't use these operators on integers.

    When intersection, union or symmetric difference is used on an array each element in the array is considered by itself. So intersecting two arrays will result in an array with all elements that are present in both arrays. Example: ({7,6,4,3,2,1}) & ({1, 23, 5, 4, 7}) will return ({7,4,1}). The order of the elements in the returned array will always be taken from the left array. Elements in multisets are treated the same as elements in arrays. When doing a set operator on a mapping however, only the indices are considered. The values are just copied with the indexes. If a particular index is present in both the right and left argument to a set operator, the one from the right side will be used. Example: ([1:2]) | ([1:3]) will return ([1:3]).

    5.5 Indexing

    The index and range operators are used to retrieve information from a complex data type.

    Function Syntax Identifier Returns
    Index a [ b ]`[] Returns the index b from a.
    Lookup a ->identifier `-> Looks up the identifier. Same as a["identifier"].
    Assign index a [ b ] = c`[]=;Sets the index b in a to c.
    Assign index a ->identifier = c`->=Sets the index "identifier" in a to c.
    Range a [ b .. c] `[..] Returns a slice of a starting at the index b and ending at c.
    Range a [ .. c] `[..] Returns a slice of a starting at the beginning of a and ending at c.
    Range a [ b .. ] `[..] Returns a slice of a from the index b to the end of a.

    The index operator can be written in two different ways. It can be written as ob [ index ] or ob->identifier. However, the latter syntax is equal to ob [ "identifier" ]. You can only index strings, arrays, mapping, multisets and objects, and some of these can only be indexed on certain things as shown in this list:

    Operation Returns
    string[int]Returns the ascii value of the Nth character in the string.
    array[int]Return the element in the array corresponding to the integer.
    array[int]=mixedSets the element in the array to the mixed value.
    multiset[mixed]
    multiset->identifier
    Returns 1 if the index (the value between the brackets) is present in the multiset, 0 otherwise.
    multiset[mixed]=mixed
    multiset->identifier=mixed
    If the mixed value is true the index is added to the multiset. Otherwise the index is removed from the multiset.
    mapping[mixed]
    mapping->identifier
    Returns the value associated with the index, 0 if it is not found.
    mapping[mixed]=mixed
    mapping->identifier=mixed
    Associate the second mixed value with the first mixed value.
    object[string]
    object->identifier
    Returns the value of the named identifier in the object.
    object[string]=mixed
    object->identifier=mixed
    Set the given identifier in the object to the mixed value. Only works if the identifier references a variable in the object.
    string[int..int]Returns a piece of the string.
    array[int..int]Returns a slice of the array.

    When indexing an array or string it is sometimes convenient to access index from the end instead of from the beginning. This function can be performed by using a negative index. Thus arr[-i] is the same as arr[sizeof(arr)-i]. Note however that this behavior does not apply to the range operator. Instead the range operator clamps it's arguments to a suitable range. This means that a[b..c] will be treated as follows:

    5.6 The assignment operators

    There is really only one assignment operator, but it can be combined with lots of other operators to make the code shorter. An assignment looks like this:
    variable = expression;
    The variable can be a local variable, a global variable or an index in an array, object, multiset or mapping. This will of course set the value stored in variable to expression. Note that the above is also an expression which returns the value of the expression. This can be used in some interesting ways:
    variable1 = variable2 = 1; // Assign 1 to both variables
    variable1 =(variable2 = 1); // Same as above

    // Write the value of the expression, if any
    if(variable = expression)
        write(variable);
    Using assignments like this can however be confusing to novice users, or users who come from a Pascal or Basic background. Especially the if statement can be mistaken for if(variable == expression) which would mean something completely different. As I mentioned earlier, the assignment operator can be combined with another operator to form operators that modify the contents of a variable instead of just assigning it. Here is a list of all the combinations:

    Syntax Same as Function
    variable += expression variable = variable + expressionAdd expression to variable
    variable -= expression variable = variable - expressionSubtract expression from variable
    variable *= expression variable = variable * expressionMultiply variable with expression
    variable /= expression variable = variable / expressionDivide variable by expression
    variable %= expression variable = variable % expressionModulo variable by expression
    variable <<= expression variable = variable << expressionShift variable expression bits left
    variable >>= expression variable = variable >> expressionShift variable expression bits right
    variable |= expression variable = variable | expressionOr variable with expression
    variable &= expression variable = variable & expressionAnd variable with expression
    variable ^= expression variable = variable ^ expressionXor variable with expression

    In all of the above expression variable can also be an index in an array, mapping or multiset.

    5.7 The rest of the operators

    Now there are only a couple of operators left. I have grouped them together in this section, not because they are not important, but because they do not fit in any particular categories.

    Function Syntax Identifier Returns
    Calling a ( arguments ) `() Calls the function a.
    splice @ anone Sends each element in the array a as an individual argument to a function call.
    Increment ++ a none Increments a and returns the new value for a.
    Decrement -- a none Decrements a and returns the new value for a.
    Post incrementa ++ none Increments a and returns the old value for a.
    Post decrementa -- none Decrements a and returns the old value for a.
    casting (type) anone Tries to convert a into a value of the specified type.
    Null a, b none Evaluates a and b, then returns b.

    The most important of these operators is the calling operator. It is used to call functions. The operator itself is just a set of parenthesis placed after the expression that returns the function. Any arguments to the function should be placed between the parenthesis, separated by commas. We have already seen many examples of this operator, although you might not have realized it was an operator at the time. The function call operator can do more than just calling functions though; if the 'function' is in fact an array, the operator will loop over the array and call each element in the array and returns an array with the results. If on the other hand, the 'function' is a program, the operator will clone an object from the program and call create() in the new object with the arguments given. In fact, the function clone is implemented like this:

    object clone(mixed p, mixed ... args) { ( (program)p )(@args); }

    On the subject of function calls, the splice operator should also be mentioned. The splice operator is an at sign in front of an expression. The expression should always be an array. The splice operator sends each of the elements in the array as a separate argument to the function call. The splice operator can only be used in an argument list for a function call.

    Then there are the increment and decrement operators. The increment and decrement operators are somewhat limited: they can only be used on integers. They provide a short and fast way to add or subtract one to an integer. If the operator is written before the variable (++a) the returned value will be what the variable is after the operator has added/subtracted one to it. If the operator is after the variable (a++) it will instead return the value of the variable before it was incremented/decremented.

    Casting is used to convert one type to another, not all casts are possible. Here is a list of all casts that actually _do_ anything:

    casting fromtooperation
    intstringConvert the int to ASCII representation
    floatstringConvert the float to ASCII representation
    stringintConvert decimal, octal or hexadecimal number to an int.
    stringfloatConvert ASCII number to a float.
    stringprogramString is a filename, compile the file and return the program. Results are cached.
    stringobjectThis first casts the string to a program, (see above) and then clones the result. Results are cached.

    You can also use the cast operator to tell the compiler things. If a is a variable of type mixed containing an int, then the expression (int)a can be used instead of a and that will tell the compiler that the type of that expression is int.

    Last, and in some respect least, is the comma operator. It doesn't do much. In fact, it simply evaluates the two arguments and then returns the right hand one. This operator is mostly useful to produce smaller code, or to make defines that can be used in expressions.

    5.8 Operator precedence

    When evaluating an expression, you can always use parenthesis to tell the compiler in which order to evaluate things. Normally, the compiler will evaluate things from left to right, but it will evaluate operators with higher priority before those will lower. The following table shows how the relative priority of all the operators in descending order:

    Operators
    (a) a() a[b] a->b a[b..c] ({}) ([]) (<>)
    a++ a--
    !a ~a (type)a ++a --a
    a*b a/b a%b
    a+b a-b
    a>>b a<<b
    a>b a>=b a<b a<=b
    a==b a!=b
    a&b
    a^b
    a|b
    &&
    ||
    a?b:c
    =
    @a
    ,

    Examples:

    The expressionis evaluated in this order:
    1+2*2 1+(2*2)
    1+2*2*4 1+((2*2)*4)
    (1+2)*2*4 ((1+2)*2)*4
    1+4,c=2|3+5 (1+4),(c=(2|3)+5)
    1+5 & 4 == 3 (1+(5 & 4)) == 3
    c=1,99 (c=1),99
    !a++ + ~--a() (!(a++)) + (~((--a)()))

    5.9 Operator functions

    As mentioned earlier a + b can just as well be written as `+(a, b). Together with the function map which calls a function for every index in an array and the splice operator this can be used to create some very very fast and compact code. Let's look at some examples:
    map(arr, `-)
    This will return an array with each element negated.
    map(text/"\n",`/," ")
    This will divide a text into lines, each line will then be mapped through `/ and divided into an array of words.
    `+(0, @arr)
    This will add all the integers in the array arr together.
    int abs(int a) { return ( a>0 ? `+ : `-)(a); }
    This is a rather absurd but working function which will return the absolute value of a.

    Chapter 6, Object orientation

    As mention several times, Pike is object oriented. This does not mean that it is identical to C++ in any way. Pike uses a less strict approach to object orientation which creates a more relaxed programming style. If you have never come in contact with object oriented programming before, be warned that the ideas expressed in Pike and in this chapter are my own and do not necessarily reflect what other people think about object orientated programming.

    6.1 Terminology

    As mentioned before, Pike uses a different terminology than C++ does. This has historic reasons, but might be changed in the future. In the meantime, you might benefit from this mini-dictionary which translates C++-ish to Pike-ish:
    a class
    a class
    a clone
    an instance of a class
    to clone
    to create an instance
    an object
    an instance of a class
    a program
    a class

    6.2 The approach

    Think of the data type program as an executable file. Then we clone this program and create an object. The object is then a running program. The object has its own data and its own functions, however, it can work together with other programs by calling functions in those objects. The functions can be thought of as message carriers, TCP sockets or just a way for programs to communicate. Now we have a running system with many running programs, each performing only the task it was designed for.

    This analogy has one major flaw, when running programs in UNIX they actually run simultaneously. UNIX is multitasking, Pike is not. When one object is executing code, all the other objects has to wait until they are called. An exception is if you are using threads as will be discussed in a later chapter.

    6.3 How does this help?

    Ok, why is it a good idea to use object oriented programming? Well if you believe what you hear, the biggest advantage is that you can re-use your code in several projects. In my experience this is not the case.

    In my experience, the advantages of object oriented programming are:

    Modular programming made easy
    Using The approach makes it easy to divide a project into smaller pieces, these pieces are usually easier to write than the whole.
    Local data scope
    This is a very nifty with object oriented programs. If your program uses several files, windows, stacks, TCP connections or whatever, you simply write a program that handles one such file, window, stack or TCP connection. If correctly written, you can then just create many clones of that program.
    Using the same interface to different objects
    I can write a function that takes a stream as an argument and writes data to this stream. Later I might wish to write this data to a window instead. I can then create an object that has the same methods as a stream (specifically the write method) and send that to the function that outputs the data.
    Most of these things can be done without object orientation, but it is object orientation that makes them easy.

    6.4 Pike and Object Orientation

    In most object oriented languages there is a way to write functions outside of all classes. Some readers might think this is what we have been doing until now. However, in Pike, all functions have to reside within a program. When you write a simple script in Pike, the file is first compiled into a program then cloned and then main() is called in that clone. All this is done by the master object, which is compiled and cloned before before all other objects. What the master object actually does is:
    	program scriptclass=compile_file(argv[0]); // Load script
    	object script=scriptclass();               // clone script
    	int ret=script->main(sizeof(argv), argv);  // call main()
    
    Similarly, if you want to load another file and call functions in it, you can do it with compile_file(), or you can use the cast operator and cast the filename to a string. You can also use the module system, which we will discuss further in the next chapter.

    If you don't want to put each program in a separate file, you can use the class keyword to write all your classes in one file. We have already seen an example how this in chapter 4, but let's go over it in more detail. The syntax looks like this:

    class class_name {
        class_definition
    }
    This construction can be used almost anywhere within a normal program. It can be used outside all functions, but it can also be used as an expression in which case the defined class will be returned. In this case you may also leave out the class_name and leave the class unnamed. The class definition is simply the functions and programs you want to add to the class. It is important to know that although the class is defined in the same file as other classes and functions it can not immediately access data in its surroundings. Only constants defined before the class in the same file can be used. Example:
    constant x = 17;
    class foobar {
         int test() { return x; }
    };
    This works because x is a constant. If x had been a variable or function it would not have worked. In future versions of Pike it may be possible to do this with variables as well. To make it easier to program, defining a class is also to define a constant with that name. Essentially, these two lines of code do the same thing:
    class foo {};
    constant foo = class {};
    Because classes defined as constants, it is possible to use a class defined inside classes you define later, like this:
    class foo
    {
        int test() { return 17; }
    };

    class bar
    {
        program test2() { return foo; }
    };

    6.5 Inherit

    A big part of writing object oriented code is the ability to add functionality to a program without changing (or even understanding) the original code. This is what inherit is all about. Let's say I want to change the hello_world program to write a version number before it writes hello world, using inherit I could do this like this:
    inherit "hello_world";
    int main(int argc, array(string) argv)
    {
        write("Hello world version 1.0\n");
        return ::main(argc,argv);
    }
    What inherit does is that it copies all the variables and functions from the inherited program into the current one. You can then re-define any function or variable you want, and you can call the original one by using a :: in front of the function name. The argument to inherit can be one of the following:
    A string
    This will have the same effect as casting the string to a program and then doing inherit on this program.
    A constant containing a program.
    Any constant from this program, module or inherited program that contains a program can be inherited.
    A class name
    A class defined with the class keyword is in fact added as a constant, so the same rule as above applies.

    Let's look at an example. We'll split up an earlier example into three parts and let each inherit the previous part. It would look something like this:


    Note that the actual code is not copied, only the list of references. Also note that the list of inherits is copied when you inherit a program this does not mean you can access those copied inherit with the :: operator, it is merely an implementation detail. Although this example does not show an example of a re-defined function, it should be easy to see how that works by just changing what an identifier is pointing at.

    6.6 Multiple inherit

    You can inherit any number of programs in one program, you can even inherit the same thing more than once. If you do this you will a separate set of functions and variables for each inherit. To access a specific function you need to name your inherits. Here is an example of named inherits:
    inherit Stdio.File; // This inherit is named File
    inherit Stdio.FILE; // This inherit is named FILE
    inherit "hello_word"; // This inherit is named hello_world
    inherit Stdio.File : test1; // This inherit is named test1
    inherit "hello_world" : test2; // This inherit is named test2

    void test()
    {
        File::read(); // Read data from the first inherit
        FILE::read(); // Read data from the second inherit
        hello_world::main(0,({})); // Call main in third inherit
        test1::read(); // Read data from fourth inherit
        test2::main(0,({})); // Call main in fourth inherit
        ::read(); // Read data from all inherits
    }
    As you can see it would be impossible to separate the different read and main functions without using inherit names. If you tried calling just read without any :: or inherit name in front of it Pike will call the last read defined, in this case it will call read in the fourth inherit.

    If you leave the inherit name blank and just call ::read Pike will call all inherited read() functions. If there is more than one inherited read function the results will be returned in an array.

    Let's look at another example:

    #!/usr/local/bin/pike

    inherit Stdio.File : input;
    inherit Stdio.File : output;

    int main(int argc, array(string) argv)
    {
        output::create("stdout");
        for(int e=1;e<sizeof(argv);e++)
        {
            input::open(argv[e],"r");
                            while(output::write(input::read(4096)) == 4096);
        }
    }
    This short piece of code works a lot like the UNIX command cat. It reads all the files given on the command line and writes them to stdout. As an example, I have inherited Stdio.File twice to show you that both files are usable from my program.

    6.7 Pike Inherit compared to other languages

    Many other languages assign special meaning to inherit. Most common is the notion that if you inherit a class, it means that your class should obey the same rules as the inherited class. In Pike, this is not necessarily so. You may wish to use inherit in Pike like this, but you can just as well choose not to. This may confuse some programmers with previous experience in object oriented programming.

    6.8 Modifiers

    Sometimes, you may wish to hide things from inheriting programs, or prevent functions from being called from other objects. To do so you use modifiers. A modifier is simply a word written before a variable definition, function definition, class definition or an inherit that specifies how this identifier should interact with other objects and programs. These modifiers are available:
    static
    Static hides this identifier from the index and arrow operators, which makes it impossible for other objects to call this function unless a function pointer to it is returned from inside this program.
    nomask
    This prevents other objects from re-defining this identifier in programs that inherit this program.
    private
    This prevents inheriting programs from accessing this identifier. Note that inheriting program can still re-define the identifier. Also note that private does not imply static.
    public
    This is the opposite of private. This is the default for all identifiers. public can be used to override the effects of a private inherit.
    protected
    Reserved for future use.
    When modifiers are used in conjunction with inherit, all the variables, functions and classes copied from the inherited class will be modified with the keywords used. For instance, private inherit means that the identifiers from this inherit will not be available to program inheriting this program. static private inherit will also hide those identifiers from the index and arrow operators, making the inherit available only to the code in this program.

    6.9 Operator Overloading

    Sometimes you want an object to act as if it was a string, an integer or some other data type. It is especially interesting to be able to use the normal operators on objects to allow short and readable syntax. In Pike, special methods are called when an operator is used with an object. To some extent, this is work in progress, but what has been done so far is very useful and will not be subject to change.

    The following table assumes that a and b are objects and shows what will be evaluated if you use that particular operation on an object. Note that some of these operators, notably == and ! have default behavior which will be used if the corresponding method is not defined in the object. Other operators will simply fail if called with objects. Refer to chapter 5 "Operators" for information on which operators can operate on objects without operator overloading.

    OperationWill call
    a+ba->`+(b)
    a+b+c+da->`+(b,c,d)
    a-ba->`-(b)
    a&ba->`&(b)
    a|ba->`|(b)
    a^ba->`^(b)
    a>>ba->`>>(b)
    a<<ba->`<<(b)
    a*ba->`*(b)
    a*b*c*da->`*(b,c,d)
    a/ba->`/(b)
    a%ba->`%(b)
    ~aa->`~()
    a==ba->`==(b) or b->`==(a)
    a!=b!( a->`==(b) ) or !( b->`==(a) )
    a<ba->`<(b)
    a>ba->`>(b)
    a<=b!( b->`>(a) )
    a>=b!( b->`<(a) )
    (int)aa->cast("int")
    !aa->`!()
    if(a) { ... } !( a->`!() )
    a[b]a->`[](b)
    a[b]=ca->`[]=(b,c)
    a->fooa->`->("foo")
    a->foo=ba->`->=("foo",b)
    sizeof(a)a->_sizeof()
    indices(a)a->_indices()
    values(a)a->_values()
    a(b)a->`()(b)

    Here is a really silly example of a program that will write 10 to stdout when executed.

    #!/usr/local/bin/pike
    class three {
        int `+(int foo) { return 3+foo; }
    };

    int main()
    {
        write(sprintf("%d\n",three()+7));
    }
    It is important to know that some optimizations are still performed even when operator overloading is in effect. If you define a multiplication operator and multiply your object with one, you should not be surprised if the multiplication operator is never called. This might not always be what you expect, in which case you are better off not using operator overloading.

    6.10 Simple exercises

    • Make a program that clones 10 hello world and then runs main() in each one of them.
    • Modify the register program to use an object for each record.
    • Modify the register program to use the following search function:
      void find_song(string title)
      {
          string name, song;
          int hits;

          title=lower_case(title);

          foreach(indices(records),name)
          {
              if(string song=records[name][title])
                              {
                                  write(name+"; "+song+"\n");
                                  hits++;
              }
          }

          if(!hits) write("Not found.\n");
      }

    Chapter 7, Miscellaneous functions

    There are some 'functions' in Pike that are not really functions at all but just as builtin as operators. These special functions can do things that no other functions can do, but they can not be re-defined or overloaded. In this chapter I will describe these functions and why they are implemented as special functions.

    7.1 sscanf

    Sscanf may look exactly like a normal function, but normal functions can not set the variables you send to it. The purpose of sscanf is to match one string against a format string and place the matching results into a list of variables. The syntax looks like this:
    int sscanf(string str, string fmt, lvalue ...)
    The string str will be matched against the format string fmt. fmt can contain strings separated by %d,%s,%c and %f. Every % corresponds to one lvalue. An lvalue is the name of a variable, a name of a local variable, an index in an array, mapping or object. It is because of these lvalues that sscanf can not be implemented as a normal function.

    Whenever a percent is found in the format string, a match is according to the following table:
    %d reads an integer
    %o reads an octal integer
    %x reads a hexadecimal integer
    %D reads an integer that is either octal (leading zero), hexadecimal (leading 0x) or decimal.
    %f reads a float
    %c matches one char and returns it as an integer
    %2c matches two chars and returns them as an integer (short)
    %s reads a string. If followed by %d, %s will read any non-numerical characters. If followed by a %[], %s will read any characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text.
    %5s gives a string of 5 characters (5 can be any number)
    %[set] matches a string containing a given set of characters (those given inside the brackets). %[^set] means any character except those inside brackets. Example: %[0-9H] means any number or 'H'.

    If a * is put between the percent and the operator, the operator will only match its argument, not assign any variables.

    Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.

    Let's look at a couple of examples:

    // a will be assigned "oo" and 1 will be returned
    sscanf("foo","f%s",a);

    // a will be 4711 and b will be "bar", 2 will be returned
    sscanf("4711bar","%d%s",a,b);

    // a will become "test"
    sscanf(" \t test","%*[ \t]%s",a)

    // Remove "the " from the beginning of a string
    // If 'str' does not begin with "the " it will not be changed
    sscanf(str,"the %s",str);

    SEE ALSO : sprintf

    7.2 catch & throw

    Catch is used to trap errors and other exceptions in Pike. It works by making a block of code into an expression, like this:
    catch { statements }
    If an error occurs, catch will return a description of the error. The description of the error has the following format:
    ({
         "error description",
         backtrace()
    })
    If no error occurs, catch will return zero. You may emulate your own errors using the function throw, described in
    chapter 15 "All the builtin functions".

    Example:

    int x,y;
    // This might generate "division by zero"
    mixed error=catch { x/=y; };

    7.3 gauge

    The syntax for gauge is the same as the syntax for catch:
    gauge { statements }
    However, gauge simply returns how many milliseconds the code took to execute. This can be used to find out how fast your code actually is.. :) Only CPU time used by the Pike process is measured. This means that if it takes two seconds to execute but only uses 50% CPU, this function will return 1000.

    7.4 typeof

    This function returns the type of an expression as a string. It does not evaluate the expression at all, which might be somewhat confusing. Example:
    typeof( exit(1) )
    This will return the string "void" since exit is a function that returns void. It will not execute the function exit and exit the process as you might expect.

    Chapter 8, Modules

    A module is a software package that plugs into the Pike programming environment. They provide you with simple interfaces to system routines and they also constitute a neat way to use your own C/C++ code from within Pike. Pike comes with a number of modules that are ready to use. In this chapter I will explain the basics of modules and how to use them.

    here is a list of the basic Pike modules:

    Stdio
    This module contains file I/O routines.
    Array
    This function contains functions that operate on arrays.
    Gdbm *
    This module contains support for Gdbm databases.
    Getopt
    Routines to parse command line options
    Gmp *
    Support for large numbers.
    Gz *
    Deflate packing algorithms.
    Image
    Image manipulation routines.
    LR
    LALR(1) parser generator.
    Msql *
    Sql database support for the mini-SQL database server.
    MIME
    Support for coding and decoding MIME.
    Mysql *
    Sql database support for the mySQL database server.
    Process
    Functions to start and control other processes.
    Regexp
    Regexp matching routines.
    Simulate
    Routines to emulate old Pike routines.
    String
    Routines that operate on strings.
    Sql *
    Generic SQL database support.
    System
    Support for system specific functions
    Thread *
    Thread support functions.
    Yp *
    Network Information System support.

    * These modules might not be available depending on how Pike was compiled and whether support for these functions exist on your system.

    8.1 How to use modules

    A module is a bunch of functions, programs or other modules collected in one symbol. For instance, the module Stdio contains the objects stdin, stdout and stderr. To access these objects you can write Stdio.stdin, Stdio.stdout or Stdio.stderr anywhere in your program where an object of that type is acceptable. If you use Stdio a lot you can use put import Stdio; in the beginning of your program. This will import all the identifiers from the module Stdio into your program, making it possible to write just stdin instead of Stdio.stdin.

    8.2 Where do modules come from?

    Modules are not loaded until you use them, which saves memory unless you use all the modules. However, if you want to write your own modules it is important to know how modules are located and loaded.

    When you use Stdio Pike will look for that module:

    1. In the same directory as the source.
    2. In directories added with add_module_path()
    3. In directories specified with -M on the command line.
    4. In directories in the environment variable PIKE_MODULE_PATH
    5. In the directory with builtin modules, usually /usr/local/lib/pike/modules/
    For each of these directories, Pike will do the following:
    1. If there is a file called Stdio.pmod.pike, Pike will load this Pike program, clone it and use that as a module.
    2. If there is a file called Stdio.pmod.so, Pike will load this with load_module(), clone it and use that as a module.
    3. If there is a directory called Stdio.pmod, Pike will create a module containing all the modules in that directory as identifiers. If there is a module called module in that directory, all identifiers from that module will overload any modules actually present in the directory.
    As you can see, quite a lot of work goes into finding the modules, this makes it possible to choose the most convenient way to build your own Pike modules.

    8.3 The . operator

    The period operator is not really an operator, as it is always evaluated during the compilation. It works similarly to the index and arrow operators, but can only be used on constant values such as modules. In most cases, modules are simply a clone of a program, in which case the identifiers in the module will be the same as those in the program. But some modules, like those created from directories, overload the index operator so that the identifiers in the module can be something other than those in the program. For directory modules, the index operator looks in the directory it was cloned for to find the identifiers.

    8.4 How to write a module

    Here is an example of a simple module:
    constant PI = 3.14159265358979323846264338327950288419716939937510;
    float cos2(float f) { return pow(cos(f),2.0); }
    if we save this short file as Trig.pike.pmod we can now use this module like this:
    int main()
    {
        write(sprintf("%f\n",Trig.cos2(Trig.PI));
    }
    or like this:
    import Trig;

    int main()
    {
        write(sprintf("%f\n",cos2(PI));
    }

    8.5 Simple exercises

    • Save the hello_world.pike program as hello_world.pike.pmod, then make a program that loads this module and calls its main().
    • Make a directory called Programs.pmod and put all the examples you have written so far in it. Make a program that runs one of those programs. Make sure the program can be modified to run another of your examples by changing what module it loads.
    • Copy the file hello_world.pike.pmod to programs/module.pike.pmod and then write a program that runs hello_world without actually using the identifier hello_world.
    • Try putting Programs.pmod in another directory and then try to run the programs from the last two examples.

    Chapter 9, File I/O

    Programming without reading and writing data from files, sockets, keyboard etc. would be quite pointless. Luckily enough, Pike provides you with an object oriented interface to files, pipes and TCP sockets. All I/O functions and classes are collected in the module Stdio.

    9.1 Stdio.File

    This is the basic I/O object, it provides socket communication as well as file access. It does not buffer reads and writes or provide line-by-line reading, that is done in the FILE object. Stdio.File is completely written in C. What follows is a description of all the functions in Stdio.File.

    METHOD
    Stdio.File->create - init file struct

    SYNTAX
    object(Stdio.File) Stdio.File();
    object(Stdio.File) Stdio.File(string fd);
    object(Stdio.File) Stdio.File(string file, string mode);

    DESCRIPTION
    There are three different ways to clone a File. The first is to clone it without any arguments, in which case the you have to call open(), connect() or some other method which connects the File object with a stream.

    However, instead of cloning and then calling open(), you can clone the File with a filename and open mode. This is the same thing as cloning and then calling open, except shorter and faster.

    Alternatively, you can clone a File with "stdin", "stdout" or "stderr" as argument. This will open the specified standard stream.

    SEE ALSO
    clone and Stdio.File->open

    METHOD
    Stdio.File->open - open a file

    SYNTAX
    int open(string filename, string how);

    DESCRIPTION
    Open a file for read, write or append. The variable how should contain one or more of the following letters:

    'r' open file for reading
    'w' open file for writing
    'a' open file for append (use with 'w')
    't' truncate file at open (use with 'w')
    'c' create file if it doesn't exist (use with 'w')
    'x' fail if file already exist (use with 'c')

    How should _always_ contain at least one of 'r' or 'w'.

    Returns 1 on success, 0 otherwise.

    SEE ALSO
    Stdio.File->close

    METHOD
    Stdio.File->close - close a file

    SYNTAX
    int close(string how);
    int close();

    DESCRIPTION
    Close the file. Optionally, specify "r", "w" or "rw" to close just the read, just the write or both read and write part of the file respectively. Note that this function will not call the close_callback.

    SEE ALSO
    Stdio.File->open

    METHOD
    Stdio.File->read - read data from a file or stream

    SYNTAX
    string read(int nbytes);
    string read(int nbytes, int notall);
    string read();

    DESCRIPTION
    Read tries to read nbytes bytes from the file, and return it as a string. If something goes wrong, zero is returned.

    If a one is given as second argument to read(), read will not try its best to read as many bytes as you asked it to read, it will merely try to read as many bytes as the system read function will return. This mainly useful with stream devices which can return exactly one row or packet at a time.

    If no arguments are given, read will read to the end of the file/stream.

    SEE ALSO
    Stdio.File->write

    METHOD
    Stdio.File->write - write data to a file or stream

    SYNTAX
    int write(string data);

    DESCRIPTION
    Write data to file or stream and return how many bytes that was actually written. -1 is returned if something went wrong and no bytes had been written.

    SEE ALSO
    Stdio.File->read

    METHOD
    Stdio.File->seek - seek to a position in a file

    SYNTAX
    int seek(int pos);

    DESCRIPTION
    Seek to a position in a file, if pos is less than zero, seek to position pos relative end of file. Returns -1 for failure, or the old position in the file when successful.

    SEE ALSO
    Stdio.File->tell

    METHOD
    Stdio.File->tell - tell where we are in a file

    SYNTAX
    int tell();

    DESCRIPTION
    Returns the current position in the file.

    SEE ALSO
    Stdio.File->seek

    METHOD
    Stdio.File->stat - do file_stat on an open file

    SYNTAX
    int *stat();

    DESCRIPTION
    This function returns the same information as the function file_stat, but for the file it is called in. If file is not an open file, zero will be returned. Zero is also returned if file is a pipe or socket.

    SEE ALSO
    file_stat

    METHOD
    Stdio.File->errno - what was last error?

    SYNTAX
    int errno();

    DESCRIPTION
    Returns the error code for the last command on this file. Error code is normally cleared when a command is successful.

    METHOD
    Stdio.File->set_buffer - set internal socket buffer

    SYNTAX
    void set_buffer(int bufsize, string mode);
    void set_buffer(int bufsize);

    DESCRIPTION
    This function sets the internal buffer size of a socket or stream. The second argument allows you to set the read or write buffer by specifying "r" or "w". It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.

    SEE ALSO
    Stdio.File->open_socket and Stdio.Port->accept

    METHOD
    Stdio.File->set_nonblocking - make stream nonblocking

    SYNTAX
    void set_nonblocking(function read_callback,
    function write_callback,
    function close_callback);
    or
    void set_nonblocking();

    DESCRIPTION
    This function sets a stream to nonblocking mode. When data arrives on the stream, read_callback will be called with some or all of this data. When the stream has buffer space over for writing, write_callback is called so you can write more data to it. If the stream is closed at the other end, close_callback is called. All callbacks will have the id of file as first argument when called.

    If no arguments are given, the callbacks are not changed. The stream is just set to nonblocking mode.

    SEE ALSO
    Stdio.File->set_blocking

    METHOD
    Stdio.File->set_read_callback - set the read callback

    SYNTAX
    void set_read_callback(function read_callback)

    DESCRIPTION
    This function sets the read callback for the file. The read callback is called whenever there is data to read from the file. Note that this function does not set the file nonblocking.

    SEE ALSO
    Stdio.File->set_nonblocking

    METHOD
    Stdio.File->set_write_callback - set the write callback

    SYNTAX
    void set_write_callback(function write_callback)

    DESCRIPTION
    This function sets the write callback for the file. The write callback is called whenever there is buffer space available to write to for the file. Note that this function does not set the file nonblocking.

    SEE ALSO
    Stdio.File->set_nonblocking

    METHOD
    Stdio.File->set_close_callback - set the close callback

    SYNTAX
    void set_close_callback(function close_callback)

    DESCRIPTION
    This function sets the close callback for the file. The close callback is called when the remote end of a socket or pipe is closed. Note that this function does not set the file nonblocking.

    SEE ALSO
    Stdio.File->set_nonblocking

    METHOD
    Stdio.File->set_blocking - make stream blocking

    SYNTAX
    void set_blocking();

    DESCRIPTION
    This function sets a stream to blocking mode. ie. all reads and writes will wait until data has been written before returning.

    SEE ALSO
    Stdio.File->set_nonblocking

    METHOD
    Stdio.File->set_id - set id of this file

    SYNTAX
    void set_id(mixed id);

    DESCRIPTION
    This function sets the id of this file. The id is mainly used as an identifier that is sent as the first arguments to all callbacks. The default id is 0. Another possible use of the id is to hold all data related to this file in a mapping or array.

    SEE ALSO
    Stdio.File->query_id

    METHOD
    Stdio.File->query_id - get id of this file

    SYNTAX
    mixed query_id();

    DESCRIPTION
    This function returns the id of this file.

    SEE ALSO
    Stdio.File->set_id

    METHOD
    Stdio.File->query_read_callback - return the read callback function

    SYNTAX
    function query_read_callback();

    DESCRIPTION
    This function returns the read_callback, which is set with set_nonblocking or set_read_callback.

    SEE ALSO
    Stdio.File->set_nonblocking and Stdio.File->set_read_callback

    METHOD
    Stdio.File->query_write_callback - return the write callback function

    SYNTAX
    function query_write_callback();

    DESCRIPTION
    This function returns the write_callback, which is set with set_nonblocking or set_write_callback.

    SEE ALSO
    Stdio.File->set_nonblocking and Stdio.File->set_write_callback

    METHOD
    Stdio.File->query_close_callback - return the close callback function

    SYNTAX
    function query_close_callback();

    DESCRIPTION
    This function returns the close_callback, which is set with set_nonblocking or set_close_callback.

    SEE ALSO
    Stdio.File->set_nonblocking and Stdio.File->set_close_callback

    METHOD
    Stdio.File->dup - duplicate a file

    SYNTAX
    object(Stdio.File) dup();

    DESCRIPTION
    This function returns a clone of Stdio.File with all variables copied from this file. Note that all variables, even id, is copied.

    SEE ALSO
    Stdio.File->assign

    METHOD
    Stdio.File->dup2 - duplicate a file over another

    SYNTAX
    int dup2(object(Stdio.File) to);

    DESCRIPTION
    This function works similarly to Stdio.File->assign, but instead of making the argument a reference to the same file, it creates a new file with the same properties and places it in the argument.

    EXAMPLE
    /* Redirect stdin to come from the file 'foo' */
    object o=Stdio.File();
    o->open("foo","r");
    o->dup2(Stdio.File("stdin"));

    SEE ALSO
    Stdio.File->assign and Stdio.File->dup

    METHOD
    Stdio.File->assign - assign a file

    SYNTAX
    void assign(object f);

    DESCRIPTION
    This function takes a clone of Stdio.File and assigns all variables of this file from it. It can be used together with file->dup to move files around.

    SEE ALSO
    Stdio.File->dup

    METHOD
    Stdio.File->open_socket - open a socket

    SYNTAX
    int open_socket(int|void port, int|void address);

    DESCRIPTION
    This makes this file into a socket ready for connection. The reason for this function is so that you can set the socket to nonblocking or blocking (default is blocking) before you call Stdio.File->connect() This function returns 1 for success, 0 otherwise.

    If you give a port number to this function, the socket will be bound to this port locally before connecting anywhere. This is only useful for some silly protocols like FTP. You may also specify an address to bind to if your machine has many IP numbers.

    SEE ALSO
    Stdio.File->connect and Stdio.File->set_nonblocking

    METHOD
    Stdio.File->connect - connect a socket to something

    SYNTAX
    int connect(string IP,int port);

    DESCRIPTION
    This function connects a socket previously created with Stdio.File->open_socket to a remote socket. The argument is the IP name or number for he remote machine.

    This function returns 1 for success, 0 otherwise. Note that if the socket is in nonblocking mode, you have to wait for a write or close callback before you know if the connection failed or not.

    SEE ALSO
    Stdio.File->query_address

    METHOD
    Stdio.File->query_address - get addresses

    SYNTAX
    string query_address();
    string query_address(1);

    DESCRIPTION
    This function returns the remote or local address of a socket on the form "x.x.x.x port". Without argument, the remote address is returned, with argument the local address is returned. If this file is not a socket, not connected or some other error occurs, zero is returned.

    SEE ALSO
    Stdio.File->connect

    METHOD
    Stdio.File->pipe - create a two-way pipe

    SYNTAX
    object pipe();

    DESCRIPTION
    This function creates a pipe between the object it was called in and an object that is returned. The two ends of the pipe are indistinguishable. If the File object this function is called in was open to begin with, it is closed before the pipe is created.

    SEE ALSO
    fork

    METHOD
    Stdio.File->set_close_on_exec - set / clear the close on exec flag

    SYNTAX
    void set_close_on_exec(int onoff);

    DESCRIPTION
    This function determines whether this file will be closed when calling exece. Default is that the file WILL be closed on exec except for stdin, stdout and stderr.

    SEE ALSO
    exece

    Here is an example of how to use the TCP functions in Stdio.File in blocking mode. This short program takes a URL as first argument, connects to the WWW server, sends a HEAD request and writes the reply to stdout. For clarity, all calls to Stdio.File use File:: even if that is not strictly necessary.

    import Stdio;
    inherit File;

    int main(int argc, array(string) argv)
    {
        string host;
        string path="";
        int port=80;
        sscanf(argv[1],"http://%s",argv[1]);
        sscanf(argv[1],"%s/%s",host,path);
        sscanf(host,"%s:%d",host,port);

        if(!File::open_socket())
        {
            perror("Open socket failed");
            exit(1);
        }

        if(!File::connect(host,port))
        {
            perror("Failed to connect to remote host");
            exit(1);
        }

        File::write(sprintf("HEAD /%s HTTP/1.0\n",path));
        stdout::write(File::read());
    }

    9.2 Stdio.FILE

    Stdio.FILE is a buffered version of Stdio.File, it inherits Stdio.File and has most of the functionality of Stdio.File. However, it has an input buffer that allows line-by-line input. Note that the output part of Stdio.FILE is not buffered at this moment. The added functionality of Stdio.FILE is described here:

    METHOD
    Stdio.FILE->gets - get one line

    SYNTAX
    string gets();

    DESCRIPTION
    This function returns one line from the FILE, it returns zero if no more lines are available.

    METHOD
    Stdio.FILE->printf - formatted print

    SYNTAX
    string printf(string format, mixed ... data);

    DESCRIPTION
    This function does approximately the same as: write(sprintf(format,@data))

    SEE ALSO
    sprintf

    METHOD
    Stdio.FILE->ungets - put a string back in the buffer

    SYNTAX
    string ungets(string s);

    DESCRIPTION
    This function puts a string back in the input buffer. The string can then be read with read, gets or getchar.

    METHOD
    Stdio.FILE->getchar - get one character from the input stream

    SYNTAX
    int getchar();

    DESCRIPTION
    This function returns one character from the input stream. Note that the return value is the ascii value of the character, not a string containing one character.

    9.3 Standard streams

    Any UNIX program has three files open from the beginning. These are called standard input, standard output and standard error stream. These streams are available from Pike as well. They are called Stdio.stdin, Stdio.stdout and Stdio.stderr respectively. Standard input is a clone of Stdio.FILE, which means you can use the line oriented functions. Stdio.stdout and Stdio.stderr are simply clones of Stdio.File.

    Example:

    int main()
    {
        int line;
        while(string s=Stdio.stdin.gets())
            write(sprintf("%5d: %s\n",line++,s));
    }
    This example will read lines from standard input for as long as there are more lines to read. Each line will then be written to stdout together with the line number. We could use Stdio.stdout.write instead of just write because they are the same function.

    9.4 Other Stdio functions

    The Stdio module also contains a collection of high level IO functions to make it easy to write short and readable Pike programs. Most of these functions are implemented using Stdio.File and Stdio.FILE.

    FUNCTION
    Stdio.file_size - return the size of a file in bytes

    SYNTAX
    int file_size(string file);

    DESCRIPTION
    Give the size of a file. Size -1 indicates that the file either does not exist, or that it is not readable by you. Size -2 indicates that it is a directory.

    SEE ALSO
    Stdio.write_file and Stdio.read_bytes

    FUNCTION
    Stdio.perror - print error

    SYNTAX
    void perror(string s);

    DESCRIPTION
    This function prints a message to stderr along with a description of what went wrong if available. It uses the system errno to find out what went wrong, so it is only applicable to IO errors.

    SEE ALSO
    Stdio.werror

    FUNCTION
    Stdio.read_bytes - read a number of bytes into a string from a file

    SYNTAX
    string read_bytes(string file,int start,int len);
    string read_bytes(string file,int start);
    string read_bytes(string file);

    DESCRIPTION
    Read len number of bytes from file file staring at byte start and return it as a string. If len is omitted, the rest of the file will be returned. If start is also omitted, the entire file will be returned.

    SEE ALSO
    Stdio.write_file

    FUNCTION
    Stdio.read_file - read a number of lines into a string from file

    SYNTAX
    string read_file(string file, int start, int len);
    string read_file(string file);

    DESCRIPTION
    Read len lines from the file file after skipping start lines and return those lines as a string. If start and len are omitted the whole file is read.

    SEE ALSO
    Stdio.read_bytes and Stdio.write_file

    FUNCTION
    Stdio.readline - read a line from stdin

    SYNTAX
    string readline(string prompt);

    DESCRIPTION
    This function writes the string prompt and then waits until the user has entered a line from the keyboard. If the readline library was available when Pike was compiled the user will have history and line editing at his/her disposal when entering the line.

    SEE ALSO
    Stdio.File

    FUNCTION
    Stdio.werror - write to stderr

    SYNTAX
    void werror(string s);

    DESCRIPTION
    Writes a message to stderr. Stderr is normally the console, even if the process output has been redirected to a file or pipe.

    FUNCTION
    Stdio.write_file - append a string to a file

    SYNTAX
    int write_file(string file, string str)

    DESCRIPTION
    Append the string str onto the file file. Returns number of bytes written.

    SEE ALSO
    Stdio.read_bytes

    9.5 Listening to sockets

    Stdio.File can handle connections to any TCP socket, but it can not listen to a local TCP port. For this purpose there is a special class called Stdio.Port. Stdio.Port cannot read or write any data, but it can accept connections which will be returned as clones of Stdio.File. These are the methods available in Stdio.Port:

    METHOD
    Stdio.Port->bind - open socket and bind it to a port

    SYNTAX
    int bind(int port);
    int bind(int port,function accept_callback);
    int bind(int port,function accept_callback, string IP);

    DESCRIPTION
    Bind opens a sockets and binds it to port number on the local machine. If the second argument is present, the socket is set to nonblocking and the callback function is called whenever something connects to the socket. The callback will receive the id for this port as argument. Bind returns 1 on success, and zero on failure.

    If the optional argument IP is given, bind will try to bind to this IP name (or number).

    SEE ALSO
    Stdio.Port->accept

    METHOD
    Stdio.Port->listen_fd - listen to an already open port

    SYNTAX
    int listen_fd(int fd);
    int listen_fd(int fd,function accept_callback);

    DESCRIPTION
    This function does the same as Stdio.Port->bind, except that instead of creating a new socket and bind it to a port, it expects that the file descriptor fd is an already open port.

    NOTA BENE
    This function is only for the advanced user, and is generally used when sockets are passed to Pike at exec time.

    SEE ALSO
    Stdio.Port->bind and Stdio.Port->accept

    METHOD
    Stdio.Port->create - create and/or setup a port

    SYNTAX
    object(Stdio.Port) Stdio.Port("stdin")
    object(Stdio.Port) Stdio.Port("stdin",function accept_callback)
    object(Stdio.Port) Stdio.Port("stdin",function accept_callback)
    object(Stdio.Port) Stdio.Port(int port)
    object(Stdio.Port) Stdio.Port(int port,function accept_callback)
    object(Stdio.Port) Stdio.Port(int port,function accept_callback, string ip)

    DESCRIPTION
    When create is called with "stdin" as argument, a socket is created out of the file descriptor 0. This is only useful if that actually is a socket to begin with. When create is called with an int as first argument, it does the same as bind() would do with the same arguments. The second and third argument has the same function as in the bind() call.

    SEE ALSO
    clone and Stdio.Port->bind

    METHOD
    Stdio.Port->set_id - set the id of a port

    SYNTAX
    void set_id(mixed id);

    DESCRIPTION
    This function sets the id used for accept_callback by this port. The default id is this_object().

    SEE ALSO
    Stdio.Port->query_id

    METHOD
    Stdio.Port->query_id - Return the id for this port.

    SYNTAX
    mixed query_id();

    DESCRIPTION
    This function returns the id for this port. The id is normally the first argument to accept_callback.

    SEE ALSO
    Stdio.Port->set_id

    METHOD
    Stdio.Port->errno - return the last error

    SYNTAX
    int errno();

    DESCRIPTION
    If the last call done on this port failed, errno will return an integer describing what went wrong. Refer to your Unix manual for further information.

    SEE ALSO
    Stdio.Port->errno

    METHOD
    Stdio.Port->accept - accept a connection

    SYNTAX
    object accept();

    DESCRIPTION
    This function completes a connection made from a remote machine to this port. It returns a two-way stream in the form of a copy of Stdio.File. The new file is by default set to blocking.

    SEE ALSO
    Stdio.File

    9.6 A more complex example - a simple WWW server

    As most of you know, WWW WWW (World Wide Web), works by using a client program which will fetch files from remote servers when asked. Usually by clicking a picture or text. This example is a program for the server which will send files to any computer that requests them. The protocol used to send the file is called HTTP. (Hyper-Text Transfer Protocol)

    Usually WWW involves HTML. HTML (Hyper-Text Markup Language) is a way to write documents with embedded pictures and links to other pages. These links are normally displayed underlined and if you click them your WWW- browser will load whatever document that link leads to.

    #!/usr/local/bin/pike

    /* A very small httpd capable of fetching files only. * Written by Fredrik Hübinette as a demonstration of Pike. */

    inherit Stdio.Port;
    We inherit Stdio.Port into this program so we can bind a TCP socket to accept incoming connection. A socket is simply a number to separate communications to and from different programs on the same computer.

    Next are some constants that will affect how uHTTPD will operate. This uses the preprocessor directive #define. The preprocessor is the first stage in the compiling process and can make textual processing of the code before it is compiled. As an example, after the first define below, all occurrences of 'BLOCK' will be replaced with 16060.

    /* Amount of data moved in one operation */
    #define BLOCK 16060

    /* Where do we have the html files ? */
    #define BASE "/usr/local/html/"

    /* File to return when we can't find the file requested */
    #define NOFILE "/user/local/html/nofile.html"

    /* Port to open */
    #define PORT 1905
    A port is a destination for a TCP connection. It is simply a number on the local computer. 1905 is not the standard port for HTTP connections though, which means that if you want to access this WWW server from a browser you need to specify the port like this: http://my.host.my.domain:1905/

    Next we declare a class called output_class. Later we will clone one instance of this class for each incoming HTTP connection.

    class output_class
    {
        inherit Stdio.File : socket;
        inherit Stdio.File : file;
    Our new class inherits Stdio.File twice. To be able to separate them they are then named 'socket' and 'file'.

        int offset=0;
    Then there is a global variable called offset which is initialized to zero. (Each instance of this class will have its own instance of this variable, so it is not truly global, but...) Note that the initialization is done when the class is cloned (or instantiated if you prefer C++ terminology).

    Next we define the function write_callback(). Later the program will go into a 'waiting' state, until something is received to process, or until there is buffer space available to write output to. When that happens a callback will be called to do this. The write_callback() is called when there is buffer space available. In the following lines 'void' means that it does not return a value. Write callback will be used further down as a callback and will be called whenever there is room in the socket output buffer.

        void write_callback()
        {
            int written;
            string data;
    The following line means: call seek in the inherited program 'file'.
            file::seek(offset);
    Move the file pointer to the where we want to the position we want to read from. The file pointer is simply a location in the file, usually it is where the last read() ended and the next will begin. seek() can move this pointer to where we want it though.

            data=file::read(BLOCK);
    Read BLOCK (16060) bytes from the file. If there are less that that left to read only that many bytes will be returned.

            if(strlen(data))
            {
    If we managed to read something...

                written=socket::write(data);
    ... we try to write it to the socket.

                if(written >= 0)
                {
                    offset+=written;
                    return;
                }
    Update offset if we managed to write to the socket without errors.

                werror("Error: "+socket::errno()+".\n");
            }
    If something went wrong during writing, or there was nothing left to read we destruct this instance of this class.

            destruct(this_object());
        }
    That was the end of write_callback()

    Next we need a variable to buffer the input received in. We initialize it to an empty string.

        string input="";
    And then we define the function that will be called when there is something in the socket input buffer. The first argument 'id' is declared as mixed, which means that it can contain any type of value. The second argument is the contents of the input buffer.

        void read_callback(mixed id,string data)
        {
            string cmd;

            input+=data;
    Append data to the string input. Then we check if we have received a a complete line yet. If so we parse this and start outputting the file.

            if(sscanf(input,"%s %s%*[\012\015 \t]",cmd,input)>2)
            {
    This sscanf is pretty complicated, but in essence it means: put the first word in 'input' in 'cmd' and the second in 'input' and return 2 if successful, 0 otherwise.

                if(cmd!="GET")
                {
                    werror("Only method GET is supported.\n");
                    destruct(this_object());
                    return;
                }
    If the first word isn't GET print an error message and terminate this instance of the program. (and thus the connection)
                sscanf(input,"%*[/]%s",input);
    Remove the leading slash.

                input=BASE+combine_path("/",input);
    Combine the requested file with the base of the HTML tree, this gives us a full filename beginning with a slash. The HTML tree is the directory on the server in which the HTML files are located. Normally all files in this directory can be accessed by anybody by using a WWW browser. So if a user requests 'index.html' then that file name is first added to BASE (/home/hubbe/www/html/ in this case) and if that file exists it will be returned to the browser.
                if(!file::open(input,"r"))
                {
    Try opening the file in read-only mode. If this fails, try opening NOFILE instead. Opening the file will enable us to read it later.

                    if(!file::open(NOFILE,"r"))
                    {
    If this fails too. Write an error message and destruct this object.

                        werror("Couldn't find default file.\n");
                        destruct(this_object());
                        return;
                    }
                }
    Ok, now we set up the socket so we can write the data back.
                socket::set_buffer(65536,"w");
    Set the buffer size to 64 kilobytes.

                socket::set_nonblocking(0,write_callback,0);
    Make it so that write_callback is called when it is time to write more data to the socket.

                write_callback();
    Jump-start the writing.
            }
        }
    That was the end of read_callback().

    This function is called if the connection is closed while we are reading from the socket.

        void selfdestruct() { destruct(this_object()); }

    This function is called when the program is instantiated. It is used to set up data the way we want it. Extra arguments to clone() will be sent to this function. In this case it is the object representing the new connection.

        void create(object f)
        {
            socket::assign(f);
    We insert the data from the file f into 'socket'.

            socket::set_nonblocking(read_callback,0,selfdestruct);
    Then we set up the callback functions and sets the file nonblocking. Nonblocking mode means that read() and write() will rather return that wait for I/O to finish. Then we sit back and wait for read_callback to be called.

        }
    End of create()

    };
    End of the new class.

    Next we define the function called when someone connects.

    void accept_callback()
    {
        object tmp_output;
    This creates a local variable of type 'object'. An object variable can contain a clone of any program. Pike does not consider clones of different programs different types. This also means that function calls to objects have to be resolved at run time.

        tmp_output=accept();
    The function accept clones a Stdio.File and makes this equal to the newly connected socket.

        if(!tmp_output) return;
    If it failed we just return.

        output_class(tmp_output);
    Otherwise we clone an instance of 'output_class' and let it take care of the connection. Each clone of output_class will have its own set of global variables, which will enable many connections to be active at the same time without data being mixed up. Note that the programs will not actually run simultaneously though.

        destruct(tmp_output);
    Destruct the object returned by accept(), output_class has already copied the contents of this object.

    }

    Then there is main, the function that gets it all started.
    int main(int argc, array(string) argv)
    {
        werror("Starting minimal httpd\n");
    Write an encouraging message to stderr.
        if(!bind(PORT, accept_callback))
        {
            werror("Failed to open socket (already bound?)\n");
            return 17;
        }

    Bind PORT and set it up to call accept_callback as soon as someone connects to it. If the bind() fails we write an error message and return the 17 to indicate failure.
        return - 17; /* Keep going */
    If everything went ok, we return -17, any negative value returned by main() means that the program WON'T exit, it will hang around waiting for events instead. (like someone connecting)
    }
    That's it, this simple program can be used as the basis for a simple WWW-server. Note that today most WWW servers are very complicated programs, and the above program can never replace a modern WWW server. However, it is very fast if you only want a couple of web pages and have a slow machine available for the server.

    Chapter 10, Threads

    Threads are used to run several Pike functions at the same time without having to start several Pike processes. Using threads often simplifies coding and because the threads are within the same process, data can be shared or sent to other threads very fast. Threads are not supported on all systems, you may test if you have thread support with the preprocessor construction #if constant(thread_create). Pike needs POSIX or UNIX thread support when compiled to support threads.

    10.1 Starting a thread

    Starting a thread is very easy. You simply call thread_create with a function pointer and any arguments it needs and that function will be executed in a separate thread. The function thread_create will return immediately and both the calling function and the called function will execute at the same time. Example:
    void foo(int x)
    {
        for(int e=0;e<5;e++)
        {
            sleep(1);
            write("Hello from thread "+x+".\n");
        }
    }

    int main()
    {
        thread_create(foo, 2);
        thread_create(foo, 3);
        foo(1);
    }
    This may all seem very simple, but there are a few complications to watch out for:
    Accessing unlocked data
    Look at this code:
    void mapadd(mapping m, int i, int j)
    {
        if(map[i])
             map[i]+=({j});
        else
             map[i]=({j});
    }
    This is quite harmless as long as it is only used from one thread at a time, but if two threads call it it at the same time, there is a slight chance that both threads will discover that map[i] is zero and both threads will then do map[i]=({j}); and one value of j will be lost. This type of bug can be extremely hard to debug. The above problem can be solved with the help of Mutexes and Condition variables. Mutexes are basically a way to keep other threads out while a task is being performed. Conditions, or condition variables, are used to inform other threads that they don't have to wait any longer. Pike also provides two different kinds of pipelines to send data from one thread to another, which makes it very simple to write threaded programs. Let's look at an example:
    #!/usr/local/bin/pike
    import Thread; // We need fifos
    inherit Fifo; // Fifo used to supply workers
    inherit Fifo : ended; // Fifo used to wait for workers

    void worker(string lookfor)
    {
        while(string file=Fifo::read())
        {
            int linenum=1;
            object o=Stdio.FILE(file,"r");
            while(string line=o->gets())
            {
                if(search(line, lookfor) >=0)
                    write(sprintf("%s:%d: %s\n",file, linenum, line));

                linenum++;
            }
        }
        ended::write(0);
    }

    int main(int argc, array(string) argv)
    {
        for(int e=0;e<4;e++) // Start workers
            thread_create(worker,argv[e]);
        for(int e=2;e<argc;e++) // Feed workers
            Fifo::write(argv[1]);
        for(int e=0;e<4;e++) // Tell workers to die
            Fifo::write(0);
        for(int e=0;e<4;e++) // Wait for workers to die
             ended::read();
        exit(0);
    }
    This is an example of a simple grep-like program. It looks for the string given as first argument to the program in the files given as the rest of the arguments. Don't worry if you do not understand it yet. Read the descriptions of the functions and classes below and come back and read this example again.
    Deadlocks
    Deadlocks arise when two threads are waiting for each other to do something. This bug can often arise when several threads need access to a number of resources such as files or other I/O devices. What may happen is that one thread has locked device #1 and is trying to lock device #2 while another thread has locked device #2 and is trying to lock device #1. This type of bug is generally easier to find, but may require a lot of work to fix.

    10.2 Threads reference section

    This section describes all thread-related functions and classes.

    FUNCTION
    Thread.thread_create - create a thread

    SYNTAX
    object thread_create(function f, mixed ... args);

    DESCRIPTION
    This function creates a new thread which will run simultaneously to the rest of the program. The new thread will call the function f with the arguments args. When f returns the thread will cease to exist. All Pike functions are 'thread safe' meaning that running a function at the same time from different threads will not corrupt any internal data in the Pike process. The returned value will be the same as the return value of this_thread() for the new thread.

    NOTA BENE
    This function is only available on systems with POSIX or UNIX threads support.

    SEE ALSO
    Thread.Mutex, Thread.Condition and Thread.this_thread

    FUNCTION
    Thread.this_thread - return thread id

    SYNTAX
    object thread_id();

    DESCRIPTION
    This function returns the object that identifies this thread.

    SEE ALSO
    Thread.thread_create

    NAME
    Thread.Mutex - mutex locks

    DESCRIPTION
    Thread.Mutex is a pre-compiled Pike program that implements mutual exclusion locks. Mutex locks are used to prevent multiple threads from simultaneously execute sections of code which access or change shared data. The basic operations for a mutex is locking and unlocking, if a thread attempts to lock an already locked mutex the thread will sleep until the mutex is unlocked.

    NOTA BENE
    Mutex locks are only available on systems with POSIX or UNIX threads support.

    In POSIX threads, mutex locks can only be unlocked by the same thread locked them. In Pike any thread can unlock a locked mutex.

    EXAMPLE
    This simple program can be used to exchange data between two programs. It is similar to Thread.Fifo, but can only hold one element of data.
    inherit Thread.Mutex : r_mutex;
    inherit Thread.Mutex : w_mutex;
    object r_lock=r_mutex::lock();
    object w_lock;
    mixed storage;

    void write(mixed data)
    {
        w_lock=w_mutex::lock();
        storage=data;
        destruct(r_lock);
    }

    mixed read()
    {
        mixed tmp;
        r_lock=r_mutex::lock();
        tmp=storage;
        storage=0;
        destruct(w_lock);
        return tmp;
    }

    NAME
    Thread.Mutex->lock - lock the mutex

    SYNTAX
    object lock();

    DESCRIPTION
    This function attempts to lock the mutex, if the mutex is already locked the current thread will sleep until the lock is unlocked by some other thread. The value returned is the 'key' to the lock. When the key is destructed or has no more references the lock will automatically be unlocked. The key will also be destructed if the lock is destructed.


    NAME
    Thread.Mutex->trylock - try to lock the mutex

    SYNTAX
    object trylock();

    DESCRIPTION
    This function performs the same operation as lock(), but if the mutex is already locked zero will be returned instead of sleeping until the lock is unlocked.


    NAME
    Thread.Condition - condition variables

    DESCRIPTION
    Thread.Condition is a pre-compiled Pike program that implements condition variables. Condition variables are used by threaded programs to wait for events happening in other threads.

    NOTA BENE
    Condition variables are only available on systems with POSIX or UNIX threads support.

    EXAMPLE
    // This program implements a fifo that can be used to send
    // data between two threads.
    inherit Thread.Condition : r_cond;
    inherit Thread.Condition: w_cond;
    inherit Thread.Mutex: lock;

    mixed *buffer = allocate(128);
    int r_ptr, w_ptr;

    int query_messages() { return w_ptr - r_ptr; }

    // This function reads one mixed value from the fifo.
    // If no values are available it blocks until a write has been done.
    mixed read()
    {
        mixed tmp;
        // We use this mutex lock to make sure no write() is executed
        // between the query_messages and the wait() call. If it did
        // we would wind up in a deadlock.
        object key=lock::lock();
        while(!query_messages()) r_cond::wait(key);
        tmp=buffer[r_ptr++ % sizeof(buffer)];
        w_cond::signal();
        return tmp;
    }

    // This function pushes one mixed value on the fifo.
    // If the fifo is full it blocks until a value has been read.
    void write(mixed v)
    {
        object key=lock::lock();
        while(query_messages() == sizeof(buffer)) w_cond::wait(key);
        buffer[w_ptr++ % sizeof(buffer)]=v;
        r_cond::signal();
    }

    SEE ALSO
    Thread.Mutex


    NAME
    Thread.Condition->wait - wait for condition

    SYNTAX
    void wait();
    or
    void wait(object mutex_key);

    DESCRIPTION
    This function makes the current thread sleep until the condition variable is signalled. The optional argument should be the 'key' to a mutex lock. If present the mutex lock will be unlocked before waiting for the condition in one atomic operation. After waiting for the condition the mutex referenced by mutex_key will be re-locked.

    SEE ALSO
    Thread.Mutex->lock


    NAME
    Thread.Condition->signal - signal a condition variable

    SYNTAX
    void signal();

    DESCRIPTION
    Signal wakes up one of the threads currently waiting for the condition.

    BUGS
    It sometimes wakes up more than one thread.


    NAME
    Thread.Condition->broadcast - signal all waiting threads

    SYNTAX
    void broadcast();

    DESCRIPTION
    This function wakes up all threads currently waiting for this condition.


    NAME
    Thread.Fifo - first in, first out object

    DESCRIPTION
    Thread.Fifo implements a fixed length fifo. A fifo is a queue of values and is often used as a stream of data between two threads.

    SEE ALSO
    Thread.Queue

    NOTA BENE
    Fifos are only available on systems with POSIX threads support.


    NAME
    Thread.Fifo->create - initialize the fifo

    SYNTAX
    void create(int size);
    or
    object(Thread.Fifo) Thread.Fifo();
    or
    object(Thread.Fifo) Thread.Fifo(int size);

    DESCRIPTION
    The function create() is called when the fifo is cloned, if the optional size argument is present it sets how many values can be written to the fifo without blocking. The default size is 128.


    NAME
    Thread.Fifo->write - queue a value

    SYNTAX
    void write(mixed value);

    DESCRIPTION
    This function puts a value last in the fifo. If there is no more room in the fifo the current thread will sleep until space is available.


    NAME
    Thread.Fifo->read - read a value from the fifo

    SYNTAX
    mixed read();

    DESCRIPTION
    This function retrieves a value from the fifo. Values will be returned in the order they were written. If there are no values present in the fifo the current thread will sleep until some other thread writes a value to the fifo.


    NAME
    Thread.Fifo->size - return number of values in fifo

    SYNTAX
    int size();

    DESCRIPTION
    This function returns how many values are currently in the fifo.


    NAME
    Thread.Queue - a queue of values

    DESCRIPTION
    Thread.Queue implements a queue, or a pipeline. The main difference between Thread.Queue and Thread.Fifo is that queues will never block in write(), only allocate more memory.

    SEE ALSO
    Thread.Fifo

    NOTA BENE
    Queues are only available on systems with POSIX or UNIX threads support.


    NAME
    Thread.Queue->write - queue a value

    SYNTAX
    void write(mixed value);

    DESCRIPTION
    This function puts a value last in the queue. If the queue is too small to hold the value the queue will be expanded to make room for it.


    NAME
    Thread.Queue->read - read a value from the queue

    SYNTAX
    mixed read();

    DESCRIPTION
    This function retrieves a value from the queue. Values will be returned in the order they were written. If there are no values present in the queue the current thread will sleep until some other thread writes a value to the queue.


    NAME
    Thread.Queue->size - return number of values in queue

    SYNTAX
    int queue->size();

    DESCRIPTION
    This function returns how many values are currently in the queue.


    10.3 Threads example

    Let's look at an example of how to work with threads. This program is the same minimal WWW server as in
    chapter 9 "File I/O" but it has been re-written to use threads, as you can see it is a lot smaller this way. This is because we can use blocking I/O operations instead of non-blocking and callbacks. This also makes the program much easier to follow:
    #!/usr/local/bin/pike

    /* A very small threaded httpd capable of fetching files only. * Written by Fredrik Hübinette as a demonstration of Pike */

    import Thread;
    inherit Stdio.Port;

    /* number of bytes to read for each write */
    #define BLOCK 16384

    /* Where do we have the html files ? */
    #define BASE "/home/hubbe/pike/src/"

    /* File to return when we can't find the file requested */
    #define NOFILE "/home/hubbe/www/html/nofile.html"

    /* Port to open */
    #define PORT 1905

    /* Number of threads to start */
    #define THREADS 5

    // There will be one of these for each thread
    class worker
    {
        inherit Stdio.FILE : socket; // For communication with the browser
        inherit Stdio.File : file; // For reading the file from disc

        void create(function accept)
        {
            string cmd, input, tmp;

            while(1)
            {
                socket::close(); // Close previous connection
                file::close();

                object o=accept(); // Accept a connection
                if(!o) continue;
                socket::assign(o);
                destruct(o);

                // Read request
                sscanf(socket::gets(),"%s %s%*[\012\015 \t]",cmd, input);
                if(cmd!="GET")
                {
                    werror("Only method GET is supported.\n");
                    continue;
                }

                // Open the requested file
                sscanf(input,"%*[/]%s",input);
                input=BASE+combine_path("/",input);
                
                if(!file::open(input,"r"))
                {
                    if(!file::open(NOFILE,"r"))
                    {
                        werror("Couldn't find default file.\n");
                        continue;
                    }
                }

                // Copy data to socket
                while(socket::write(file::read(BLOCK))==BLOCK);
            }
        }
    };

    int main(int argc, array(string) argv)
    {
        werror("Starting minimal threaded httpd\n");

        // Bind the port, don't set it nonblocking
        if(!bind(PORT))
        {
            werror("Failed to open socket (already bound?)\n");
            return 17;
        }

        // Start worker threads
        for(int e=1;e<THREADS;e++) thread_create(worker,accept);
        worker(accept);
    }

    As stated in the beginning of this chapter; Pike threads are only available on some UNIX systems. The above example does not work if your system does not have threads.

    Chapter 11, Modules for specific data types

    There are a few modules that provide extra functions that operate specifically on one data type. These modules have the same name as the data type, but are capitalized so you can tell the difference. At the time of writing, the only such modules are String and Array, but more are expected to show up in the future.

    11.1 String

    The module String contains some extra string functionality which is not always used. These functions are mostly implemented in Pike as a complement to those written in C.
    NAME
    String.implode_nicely - make an English comma separated list

    SYNTAX
    string implode_nicely(array(string) words, string|void separator)

    DESCRIPTION
    This function implodes a list of words to a readable string. If the separator is omitted, the default is "and".

    EXAMPLES
    > implode_nicely(({"green"}));
    Result: green
    > implode_nicely(({"green","blue"}));
    Result: green and blue
    > implode_nicely(({"green","blue","white"}));
    Result: green, blue and white
    > implode_nicely(({"green","blue","white"}),"or");
    Result: green, blue or white

    SEE ALSO
    `*

    NAME
    String.capitalize - capitalize a string

    SYNTAX
    string capitalize(string str)

    DESCRIPTION
    Convert the first character in str to upper case, and return the new string.

    SEE ALSO
    lower_case and upper_case


    NAME
    String.strmult - multiply strings

    SYNTAX
    string strmult(string s, int num);

    DESCRIPTION
    This function multiplies 's' by 'num'. The return value is the same as appending 's' to an empty string 'num' times.


    11.2 Array

    As with String these functions are Pike functions written to supplement those written in C.
    NAME
    Array.map - map an array or mapping over a function

    SYNTAX
    array map(array arr,function fun,mixed ... args);
    array map(array(object) arr,string fun,mixed ... args);
    array map(array(function) arr,-1,mixed ... arg);

    DESCRIPTION
    First syntax: Map array returns an array holding the items of arr mapped through the function fun. ie. arr[x]=fun(arr[x], @args) for all x.

    Second syntax: Map array calls function fun in all objects in the array arr. ie. arr[x]=arr[x]->fun(@ args);

    Third syntax: Map array calls the functions in the array arr: arr[x]=arr[x]->fun(@ args);

    SEE ALSO
    Array.sum_arrays and Array.filter


    NAME
    Array.filter - filter an array or mapping through a function

    SYNTAX
    array filter(array arr,function fun,mixed ... args);
    array filter(array(object) arr,string fun,mixed ... args);
    or
    array filter(array(function) arr,-1,mixed ... args);

    DESCRIPTION
    First syntax: Filter array returns an array holding the items of arr for which fun returns true.

    Second syntax: Filter array calls fun in all the objects in the array arr, and return all objects that returned true.

    Third syntax: Filter array calls all function pointers in the array arr, and return all that returned true.

    SEE ALSO
    Array.sum_arrays and Array.map

    NAME
    Array.search_array - search for something in an array

    SYNTAX
    int search_array(mixed *arr,function fun,mixed arg, ...);
    or
    int search_array(object *arr,string fun,mixed arg, ...);
    or
    int search_array(function *arr,-1,mixed arg, ...);

    DESCRIPTION
    search_array works like map_array, only it returns the index of the first call that returned true instead or returning an array of the returned values. If no call returns true, -1 is returned.

    SEE ALSO
    Array.sum_arrays and Array.filter


    NAME
    Array.sum_arrays - map any number of arrays over a function.

    SYNTAX
    mixed *sum_arrays(function fun,mixed *arr1,...);

    DESCRIPTION
    Works like this:

    mixed *sum_arrays(function fun,mixed *arr1,...)
    {

    int e;
    mixed *res=allocate(sizeof(arr1));
    for(e=0;e<sizeof(arr1);e++)
    {
    res[e]=fun(arr1[e],arr2[e],...);
    }
    return res;
    }

    Simple ehh?

    SEE ALSO
    Array.map, Array.filter and Array.search_array

    NAME
    Array.sort_array - sort an array

    SYNTAX
    mixed *sort_array(mixed *arr,function fun,mixed ... args);

    DESCRIPTION
    This function sorts an array after a compare-function fun which takes two arguments and should return 1 if the first argument is larger then the second. The rest of the arguments args will be sent as 3rd, 4th etc. argument to fun. If fun is omitted, `< is used instead.

    SEE ALSO
    Array.map and sort

    NAME
    Array.uniq - return one of each element

    SYNTAX
    array uniq(array a);

    DESCRIPTION
    This function returns an copy of the array a with all duplicate values removed. The order of the values in the result is undefined.


    Chapter 12, Image

    The Image module is used to manipulate bit-mapped color images. It can read PPM images and do various manipulations, or it can be used to create completely new images. The created images can be saved as PPM or converted to GIF.

    All images handled by this module are stored as 24-bit RGB images. This means that a 1024 pixel wide and 1024 pixel high image will use 1024*1024*3 bytes = 3 megabytes. It is quite easy to mess up and use up all the memory by giving the wrong argument to one of the scaling functions.

    Most functions in this module work by creating a new Image and then returning that instead of changing the Image you are working with. This makes it possible to share the same image between many variables without having to worry that it will be changed by accident. This can reduce the amount of memory used.

    Many functions in this module work with the 'current color', this can be thought of as the background color if you wish. To change the current color you use 'setcolor'.

    Let's look at an example of how this can be used:

    #!/usr/local/bin/pike

    int main()
    {
        write("Content-type: image/gif\n\n");
        object font=Image.font();
        font->load("testfont");
        object image=font->write(ctime(time));
        write(image->togif());
    }
    This very simple example can be used as a CGI script to produce a gif image which says what time it is in white text on a black background.

    NAME
    Image

    DESCRIPTION
    This module adds image-drawing and -manipulating capabilities to pike.

    Image.image Basic image manipulation
    Image.font Creating images from text
    Image.colortable Color reduction, quantisation and dither
    Image.GIF GIF encoding/decoding capabilities
    Image.PNM PNM (PBM/PGM/PPM) encoding/decoding capabilities

    NOTA BENE
    Image module documentation is based on these file versions:
         $Id: blit.c,v 1.24 1997/11/24 16:11:55 mirar Exp $
         $Id: blit_layer_include.h,v 1.4 1997/10/27 22:41:17 mirar Exp $
         $Id: colortable.c,v 1.27 1997/11/29 22:47:39 mirar Exp $
         $Id: colortable.h,v 1.10 1997/11/11 22:17:47 mirar Exp $
         $Id: dct.c,v 1.9 1997/10/27 22:41:19 mirar Exp $
         $Id: font.c,v 1.21 1997/11/11 22:17:48 mirar Exp $
         $Id: image.c,v 1.69 1997/11/29 18:59:35 hedda Exp $
         $Id: image.h,v 1.15 1997/11/23 05:28:29 per Exp $
         $Id: matrix.c,v 1.10 1997/10/27 22:41:25 mirar Exp $
         $Id: operator.c,v 1.9 1997/10/27 22:41:26 mirar Exp $
         $Id: pattern.c,v 1.9 1997/11/02 18:49:11 grubba Exp $
         $Id: pnm.c,v 1.8 1997/11/02 03:46:52 mirar Exp $
         $Id: polyfill.c,v 1.15 1997/11/12 03:40:20 mirar Exp $
         $Id: togif.c,v 1.28 1997/11/26 15:41:35 mirar Exp $
         $Id: gif.c,v 1.20 1997/11/29 22:48:50 mirar Exp $
         $Id: gif_lzw.c,v 1.4 1997/11/05 03:42:50 mirar Exp $
         $Id: gif_lzw.h,v 1.4 1997/11/02 03:44:51 mirar Exp $
         $Id: pnm.c,v 1.5 1997/11/29 21:33:36 grubba Exp $
         

    12.1 Image.colortable


    NAME
    Image.colortable

    DESCRIPTION
    This object keeps colortable information, mostly for image re-coloring (quantization).

    The object has color reduction, quantisation, mapping and dithering capabilities.

    SEE ALSO
    Image, Image.image, Image.font, Image.GIF


    NAME
    Image.colortable->add
    Image.colortable->create

    SYNTAX
    void create()
    void create(array(array(int)) colors)
    void create(object(Image.image) image, int number)
    void create(object(Image.image) image, int number, array(array(int)) needed)
    void create(int r, int g, int b)
    void create(int r, int g, int b,  array(int) from1, array(int) to1, int steps1,  ...,  array(int) fromn, array(int) ton, int stepsn)
    object add(array(array(int)) colors)
    object add(object(Image.image) image, int number)
    object add(object(Image.image) image, int number, array(array(int)) needed)
    object add(int r, int g, int b)
    object add(int r, int g, int b,  array(int) from1, array(int) to1, int steps1,  ...,  array(int) fromn, array(int) ton, int stepsn)

    DESCRIPTION
    create initiates a colortable object. Default is that no colors are in the colortable.

    add takes the same argument(s) as create, thus adding colors to the colortable.

    The colortable is mostly a list of colors, or more advanced, colors and weight.

    The colortable could also be a colorcube, with or without additional scales. A colorcube is the by-far fastest way to find colors.

    Example:

         ct=colortable(my_image,256); // the best 256 colors
         ct=colortable(my_image,256,({0,0,0})); // black and the best other 255
    
    

    ct=colortable(({({0,0,0}),({255,255,255})})); // black and white

    ct=colortable(6,7,6); // a colortable of 252 colors ct=colortable(7,7,5, ({0,0,0}),({255,255,255}),11); // a colorcube of 245 colors, and a greyscale of the rest -> 256

    ARGUMENTS
    argument(s) description
    array(array(int)) colors list of colors
    object(Image.image) image source image

    note: you may not get all colors from image, max hash size is (probably, set by a #define) 32768 entries, giving maybe half that number of colors as maximum.

    int number number of colors to get from the image 0 (zero) gives all colors in the image.

    Default value is 256.

    array(array(int)) needed needed colors (to optimize selection of others to these given) this will add to the total number of colors (see argument 'number')
    int r
    int g
    int b
    size of sides in the colorcube, must (of course) be equal or larger than 2 - if smaller, the cube is ignored (no colors). This could be used to have only scales (like a greyscale) in the output.
    array(int) fromi
    array(int) toi
    int stepi
    This is to add the possibility of adding a scale of colors to the colorcube; for instance a grayscale using the arguments ({0,0,0}),({255,255,255}),17, adding a scale from black to white in 17 or more steps.

    Colors already in the cube is used again to add the number of steps, if possible.

    The total number of colors in the table is therefore r*b*g+step1+...+stepn.


    NAME
    Image.colortable->cast

    SYNTAX
    object cast(string to)

    DESCRIPTION
    cast the colortable to an array

    example: (array)Image.colortable(img)

    ARGUMENTS
    argument(s) description
    string to must be "array".

    RETURN VALUE
    the resulting array


    NAME
    Image.colortable->cubicles

    SYNTAX
    object cubicles()
    object cubicles(int r, int g, int b)
    object cubicles(int r, int g, int b, int accuracy)

    DESCRIPTION
    Set the colortable to use the cubicles algorithm to lookup the closest color. This is a mostly very fast and very accurate way to find the correct color, and the default algorithm.

    The colorspace is divided in small cubes, each cube containing the colors in that cube. Each cube then gets a list of the colors in the cube, and the closest from the corners and midpoints between corners.

    When a color is needed, the algorithm first finds the correct cube and then compares with all the colors in the list for that cube.

    example: colors=Image.colortable(img)->cubicles();

    algorithm time: between O[m] and O[m * n], where n is numbers of colors and m is number of pixels

    The arguments can be heavy trimmed for the usage of your colortable; a large number (10×10×10 or bigger) of cubicles is recommended when you use the colortable repeatedly, since the calculation takes much more time than usage.

    recommended values:

       
         image size  setup
         100×100     cubicles(4,5,4) (default)
         1000×1000   cubicles(12,12,12) (factor 2 faster than default)
         

    In some cases, the full method is faster.

    original default cubicles,
    16 colors
    accuracy=200

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    Size, ie how much the colorspace is divided. Note that the size of each cubicle is at least about 8b, and that it takes time to calculate them. The number of cubicles are r*g*b, and default is 4,5,4, ie 80 cubicles. This works good for 200±100 colors.
    int accuracy Accuracy when checking sides of cubicles. Default is 16. A value of 1 gives complete accuracy, ie cubicle() method gives exactly the same result as full(), but takes (in worst case) 16× the time to calculate.

    RETURN VALUE
    the called object

    NOTA BENE
    this method doesn't figure out the cubicles, this is done on the first use of the colortable.

    Not applicable to colorcube types of colortable.


    NAME
    Image.colortable->floyd_steinberg

    SYNTAX
    object floyd_steinberg()
    object floyd_steinberg(int dir, int|float forward, int|float downforward, int|float down, int|float downback, int|float factor)

    DESCRIPTION
    Set dithering method to floyd_steinberg. The arguments to this method is for fine-tuning of the algorithm (for computer graphics wizards).

    original floyd_steinberg to a 4×4×4 colorcube floyd_steinberg to 16 chosen colors

    ARGUMENTS
    argument(s) description
    int bidir Set algorithm direction of forward. -1 is backward, 1 is forward, 0 for toggle of direction each line (default).
    int|float forward
    int|float downforward
    int|float down
    int|float downback
    Set error correction directions. Default is forward=7, downforward=1, down=5, downback=3.
    int|float factor Error keeping factor. Error will increase if more than 1.0 and decrease if less than 1.0. A value of 0.0 will cancel any dither effects. Default is 0.95.

    RETURN VALUE
    the called object


    NAME
    Image.colortable->full

    SYNTAX
    object full()

    DESCRIPTION
    Set the colortable to use full scan to lookup the closest color.

    example: colors=Image.colortable(img)->full();

    algorithm time: O[n*m], where n is numbers of colors and m is number of pixels

    RETURN VALUE
    the called object

    NOTA BENE
    Not applicable to colorcube types of colortable.

    SEE ALSO
    cubicles, map


    NAME
    Image.colortable->map
    Image.colortable->`*
    Image.colortable->``*

    SYNTAX
    object map(object image)
    object `*(object image)
    object ``*(object image)

    DESCRIPTION
    Map colors in an image object to the colors in the colortable, and creates a new image with the closest colors.

    no dither
    floyd_steinberg dither
    ordered dither
    randomcube dither
    original 2 4 8 16 32 colors

    RETURN VALUE
    a new image object

    NOTA BENE
    Flat (not cube) colortable and not 'full' method: this method does figure out the data needed for the lookup method, which may take time the first use of the colortable - the second use is quicker.

    SEE ALSO
    cubicles, full


    NAME
    Image.colortable->nodither

    SYNTAX
    object nodither()

    DESCRIPTION
    Set no dithering (default).

    RETURN VALUE
    the called object


    NAME
    Image.colortable->ordered

    SYNTAX
    object ordered()
    object ordered(int r, int g, int b)
    object ordered(int r, int g, int b, int xsize, int ysize)
    object ordered(int r, int g, int b, int xsize, int ysize, int x, int y)
    object ordered(int r, int g, int b, int xsize, int ysize, int rx, int ry, int gx, int gy, int bx, int by)

    DESCRIPTION
    Set ordered dithering, which gives a position-dependent error added to the pixel values.

    original mapped to
    Image.colortable(6,6,6)->
    ordered
    (42,42,42,2,2)
    ordered() ordered
    (42,42,42, 8,8,
    0,0, 0,1, 1,0)

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    The maximum error. Default is 32, or colorcube steps (256/size).
    int xsize
    int ysize
    Size of error matrix. Default is 8×8. Only values which factors to multiples of 2 and 3 are possible to choose (2,3,4,6,8,12,...).
    int x
    int y
    int rx
    int ry
    int gx
    int gy
    int bx
    int by
    Offset for the error matrix. x and y is for both red, green and blue values, the other is individual.

    RETURN VALUE
    the called object

    SEE ALSO
    randomcube, nodither, floyd_steinberg, create


    NAME
    Image.colortable->randomcube
    Image.colortable->randomgrey

    SYNTAX
    object randomcube()
    object randomcube(int r, int g, int b)
    object randomgrey()
    object randomgrey(int err)

    DESCRIPTION
    Set random cube dithering. Color choosen is the closest one to color in picture plus (flat) random error; color±random(error).

    The randomgrey method uses the same random error on red, green and blue and the randomcube method has three random errors.

    original mapped to
    Image.colortable(4,4,4)->
    randomcube() randomgrey()

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    int err
    The maximum error. Default is 32, or colorcube step.

    RETURN VALUE
    the called object

    NOTA BENE
    randomgrey method needs colorcube size to be the same on red, green and blue sides to work properly. It uses the red colorcube value as default.

    SEE ALSO
    ordered, nodither, floyd_steinberg, create


    NAME
    Image.colortable->reduce

    SYNTAX
    object reduce(int colors)

    DESCRIPTION
    reduces the number of colors

    All needed (see create) colors are kept.

    ARGUMENTS
    argument(s) description
    int colors target number of colors

    RETURN VALUE
    the new colortable object


    NAME
    Image.colortable->spacefactors

    SYNTAX
    object spacefactors(int r, int g, int b)

    DESCRIPTION
    Colortable tuning option, this sets the color space distance factors. This is used when comparing distances in the colorspace and comparing grey levels.

    Default factors are 3, 4 and 1; blue is much darker than green. Compare with Image.image->grey().

    RETURN VALUE
    the called object

    NOTA BENE
    This has no sanity check. Some functions may bug if the factors are to high - color reduction functions sums grey levels in the image, this could exceed maxint in the case of high factors. Negative values may also cause strange effects. *grin*


    NAME
    Image.colortable->`+

    SYNTAX
    object `+(object with, ...)

    DESCRIPTION
    sums colortables

    ARGUMENTS
    argument(s) description
    object(colortable) with colortable object with colors to add

    RETURN VALUE
    the resulting new colortable object


    NAME
    Image.colortable->`-

    SYNTAX
    object `-(object with, ...)

    DESCRIPTION
    subtracts colortables

    ARGUMENTS
    argument(s) description
    object(colortable) with colortable object with colors to subtract

    RETURN VALUE
    the resulting new colortable object

    12.2 Image.font


    NAME
    Image.font

    DESCRIPTION

    NOTA BENE
    Short technical documentation on a font file: This object adds the text-drawing and -creation capabilities of the Image module.

    For simple usage, see write and load.

    other methods: baseline, height, set_xspacing_scale, set_yspacing_scale, text_extents

                struct file_head 
                {
                   unsigned INT32 cookie;   - 0x464f4e54 
                   unsigned INT32 version;  - 1 
                   unsigned INT32 chars;    - number of chars
                   unsigned INT32 height;   - height of font
                   unsigned INT32 baseline; - font baseline
                   unsigned INT32 o[1];     - position of char_head's
                } *fh;
                struct char_head
                {
                   unsigned INT32 width;    - width of this character
                   unsigned INT32 spacing;  - spacing to next character
                   unsigned char data[1];   - pixmap data (1byte/pixel)
                } *ch;
         

    SEE ALSO
    Image, Image.image


    NAME
    Image.font->baseline

    SYNTAX
    int baseline()

    RETURN VALUE
    font baseline (pixels from top)

    SEE ALSO
    height, text_extents


    NAME
    Image.font->height
    Image.font->text_extents

    SYNTAX
    int height()
    array(int) text_extents(string text, ...)

    DESCRIPTION
    Calculate extents of a text-image, that would be created by calling write with the same arguments.

    ARGUMENTS
    argument(s) description
    string text, ... One or more lines of text.

    RETURN VALUE
    an array of width and height

    SEE ALSO
    write, height, baseline


    NAME
    Image.font->load

    SYNTAX
    object|int load(string filename)

    DESCRIPTION
    Loads a font file to this font object.

    ARGUMENTS
    argument(s) description
    string filename Font file

    RETURN VALUE
    zero upon failure, font object upon success

    SEE ALSO
    write


    NAME
    Image.font->set_xspacing_scale
    Image.font->set_yspacing_scale

    SYNTAX
    void set_xspacing_scale(float scale)
    void set_yspacing_scale(float scale)

    DESCRIPTION
    Set spacing scale to write characters closer or more far away. This does not change scale of character, only the space between them.

    ARGUMENTS
    argument(s) description
    float scale what scale to use


    NAME
    Image.font->write

    SYNTAX
    object write(string text, ...)

    DESCRIPTION
    Writes some text; thus creating an image object that can be used as mask or as a complete picture.

    ARGUMENTS
    argument(s) description
    string text, ... One or more lines of text.

    RETURN VALUE
    an Image.image object

    SEE ALSO
    text_extents, load, Image.image->paste_mask, Image.image->paste_alpha_color

    12.3 Image.image


    NAME
    Image.image

    DESCRIPTION
    The main object of the Image module, this object is used as drawing area, mask or result of operations.

    init: clear, clone, create, xsize, ysize

    plain drawing: box, circle, getpixel, line, setcolor, setpixel, threshold, tuned_box, polyfill

    operators: `&, `*, `+, `-, `|

    pasting images, layers: add_layers, paste, paste_alpha, paste_alpha_color, paste_mask

    getting subimages, scaling, rotating: autocrop, clone, copy, dct, mirrorx, rotate, rotate_expand, rotate_ccw, rotate_cw, scale, skewx, skewx_expand, skewy, skewy_expand

    calculation by pixels: apply_matrix, change_color, color, distancesq, grey, invert, modify_by_intensity, select_from, rgb_to_hsv, hsv_to_rgb, Image.colortable

    converting to other datatypes: Image.GIF, Image.PNM

    special pattern drawing: noise, turbulence

    SEE ALSO
    Image, Image.font


    NAME
    Image.image->add_layers

    SYNTAX
    object add_layers(array(int|object)) layer0, ...)
    object add_layers(int x1, int y1, int x2, int y2, array(int|object)) layer0, ...)

    DESCRIPTION
    Using the called object as base, adds layers using masks, opaque channel values and special methods.

    The destination image can also be cropped, thus speeding up the process.

    Each array in the layers array is one of:

         ({object image,object|int mask})
         ({object image,object|int mask,int opaque_value})
         ({object image,object|int mask,int opaque_value,int method})
         
    Given 0 as mask means the image is totally opaque.

    Default opaque value is 255, only using the mask.

    Methods for now are:

         0  no operation (just paste with mask, default)
         1  maximum  (`|)
         2  minimum  (`&)
         3  multiply (`*)
         4  add      (`+)
         5  diff     (`-)
         
    The layer image and the current source are calculated through the given method and then pasted using the mask and the opaque channel value.

    All given images must be the same size.

    ARGUMENTS
    argument(s) description
    array(int|object) layer0 image to paste
    int x1
    int y1
    int x2
    int y2
    rectangle for cropping

    RETURN VALUE
    a new image object

    SEE ALSO
    paste_mask, paste_alpha, paste_alpha_color, `|, `&, `*, `+, `-


    NAME
    Image.image->apply_matrix

    SYNTAX
    object apply_matrix(array(array(int|array(int))) matrix)
    object apply_matrix(array(array(int|array(int))) matrix, int r, int g, int b)
    object apply_matrix(array(array(int|array(int))) matrix, int r, int g, int b, int|float div)

    DESCRIPTION
    Applies a pixel-transform matrix, or filter, to the image.
                                2   2
         pixel(x,y)= base+ k ( sum sum pixel(x+k-1,y+l-1)*matrix(k,l) ) 
                               k=0 l=0 
         
    1/k is sum of matrix, or sum of matrix multiplied with div. base is given by r,g,b and is normally black.

    blur (ie a 2d gauss function):
         ({({1,2,1}),
           ({2,5,2}),
           ({1,2,1})})
         
    original
    sharpen (k>8, preferably 12 or 16):
         ({({-1,-1,-1}),
           ({-1, k,-1}),
           ({-1,-1,-1})})
         
    edge detect:
         ({({1, 1,1}),
           ({1,-8,1}),
           ({1, 1,1})})
         
    horisontal edge detect (get the idea):
         ({({0, 0,0}),
           ({1,-2,1}),
           ({0, 0,0})})
         
    emboss (might prefer to begin with a grey image):
         ({({2, 1, 0}),
           ({1, 0,-1}),
           ({0,-1,-2})}), 128,128,128, 3
         
    greyed

    This function is not very fast.

    ARGUMENTS
    argument(s) description
    array(array(int|array(int))) the matrix; innermost is a value or an array with red, green, blue values for red, green, blue separation.
    int r
    int g
    int b
    base level of result, default is zero
    int|float div division factor, default is 1.0.

    RETURN VALUE
    the new image object


    NAME
    Image.image->autocrop

    SYNTAX
    object autocrop()
    object autocrop(int border)
    object autocrop(int border, int r, int g, int b)
    object autocrop(int border, int left, int right, int top, int bottom)
    object autocrop(int border, int left, int right, int top, int bottom, int r, int g, int b)

    DESCRIPTION
    Removes "unneccesary" borders around the image, adds one of its own if wanted to, in selected directions.

    "Unneccesary" is all pixels that are equal -- ie if all the same pixels to the left are the same color, that column of pixels are removed.

    ARGUMENTS
    argument(s) description
    int border added border size in pixels
    int r
    int g
    int b
    color of the new border
    int left
    int right
    int top
    int bottom
    which borders to scan and cut the image; a typical example is removing the top and bottom unneccesary pixels:
    img=img->autocrop(0, 0,0,1,1);

    RETURN VALUE
    the new image object

    SEE ALSO
    copy


    NAME
    Image.image->box

    SYNTAX
    object box(int x1, int y1, int x2, int y2)
    object box(int x1, int y1, int x2, int y2, int r, int g, int b)
    object box(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

    DESCRIPTION
    Draws a filled rectangle on the image.

    ARGUMENTS
    argument(s) description
    int x1
    int y1
    int x2
    int y2
    box corners
    int r
    int g
    int b
    color of the box
    int alpha alpha value

    RETURN VALUE
    the object called


    NAME
    Image.image->cast

    SYNTAX
    string cast(string type)

    RETURN VALUE
    the image data as a string ("rgbrgbrgb...")

    SEE ALSO
    Image.colortable


    NAME
    Image.image->change_color

    SYNTAX
    object change_color(int tor, int tog, int tob)
    object change_color(int fromr, int fromg, int fromb,  int tor, int tog, int tob)

    DESCRIPTION
    Changes one color (exakt match) to another. If non-exakt-match is preferred, check distancesq and paste_alpha_color.

    ARGUMENTS
    argument(s) description
    int tor
    int tog
    int tob
    destination color and next current color
    int fromr
    int fromg
    int fromb
    source color, default is current color

    RETURN VALUE
    a new (the destination) image object


    NAME
    Image.image->circle

    SYNTAX
    object circle(int x, int y, int rx, int ry)
    object circle(int x, int y, int rx, int ry, int r, int g, int b)
    object circle(int x, int y, int rx, int ry, int r, int g, int b, int alpha)

    DESCRIPTION
    Draws a line on the image. The line is not antialiased.

    ARGUMENTS
    argument(s) description
    int x
    int y
    circle center
    int rx
    int ry
    circle radius in pixels
    int r
    int g
    int b
    color
    int alpha alpha value

    RETURN VALUE
    the object called


    NAME
    Image.image->clear

    SYNTAX
    void clear()
    void clear(int r, int g, int b)
    void clear(int r, int g, int b, int alpha)

    DESCRIPTION
    gives a new, cleared image with the same size of drawing area

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    color of the new image
    int alpha new default alpha channel value

    SEE ALSO
    copy, clone


    NAME
    Image.image->clone

    SYNTAX
    object clone()
    object clone(int xsize, int ysize)
    object clone(int xsize, int ysize, int r, int g, int b)
    object clone(int xsize, int ysize, int r, int g, int b, int alpha)

    DESCRIPTION
    Copies to or initialize a new image object.

    ARGUMENTS
    argument(s) description
    int xsize
    int ysize
    size of (new) image in pixels, called image is cropped to that size
    int r
    int g
    int b
    current color of the new image, default is black. Will also be the background color if the cloned image is empty (no drawing area made).
    int alpha new default alpha channel value

    RETURN VALUE
    the new object

    SEE ALSO
    copy, create


    NAME
    Image.image->color

    SYNTAX
    object color()
    object color(int value)
    object color(int r, int g, int b)

    DESCRIPTION
    Colorize an image.

    The red, green and blue values of the pixels are multiplied with the given value(s). This works best on a grey image...

    The result is divided by 255, giving correct pixel values.

    If no arguments are given, the current color is used as factors.

    original ->color(128,128,255);

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    red, green, blue factors
    int value factor

    RETURN VALUE
    the new image object

    SEE ALSO
    grey, `*, modify_by_intensity


    NAME
    Image.image->copy

    SYNTAX
    object copy()
    object copy(int x1, int y1, int x2, int y2)
    object copy(int x1, int y1, int x2, int y2, int r, int g, int b)
    object copy(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

    DESCRIPTION
    Copies this part of the image. The requested area can be smaller, giving a cropped image, or bigger - the new area will be filled with the given or current color.

    ARGUMENTS
    argument(s) description
    int x1
    int y1
    int x2
    int y2
    The requested new area. Default is the old image size.
    int r
    int g
    int b
    color of the new image
    int alpha new default alpha channel value

    RETURN VALUE
    a new image object

    NOTA BENE
    clone(void) and copy(void) does the same operation

    SEE ALSO
    clone, autocrop


    NAME
    Image.image->create

    SYNTAX
    void create()
    void create(int xsize, int ysize)
    void create(int xsize, int ysize, int r, int g, int b)
    void create(int xsize, int ysize, int r, int g, int b, int alpha)

    DESCRIPTION
    Initializes a new image object.

    ARGUMENTS
    argument(s) description
    int xsize
    int ysize
    size of (new) image in pixels
    int r
    int g
    int b
    background color (will also be current color), default color is black
    int alpha default alpha channel value

    SEE ALSO
    copy, clone, Image.image


    NAME
    Image.image->dct

    SYNTAX
    object dct(int newx, int newy)

    DESCRIPTION
    Scales the image to a new size. Method for scaling is rather complex; the image is transformed via a cosine transform, and then resampled back.

    This gives a quality-conserving upscale, but the algorithm used is n*n+n*m, where n and m is pixels in the original and new image.

    Recommended wrapping algorithm is to scale overlapping parts of the image-to-be-scaled.

    This functionality is actually added as an true experiment, but works...

    ARGUMENTS
    argument(s) description
    int newx
    int newy
    new image size in pixels

    RETURN VALUE
    the new image object

    NOTA BENE
    Do NOT use this function if you don't know what you're dealing with! Read some signal theory first...


    NAME
    Image.image->distancesq

    SYNTAX
    object distancesq()
    object distancesq(int r, int g, int b)

    DESCRIPTION
    Makes an grey-scale image, for alpha-channel use. The given value (or current color) are used for coordinates in the color cube. Each resulting pixel is the distance from this point to the source pixel color, in the color cube, squared, rightshifted 8 steps:

        p = pixel color
        o = given color
        d = destination pixel
        d.red=d.blue=d.green=
            ((o.red-p.red)²+(o.green-p.green)²+(o.blue-p.blue)²)>>8
        

    original ->distancesq(255,0,128);

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    red, green, blue coordinates

    RETURN VALUE
    the new image object

    SEE ALSO
    select_from


    NAME
    Image.image->frompnm
    Image.image->fromppm

    SYNTAX
    object|string frompnm(string pnm)
    object|string fromppm(string pnm)

    DESCRIPTION
    compability method - do not use in new programs. See Image.PNM.decode().

    ARGUMENTS
    argument(s) description
    string pnm pnm data, as a string

    RETURN VALUE
    the called object or a hint of what wronged.


    NAME
    Image.image->getpixel

    SYNTAX
    array(int) getpixel(int x, int y)

    DESCRIPTION

    ARGUMENTS
    argument(s) description
    int x
    int y
    position of the pixel

    RETURN VALUE
    color of the requested pixel -- ({int red,int green,int blue})


    NAME
    Image.image->gif_add
    Image.image->gif_add*
    Image.image->gif_add_fs
    Image.image->gif_add_fs_nomap
    Image.image->gif_add_nomap
    Image.image->gif_begin
    Image.image->gif_end
    Image.image->gif_netscape_loop
    Image.image->togif
    Image.image->togif_fs

    SYNTAX
    string gif_begin()
    string gif_begin(int num_colors)
    string gif_begin(array(array(int)) colors)
    string gif_end()
    string gif_netscape_loop(int loops)
    string togif()
    string togif(int trans_r, int trans_g, int trans_b)
    string togif(int num_colors, int trans_r, int trans_g, int trans_b)
    string togif(array(array(int)) colors, int trans_r, int trans_g, int trans_b)
    string togif_fs()
    string togif_fs(int trans_r, int trans_g, int trans_b)
    string togif_fs(int num_colors, int trans_r, int trans_g, int trans_b)
    string togif_fs(array(array(int)) colors, int trans_r, int trans_g, int trans_b)
    string gif_add()
    string gif_add_fs()
    string gif_add_nomap()
    string gif_add_fs_nomap()
    string gif_add*(int x, int y)
    string gif_add*(int x, int y, int delay_cs)
    string gif_add*(int x, int y, int num_colors, int delay_cs)
    string gif_add*(int x, int y, array(array(int)) colors, int delay_cs)

    DESCRIPTION
    old GIF API compatibility function. Don't use in any new code.

    is replaced by
    gif_beginImage.GIF.header_block
    gif_endImage.GIF.end_block
    gif_netscape_loopImage.GIF.netscape_loop_block
    togifImage.GIF.encode
    togif_fsImage.GIF.encode¹
    gif_addImage.GIF.render_block¹²
    gif_add_fsImage.GIF.render_block¹
    gif_add_nomapImage.GIF.render_block²
    gif_add_fs_nomapImage.GIF.render_block¹²

    ¹ Use Image.colortable to get whatever dithering you want.

    ² local map toggle is sent as an argument

    RETURN VALUE
    GIF data.


    NAME
    Image.image->grey

    SYNTAX
    object grey()
    object grey(int r, int g, int b)

    DESCRIPTION
    Makes a grey-scale image (with weighted values).

    original ->grey(); ->grey(0,0,255);

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    weight of color, default is r=87,g=127,b=41, which should be pretty accurate of what the eyes see...

    RETURN VALUE
    the new image object

    SEE ALSO
    color, `*, modify_by_intensity


    NAME
    Image.image->hsv_to_rgb
    Image.image->rgb_to_hsv

    SYNTAX
    object rgb_to_hsv()
    object hsv_to_rgb()

    DESCRIPTION
    Converts RGB data to HSV data, or the other way around. When converting to HSV, the resulting data is stored like this: pixel.r = h; pixel.g = s; pixel.b = v;

    When converting to RGB, the input data is asumed to be placed in the pixels as above.

    original ->hsv_to_rgb(); ->rgb_to_hsv();
    tuned box (below) the rainbow (below) same, but rgb_to_hsv()

    HSV to RGB calculation:

        in = input pixel
        out = destination pixel
        h=-pos*c_angle*3.1415/(float)NUM_SQUARES;
        out.r=(in.b+in.g*cos(in.r));
        out.g=(in.b+in.g*cos(in.r + pi*2/3));
        out.b=(in.b+in.g*cos(in.r + pi*4/3));
        

    RGB to HSV calculation: Hmm.

        

    Example: Nice rainbow.

         object i = Image.image(200,200);
         i = i->tuned_box(0,0, 200,200,
                          ({ ({ 255,255,128 }), ({ 0,255,128 }),
                             ({ 255,255,255 }), ({ 0,255,255 })}))
              ->hsv_to_rgb();
         

    RETURN VALUE
    the new image object


    NAME
    Image.image->invert

    SYNTAX
    object invert()

    DESCRIPTION
    Invert an image. Each pixel value gets to be 255-x, where x is the old value.

    original ->invert(); ->rgb_to_hsv()->invert()->hsv_to_rgb();

    RETURN VALUE
    the new image object


    NAME
    Image.image->line

    SYNTAX
    object line(int x1, int y1, int x2, int y2)
    object line(int x1, int y1, int x2, int y2, int r, int g, int b)
    object line(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

    DESCRIPTION
    Draws a line on the image. The line is not antialiased.

    ARGUMENTS
    argument(s) description
    int x1
    int y1
    int x2
    int y2
    line endpoints
    int r
    int g
    int b
    color
    int alpha alpha value

    RETURN VALUE
    the object called


    NAME
    Image.image->map_closest
    Image.image->map_fast
    Image.image->map_fs
    Image.image->select_colors

    SYNTAX
    object map_closest(array(array(int)) colors)
    object map_fast(array(array(int)) colors)
    object map_fs(array(array(int)) colors)
    array select_colors(int num)

    DESCRIPTION
    Compatibility functions. Do not use!

    Replacement examples:

    Old code:

    img=map_fs(img->select_colors(200));
    New code:
    img=Image.colortable(img,200)->floyd_steinberg()->map(img);

    Old code:

    img=map_closest(img->select_colors(17)+({({255,255,255}),({0,0,0})}));
    New code:
    img=Image.colortable(img,19,({({255,255,255}),({0,0,0})}))->map(img);


    NAME
    Image.image->mirrorx

    SYNTAX
    object mirrorx()

    DESCRIPTION
    mirrors an image:
    original ->mirrorx();

    RETURN VALUE
    the new image object


    NAME
    Image.image->mirrory

    SYNTAX
    object mirrory()

    DESCRIPTION
    mirrors an image:
    original ->mirrory();


    NAME
    Image.image->modify_by_intensity

    SYNTAX
    object modify_by_intensity(int r, int g, int b, int|array(int) v1, ..., int|array(int) vn)

    DESCRIPTION
    Recolor an image from intensity values.

    For each color an intensity is calculated, from r, g and b factors (see grey), this gives a value between 0 and max.

    The color is then calculated from the values given, v1 representing the intensity value of 0, vn representing max, and colors between representing intensity values between, linear.

    original ->grey()->modify_by_intensity(1,0,0, 0,({255,0,0}),({0,255,0}));

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    red, green, blue intensity factors
    int|array(int) v1
    int|array(int) vn
    destination color

    RETURN VALUE
    the new image object

    SEE ALSO
    grey, `*, color


    NAME
    Image.image->noise

    SYNTAX
    void noise(array(float|int|array(int)) colorrange)
    void noise(array(float|int|array(int)) colorrange, float scale, float xdiff, float ydiff, float cscale)

    DESCRIPTION
    Gives a new image with the old image's size, filled width a 'noise' pattern.

    The random seed may be different with each instance of pike.

    Example: ->noise( ({0,({255,0,0}), 0.3,({0,255,0}), 0.6,({0,0,255}), 0.8,({255,255,0})}), 0.005,0,0,0.5 );

    ARGUMENTS
    argument(s) description
    array(float|int|array(int)) colorrange colorrange table
    float scale default value is 0.1
    float xdiff
    float ydiff
    default value is 0,0
    float cscale default value is 1

    SEE ALSO
    turbulence


    NAME
    Image.image->paste

    SYNTAX
    object paste(object image)
    object paste(object image, int x, int y)

    DESCRIPTION
    Pastes a given image over the current image.

    ARGUMENTS
    argument(s) description
    object image image to paste (may be empty, needs to be an image object)
    int x
    int y
    where to paste the image; default is 0,0

    RETURN VALUE
    the object called

    SEE ALSO
    paste_mask, paste_alpha, paste_alpha_color


    NAME
    Image.image->paste_alpha

    SYNTAX
    object paste_alpha(object image, int alpha)
    object paste_alpha(object image, int alpha, int x, int y)

    DESCRIPTION
    Pastes a given image over the current image, with the specified alpha channel value. An alpha channel value of 0 leaves nothing of the original image in the paste area, 255 is meaningless and makes the given image invisible.

    ARGUMENTS
    argument(s) description
    object image image to paste
    int alpha alpha channel value
    int x
    int y
    where to paste the image; default is 0,0

    RETURN VALUE
    the object called

    SEE ALSO
    paste_mask, paste, paste_alpha_color


    NAME
    Image.image->paste_alpha_color

    SYNTAX
    object paste_alpha_color(object mask)
    object paste_alpha_color(object mask, int x, int y)
    object paste_alpha_color(object mask, int r, int g, int b)
    object paste_alpha_color(object mask, int r, int g, int b, int x, int y)

    DESCRIPTION
    Pastes a given color over the current image, using the given mask as opaque channel. A pixel value of 255 makes the result become the color given, 0 doesn't change anything. The masks red, green and blue values are used separately. If no color are given, the current is used.

    ARGUMENTS
    argument(s) description
    object mask mask image
    int r
    int g
    int b
    what color to paint with; default is current
    int x
    int y
    where to paste the image; default is 0,0

    RETURN VALUE
    the object called

    SEE ALSO
    paste_mask, paste_alpha, paste_alpha_color


    NAME
    Image.image->paste_mask

    SYNTAX
    object paste_mask(object image, object mask)
    object paste_mask(object image, object mask, int x, int y)

    DESCRIPTION
    Pastes a given image over the current image, using the given mask as opaque channel. A pixel value of 255 makes the result become a pixel from the given image, 0 doesn't change anything.

    The masks red, green and blue values are used separately.

    ARGUMENTS
    argument(s) description
    object image image to paste
    object mask mask image
    int x
    int y
    where to paste the image; default is 0,0

    RETURN VALUE
    the object called

    SEE ALSO
    paste, paste_alpha, paste_alpha_color


    NAME
    Image.image->polyfill

    SYNTAX
    object polyfill(array(int|float) ... curve)

    DESCRIPTION
    fills an area with the current color

    ARGUMENTS
    argument(s) description
    array(int|float) curve curve(s), ({x1,y1,x2,y2,...,xn,yn}), automatically closed.

    If any given curve is inside another, it will make a hole.

    RETURN VALUE
    the current object

    NOTA BENE
    Lines in the polygon may not be crossed without midpoints.

    SEE ALSO
    setcolor


    NAME
    Image.image->read_lsb_grey
    Image.image->read_lsb_rgb
    Image.image->write_lsb_grey
    Image.image->write_lsb_rgb

    SYNTAX
    object write_lsb_rgb(string what)
    object write_lsb_grey(string what)
    string read_lsb_rgb()
    string read_lsb_grey()

    DESCRIPTION
    These functions read/write in the least significant bit of the image pixel values. The _rgb() functions read/write on each of the red, green and blue values, and the grey keeps the same lsb on all three.

    The string is nullpadded or cut to fit.

    ARGUMENTS
    argument(s) description
    string what the hidden message

    RETURN VALUE
    the current object or the read string


    NAME
    Image.image->rotate
    Image.image->rotate_expand

    SYNTAX
    object rotate(int|float angle)
    object rotate(int|float angle, int r, int g, int b)
    object rotate_expand(int|float angle)
    object rotate_expand(int|float angle, int r, int g, int b)

    DESCRIPTION
    Rotates an image a certain amount of degrees (360° is a complete rotation) counter-clockwise:

    original ->rotate(15,255,0,0); ->rotate_expand(15);

    The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.

    This rotate uses the skewx() and skewy() functions.

    ARGUMENTS
    argument(s) description
    int|float angle the number of degrees to rotate
    int r
    int g
    int b
    color to fill with; default is current

    RETURN VALUE
    the new image object


    NAME
    Image.image->rotate_ccw

    SYNTAX
    object rotate_ccw()

    DESCRIPTION
    rotates an image counter-clockwise, 90 degrees.

    original ->rotate_ccw();

    RETURN VALUE
    the new image object


    NAME
    Image.image->rotate_cw

    SYNTAX
    object rotate_cw()

    DESCRIPTION
    rotates an image clockwise, 90 degrees.

    original ->rotate_cw();

    RETURN VALUE
    the new image object


    NAME
    Image.image->scale

    SYNTAX
    object scale(float factor)
    object scale(0.5)
    object scale(float xfactor, float yfactor)

    DESCRIPTION
    scales the image with a factor, 0.5 is an optimized case.

    ARGUMENTS
    argument(s) description
    float factor factor to use for both x and y
    float xfactor
    float yfactor
    separate factors for x and y

    RETURN VALUE
    the new image object


    NAME
    Image.image->scale

    SYNTAX
    object scale(int newxsize, int newysize)
    object scale(0, int newysize)
    object scale(int newxsize, 0)

    DESCRIPTION
    scales the image to a specified new size, if one of newxsize or newysize is 0, the image aspect ratio is preserved.

    ARGUMENTS
    argument(s) description
    int newxsize
    int newysize
    new image size in pixels

    RETURN VALUE
    the new image object


    NAME
    Image.image->select_from

    SYNTAX
    object select_from(int x, int y)
    object select_from(int x, int y, int edge_value)

    DESCRIPTION
    Makes an grey-scale image, for alpha-channel use. This is very close to a floodfill. The image is scanned from the given pixel, filled with 255 if the color is the same, or 255 minus distance in the colorcube, squared, rightshifted 8 steps (see distancesq).

    When the edge distance is reached, the scan is stopped. Default edge value is 30. This value is squared and compared with the square of the distance above.

    ARGUMENTS
    argument(s) description
    int x
    int y
    originating pixel in the image

    RETURN VALUE
    the new image object

    SEE ALSO
    distancesq


    NAME
    Image.image->setcolor

    SYNTAX
    object setcolor(int r, int g, int b)
    object setcolor(int r, int g, int b, int alpha)

    DESCRIPTION
    set the current color

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    new color
    int alpha new alpha value

    RETURN VALUE
    the object called


    NAME
    Image.image->setpixel

    SYNTAX
    object setpixel(int x, int y)
    object setpixel(int x, int y, int r, int g, int b)
    object setpixel(int x, int y, int r, int g, int b, int alpha)

    DESCRIPTION

    ARGUMENTS
    argument(s) description
    int x
    int y
    position of the pixel
    int r
    int g
    int b
    color
    int alpha alpha value

    RETURN VALUE
    the object called


    NAME
    Image.image->skewx
    Image.image->skewx_expand

    SYNTAX
    object skewx(int x)
    object skewx(int yfactor)
    object skewx(int x, int r, int g, int b)
    object skewx(int yfactor, int r, int g, int b)
    object skewx_expand(int x)
    object skewx_expand(int yfactor)
    object skewx_expand(int x, int r, int g, int b)
    object skewx_expand(int yfactor, int r, int g, int b)

    DESCRIPTION
    Skews an image an amount of pixels or a factor; a skew-x is a transformation:

    original ->skewx(15,255,0,0); ->skewx_expand(15);

    ARGUMENTS
    argument(s) description
    int x the number of pixels The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.
    float yfactor best described as: x=yfactor*this->ysize()
    int r
    int g
    int b
    color to fill with; default is current

    RETURN VALUE
    the new image object


    NAME
    Image.image->skewy
    Image.image->skewy_expand

    SYNTAX
    object skewy(int y)
    object skewy(int xfactor)
    object skewy(int y, int r, int g, int b)
    object skewy(int xfactor, int r, int g, int b)
    object skewy_expand(int y)
    object skewy_expand(int xfactor)
    object skewy_expand(int y, int r, int g, int b)
    object skewy_expand(int xfactor, int r, int g, int b)

    DESCRIPTION
    Skews an image an amount of pixels or a factor; a skew-y is a transformation:

    original ->skewy(15,255,0,0); ->skewy_expand(15);

    The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.

    ARGUMENTS
    argument(s) description
    int y the number of pixels
    float xfactor best described as: t=xfactor*this->xsize()
    int r
    int g
    int b
    color to fill with; default is current

    RETURN VALUE
    the new image object


    NAME
    Image.image->threshold

    SYNTAX
    object threshold()
    object threshold(int r, int g, int b)

    DESCRIPTION
    Makes a black-white image.

    If all red, green, blue parts of a pixel is larger or equal then the given value, the pixel will become white, else black.

    This method works fine with the grey method.

    If no arguments are given, the current color is used for threshold values.

    original ->threshold(90,100,110);

    ARGUMENTS
    argument(s) description
    int r
    int g
    int b
    red, green, blue threshold values

    RETURN VALUE
    the new image object

    SEE ALSO
    grey


    NAME
    Image.image->toppm

    SYNTAX
    string toppm()

    DESCRIPTION
    compability method - do not use in new programs. See Image.PNM.encode().

    RETURN VALUE
    PPM data


    NAME
    Image.image->tuned_box

    SYNTAX
    object tuned_box(int x1, int y1, int x2, int y2, array(array(int)) corner_color)

    DESCRIPTION
    Draws a filled rectangle with colors (and alpha values) tuned between the corners.

    Tuning function is (1.0-x/xw)*(1.0-y/yw) where x and y is the distance to the corner and xw and yw are the sides of the rectangle.

    original solid tuning
    (blue,red,green,yellow)
    tuning transparency
    (as left + 255,128,128,0)

    ARGUMENTS
    argument(s) description
    int x1
    int y1
    int x2
    int y2
    rectangle corners
    array(array(int)) corner_color colors of the corners:
         ({x1y1,x2y1,x1y2,x2y2})
         
    each of these is an array of integeres:
         ({r,g,b}) or ({r,g,b,alpha})
         
    Default alpha channel value is 0 (opaque).

    RETURN VALUE
    the object called


    NAME
    Image.image->turbulence

    SYNTAX
    void turbulence(array(float|int|array(int)) colorrange)
    void turbulence(array(float|int|array(int)) colorrange, int octaves, float scale, float xdiff, float ydiff, float cscale)

    DESCRIPTION
    gives a new image with the old image's size, filled width a 'turbulence' pattern

    The random seed may be different with each instance of pike.

    Example:
    ->turbulence( ({0,({229,204,204}), 0.9,({229,20,20}), 0.9,0}) );

    ARGUMENTS
    argument(s) description
    array(float|int|array(int)) colorrange colorrange table
    int octaves default value is 3
    float scale default value is 0.1
    float xdiff
    float ydiff
    default value is 0,0
    float cscale default value is 1

    SEE ALSO
    noise


    NAME
    Image.image->xsize

    SYNTAX
    int xsize()

    RETURN VALUE
    the width of the image


    NAME
    Image.image->ysize

    SYNTAX
    int ysize()

    RETURN VALUE
    the height of the image


    NAME
    Image.image->`&

    SYNTAX
    object `&(object operand)
    object `&(array(int) color)
    object `&(int value)

    DESCRIPTION
    makes a new image out of the minimum pixels values

    ARGUMENTS
    argument(s) description
    object operand the other image to compare with; the images must have the same size.
    array(int) color an array in format ({r,g,b}), this is equal to using an uniform-colored image.
    int value equal to ({value,value,value}).

    RETURN VALUE
    the new image object

    SEE ALSO
    `-, `+, `|, `*, add_layers


    NAME
    Image.image->`*

    SYNTAX
    object `*(object operand)
    object `*(array(int) color)
    object `*(int value)

    DESCRIPTION
    Multiplies pixel values and creates a new image.

    This can be useful to lower the values of an image, making it greyer, for instance:

    image=image*128+64;

    ARGUMENTS
    argument(s) description
    object operand the other image to multiply with; the images must have the same size.
    array(int) color an array in format ({r,g,b}), this is equal to using an uniform-colored image.
    int value equal to ({value,value,value}).

    RETURN VALUE
    the new image object

    SEE ALSO
    `-, `+, `|, `&, add_layers


    NAME
    Image.image->`+

    SYNTAX
    object `+(object operand)
    object `+(array(int) color)
    object `+(int value)

    DESCRIPTION
    adds two images; values are truncated at 255.

    ARGUMENTS
    argument(s) description
    object operand the image which to add.
    array(int) color an array in format ({r,g,b}), this is equal to using an uniform-colored image.
    int value equal to ({value,value,value}).

    RETURN VALUE
    the new image object

    SEE ALSO
    `-, `|, `&, `*, add_layers


    NAME
    Image.image->`-

    SYNTAX
    object `-(object operand)
    object `-(array(int) color)
    object `-(int value)

    DESCRIPTION
    makes a new image out of the difference

    ARGUMENTS
    argument(s) description
    object operand the other image to compare with; the images must have the same size.
    array(int) color an array in format ({r,g,b}), this is equal to using an uniform-colored image.
    int value equal to ({value,value,value}).

    RETURN VALUE
    the new image object

    SEE ALSO
    `+, `|, `&, `*, add_layers


    NAME
    Image.image->`|

    SYNTAX
    object `|(object operand)
    object `|(array(int) color)
    object `|(int value)

    DESCRIPTION
    makes a new image out of the maximum pixels values

    ARGUMENTS
    argument(s) description
    object operand the other image to compare with; the images must have the same size.
    array(int) color an array in format ({r,g,b}), this is equal to using an uniform-colored image.
    int value equal to ({value,value,value}).

    RETURN VALUE
    the new image object

    SEE ALSO
    `-, `+, `&, `*, add_layers

    12.4 Image.GIF


    NAME
    Image.GIF

    DESCRIPTION
    This submodule keep the GIF encode/decode capabilities of the Image module.

    GIF is a common image storage format, usable for a limited color palette - a GIF image can only contain as most 256 colors - and animations.

    Simple encoding: encode, encode_trans

    Advanced stuff: render_block, header_block, end_block, netscape_loop_block

    Very advanced stuff: _render_block, _gce_block

    SEE ALSO
    Image, Image.image, Image.colortable


    NAME
    Image.GIF.encode
    Image.GIF.encode_trans

    SYNTAX
    string encode(object img);
    string encode(object img, int colors);
    string encode(object img, object colortable);
    string encode_trans(object img, object alpha);
    string encode_trans(object img, int tr_r, int tr_g, int tr_b);
    string encode_trans(object img, int colors, object alpha);
    string encode_trans(object img, int colors, int tr_r, int tr_g, int tr_b);
    string encode_trans(object img, int colors, object alpha, int tr_r, int tr_g, int tr_b);
    string encode_trans(object img, object colortable, object alpha);
    string encode_trans(object img, object colortable, int tr_r, int tr_g, int tr_b);
    string encode_trans(object img, object colortable, object alpha, int a_r, int a_g, int a_b);
    string encode_trans(object img, object colortable, int transp_index);

    DESCRIPTION
    Create a complete GIF file.

    The latter (encode_trans) functions add transparency capabilities.

    Example:

         img=Image.image([...]);
         [...] // make your very-nice image
         write(Image.GIF.encode(img)); // write it as GIF on stdout 
         

    ARGUMENTS
    argument(s) description
    object img The image which to encode.
    int colors
    object colortable
    These arguments decides what colors the image should be encoded with. If a number is given, a colortable with be created with (at most) that amount of colors. Default is '256' (GIF maximum amount of colors).
    object alpha Alpha channel image (defining what is transparent); black color indicates transparency. GIF has only transparent or nontransparent (no real alpha channel). You can always dither a transparency channel: Image.colortable(my_alpha, ({({0,0,0}),({255,255,255})})) ->full()->floyd_steinberg()->map(my_alpha)
    int tr_r
    int tr_g
    int tr_b
    Use this (or the color closest to this) color as transparent pixels.
    int a_r
    int a_g
    int a_b
    Encode transparent pixels (given by alpha channel image) to have this color. This option is for making GIFs for the decoders that doesn't support transparency.
    int transp_index Use this color no in the colortable as transparent color.

    NOTA BENE
    For advanced users:
    Image.GIF.encode_trans(img,colortable,alpha);
    is equivalent of using
    Image.GIF.header_block(img->xsize(),img->ysize(),colortable)+
         Image.GIF.render_block(img,colortable,0,0,0,alpha)+
         Image.GIF.end_block();
    and is actually implemented that way.


    NAME
    Image.GIF.end_block

    SYNTAX
    string end_block();

    DESCRIPTION
    This function gives back a GIF end (trailer) block.

    RETURN VALUE
    the end block as a string.

    NOTA BENE
    This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

    The result of this function is always ";" or "\x3b", but I recommend using this function anyway for code clearity.

    SEE ALSO
    header_block, end_block


    NAME
    Image.GIF.header_block

    SYNTAX
    string header_block(int xsize, int ysize, int numcolors);
    string header_block(int xsize, int ysize, object colortable);
    string header_block(int xsize, int ysize, object colortable, int background_color_index, int gif87a, int aspectx, int aspecty);
    string header_block(int xsize, int ysize, object colortable, int background_color_index, int gif87a, int aspectx, int aspecty, int r, int g, int b);

    DESCRIPTION
    This function gives back a GIF header block.

    Giving a colortable to this function includes a global palette in the header block.

    ARGUMENTS
    argument(s) description
    int xsize
    int ysize
    Size of drawing area. Usually same size as in the first (or only) render block(s).
    int background_color_index This color in the palette is the background color. Background is visible if the following render block(s) doesn't fill the drawing area or are transparent. Most decoders doesn't use this value, though.
    int gif87a If set, write 'GIF87a' instead of 'GIF89a' (default 0 == 89a).
    int aspectx
    int aspecty
    Aspect ratio of pixels, ranging from 4:1 to 1:4 in increments of 1/16th. Ignored by most decoders. If any of aspectx or aspecty is zero, aspectratio information is skipped.
    int r
    int g
    int b
    Add this color as the transparent color. This is the color used as transparency color in case of alpha-channel given as image object. This increases (!) the number of colors by one.

    RETURN VALUE
    the created header block as a string

    NOTA BENE
    This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

    This GIF encoder doesn't support different size of colors in global palette and color resolution.

    SEE ALSO
    header_block, end_block


    NAME
    Image.GIF.netscape_loop_block

    SYNTAX
    string netscape_loop_block();
    string netscape_loop_block(int number_of_loops);

    DESCRIPTION
    Creates a application-specific extention block; this block makes netscape and compatible browsers loop the animation a certain amount of times.

    ARGUMENTS
    argument(s) description
    int number_of_loops Number of loops. Max and default is 65535.


    NAME
    Image.GIF.render_block

    SYNTAX
    string render_block(object img, object colortable, int x, int y, int localpalette);
    string render_block(object img, object colortable, int x, int y, int localpalette, object alpha);
    string render_block(object img, object colortable, int x, int y, int localpalette, object alpha, int r, int g, int b);
    string render_block(object img, object colortable, int x, int y, int localpalette, int delay, int transp_index, int interlace, int user_input, int disposal);
    string render_block(object img, object colortable, int x, int y, int localpalette, object alpha, int r, int g, int b, int delay, int interlace, int user_input, int disposal);

    DESCRIPTION
    This function gives a image block for placement in a GIF file, with or without transparency. The some options actually gives two blocks, the first with graphic control extensions for such things as delay or transparency.

    Example:

         img1=Image.image([...]);
         img2=Image.image([...]);
         [...] // make your very-nice images
         nct=Image.colortable([...]); // make a nice colortable
         write(Image.GIF.header_block(xsize,ysize,nct)); // write a GIF header
         write(Image.GIF.render_block(img1,nct,0,0,0,10)); // write a render block
         write(Image.GIF.render_block(img2,nct,0,0,0,10)); // write a render block
         [...]
         write(Image.GIF.end_block()); // write end block
         // voila! A GIF animation on stdout.
         

    The above animation is thus created:

         object nct=colortable(lena,32,({({0,0,0})}));
         string s=GIF.header_block(lena->xsize(),lena->ysize(),nct);
         foreach ( ({lena->xsize(),
                     (int)(lena->xsize()*0.75),
                     (int)(lena->xsize()*0.5),
                     (int)(lena->xsize()*0.25),
                     (int)(1),
                     (int)(lena->xsize()*0.25),
                     (int)(lena->xsize()*0.5),
                     (int)(lena->xsize()*0.75)}),int xsize)
         {
            object o=lena->scale(xsize,lena->ysize());
            object p=lena->clear(0,0,0);
            p->paste(o,(lena->xsize()-o->xsize())/2,0);
            s+=GIF.render_block(p,nct,0,0,0,25);
         }
         s+=GIF.netscape_loop_block(200);
         s+=GIF.end_block();
         write(s);
         

    ARGUMENTS
    argument(s) description
    object img The image.
    object colortable Colortable with colors to use and to write as palette.
    int x
    int y
    Position of this image.
    int localpalette If set, writes a local palette.
    object alpha Alpha channel image; black is transparent.
    int r
    int g
    int b
    Color of transparent pixels. Not all decoders understands transparency. This is ignored if localpalette isn't set.
    int delay View this image for this many centiseconds. Default is zero.
    int transp_index Index of the transparent color in the colortable. -1 indicates no transparency.
    int user_input If set: wait the delay or until user input. If delay is zero, wait indefinitely for user input. May sound the bell upon decoding. Default is non-set.
    int disposal Disposal method number;
    0
    No disposal specified. The decoder is not required to take any action. (default)
    1
    Do not dispose. The graphic is to be left in place.
    2
    Restore to background color. The area used by the graphic must be restored to the background color.
    3
    Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic.
    4-7
    To be defined.

    NOTA BENE
    This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

    The user_input and disposal method are unsupported in most decoders.

    SEE ALSO
    encode, header_block, end_block


    NAME
    Image.GIF._gce_block

    SYNTAX
    string _gce_block(int transparency, int transparency_index, int delay, int user_input, int disposal);

    DESCRIPTION
    This function gives back a Graphic Control Extension block. A GCE block has the scope of the following render block.

    ARGUMENTS
    argument(s) description
    int transparency
    int transparency_index
    The following image has transparency, marked with this index.
    int delay View the following rendering for this many centiseconds (0..65535).
    int user_input Wait the delay or until user input. If delay is zero, wait indefinitely for user input. May sound the bell upon decoding.
    int disposal Disposal method number;
    0
    No disposal specified. The decoder is not required to take any action.
    1
    Do not dispose. The graphic is to be left in place.
    2
    Restore to background color. The area used by the graphic must be restored to the background color.
    3
    Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic.
    4-7
    To be defined.

    NOTA BENE
    This is in the very advanced sector of the GIF support; please read about how GIFs file works.

    Most decoders just ignore some or all of these parameters.

    SEE ALSO
    _render_block, render_block


    NAME
    Image.GIF._render_block

    SYNTAX
    string _render_block(int x, int y, int xsize, int ysize, int bpp, string indices, 0|string colortable, int interlace);

    DESCRIPTION
    Advanced (!) method for writing renderblocks for placement in a GIF file. This method only applies LZW encoding on the indices and makes the correct headers.

    ARGUMENTS
    argument(s) description
    int x
    int y
    Position of this image.
    int xsize
    int ysize
    Size of the image. Length if the indices string must be xsize*ysize.
    int bpp Bits per pixels in the indices. Valid range 1..8.
    string indices The image indices as an 8bit indices.
    string colortable Colortable with colors to write as palette. If this argument is zero, no local colortable is written. Colortable string len must be 1&lt;&lt;bpp.
    int interlace Interlace index data and set interlace bit. The given string should _not_ be pre-interlaced.

    NOTA BENE
    This is in the very advanced sector of the GIF support; please read about how GIFs file works.

    SEE ALSO
    encode, _encode, header_block, end_block

    12.5 Image.PNM


    NAME
    Image.PNM

    DESCRIPTION
    This submodule keeps the PNM encode/decode capabilities of the Image module.

    PNM is a common image storage format on unix systems, and is a very simple format.

    This format doesn't use any color palette.

    The format is divided into seven subformats;

         P1(PBM) - ascii bitmap (only two colors)
         P2(PGM) - ascii greymap (only grey levels)
         P3(PPM) - ascii truecolor
         P4(PBM) - binary bitmap 
         P5(PGM) - binary greymap 
         P6(PPM) - binary truecolor
         

    Simple encoding:
    encode,
    encode_binary,
    encode_ascii

    Simple decoding:
    decode

    Advanced encoding:
    encode_P1,
    encode_P2,
    encode_P3,
    encode_P4,
    encode_P5,
    encode_P6

    SEE ALSO
    Image, Image.image, Image.GIF


    NAME
    Image.PNM.decode

    SYNTAX
    object decode(string data)

    DESCRIPTION
    Decodes PNM (PBM/PGM/PPM) data and creates an image object.

    RETURN VALUE
    the decoded image as an image object

    NOTA BENE
    This function may throw errors upon illegal PNM data.

    SEE ALSO
    encode


    NAME
    Image.PNM.encode
    Image.PNM.encode_P6
    Image.PNM.encode_binary

    SYNTAX
    string encode(object image)
    string encode_binary(object image)
    string encode_P6(object image)

    DESCRIPTION
    Make a complete PNM file from an image.

    encode_binary() and encode_ascii() uses the most optimized encoding for this image (bitmap, grey or truecolor) - P4, P5 or P6 respective P1, P2 or P3.

    encode() maps to encode_binary().

    RETURN VALUE
    the encoded image as a string

    SEE ALSO
    decode

    Chapter 13, Other modules

    Pike also include a number of smaller modules. These modules implement support for various algorithms, data structures and system routines.

    13.1 System

    The system module contains some system-specific functions that may or may not be available on your system. Most of these functions do exactly the same thing as their UNIX counterpart. See the UNIX man pages for detailed information about what these functions do on your system.

    Please note that these functions are available globally, you do not need to import System to use these functions.


    NAME
    chroot - change the root directory

    SYNTAX
    int chroot(string newroot);
    or
    int chroot(object(File) obj);

    DESCRIPTION
    Changes the root directory for this process to the indicated directory.

    NOTA BENE
    Since this function modifies the directory structure as seen from Pike, you have to modify the environment variables PIKE_MODULE_PATH and PIKE_INCLUDE_PATH to compensate for the new root-directory.

    This function only exists on systems that have the chroot(2) system call. The second variant only works on systems that also have the fchroot(2) system call.


    NAME
    getegid - get the effective group ID

    SYNTAX
    int getegid();

    DESCRIPTION
    Get the effective group ID.

    SEE ALSO
    setuid, getuid, setgid, getgid, seteuid, geteuid and setegid


    NAME
    geteuid - get the effective user ID

    SYNTAX
    int geteuid();

    DESCRIPTION
    Get the effective user ID.

    SEE ALSO
    setuid, getuid, setgid, getgid, seteuid, setegid and getegid


    NAME
    getgid - get the group ID

    SYNTAX
    int getgid();

    DESCRIPTION
    Get the real group ID.

    SEE ALSO
    setuid, getuid, setgid, seteuid, geteuid, setegid and getegid


    NAME
    gethostbyaddr - gets information about a host given its address

    SYNTAX
    array gethostbyaddr(string addr);

    DESCRIPTION
    Returns an array with information about the specified IP address.

    The returned array contains the same information as that returned by gethostbyname().

    NOTA BENE
    This function only exists on systems that have the gethostbyaddr(2) or similar system call.

    SEE ALSO
    gethostbyname


    NAME
    gethostbyname - gets information about a host given its name

    SYNTAX
    array gethostbyname(string hostname);

    DESCRIPTION
    Returns an array with information about the specified host.

    The array contains three elements:

    The first element is the hostname.

    The second element is an array(string) of IP numbers for the host.

    The third element is an array(string) of aliases for the host.

    NOTA BENE
    This function only exists on systems that have the gethostbyname(2) or similar system call.

    SEE ALSO
    gethostbyaddr


    NAME
    gethostname - get the name of this host

    SYNTAX
    string gethostname();

    DESCRIPTION
    Returns a string with the name of the host.

    NOTA BENE
    This function only exists on systems that have the gethostname(2) or uname(2) system calls.


    NAME
    getpgrp - get the process group ID

    SYNTAX
    int getpgrp();
    or
    int getpgrp(int pid);

    DESCRIPTION
    With no arguments or with pid equal to zero, returns the process group ID of this process.

    If pid is specified, returns the process group ID of that process.

    SEE ALSO
    getpid and getppid


    NAME
    getpid - get the process ID

    SYNTAX
    int getpid();

    DESCRIPTION
    Returns the process ID of this process.

    SEE ALSO
    getppid and getpgrp


    NAME
    getppid - get the parent process ID

    SYNTAX
    int getppid();

    DESCRIPTION
    Returns the process ID of the parent process.

    SEE ALSO
    getpid and getpgrp


    NAME
    getuid - get the user ID

    SYNTAX
    int getuid();

    DESCRIPTION
    Get the real user ID.

    SEE ALSO
    setuid, setgid, getgid, seteuid, geteuid, setegid and getegid


    NAME
    hardlink - create a hardlink

    SYNTAX
    void hardlink(string from, string to);

    DESCRIPTION
    Creates a hardlink named to from the file from.

    SEE ALSO
    symlink, mv and rm


    NAME
    initgroups - initialize the group access list

    SYNTAX
    void initgroups(string username, int base_gid);

    DESCRIPTION
    Initializes the group access list according to the system group database. base_gid is also added to the group access list.

    SEE ALSO
    setuid, getuid, setgid, getgid, seteuid, geteuid, setegid, getegid, system/getgroups and system/setgroups


    NAME
    openlog - initializes the connection to syslogd

    SYNTAX
    void openlog(string ident, int options, facility);

    DESCRIPTION
    Initializes the connection to syslogd.

    The ident argument specifies an identifier to tag all log entries with.

    options is a bit field specifying the behavior of the message logging. Valid options are:

    LOG_PID Log the process ID with each message.
    LOG_CONS Write messages to the console if they can't be sent to syslogd.
    LOG_NDELAY Open the connection to syslogd now and not later.
    LOG_NOWAIT Do not wait for subprocesses talking to syslogd.

    facility specifies what subsystem you want to log as. Valid facilities are:

    LOG_AUTH Authorization subsystem
    LOG_AUTHPRIV
    LOG_CRON Crontab subsystem
    LOG_DAEMON System daemons
    LOG_KERN Kernel subsystem (NOT USABLE)
    LOG_LOCAL For local use
    LOG_LOCAL[1-7] For local use
    LOG_LPR Line printer spooling system
    LOG_MAIL Mail subsystem
    LOG_NEWS Network news subsystem
    LOG_SYSLOG
    LOG_USER
    LOG_UUCP UUCP subsystem

    NOTA BENE
    Only available on systems with syslog(3). BUGS LOG_NOWAIT should probably always be specified.

    SEE ALSO
    syslog, closelog and setlogmask


    NAME
    readlink - read a symbolic link

    SYNTAX
    string readlink(string linkname);

    DESCRIPTION
    Returns what the symbolic link linkname points to.

    SEE ALSO
    symlink


    NAME
    setegid - set the effective group ID

    SYNTAX
    void setegid(int uid);

    DESCRIPTION
    Sets the effective group ID to gid.

    SEE ALSO
    setuid, getuid, setgid, getgid, seteuid, geteuid and getegid


    NAME
    seteuid - set the effective user ID

    SYNTAX
    void seteuid(int uid);

    DESCRIPTION
    Sets the effective user ID to uid.

    SEE ALSO
    setuid, getuid, setgid, getgid, geteuid, setegid and getegid


    NAME
    setgid - set the group ID

    SYNTAX
    void setgid(int gid);

    DESCRIPTION
    Sets the real group ID, effective group ID and saved group ID to gid.

    SEE ALSO
    setuid, getuid, getgid, seteuid, geteuid, setegid and getegid


    NAME
    setuid - set the user ID

    SYNTAX
    void setuid(int uid);

    DESCRIPTION
    Sets the real user ID, effective user ID and saved user ID to uid.

    SEE ALSO
    getuid, setgid, getgid, seteuid, geteuid, setegid and getegid


    NAME
    symlink - create a symbolic link

    SYNTAX
    void symlink(string from, string to);

    DESCRIPTION
    Creates a symbolic link named to pointing to from.

    SEE ALSO
    hardlink, readlink, mv and rm


    NAME
    uname - get operating system information

    SYNTAX
    mapping(string:string) uname();

    DESCRIPTION
    Returns a mapping describing the operating system.

    The mapping contains the following fields:

    "sysname": Operating system name
    "nodename": "release": "version": "machine": Host name Release of this OS Version number of this OS Machine architecture

    NOTA BENE
    This function only exists on systems that have the uname(2) system call.


    13.2 Process

    The Process module contains functions to start and control other programs from Pike.
    NAME
    Process.popen - pipe open

    SYNTAX
    string popen(string cmd);

    DESCRIPTION
    This function runs the command cmd as in a shell and returns the output. See your Unix/C manual for details on popen.


    NAME
    Process.system - run an external program

    SYNTAX
    void system(string cmd);

    DESCRIPTION
    This function runs the external program cmd and waits until it is finished. Standard /bin/sh completions/redirections/etc. can be used.

    SEE ALSO
    Process.popen, Process.exec and Process.spawn


    NAME
    Process.spawn - spawn a process

    SYNTAX
    int spawn(string cmd);
    or
    int spawn(string cmd, object stdin);
    or
    int spawn(string cmd, object stdin, object stdout);
    or
    int spawn(string cmd, object stdin, object stdout, object stderr);

    DESCRIPTION
    This function spawns a process but does not wait for it to finish. Optionally, clones of Stdio.File can be sent to it to specify where stdin, stdout and stderr of the spawned processes should go.

    SEE ALSO
    Process.popen, fork, Process.exec, Stdio.File->pipe and Stdio.File->dup2


    NAME
    exece - execute a program

    SYNTAX
    int exece(string file, array(string) args);
    or
    int exece(string file, array(string) args, mapping(string:string) env);

    DESCRIPTION
    This function transforms the Pike process into a process running the program specified in the argument file with the argument args. If the mapping env is present, it will completely replace all environment variables before the new program is executed. This function only returns if something went wrong during exece(), and in that case it returns zero.

    NOTA BENE
    The Pike driver _dies_ when this function is called. You must use fork() if you wish to execute a program and still run the Pike driver.

    EXAMPLES
    exece("/bin/ls", ({"-l"}));
    exece("/bin/sh", ({"-c", "echo $HOME"}), (["HOME":"/not/home"]));

    SEE ALSO
    fork and Stdio.File->pipe


    NAME
    Process.exec - simple way to use exece()

    SYNTAX
    int exec(string file, string ... args);

    DESCRIPTION
    This function destroys the Pike parser and runs the program file instead with the arguments. If no there are no '/' in the filename, the variable PATH will be consulted when looking for the program. This function does not return except when the exec fails for some reason.

    EXAMPLE
    exec("/bin/echo","hello","world");

    13.3 Regexp

    Regexp is short for Regular Expression. A regular expression is a standardized way to make pattern that match certain strings. In Pike you can often use the sscanf, range and index operators to match strings, but sometimes a regexp is both faster and easier.

    A regular expression is actually a string, then compiled into an object. The string contains characters that make up a pattern for other strings to match. Normal characters, such as A through Z only match themselves, but some characters have special meaning.
    pattern Matches
    . any one character
    [abc] a, b or c
    [a-z] any character a to z inclusive
    [^ac] any character except a and c
    (x) x (x might be any regexp) If used with split, this also puts the string matching x into the result array.
    x* zero or more occurrences of 'x' (x may be any regexp)
    x+ one or more occurrences of 'x' (x may be any regexp)
    x|y x or y. (x or y may be any regexp)
    xy xy (x and y may be any regexp)
    ^ beginning of string (but no characters)
    $ end of string (but no characters)
    \< the beginning of a word (but no characters)
    \> the end of a word (but no characters)
    Let's look at a few examples:
    RegexpMatches
    [0-9]+one or more digits
    [^ \t\n]exactly one non-whitespace character
    (foo)|(bar)either 'foo' or 'bar'
    \.html$any string ending in '.html'
    ^\.any string starting with a period

    Note that \ can be used to quote these characters in which case they match themselves, nothing else. Also note that when quoting these something in Pike you need two \ because Pike also uses this character for quoting.

    To make make regexps fast, they are compiled in a similar way that Pike is, they can then be used over and over again without needing to be recompiled. To give the user full control over the compilations and use of regexp an object oriented interface is provided.

    You might wonder what regexps are good for, hopefully it should be more clear when you read about the following functions:


    NAME
    Regexp.create - compile regexp

    SYNTAX
    void create();
    or
    void create(string regexp);
    or
    object(Regexp) Regexp();
    or
    object(Regexp) Regexp(string regexp);

    DESCRIPTION
    When create is called, the current regexp bound to this object is cleared. If a string is sent to create(), this string will be compiled to an internal representation of the regexp and bound to this object for later calls to match or split. Calling create() without an argument can be used to free up a little memory after the regexp has been used.

    SEE ALSO
    clone and Regexp->match


    NAME
    Regexp.match - match a regexp

    SYNTAX
    int match(string s)

    DESCRIPTION
    Return 1 if s matches the regexp bound to the object regexp, zero otherwise.

    SEE ALSO
    Regexp->create and Regexp->split


    NAME
    Regexp.split - split a string according to a pattern

    SYNTAX
    array(string) split(string s)

    DESCRIPTION
    Works as regexp->match, but returns an array of the strings that matched the sub-regexps. Sub-regexps are those contained in ( ) in the regexp. Sub-regexps that were not matched will contain zero. If the total regexp didn't match, zero is returned.

    BUGS
    You can only have 40 sub-regexps.

    SEE ALSO
    Regexp->create and Regexp->match


    13.4 Gmp

    Gmp is short for GNU Multi-Precision library. It is a set of routines that can manipulate very large numbers. Although much slower than regular integers they are very useful when you need to handle extremely large numbers. Billions and billions as Mr Attenborough would have said..

    The Gmp library can handle large integers, floats and rational numbers, but currently Pike only has support for large integers. The others will be added later or when demand arises. Large integers are implemented as objects cloned from Gmp.Mpz.

    NAME
    Gmp.mpz - bignum program

    DESCRIPTION
    Gmp.mpz is a builtin program written in C. It implements large, very large integers. In fact, the only limitation on these integers is the available memory.

    The mpz object implements all the normal integer operations. (except xor) There are also some extra operators:

    NOTA BENE
    This module is only available if libgmp.a was available and found when Pike was compiled.

    NAME
    Gmp.mpz->create - initialize a bignum

    SYNTAX
    object Mpz();
    or
    object Mpz(int|object|float i);
    or
    object Mpz(string digits, int base);

    DESCRIPTION
    When cloning an mpz it is by default initialized to zero. However, you can give a second argument to clone to initialize the new object to that value. The argument can be an int, float another mpz object, or a string containing an ascii number. You can also give the number in the string in another base by specifying the base as a second argument. Valid bases are 2-36 and 256.

    SEE ALSO
    clone


    NAME
    Gmp.mpz->powm - raise and modulo

    SYNTAX
    object powm(int|string|float|object a,int|string|float|object b);

    DESCRIPTION
    This function returns ( mpz ** a ) % b. For example, Mpz(2)->powm(10,42); would return 16 since 2 to the power of 10 is 1024 and 1024 modulo 42 is 16.

    NAME
    Gmp.mpz->sqrt - square root

    SYNTAX
    object sqrt();

    DESCRIPTION
    This function returns the truncated integer part of the square root of the value of mpz.

    NAME
    Gmp.mpz->probably_prime_p - is this number a prime?

    SYNTAX
    int probably_prime_p();

    DESCRIPTION
    This function returns 1 if mpz is a prime, and 0 most of the time if it is not.

    NAME
    Gmp.mpz->gcd - greatest common divisor

    SYNTAX
    object gcd(object|int|float|string arg)

    DESCRIPTION
    This function returns the greatest common divisor for arg and mpz.

    NAME
    Gmp.mpz->cast - cast to other type

    SYNTAX
    object cast( "string" | "int" | "float" );
    or
    (string) mpz
    or
    (int) mpz
    or
    (float) mpz

    DESCRIPTION
    This function converts an mpz to a string, int or float. This is necessary when you want to view, store or use the result of an mpz calculation.

    SEE ALSO
    cast


    NAME
    Gmp.mpz->digits - convert mpz to a string

    SYNTAX
    string digits();
    or
    string digits(int|void base);

    DESCRIPTION
    This function converts an mpz to a string. If a base is given the number will be represented in that base. Valid bases are 2-36 and 256. The default base is 10.

    SEE ALSO
    Gmp.mpz->cast


    NAME
    Gmp.mpz->size - how long is a number

    SYNTAX
    string size();
    or
    string size(int|void base);

    DESCRIPTION
    This function returns how long the mpz would be represented in the specified base. The default base is 2.

    SEE ALSO
    Gmp.mpz->digits


    13.5 Gdbm

    Gdbm is short for GNU Data Base Manager. It provides a simple data base similar to a file system. The functionality is similar to a mapping, but the data is located on disk, not in memory. Each gdbm database is one file which contains a key-pair values, both keys and values have to be strings. All keys are always unique, just as with a mapping.

    This is the an interface to the gdbm library. This module might or might not be available in your Pike depending on whether the gdbm library was available on your system when Pike was compiled.


    NAME
    Gdbm.create - open database

    SYNTAX
    int create();
    or
    int create(string file);
    or
    int create(string file, string mode);
    or
    object(Gdbm) Gdbm(); or
    object(Gdbm) Gdbm(string file); or
    object(Gdbm) Gdbm(string file, string mode);

    DESCRIPTION
    Without arguments, this function does nothing. With one argument it opens the given file as a gdbm database, if this fails for some reason, an error will be generated. If a second argument is present, it specifies how to open the database using one or more of the follow flags in a string:

    r open database for reading
    w open database for writing
    c create database if it does not exist
    t overwrite existing database
    f fast mode

    The fast mode prevents the database from synchronizing each change in the database immediately. This is dangerous because the database can be left in an unusable state if Pike is terminated abnormally.

    The default mode is "rwc".


    NAME
    Gdbm.close - close database

    SYNTAX
    void close();

    DESCRIPTION
    This closes the database.


    NAME
    Gdbm.store - store a value in the database

    SYNTAX
    int Gdbm.store(string key, string data);

    DESCRIPTION
    Associate the contents of data with the key key. If the key key already exists in the database the data for that key will be replaced. If it does not exist it will be added. An error will be generated if the database was not open for writing.


    NAME
    Gdbm.fetch - fetch a value from the database

    SYNTAX
    string fetch(string key);

    DESCRIPTION
    Returns the data associated with the key key in the database. If there was no such key in the database, zero is returned.


    NAME
    Gdbm.delete - delete a value from the database

    SYNTAX
    int delete(string key);

    DESCRIPTION
    Remove a key from the database. Note that no error will be generated if the key does not exist.


    NAME
    Gdbm.firstkey - get first key in database

    SYNTAX
    string firstkey();

    DESCRIPTION
    Returns the first key in the database, this can be any key in the database.


    NAME
    nextkey - get next key in database

    SYNTAX
    string nextkey(string key);

    DESCRIPTION
    This returns the key in database that follows the key key. This is of course used to iterate over all keys in the database.

    EXAMPLE
    /* Write the contents of the database */
    for(key=gdbm->firstkey(); k; k=gdbm->nextkey(k))
    write(k+":"+gdbm->fetch(k)+"\n");


    NAME
    Gdbm.reorganize - reorganize database

    SYNTAX
    int reorganize();

    DESCRIPTION
    Deletions and insertions into the database can cause fragmentation which will make the database bigger. This routine reorganizes the contents to get rid of fragmentation. Note however that this function can take a LOT of time to run.


    NAME
    sync - synchronize database

    SYNTAX
    void sync();

    DESCRIPTION
    When opening the database with the 'f' flag writings to the database can be cached in memory for a long time. Calling sync will write all such caches to disk and not return until everything is stored on the disk.


    13.6 Getopt

    Getopt is a group of function which can be used to find command line options. Command line options come in two flavors: long and short. The short ones consists of a dash followed by a character (-t), the long ones consist of two dashes followed by a string of text (--test). The short options can also be combined, which means that you can write -tda instead of -t -d -a. Options can also require arguments, in which case they cannot be combined. To write an option with an argument you write -t argument or -targument or --test=argument.
    NAME
    Getopt.find_option - find command line options

    SYNTAX

    mixed find_option(array(string) argv,

    string shortform,
    void|string longform,
    void|string envvar,
    void|mixed def,
    void|int throw_errors);

    DESCRIPTION
    This is a generic function to parse command line options of the type '-f', '--foo' or '--foo=bar'. The first argument should be the array of strings that is sent as second argument to your main() function, the second is a string with the short form of your option. The short form must be only one character long. The 'longform' is an alternative and maybe more readable way to give the same option. If you give "foo" as longform your program will accept --foo as argument. The envvar argument specifies what environment variable can be used to specify the same option. The envvar option exists to make it easier to customize program usage. The 'def' has two functions: It specifies that the option takes an argument and it tells find_option what to return if the option is not present. If 'def' is given and the option does not have an argument find_option will print an error message and exit the program.

    Also, as an extra bonus: shortform, longform and envvar can all be arrays, in which case either of the options in the array will be accpted.

    NOTA BENE
    find_option modifies argv.
    This function reads options even if they are written after the first non-option on the line.

    EXAMPLE
    This program tests two different options. One is called -f or -foo and the other is called -b or --bar and can also be given by using the BAR_OPTION environment variable.
    int main(int argc, array(string) argv)

    SEE ALSO
    Getopt.get_args


    NAME
    Getopt.find_all_options - find command line options

    SYNTAX

    array find_all_options(array(string) argv, array option, int|void posix_me_harder, int|void throw_errors);

    DESCRIPTION
    This function does the job of several calls to find_option. The main advantage of this is that it allows it to handle the POSIX_ME_HARDER environment variable better. When the either the argument posix_me_harder or the environment variable POSIX_ME_HARDER is true, no arguments will be parsed after the first non-option on the command line.

    Each element in the array options should be an array on the following form:

    ({
    string name,
    int type,
    string|array(string) aliases,
    void|string|array(string) env_var,
    void|mixed default
    })
    Only the first three elements has to be included.
    name
    Name is a tag used to identify the option in the output.
    type
    Type is one of Getopt.HAS_ARG, Getopt.NO_ARG and Getopt.MAY_HAVE_ARG and it affects how the error handling and parsing works. You should use HAS_ARG for options that require a path, a number or similar. NO_ARG should be used for options that do not need an argument, such as --version. MAY_HAVE_ARG should be used for options that may or may not need an argument.
    aliases
    This is a string or an array of string of options that will be looked for. Short and long options can be mixed, and short options can be combined into one string. Note that you must include the dashes in aliases so find_all_options can distinguish between long and short options. Example: ({"-tT","--test"}) This would make find_all_options look for -t, -T and --test.
    env_var
    This is a string or an array of strings containing names of environment variables that can be used instead of the command line option.
    default
    This is the default value the option will have in the output from this function. Options without defaults will be omitted from the output if they are not found in argv.
    The good news is that the output from this function is a lot simpler. Find_all_options returns an array where each element is an array on this form:
    ({
    string name,
    mixed value
    })
    The name is the identifier from the input and value is the value given to it from the argument, environment variable or default. If no default is given, value will be 1.

    NOTA BENE
    find_all_options modifies argv.

    EXAMPLE
    First let's take a look at input and output:
    > Getopt.find_all_options(({"test","-dd"}),
    >>  ({ ({ "debug", Getopt.NO_ARG, ({"-d","--debug"}), "DEBUG", 1}) }));
    Result: ({
      ({ "debug",  1 }),
      ({ "debug",  1 })
    })
    

    This is what it would look like in real code:

    import Getopt;

    int debug=0;

    int main(int argc, array(string) argv
    {
        foreach(find_all_options(argv, ({
            ({ "debug", MAY_HAVE_ARG, ({"-d","--debug"}), "DEBUG", 1}),
            ({ "version", NO_ARG, ({"-v","--version" }) }) })),
            mixed option)
        {
            switch(option[0])
            {
                case "debug": debug+=option[1]; break;
                case "version":
                    write("Test program version 1.0\n");
                    exit(1);
            }
        }

        argv=Getopt.get_args(argv);
    }

    SEE ALSO
    Getopt.get_args


    NAME
    Getopt.get_args - get the non-option arguments

    SYNTAX
    array(string) get_args(array(string) argv,void|int throw_errors);

    DESCRIPTION
    This function returns the remaining command line arguments after you have run find_options to find all the options in the argument list. If there are any options left not handled by find_options an error message will be written and the program will exit. Otherwise a new 'argv' array without the parsed options is returned.

    EXAMPLE
    int main(int argc, array(string) argv)
    {
    if(find_option(argv,"f","foo"))
    werror("The FOO option was given.\n");

    argv=get_args(argv);
    werror("The arguments are: "+(argv*" ")+".\n");
    }

    SEE ALSO
    Getopt.find_option


    13.7 Gz

    The Gz module contains functions to compress and uncompress strings using the same algorithm as the program gzip. Packing can be done in streaming mode or all at once. Note that this module is only available if the gzip library was available when Pike was compiled. The Gz module consists of two classes; Gz.deflate and Gz.inflate. Gz.deflate is used to pack data and Gz.inflate is used to unpack data. (Think "inflatable boat") Note that these functions use the same algorithm as gzip, they do not use the exact same format however, so you cannot directly unzip gzipped files with these routines. Support for this will be added in the future.

    NAME
    Gz.deflate - string packer

    DESCRIPTION
    Gz.inflate is a builtin program written in C. It interfaces the packing routines in the libz library.

    NOTA BENE
    This program is only available if libz was available and found when Pike was compiled.

    SEE ALSO
    Gz.inflate


    NAME
    Gz.deflate->create - initialize packer

    SYNTAX
    void create(int X)
    or
    object(Gz.deflate) Gz.deflate(int X)

    DESCRIPTION
    This function is called when a new Gz.deflate is created. If given, X should be a number from 0 to 9 indicating the packing / CPU ratio. Zero means no packing, 2-3 is considered 'fast', 6 is default and higher is considered 'slow' but gives better packing.

    This function can also be used to re-initialize a Gz.deflate object so it can be re-used.


    NAME
    Gz.deflate->deflate - pack data

    SYNTAX
    string deflate(string data, int flush);

    DESCRIPTION
    This function performs gzip style compression on a string and returns the packed data. Streaming can be done by calling this function several times and concatenating the returned data. The optional 'flush' argument should be one f the following:

    Gz.NO_FLUSH Only data that doesn't fit in the internal buffers is returned.
    Gz.PARTIAL_FLUSH All input is packed and returned.
    Gz.SYNC_FLUSH All input is packed and returned.
    Gz.FINISH All input is packed and an 'end of data' marker is appended.

    Using flushing will degrade packing. Normally NO_FLUSH should be used until the end of the data when FINISH should be used. For interactive data PARTIAL_FLUSH should be used.

    SEE ALSO
    Gz.inflate->inflate


    NAME
    Gz.inflate - string unpacker

    DESCRIPTION
    Gz.inflate is a builtin program written in C. It interfaces the packing routines in the libz library.

    NOTA BENE
    This program is only available if libz was available and found when Pike was compiled.

    SEE ALSO
    Gz.deflate


    NAME
    Gz.inflate->create - initialize unpacker

    SYNTAX
    void create()
    or
    object(Gz.inflate) Gz.inflate()

    DESCRIPTION
    This function is called when a new Gz.inflate is created. It can also be called after the object has been used to re-initialize it.


    NAME
    Gz.inflate->inflate - unpack data

    SYNTAX
    string inflate(string data);

    DESCRIPTION
    This function performs gzip style decompression. It can inflate a whole file at once or in blocks.

    EXAMPLES
    import Stdio;
    // whole file
    write(Gz.inflate()->inflate(stdin->read());

    // streaming (blocks)
    function inflate=Gz.inflate()->inflate;
    while(string s=stdin->read(8192))

    write(inflate(s));

    SEE ALSO
    Gz.deflate->deflate


    13.8 Yp

    This module is an interface to the Yellow Pages functions. Yp is also known as NIS (Network Information System) and is most commonly used to distribute passwords and similar information within a network.
    NAME
    Yp.default_yp_domain - get the default Yp domain

    SYNTAX
    string default_yp_domain()

    DESCRIPTION
    Returns the default yp-domain.


    NAME
    Yp.YpDomain - class representing an Yp domain

    SYNTAX
    object(Yp.YpDomain) Yp.YpDomain(string|void domain);

    DESCRIPTION
    This creates a new YpDomain object.

    If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable from the C interface to Yp either.

    If no domain is given, the default domain will be used. (As returned by Yp.default_yp_domain)


    NAME
    Yp.YpDomain->bind - bind this object to another domain

    SYNTAX
    void bind(string|void domain)

    DESCRIPTION
    Re-bind the object to another (or the same) domain. If no domain is given, the default domain will be used.


    NAME
    Yp.Ypdomain->match - match a key in a map

    SYNTAX
    string match(string map, string key)

    DESCRIPTION
    If 'map' does not exist, an error will be generated. Otherwise the string matching the key will be returned. If there is no such key in the map, 0 will be returned.

    arguments is the map Yp-map to search in. This must be a full map name, for example, you should use passwd.byname instead of just passwd. key is the key to search for. The key must match exactly, no pattern matching of any kind is done.

    EXAMPLE
    object dom = Yp.YpDomain();
    write(dom->match("passwd.byname", "root"));

    NAME
    Yp.YpDomain->all - return the whole map

    SYNTAX
    mapping(string:string) all(string map)

    DESCRIPTION
    Returns the whole map as a mapping. map is the YP-map to search in. This must be the full map name, you have to use passwd.byname instead of just passwd.


    NAME
    Yp.YpDomain->map - call a function for each entry in an Yp map

    SYNTAX
    void map(string map, function(string,string:void) over)

    DESCRIPTION
    For each entry in 'map', call the function(s) specified by 'over'. Over will get two arguments, the first being the key, and the second the value. map is the YP-map to search in. This must be the full map name, as an example, passwd.byname instead of just passwd.


    NAME
    Yp.YpDomain->server - find an Yp server

    SYNTAX
    string server(string map)

    DESCRIPTION
    Returns the hostname of the server serving the map map. map is the YP-map to search in. This must be the full map name, as an example, passwd.byname instead of just passwd.


    NAME
    Yp.YpDomain->order - get the 'order' for specified map

    SYNTAX
    int order(string map)

    DESCRIPTION
    Returns the 'order' number for the map map. This is usually a time_t (see the global function time()). When the map is changed, this number will change as well. map is the YP-map to search in. This must be the full map name, as an example, passwd.byname instead of just passwd.

    NAME
    Yp.YpMap - class representing one Yp map

    SYNTAX
    object(Yp.YpMap) Yp.Ypmap(string map, string|void domain)
    DESCRIPTION
    This creates a new YpMap object.

    If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable from the C-yp interface either. map is the YP-map to bind to. This must be the full map name, as an example, passwd.byname instead of just passwd. If no domain is specified, the default domain will be used. This is usually best.


    NAME
    Yp.YpMap->match - find key in map

    SYNTAX
    string match(string key)
    or
    string Yp.YpMap[string key]

    DESCRIPTION
    Search for the key key. If there is no key in the map, 0 will be returned, otherwise the string matching the key will be returned. key must match exactly, no pattern matching of any kind is done.

    NAME
    Yp.YpMap->all - return the whole map as a mapping

    SYNTAX
    mapping(string:string) all();
    or
    (mapping) Yp.YpMap

    DESCRIPTION
    Returns the whole map as a mapping.

    NAME
    Yp.YpMap->map - call a function for each entry in the map

    SYNTAX
    void map(function(string,string:void) over)

    DESCRIPTION
    For each entry in the map, call the function(s) specified by 'over'. The function will be called like 'void over(string key, string value)'

    NAME
    Yp.YpMap->server - find what server servers this map

    SYNTAX
    string server()

    DESCRIPTION
    Returns the hostname of the server serving this map.

    NAME
    Yp.YpMap->order() - find the 'order' of this map

    SYNTAX
    int order()

    DESCRIPTION
    Returns the 'order' number for this map. This is usually a time_t (see the global function time())

    NAME
    Yp.YpMap._sizeof - return the number of entries in the map

    SYNTAX
    int sizeof(Yp.YpMap)

    DESCRIPTION
    Returns the number of entries in the map. This is equivalent to sizeof((mapping)map);

    NAME
    Yp.YpMap._indices - return the indices from the map
    Yp.YpMap._values - return the values from the map

    SYNTAX
    array(string) indices(Yp.YpMap)
    array(string) values(Yp.Ypmap)

    DESCRIPTION
    Returns the indices of the map. If indices is called first, values must be called immediately after. If values is called first, it is the other way around.


    Here is an example program using the Yp module, it lists users and their GECOS field from the Yp map "passwd.byname" if your system uses Yp.
    import Yp;

    void print_entry(string key, string val)
    {
        val = (val/":")[4];
        if(strlen(val))
        {
            string q = ".......... ";
            werror(key+q[strlen(key)..]+val+"\n");
        }
    }
        
    void main(int argc, array(string) argv)
    {
        object (YpMap) o = YpMap("passwd.byname");

        werror("server.... "+ o->server() + "\n"
         "age....... "+ (-o->order()+time()) + "\n"
         "per....... "+ o["per"] + "\n"
         "size...... "+ sizeof(o) + "\n");
        
        o->map(print_entry); // Print username/GECOS pairs
    }

    13.9 MIME

    RFC1521, the Multipurpose Internet Mail Extensions memo, defines a structure is the base for all messages read and written by modern mail and news programs. It is also partly the base for the HTTP protocol. Just like RFC822, MIME declares that a message should consist of two entities, the headers and the body. In addition, the following properties are given to these two entities:
    Headers
    Body
    The MIME module can extract and analyze these two entities from a stream of bytes. It can also recreate such a stream from these entities. To encapsulate the headers and body entities, the class MIME.Message is used. An object of this class holds all the headers as a mapping from string to string, and it is possible to obtain the body data in either raw or encoded form as a string. Common attributes such as message type and text char set are also extracted into separate variables for easy access.

    The Message class does not make any interpretation of the body data, unless the content type is multipart. A multipart message contains several individual messages separated by boundary strings. The create method of the Message class will divide a multipart body on these boundaries, and then create individual Message objects for each part. These objects will be collected in the array body_parts within the original Message object. If any of the new Message objects have a body of type multipart, the process is of course repeated recursively. The following figure illustrates a multipart message containing three parts, one of which contains plain text, one containing a graphical image, and the third containing raw uninterpreted data:


    13.9.1 Global functions

    NAME
    MIME.decode - Remove transfer encoding

    SYNTAX
    string decode(string data, string encoding);

    DESCRIPTION
    Extract raw data from an encoded string suitable for transport between systems. The encoding can be any of
    • 7bit
    • 8bit
    • base64
    • binary
    • quoted-printable
    • x-uue
    • x-uuencode
    The encoding string is not case sensitive.

    SEE ALSO
    MIME.encode


    NAME
    MIME.decode_base64 - Decode base64 transfer encoding

    SYNTAX
    string decode_base64(string encoded_data);

    DESCRIPTION
    This function decodes data encoded using the base64 transfer encoding.

    SEE ALSO
    MIME.encode_base64


    NAME
    MIME.decode_qp - Decode quoted-printable transfer encoding

    SYNTAX
    string decode_qp(string encoded_data);

    DESCRIPTION
    This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.

    SEE ALSO
    MIME.encode_qp


    NAME
    MIME.decode_uue - Decode x-uue transfer encoding

    SYNTAX
    string decode_uue(string encoded_data);

    DESCRIPTION
    This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.

    SEE ALSO
    MIME.encode_uue


    NAME
    MIME.decode_word - De-scramble RFC1522 encoding

    SYNTAX
    array(string) decode_word(string word);

    DESCRIPTION
    Extracts the textual content and character set from an encoded word as specified by RFC1522. The result is an array where the first element is the raw text, and the second element the name of the character set. If the input string is not an encoded word, the result is still an array, but the char set element will be set to 0. Note that this function can only be applied to individual encoded words.

    EXAMPLES
    > Array.map("=?iso-8859-1?b?S2lscm95?= was =?us-ascii?q?h=65re?="/" ",
                MIME.decode_word);
    Result: ({ /* 3 elements */
        ({ /* 2 elements */
            "Kilroy",
            "iso-8859-1"
        }),
        ({ /* 2 elements */
            "was",
            0
        }),
        ({ /* 2 elements */
            "here",
            "us-ascii"
        })
    })
    

    SEE ALSO
    MIME.encode_word


    NAME
    MIME.encode - Apply transfer encoding

    SYNTAX
    string encode(string data, string encoding, void|string filename,
                  void|int no_linebreaks);

    DESCRIPTION
    Encode raw data into something suitable for transport to other systems. The encoding can be any of
    • 7bit
    • 8bit
    • base64
    • binary
    • quoted-printable
    • x-uue
    • x-uuencode
    The encoding string is not case sensitive. For the x-uue encoding, an optional filename string may be supplied. If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks (base64 and quoted-printable only).

    SEE ALSO
    MIME.decode


    NAME
    MIME.encode_base64 - Encode string using base64 transfer encoding

    SYNTAX
    string encode_base64(string data, void|int no_linebreaks);

    DESCRIPTION
    This function encodes data using the base64 transfer encoding. If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks.

    SEE ALSO
    MIME.decode_base64


    NAME
    MIME.encode_qp - Encode string using quoted-printable transfer encoding

    SYNTAX
    string encode_qp(string data, void|int no_linebreaks);

    DESCRIPTION
    This function encodes data using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding. If a nonzero value is passed as no_linebreaks, the result string will not contain any linebreaks. Please do not use this function. QP is evil, and there's no excuse for using it.

    SEE ALSO
    MIME.decode_qp


    NAME
    MIME.encode_uue - Encode string using x-uue transfer encoding

    SYNTAX
    string encode_uue(string encoded_data, void|string filename);

    DESCRIPTION
    This function encodes data using the x-uue transfer encoding. The optional argument filename specifies an advisory filename to include in the encoded data, for extraction purposes. This function can also be used to produce generic UUEncoded files.

    SEE ALSO
    MIME.decode_uue


    NAME
    MIME.encode_word - Encode word according to RFC1522

    SYNTAX
    string encode_word(array(string) word, string encoding);

    DESCRIPTION
    Create an encoded word as specified in RFC1522 from an array containing a raw text string and a char set name. The text will be transfer encoded according to the encoding argument, which can be either "base64" or "quoted-printable" (or either "b" or "q" for short). If either the second element of the array (the char set name), or the encoding argument is 0, the raw text is returned as is.

    EXAMPLES
    > MIME.encode_word( ({ "Quetzalcoatl", "iso-8859-1" }), "base64" );
    Result: =?iso-8859-1?b?UXVldHphbGNvYXRs?=
    > MIME.encode_word( ({ "Foo", 0 }), "base64" );
    Result: Foo
    

    SEE ALSO
    MIME.decode_word


    NAME
    MIME.generate_boundary - Create a suitable boundary string for multiparts

    SYNTAX
    string generate_boundary();

    DESCRIPTION
    This function will create a string that can be used as a separator string for multipart messages. The generated string is guaranteed not to appear in base64, quoted-printable, or x-uue encoded data. It is also unlikely to appear in normal text. This function is used by the cast method of the Message class if no boundary string is specified.


    NAME
    MIME.guess_subtype - Provide a reasonable default for the subtype field

    SYNTAX
    string guess_subtype(string type);

    DESCRIPTION
    Some pre-RFC1521 mailers provide only a type and no subtype in the Content-Type header field. This function can be used to obtain a reasonable default subtype given the type of a message. (This is done automatically by the MIME.Message class.) Currently, the function uses the following guesses:
    typesubtype
    textplain
    messagerfc822
    multipartmixed


    NAME
    MIME.parse_headers - Separate a bytestream into headers and body

    SYNTAX
    array(mapping(string:string)|string) parse_headers(string message);

    DESCRIPTION
    This is a low level function that will separate the headers from the body of an encoded message. It will also translate the headers into a mapping. It will however not try to analyze the meaning of any particular header, This also means that the body is returned as is, with any transfer-encoding intact. It is possible to call this function with just the header part of a message, in which case an empty body will be returned.

    The result is returned in the form of an array containing two elements. The first element is a mapping containing the headers found. The second element is a string containing the body.


    NAME
    MIME.quote - Create an RFC822 header field from lexical elements

    SYNTAX
    string quote(array(string|int) lexical_elements);

    DESCRIPTION
    This function is the inverse of the tokenize function. A header field value is constructed from a sequence of lexical elements. Characters (ints) are taken to be special-characters, whereas strings are encoded as atoms or quoted-strings, depending on whether they contain any special characters.

    EXAMPLES
    > MIME.quote( ({ "attachment", ';', "filename", '=', "/usr/dict/words" }) );
    Result: attachment;filename="/usr/dict/words"
    

    NOTA BENE
    There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.

    SEE ALSO
    MIME.tokenize


    NAME
    MIME.reconstruct_partial - Join a fragmented message to its original form

    SYNTAX
    int|object reconstruct_partial(array(object) collection);

    DESCRIPTION
    This function will attempt to reassemble a fragmented message from its parts. The array collection should contain MIME.Message objects forming a complete set of parts for a single fragmented message. The order of the messages in this array is not important, but every part must exist at least once.

    Should the function succeed in reconstructing the original message, a new MIME.Message object is returned. Note that this message may in turn be a part of another, larger, fragmented message. If the function fails to reconstruct an original message, it returns an integer indicating the reason for its failure:

    • If an empty collection is passed in, or one that contains messages which are not of type message/partial, or parts of different fragmented messages, the function returns 0.
    • If more fragments are needed to reconstruct the entire message, the number of additional messages needed is returned.
    • If more fragments are needed, but the function can't tell exactly how many, -1 is returned.

    SEE ALSO
    MIME.Message->is_partial


    NAME
    MIME.tokenize - Separate an RFC822 header field into lexical elements

    SYNTAX
    array(string|int) tokenize(string header);

    DESCRIPTION
    A structured header field, as specified by RFC822, is constructed from a sequence of lexical elements. These are:
    • individual special characters
    • quoted-strings
    • domain-literals
    • comments
    • atoms
    This function will analyze a string containing the header value, and produce an array containing the lexical elements. Individual special characters will be returned as characters (i.e. ints). Quoted-strings, domain-literals and atoms will be decoded and returned as strings. Comments are not returned in the array at all.

    EXAMPLES
    > MIME.tokenize("multipart/mixed; boundary=\"foo/bar\" (Kilroy was here)");
    Result: ({ /* 7 elements */
        "multipart",
        47,
        "mixed",
        59,
        "boundary",
        61,
        "foo/bar"
    })
    

    NOTA BENE
    As domain-literals are returned as strings, there is no way to tell the domain-literal [127.0.0.1] from the quoted-string "[127.0.0.1]". Hopefully this won't cause any problems. Domain-literals are used seldom, if at all, anyway...

    The set of special-characters is the one specified in RFC1521 (i.e. "<", ">", "@", ",", ";", ":", "\", "/", "?", "="), and not the one specified in RFC822.

    SEE ALSO
    MIME.quote


    13.9.2 The MIME.Message class

    This class is used to hold a decoded MIME message.

    13.9.2.1 Public fields


    NAME
    MIME.Message->body_parts - Multipart sub-messages

    SYNTAX
    array(object) msg->body_parts;

    DESCRIPTION
    If the message is of type multipart, this is an array containing one Message object for each part of the message. If the message is not a multipart, this field is 0.

    SEE ALSO
    MIME.Message->type, MIME.Message->boundary


    NAME
    MIME.message->boundary - Boundary string for multipart messages

    SYNTAX
    string msg->boundary;

    DESCRIPTION
    For multipart messages, this Content-Type parameter gives a delimiter string for separating the individual messages. As multiparts are handled internally by the module, you should not need to access this field.

    SEE ALSO
    MIME.Message->setboundary


    NAME
    MIME.Message->charset - Character encoding for text bodies

    SYNTAX
    string msg->charset;

    DESCRIPTION
    One of the possible parameters of the Content-Type header is the charset attribute. It determines the character encoding used in bodies of type text. If there is no Content-Type header, the value of this field is "us-ascii".

    SEE ALSO
    MIME.Message->type


    NAME
    MIME.Message->disposition - Multipart subpart disposition

    SYNTAX
    string msg->disposition;

    DESCRIPTION
    The first part of the Content-Disposition header, hinting on how this part of a multipart message should be presented in an interactive application. If there is no Content-Disposition header, this field is 0.


    NAME
    MIME.Message->disp_params - Content-Disposition parameters

    SYNTAX
    mapping(string:string) msg->disp_params;

    DESCRIPTION
    A mapping containing all the additional parameters to the Content-Disposition header.

    SEE ALSO
    MIME.Message->setdisp_param, MIME.Message->get_filename


    NAME
    MIME.Message->headers - All header fields of the message

    SYNTAX
    mapping(string:string) msg->headers;

    DESCRIPTION
    This mapping contains all the headers of the message. The key is the header name (in lower case) and the value is the header value. Although the mapping contains all headers, some particular headers get special treatment by the module and should not be accessed through this mapping. These fields are currently:
    • content-type
    • content-disposition
    • content-length
    • content-transfer-encoding
    The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.

    SEE ALSO
    MIME.Message->type, MIME.Message->subtype, MIME.Message->charset, MIME.Message->boundary, MIME.Message->transfer_encoding, MIME.Message->params, MIME.Message->disposition, MIME.Message->disp_params, MIME.Message->setencoding, MIME.Message->setparam, MIME.Message->setdisp_param, MIME.Message->setcharset, MIME.Message->setboundary


    NAME
    MIME.Message->params - Content-Type parameters

    SYNTAX
    mapping(string:string) msg->params;

    DESCRIPTION
    A mapping containing all the additional parameters to the Content-Type header. Some of these parameters have fields of their own, which should be accessed instead of this mapping wherever applicable.

    SEE ALSO
    MIME.Message->charset, MIME.Message->boundary, MIME.Message->setparam


    NAME
    MIME.Message->subtype - The subtype attribute of the Content-Type header

    SYNTAX
    string msg->subtype;

    DESCRIPTION
    The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the subtype attribute extracted from the header. If there is no Content-Type header, the value of this field is "plain".

    SEE ALSO
    MIME.Message->type, MIME.Message->params


    NAME
    MIME.Message->transfer_encoding - Body encoding method

    SYNTAX
    string msg->transfer_encoding;

    DESCRIPTION
    The contents of the Content-Transfer-Encoding header. If no Content-Transfer-Encoding header is given, this field is 0. Transfer encoding and decoding is done transparently by the module, so this field should be interesting only to applications wishing to do auto conversion of certain transfer encodings.

    SEE ALSO
    MIME.Message->setencoding


    NAME
    MIME.Message->type - The type attribute of the Content-Type header

    SYNTAX
    string msg->type;

    DESCRIPTION
    The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the type attribute extracted from the header. If there is no Content-Type header, the value of this field is "text".

    SEE ALSO
    MIME.Message->subtype, MIME.Message->params


    13.9.2.2 Public methods


    NAME
    MIME.Message->cast - Encode message into byte stream

    SYNTAX
    string (string )MIME.Message;

    DESCRIPTION
    Casting the message object to a string will yield a byte stream suitable for transmitting the message over protocols such as ESMTP and NNTP. The body will be encoded using the current transfer encoding, and subparts of a multipart will be collected recursively. If the message is a multipart and no boundary string has been set, one is generated using generate_boundary.

    EXAMPLES
    > object msg = MIME.Message( "Hello, world!",
            ([ "MIME-Version" : "1.0",
               "Content-Type":"text/plain",
               "Content-Transfer-Encoding":"base64" ]) );
    Result: object
    > (string )msg;
    Result: Content-Type: text/plain
    Content-Length: 20
    Content-Transfer-Encoding: base64
    MIME-Version: 1.0
     
    SGVsbG8sIHdvcmxkIQ==
    

    SEE ALSO
    MIME.Message->create


    NAME
    MIME.Message->create - Create a Message object

    SYNTAX
    object MIME.Message(void | string message,
                        void | mapping(string:string) headers,
                        void | array(object) parts);

    DESCRIPTION
    There are several ways to call the constructor of the Message class;
    • With zero arguments, you will get a dummy message without either headers or body. Not very useful.
    • With one argument, the argument is taken to be a byte stream containing a message in encoded form. The constructor will analyze the string and extract headers and body.
    • With two or three arguments, the first argument is taken to be the raw body data, and the second argument a desired set of headers. The keys of this mapping are not case-sensitive. If the given headers indicate that the message should be of type multipart, an array of Message objects constituting the subparts should be given as a third argument.

    EXAMPLES
    > object msg = MIME.Message( "Hello, world!",
            ([ "MIME-Version" : "1.0",
               "Content-Type" : "text/plain; charset=iso-8859-1" ]) );
    Result: object
    > msg->charset;
    Result: iso-8859-1
    

    SEE ALSO
    MIME.Message->cast


    NAME
    MIME.Message->getdata - Obtain raw body data

    SYNTAX
    string getdata();

    DESCRIPTION
    This method returns the raw data of the message body entity. The type and subtype attributes indicate how this data should be interpreted.

    SEE ALSO
    MIME.Message->getencoded


    NAME
    MIME.Message->getencoded - Obtain encoded body data

    SYNTAX
    string getencoded();

    DESCRIPTION
    This method returns the data of the message body entity, encoded using the current transfer encoding. You should never have to call this function.

    SEE ALSO
    MIME.Message->getdata


    NAME
    MIME.Message->get_filename - Get supplied filename for body data

    SYNTAX
    string get_filename();

    DESCRIPTION
    This method tries to find a suitable filename should you want to save the body data to disk. It will examine the filename attribute of the Content-Disposition header, and failing that the name attribute of the Content-Type header. If neither attribute is set, the method returns 0.

    NOTA BENE
    An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.


    NAME
    MIME.Message->is_partial - Identify message/partial message

    SYNTAX
    array(string|int) is_partial();

    DESCRIPTION
    If this message is a part of a fragmented message (i.e. has a Content-Type of message/partial), an array with three elements is returned. The first element is an identifier string. This string should be used to group this message with the other fragments of the message (which will have the same id string). The second element is the sequence number of this fragment. The first part will have number 1, the next number 2 etc. The third element of the array is either the total number of fragments that the original message has been split into, or 0 of this information was not available. If this method is called in a message that is not a part of a fragmented message, it will return 0.

    SEE ALSO
    MIME.reconstruct_partial


    NAME
    MIME.Message->setboundary - Set boundary parameter

    SYNTAX
    void setboundary(string boundary);

    DESCRIPTION
    Sets the boundary parameter of the Content-Type header. This is equivalent of calling msg->setparam("boundary", boundary).

    SEE ALSO
    MIME.Message->setparam


    NAME
    MIME.Message->setcharset - Set charset parameter

    SYNTAX
    void setcharset(string charset);

    DESCRIPTION
    Sets the charset parameter of the Content-Type header. This is equivalent of calling msg->setparam("charset", charset).

    SEE ALSO
    MIME.Message->setparam


    NAME
    MIME.Message->setdata - Replace body data

    SYNTAX
    void setdata(string data);

    DESCRIPTION
    Replaces the body entity of the data with a new piece of raw data. The new data should comply to the format indicated by the type and subtype attributes. Do not use this method unless you know what you are doing.

    SEE ALSO
    MIME.Message->getdata


    NAME
    MIME.Message->setdisp_param - Set Content-Disposition parameters

    SYNTAX
    void setdisp_param(string param, string value);

    DESCRIPTION
    Set or modify the named parameter of the Content-Disposition header. A common parameters is e.g. filename. It is not allowed to modify the Content-Disposition header directly, please use this function instead.

    SEE ALSO
    MIME.Message->setparam, MIME.Message->get_filename


    NAME
    MIME.Message->setencoding - Set transfer encoding for message body

    SYNTAX
    void setencoding(string encoding);

    DESCRIPTION
    Select a new transfer encoding for this message. The Content-Transfer-Encoding header will be modified accordingly, and subsequent calls to getencoded will produce data encoded using the new encoding. See encode for a list of valid encodings.

    SEE ALSO
    MIME.Message->getencoded


    NAME
    MIME.Message->setparam - Set Content-Type parameters

    SYNTAX
    void setparam(string param, string value);

    DESCRIPTION
    Set or modify the named parameter of the Content-Type header. Common parameters include charset for text messages, and boundary for multipart messages. It is not allowed to modify the Content-Type header directly, please use this function instead.

    SEE ALSO
    MIME.Message->setcharset, MIME.Message->setboundary, MIME.Message->setdisp_param


    13.10 Simulate

    This module is used to achieve better compatibility with older versions of Pike. It can also be used for convenience, but I would advice against it since some functions defined here are much slower than using similar functions in other modules. The purpose of this section in the manual is to make it easier for the reader to understand code that uses the Simulate module, not to encourage the use of the Simulate module.

    Simulate inherits the Array, Stdio, String and Process modules, so importing he Simulate module also imports all identifiers from these modules. In addition, these functions are available:


    NAME
    Simulate.member_array - find first occurrence of a value in an array

    SYNTAX
    int member_array(mixed item, mixed *arr);

    DESCRIPTION
    Returns the index of the first occurrence of item in array arr. If not found, then -1 is returned. This is the same as search(arr, item).


    NAME
    Simulate.previous_object - return the calling object

    SYNTAX
    object previous_object();

    DESCRIPTION
    Returns an object pointer to the object that called current function, if any.

    SEE ALSO
    backtrace


    NAME
    Simulate.this_function - return a function pointer to the current function

    SYNTAX
    function this_function();

    DESCRIPTION
    Returns a function pointer to the current function, useful for making recursive lambda-functions.

    SEE ALSO
    backtrace


    NAME
    Simulate.get_function - fetch a function from an object

    SYNTAX
    function get_function(object o, string name);

    DESCRIPTION
    Defined as: return o[name];


    NAME
    Simulate.map_regexp - filter an array through a regexp

    SYNTAX
    array(string) regexp(array(string) arr, string reg);

    DESCRIPTION
    Returns those strings in arr that matches the regexp in reg.

    SEE ALSO
    Regexp


    NAME
    Simulate.PI - pi

    SYNTAX
    PI

    DESCRIPTION
    This is not a function, it is a constant roughly equal to the mathematical constant Pi.


    NAME
    all_efuns - return all 'efuns'

    SYNTAX
    mapping all_efuns();

    DESCRIPTION
    This function is the same as all_constants.

    SEE ALSO
    all_constants


    NAME
    Simulate.explode - explode a string on a delimeter

    SYNTAX
    string explode(string s, string delimiter);

    DESCRIPTION
    This function is really the same as the division operator. It simly divides the string s into an array by splitting s at every occurance of delimeter.

    SEE ALSO
    Simulate.implode


    NAME
    Simulate.filter_array - filter an array through a function

    SYNTAX

    mixed *filter_array(mixed *arr,function fun,mixed ... args);
    or
    mixed *filter_array(object *arr,string fun,mixed ... args);
    or
    mixed *filter_array(function *arr,-1,mixed ... args);

    DESCRIPTION
    Filter array is the same function as Array.filter.

    SEE ALSO
    Array.filter


    NAME
    Simulate.implode - implode an array of strings

    SYNTAX
    string implode(array(string) a, string delimiter);

    DESCRIPTION
    This function is the inverse of explode. It concatenates all the strings in a with a delimiter in between each.

    This function is the same as multiplication.

    EXAMPLES
    > implode( ({ "foo","bar","gazonk"}), "-" );
    Result: foo-bar-gazonk
    > ({ "a","b","c" })*" and ";
    Result: a and b and c
    >

    SEE ALSO
    Simulate.explode


    NAME
    Simulate.m_indices - return all indices from a mapping

    SYNTAX
    mixed *m_indices(mapping m);

    DESCRIPTION
    This function is equal to indices.

    SEE ALSO
    indices


    NAME
    Simulate.m_sizeof - return the size of a mapping

    SYNTAX
    int m_sizeof(mapping m);

    DESCRIPTION
    This function is equal to sizeof.

    SEE ALSO
    sizeof


    NAME
    Simulate.m_values - return all values from a mapping

    SYNTAX
    mixed *m_values(mapping m);

    DESCRIPTION
    This function is equal to values.

    SEE ALSO
    values


    NAME
    Simulate.map_array - map an array over a function

    SYNTAX
    mixed *map_array(mixed *arr,function fun,mixed ... args);
    or
    mixed *map_array(object *arr,string fun,mixed ... args);
    or
    mixed *map_array(function *arr,-1,mixed ... arg);

    DESCRIPTION
    This function is the same as Array.map.

    SEE ALSO
    Array.map


    NAME
    Simulate.strstr - find a string inside a string

    SYNTAX
    int strstr(string str1,string str2);

    DESCRIPTION
    Returns the position of str2 in str1, if str2 can't be found in str1 -1 is returned.

    SEE ALSO
    sscanf, Simulate.explode, search


    NAME
    Simulate.sum - add values together

    SYNTAX

    int sum(int ... i);
    or
    float sum(float ... f);
    or
    string sum(string|float|int ... p);
    or
    array sum(array ... a);
    or
    mapping sum(mapping ... m);
    or
    list sum(multiset ... l);

    DESCRIPTION
    This function does exactly the same thing as adding all the arguments together with +. It's just here so you can get a function pointer to the summation operator.


    NAME
    Simulate.add_efun - add an efun or constant

    SYNTAX
    void add_efun(string func_name, mixed function)
    or
    void add_efun(string func_name)

    DESCRIPTION
    This function is the same as add_constant.

    SEE ALSO
    Simulate.add_constant


    NAME
    Simulate.l_sizeof - return the size of a multiset

    SYNTAX
    int l_sizeof(multiset m);

    DESCRIPTION
    This function is equal to sizeof.

    SEE ALSO
    sizeof


    NAME
    Simulate.listp - is the argument a list? (multiset)

    SYNTAX
    int listp(mixed l)

    DESCRIPTION
    This function is the same as multisetp.

    SEE ALSO
    Simulate.multisetp


    NAME
    Simulate.mklist - make a multiset

    SYNTAX
    multiset mklist(mixed *a)

    DESCRIPTION
    This function creates a multiset from an array.

    EXAMPLE
    > mklist( ({1,2,3}) );
    Result: (< /* 3 elements */
    1,
    2,
    3
    >)

    SEE ALSO
    aggregate_multiset


    NAME
    Simulate.aggregate_list - aggregate a multiset

    SYNTAX
    multiset aggregate_list(mixed ... args);

    DESCRIPTION
    This function is exactly the same as aggregate_multiset.

    SEE ALSO
    aggregate_multiset


    NAME
    Simulate.query_host_name - return the name of the host we are running on

    SYNTAX
    string query_host_name();

    DESCRIPTION
    This function returns the name of the machine the interpreter is running on. This is the same thing that the command 'hostname' prints.


    Chapter 14, The preprocessor

    Pike has a builtin C-style preprocessor. The preprocessor reads the source before it is compiled and removes comments and expands macros. The preprocessor can also remove code depending on an expression that is evaluated when you compile the program. The preprocessor helps to keep your programming abstract by using defines instead of writing the same constant everywhere.

    It currently works similar to old C preprocessors but has a few extra features. This chapter describes the different preprocessor directives. This is what it can do:


    DIRECTIVE
    #!

    DESCRIPTION
    This directive is in effect a comment statement, since the preprocessor will ignore everything to the end of the line. This is used to write Unix type scripts in Pike by starting the script with

    #!/usr/local/bin/pike


    DIRECTIVE
    #define

    DESCRIPTION
    The simplest way to use define is to write

    #define <identifier> <replacement string>

    which will cause all subsequent occurrences of 'identifier' to be replaced with the replacement string.

    Define also has the capability to use arguments, thus a line like

    #define <identifier>(arg1, arg2) <replacement string>

    would cause identifier to be a macro. All occurrences of 'identifier(something1,something2d)' would be replaced with the replacement string. And in the replacement string, arg1 and arg2 will be replaced with something1 and something2.

    BUGS
    Note that it is not a good idea to do something like this:

    #define foo bar // a comment

    The comment will be included in the define, and thus inserted in the code. This will have the effect that the rest of the line will be ignored when the word foo is used. Not exactly what you might expect.

    EXAMPLE
    #define A "test"
    #define B 17
    #define C(X) (X)+(B)+"\n"
    #define W write
    #define Z Stdio.stdout
    int main()
    {
        Z->W(C(A));
    }


    DIRECTIVE
    #undef

    DESCRIPTION
    This removes the effect of a #define, all subsequent occurrences of the undefined identifier will not be replaced by anything. Note that when undefining a macro, you just give the identifier, not the arguments.

    EXAMPLES
    #define foo bar
    #undef foo
    #define foo(bar) gazonk bar
    #undef foo


    DIRECTIVE
    #if
    #elif
    #elseif
    #else
    #endif

    DESCRIPTION
    The #if directive causes conditional compiling of code depending on the expression after the #if directive. That is, if the expression is true, the code up to the next #else, #elif, #elseif or #endif is compiled. If the expression is false, that code will be skipped. If the skip leads up to a #else, the code after the else will be compiled. #elif and #elseif are equivalent and causes the code that follow them to be compiled if the previous #if or #elif evaluated false and the expression after the #elif evaluates true.

    Expressions given to #if, #elif or #endif are special, all identifiers evaluate to zero unless they are defined to something else. Integers, strings and floats are the only types that can be used, but all pike operators can be used on these types.

    Also, two special functions can be used, defined() and constant(). defined(identifier) expands to 1 if identifier is defined and 0 otherwise. constant(identifier) expands to 1 if identifier is an predefined constant (with add_constant), 0 otherwise.

    EXAMPLES
    #if 1
    write("foo");
    #else
    write("bar");
    #endif

    #if defined(FOO)

    write(FOO);
    #elif defined(BAR)
    write(BAR);
    #else
    write("default");
    #endif

    #if !constant(write_file)
    inherit "simulate.pike"
    #endif


    DIRECTIVE
    #error

    DESCRIPTION
    This directive causes a compiler error, it can be used to notify the user that certain functions are missing and similar things.

    EXAMPLES
    #if !constant(write_file)
    #error write_file function is missing
    #endif


    DIRECTIVE
    #include

    DESCRIPTION
    This directive should be given a file as argument, it will then be compiled as if all those lines were written at the #include line. The compiler then continues to compile this file.

    EXAMPLES
    #include "foo.h"


    DIRECTIVE
    #line

    DESCRIPTION
    This directive tells the compiler what line and file we are compiling. This is for instance used by the #include directive to tell the compiler that we are compiling another file. The directive takes the line number first, and optionally, the file afterwards.

    This can also be used when generating Pike from something else, to tell the compiler where the code originally originated from.

    EXAMPLES
    #line 4 "foo.cf" /* The next line was generated from 4 in foo.cf */


    DIRECTIVE
    #pragma

    DESCRIPTION
    This is a generic directive for flags to the compiler. Currently, the only flag available is 'all_inline' which is the same as adding the modifier 'inline' to all functions that follows.

    Chapter 15, All the builtin functions

    This chapter is a reference for all the builtin functions in Pike. They are listed in alphabetical order.
    NAME
    _memory_usage - check memory usage

    SYNTAX
    mapping(string:int) _memory_usage();

    DESCRIPTION
    This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use. Try evaluating the function in hilfe to see precisely what it returns.

    SEE ALSO
    _verify_internals


    NAME
    _next - find the next object/array/whatever

    SYNTAX
    mixed _next(mixed p);

    DESCRIPTION
    All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next object/array/mapping/string/etc in the linked list. It is mainly meant for debugging Pike but can also be used to control memory usage.

    SEE ALSO
    next_object and _prev


    NAME
    _prev - find the previous object/array/whatever

    SYNTAX
    mixed _next(mixed p);

    DESCRIPTION
    This function returns the 'previous' object/array/mapping/etc in the linked list. It is mainly meant for debugging Pike but can also be used to control memory usage. Note that this function does not work on strings.

    SEE ALSO
    _next


    NAME
    _refs - find out how many references a pointer type value has

    SYNTAX
    int _refs(string|array|mapping|multiset|function|object|program o);

    DESCRIPTION
    This function checks how many references the value o has. Note that the number of references will always be at least one since the value is located on the stack when this function is executed. _refs() is mainly meant for debugging Pike but can also be used to control memory usage.

    SEE ALSO
    _next and _prev


    NAME
    _verify_internals - check Pike internals

    SYNTAX
    void _verify_internals();

    DESCRIPTION
    This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.


    NAME
    acos - Trigonometrical inverse cosine

    SYNTAX
    float acos(float f);

    DESCRIPTION
    Return the arcus cosine value for f. The result will be in radians.

    SEE ALSO
    cos and asin


    NAME
    add_constant - add new predefined functions or constants

    SYNTAX
    void add_constant(string name, mixed value);
    or
    void add_constant(string name);

    DESCRIPTION
    This function adds a new constant to Pike, it is often used to add builtin functions. All programs compiled after add_constant function is called can access 'value' by the name given by 'name'. If there is a constant called 'name' already, it will be replaced by by the new definition. This will not affect already compiled programs.

    Calling add_constant without a value will remove that name from the list of constants. As with replacing, this will not affect already compiled programs.

    EXAMPLES
    add_constant("true",1);
    add_constant("false",0);
    add_constant("PI",4.0);
    add_constant("sqr",lambda(mixed x) { return x * x; });
    add_constant("add_constant");

    SEE ALSO
    all_constants


    NAME
    add_include_path - add a directory to search for include files

    SYNTAX
    void add_include_path(string path);

    DESCRIPTION
    This function adds another directory to the search for include files. This is the same as the command line option -I. Note that the added directory will only be searched when using < > to quote the included file.

    SEE ALSO
    remove_include_path and #include


    NAME
    add_module_path - add a directory to search for modules

    SYNTAX
    void add_module_path(string path);

    DESCRIPTION
    This function adds another directory to the search for modules. This is the same as the command line option -M. For more information about modules, see chapter 8 "Modules".

    SEE ALSO
    remove_module_path


    NAME
    add_program_path - add a directory to search for modules

    SYNTAX
    void add_program_path(string path);

    DESCRIPTION
    This function adds another directory to the search for programs. This is the same as the command line option -P. For more information about programs, see section 4.2.4 "program".

    SEE ALSO
    remove_program_path


    NAME
    aggregate - construct an array

    SYNTAX
    mixed *aggregate(mixed ... elems);
    or
    ({ elem1, elem2, ... })

    DESCRIPTION
    Construct an array with the arguments as indices. This function could be written in Pike as:

    mixed *aggregate(mixed ... elems) { return elems; }

    NOTA BENE
    Arrays are dynamically allocated there is no need to declare them like int a[10]=allocate(10); (and it isn't possible either) like in C, just int *a=allocate(10); will do.

    SEE ALSO
    sizeof, arrayp and allocate


    NAME
    aggregate_mapping - construct a mapping

    SYNTAX
    mapping aggregate_mapping(mixed ... elems);
    or
    ([ key1:val1, key2:val2, ... ])

    DESCRIPTION
    Groups the arguments together two and two to key-index pairs and creates a mapping of those pairs. The second syntax is always preferable.

    SEE ALSO
    sizeof, mappingp and mkmapping


    NAME
    aggregate_multiset - construct a multiset

    SYNTAX
    multiset aggregate_multiset(mixed ... elems);
    or
    (< elem1, elem2, ... >)

    DESCRIPTION
    Construct a multiset with the arguments as indexes. This function could be written in Pike as:

    multiset aggregate(mixed ... elems) { return mkmultiset(elems); }

    The only problem is that mkmultiset is implemented using aggregate_multiset...

    SEE ALSO
    sizeof, multisetp and mkmultiset


    NAME
    alarm - set an alarm clock for delivery of a signal

    SYNTAX
    int alarm(int seconds);

    DESCRIPTION
    alarm arranges for a SIGALRM signal to be delivered to the process in seconds seconds.

    If seconds is zero, no new alarm is scheduled.

    In any event any previously set alarm is canceled.

    RETURN VALUE
    alarm returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

    SEE ALSO
    signal


    NAME
    all_constants - return all predefined constants

    SYNTAX
    mapping (string:mixed) all_constant();

    DESCRIPTION
    Returns a mapping containing all constants, indexed on the names of the constant, and with the value of the efun as argument.

    SEE ALSO
    add_constant


    NAME
    allocate - allocate an array

    SYNTAX
    mixed *allocate(int size);

    DESCRIPTION
    Allocate an array of size elements and initialize them to zero.

    EXAMPLES
    mixed *a=allocate(17);

    NOTA BENE
    Arrays are dynamically allocated there is no need to declare them like int a[10]=allocate(10); (and it is not possible either) like in C, just array(int) a=allocate(10); will do.

    SEE ALSO
    sizeof, aggregate and arrayp


    NAME
    arrayp - is the argument an array?

    SYNTAX
    int arrayp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is an array, zero otherwise.

    SEE ALSO
    allocate, intp, programp, floatp, stringp, objectp, mappingp, multisetp and functionp


    NAME
    asin - Trigonometrical inverse sine

    SYNTAX
    float asin(float f);

    DESCRIPTION
    Returns the arcus sinus value for f.

    SEE ALSO
    sin and acos


    NAME
    atan - Trigonometrical inverse tangent

    SYNTAX
    float atan(float f);

    DESCRIPTION
    Returns the arcus tangent value for f.

    SEE ALSO
    tan, asin and acos


    NAME
    backtrace - get a description of the call stack

    SYNTAX
    array(array) backtrace();

    DESCRIPTION
    This function returns a description of the call stack at this moment. The description is returned in an array with one entry for each call in the stack. Each entry has this format:

    ({

    file, /* a string with the filename if known, else zero */
    line, /* an integer containing the line if known, else zero */
    function, /* The function pointer to the called function */
    mixed|void ..., /* The arguments the function was called with */
    })

    The current call frame will be last in the array, and the one above that the last but one and so on.

    SEE ALSO
    catch and throw


    NAME
    call_function - call a function with arguments

    SYNTAX
    mixed call_function(function fun,mixed ... args);
    or
    mixed fun ( mixed ... args );

    DESCRIPTION
    This function takes a function pointer as first argument and calls this function with the rest of the arguments as arguments. Normally, you will never have to write call_function(), because you will use the second syntax instead.

    SEE ALSO
    backtrace and Simulate.get_function


    NAME
    call_out - make a delayed call to a function

    SYNTAX
    mixed call_out(function f, int delay, mixed ... args);

    DESCRIPTION
    Call_out places a call to the function f with the argument args in a queue to be called in about delay seconds. The return value identifies this call out. The return value can be sent to find_call_out or remove_call_out to remove the call out again.

    SEE ALSO
    remove_call_out, find_call_out and call_out_info


    NAME
    call_out_info - get info about all call outs

    SYNTAX
    mixed **call_out_info();

    DESCRIPTION
    This function returns an array with one entry for each entry in the call out queue. The first in the queue will be in index 0. Each index contains an array that looks like this:

    ({

    time_left, /* an int */
    caller, /* the object that made the call out */
    function, /* the function to be called */
    arg1, /* the first argument, if any */
    arg2, /* the second argument, if any */
    ... /* and so on... */
    })

    SEE ALSO
    call_out, find_call_out and remove_call_out


    NAME
    _do_call_outs - do all pending call_outs.
    SYNTAX
    void _do_call_out();
    DESCRIPTION
    This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.

    As a side-effect, this function sets the value returned by time(1) to the current time.

    SEE ALSO
    call_out, find_call_out and remove_call_out


    NAME
    catch - catch errors

    SYNTAX
    catch { commands }
    or
    catch ( expression )

    DESCRIPTION
    catch traps exceptions such as run time errors or calls to throw() and returns the argument given to throw. For a run time error, this value is ({ "error message", backtrace })

    SEE ALSO
    throw


    NAME
    cd - change directory

    SYNTAX
    int cd(string s);

    DESCRIPTION
    Change the current directory for the whole Pike process, return 1 for success, 0 otherwise.

    SEE ALSO
    getcwd


    NAME
    ceil - Truncate a number upward

    SYNTAX
    float ceil(float f);

    DESCRIPTION
    Return the closest integer value higher or equal to f. Note that ceil() does not return an int, merely an integer value stored in a float.

    SEE ALSO
    floor


    NAME
    clone - clone an object from a program

    SYNTAX
    object clone(program p,mixed ... args);
    or
    object new(program p,mixed ... args);

    DESCRIPTION
    new() or clone() creates an object from the program p. Or in C++ terms: It creates an instance of the class p. This clone will first have all global variables initialized, and then create() will be called with args as arguments.

    SEE ALSO
    destruct, compile_string and compile_file


    NAME
    column - extract a column

    SYNTAX
    array column(mixed *data,mixed index)

    DESCRIPTION
    This function is exactly equivalent to:
    map_array(data, lambda(mixed x,mixed y) { return x[y]; }, index)
    Except of course it is a lot shorter and faster. That is, it indexes every index in the array data on the value of the argument index and returns an array with the results.

    EXAMPLE
    	> column( ({ ({1,2}), ({3,4}), ({5,6}) }), 1)
    	Result: ({2, 4, 6})
    
    SEE ALSO
    rows


    NAME
    combine_path - concatenate paths

    SYNTAX
    string combine_path(string absolute, string relative);

    DESCRIPTION
    Concatenate a relative path to an absolute path and remove any "//", "/.." or "/." to produce a straightforward absolute path as a result.

    EXAMPLES
    > combine_path("/foo/bar/","..");
    Result: /foo
    > combine_path("/foo/bar/","../apa.c");
    Result: /foo/apa.c
    > combine_path("/foo/bar","./sune.c");
    Result: /foo/bar/sune.c

    SEE ALSO
    getcwd


    NAME
    compile_file - compile a file to a program

    SYNTAX
    program compile_file(string filename);

    DESCRIPTION
    This function will compile the file filename to a Pike program that can later be used for cloning.

    SEE ALSO
    clone and compile_string


    NAME
    compile_string - compile a string to a program

    SYNTAX
    program compile_string(string prog, string name);

    DESCRIPTION
    compile_string() takes a piece of Pike code as a string and compiles it into a clonable program. Note that prog must contain the complete source for a program. You can not compile a single expression or statement.The second argument will be used as the file name of the program and will be used for error messages and such.

    SEE ALSO
    compile_string and clone


    NAME
    copy_value - copy a value recursively

    SYNTAX
    mixed copy_value(mixed value);

    DESCRIPTION
    Copy value will copy the value given to it recursively. If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed. The resulting value will always be equal to the copied (tested with the efun equal), but they may not the the same value. (tested with ==)

    SEE ALSO
    equal


    NAME
    cos - Trigonometrical cosine

    SYNTAX
    float cos(float f);

    DESCRIPTION
    Returns the cosine value for f.

    SEE ALSO
    acos and sin


    NAME
    crypt - crypt a password

    SYNTAX
    string crypt(string password);
    or
    int crypt(string typed_password, string crypted_password);

    DESCRIPTION
    This function crypts and verifies a short string. (normally only the first 8 characters are significant) The first syntax crypts the string password into something that is hopefully hard to decrypt, and the second function crypts the first string and verifies that the crypted result matches the second argument and returns 1 if they matched, 0 otherwise.

    EXAMPLES
    To crypt a password use:
    crypted_password = crypt(typed_password);
    To see if the same password was used again use:
    matched = crypt(typed_password, crypted_password);

    NAME
    ctime - convert time int to readable date string

    SYNTAX
    string ctime(int current_time);

    DESCRIPTION
    Convert the output from a previous call to time() into a readable string containing the current year, month, day and time.

    EXAMPLE
    > ctime(time());
    Result: Wed Jan 14 03:36:08 1970

    SEE ALSO
    time


    NAME
    decode_value - code a value into a string

    SYNTAX
    mixed decode_value(string coded_value);

    DESCRIPTION
    This function takes a string created with encode_value() and converts it back to the value that was coded.

    SEE ALSO
    encode_value


    NAME
    describe_backtrace - make a backtrace readable

    SYNTAX
    string describe_backtrace(mixed **backtrace);

    DESCRIPTION
    Describe backtrace returns a string containing a readable message that describes where the backtrace was made. The argument 'backtrace' should normally be the return value from a call to backtrace()

    SEE ALSO
    backtrace


    NAME
    destruct - destruct an object

    SYNTAX
    void destruct(object o);

    DESCRIPTION
    Destruct marks an object as destructed, all pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible. This will also call o->destroy.

    SEE ALSO
    clone


    NAME
    encode_value - code a value into a string

    SYNTAX
    string encode_value(mixed value);

    DESCRIPTION
    This function takes a value, and converts it to a string. This string can then be saved, sent to another Pike process, packed or used in any way you like. When you want your value back you simply send this string to decode_value() and it will return the value you encoded.

    Almost any value can be coded, mappings, floats, arrays, circular structures etc. At present, objects, programs and functions cannot be saved in this way. This is being worked on.

    SEE ALSO
    decode_value and sprintf


    NAME
    equal - check if two values are equal or not

    SYNTAX
    int equal(mixed a, mixed b);

    DESCRIPTION
    This function checks if the values a and b are equal. For all types but arrays, multisets and mappings, this operation is the same as doing a == b. For arrays, mappings and multisets however, their contents are checked recursively, and if all their contents are the same and in the same place, they are considered equal.

    EXAMPLES
    > ({ 1 }) == ({ 1 });
    Result: 0
    > equal( ({ 1 }), ({ 1 }) );
    Result: 1
    >

    SEE ALSO
    copy_value


    NAME
    errno - return system error number

    SYNTAX
    int errno();

    DESCRIPTION
    This function returns the system error from the last file operation. Note that you should normally use the function errno in the file object instead.

    SEE ALSO
    errno


    NAME
    exece - execute a program

    SYNTAX
    int exece(string file, array(string) args);
    or
    int exece(string file, array(string) args, mapping(string:string) env);

    DESCRIPTION
    This function transforms the Pike process into a process running the program specified in the argument 'file' with the argument 'args'. If the mapping 'env' is present, it will completely replace all environment variables before the new program is executed. This function only returns if something went wrong during exece(), and in that case it returns zero.

    NOTA BENE
    The Pike driver _dies_ when this function is called. You must use fork() if you wish to execute a program and still run the Pike driver.

    EXAMPLES
    exece("/bin/ls", ({"-l"}));
    exece("/bin/sh", ({"-c", "echo $HOME"}), (["HOME":"/not/home"]));

    SEE ALSO
    fork and file->pipe


    NAME
    exit - exit Pike interpreter

    SYNTAX
    void exit(int returncode);

    DESCRIPTION
    This function exits the whole Pike program with the return code given. Using exit() with any other value than 0 indicates that something went wrong during execution. See your system manuals for more information about return codes.


    NAME
    exp - Natural exponent

    SYNTAX
    float exp(float f);

    DESCRIPTION
    Return the natural exponent of f.

    SEE ALSO
    pow and log


    NAME
    file_stat - stat a file

    SYNTAX
    int *file_stat(string file);
    or
    int *file_stat(string file, 1);
    or
    int *file->stat();

    DESCRIPTION
    file_stat returns an array of integers describing some properties
    about the file. Currently file_stat returns 7 entries:
    ({
    mode, /* file mode, protection bits etc. etc. */
    size, /* file size for regular files, -2 for dirs, -3 for links, -4 for otherwise */
    atime, /* last access time */
    mtime, /* last modify time */
    ctime, /* last status time change */
    uid, /* The user who owns this file */
    gid /* The group this file belongs to */
    })
    If you give 1 as a second argument, file_stat does not follow links.
    You can never get -3 as size if you don't give a second argument.

    If there is no such file or directory, zero is returned.

    SEE ALSO
    get_dir


    NAME
    find_call_out - find a call out in the queue

    SYNTAX
    int find_call_out(function f);
    or
    int find_call_out(mixed id);

    DESCRIPTION
    This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function. The argument can also be a call out id as returned by call_out, in which case that call_out will be found. (Unless it has already been called.) find_call_out will then return how many seconds remains before that call will be executed. If no call is found, zero_type(find_call_out(f)) will return 1.

    SEE ALSO
    call_out, remove_call_out and call_out_info


    NAME
    floatp - is the argument a float?

    SYNTAX
    int floatp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a float, zero otherwise.

    SEE ALSO
    intp, programp, arrayp, stringp, objectp, mappingp, multisetp and functionp


    NAME
    floor - Truncate a number downward

    SYNTAX
    float floor(float f);

    DESCRIPTION
    Return the closest integer value lower or equal to f. Note that floor() does not return an int, merely an integer value stored in a float.

    SEE ALSO
    ceil


    NAME
    fork - fork the process in two

    SYNTAX
    int fork();

    DESCRIPTION
    Fork splits the process in two, and for the parent it returns the pid of the child. Refer to your Unix manual for further details.

    NOTA BENE
    This function cause endless bugs if used without proper care.

    SEE ALSO
    Process.exec and Stdio.File->pipe


    NAME
    function_name - return the name of a function, if known

    SYNTAX
    string function_name(function f);

    DESCRIPTION
    This function returns the name of the function f. If the function is a pre-defined function in the driver, zero will be returned.

    SEE ALSO
    function_object and Simulate.get_function


    NAME
    function_object - return what object a function is in

    SYNTAX
    object function_object(function f);

    DESCRIPTION
    Function_object will return the object the function f is in. If the function is a predefined function from the driver, zero will be returned.

    SEE ALSO
    function_name and Simulate.get_function


    NAME
    functionp - is the argument a function?

    SYNTAX
    int functionp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a function, zero otherwise.

    SEE ALSO
    intp, programp, arrayp, stringp, objectp, mappingp, multisetp and floatp


    NAME
    gc - do garbage collection

    SYNTAX
    int gc();

    DESCRIPTION
    This function checks all the memory for cyclic structures such as arrays containing themselves and frees them if appropriate. It also frees up destructed objects. It then returns how many arrays/objects/programs/etc. it managed to free by doing this. Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)

    NAME
    get_dir - read a directory

    SYNTAX
    array(string) get_dir(string dirname);

    DESCRIPTION
    Returns an array of all filenames in the directory dirname, or zero if no such directory exists.

    SEE ALSO
    mkdir and cd


    NAME
    getcwd - return current working directory

    SYNTAX
    string getcwd();

    DESCRIPTION
    getcwd returns the current working directory.

    SEE ALSO
    cd


    NAME
    getenv - get an environment variable

    SYNTAX
    string getenv(string varname);

    DESCRIPTION
    Returns the value of the environment variable with the name varname, if no such environment variable exists, zero is returned.

    NOTA BENE
    This function is provided by master.pike


    NAME
    getpid - get the process id of this process

    SYNTAX
    int getpid();

    DESCRIPTION
    This returns the pid of this process. Useful for sending signals to yourself.

    SEE ALSO
    kill, fork and signal


    NAME
    glob - match strings against globs

    SYNTAX
    int glob(string glob, string str);
    or
    array(string) glob(string glob, array(string) arr);

    DESCRIPTION
    This function matches "globs". In a glob string a question sign matches any character and an asterisk matches any string. When given two strings as argument a true/false value is returned which reflects if the str matches glob. When given an array as second argument, an array containing all matching strings is returned.

    SEE ALSO
    sscanf and Regexp


    NAME
    hash - hash a string

    SYNTAX
    int hash(string s);
    or
    int hash(string s, int max);

    DESCRIPTION
    This function will return an int derived from the string s. The same string will always hash to the same value. If a second argument is given, the result will be >= 0 and lesser than that argument.


    NAME
    indices - return an array of all index possible for a value

    SYNTAX
    mixed *indices(string|array|mapping|multiset|object foo);

    DESCRIPTION
    indices returns an array of all values you can use as index when indexing foo. For strings and arrays this is simply an array of the ascending numbers. For mappings and multisets, the array may contain any kind of value. For objects, the result is an array of strings.

    SEE ALSO
    values


    NAME
    intp - is the argument an int?

    SYNTAX
    array intp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is an int, zero otherwise.

    SEE ALSO
    arrayp, programp, floatp, stringp, objectp, mappingp, multisetp and functionp


    NAME
    kill - send signal to other process

    SYNTAX
    int kill(int pid, int signal)

    DESCRIPTION
    Kill sends a signal to another process. If something goes wrong -1 is returned, 0 otherwise.

    Some signals and their supposed purpose:

    SIGHUP Hang-up, sent to process when user logs out
    SIGINT Interrupt, normally sent by ctrl-c
    SIGQUIT Quit, sent by ctrl-\
    SIGILL Illegal instruction
    SIGTRAP Trap, mostly used by debuggers
    SIGABRT Aborts process, can be caught, used by Pike whenever something goes seriously wrong.
    SIGBUS Bus error
    SIGFPE Floating point error (such as division by zero)
    SIGKILL Really kill a process, cannot be caught
    SIGUSR1 Signal reserved for whatever you want to use it for.
    SIGSEGV Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike.
    SIGUSR2 Signal reserved for whatever you want to use it for.
    SIGALRM Signal used for timer interrupts.
    SIGTERM Termination signal
    SIGSTKFLT Stack fault
    SIGCHLD Child process died
    SIGCONT Continue suspended
    SIGSTOP Stop process
    SIGSTP Suspend process
    SIGTTIN tty input for background process
    SIGTTOU tty output for background process
    SIGXCPU Out of CPU
    SIGXFSZ File size limit exceeded
    SIGPROF Profile trap
    SIGWINCH Window change signal

    Note that you have to use signame to translate the name of a signal to its number.

    SEE ALSO
    signal, signum, signame and fork


    NAME
    load_module - load a binary module

    SYNTAX
    int load_module(string module_name);

    DESCRIPTION
    This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.

    When a module is loaded the functions init_module_efuns and init_module_programs are called to initialize it. When Pike exits exit_module is called in all dynamically loaded modules. These functions _must_ be available in the module.

    Please see the source and any examples available at ftp://www.idonex.se/pub/pike for more information on how to write modules for Pike in C.

    BUGS
    Please use "./name.so" instead of just "foo.so" for the module name. If you use just "foo.se" the module will not be found.


    NAME
    localtime - break down time() into intelligible components

    SYNTAX
    mapping(string:int) localtime(int time);

    DESCRIPTION
    Given a time represented as second since 1970, as returned by the function time(), this function returns a mapping with the following components:

    sec seconds over the minute 0 - 59
    min minutes over the hour 0 - 59
    hour what hour in the day 0 - 23
    mday day of the month 1 - 31
    mon what month 0 - 11
    year years since 1900 0 -
    wday day of week (0=Sunday) 0 - 6
    yday day of year 0 - 365
    isdst is daylight saving time 0/1
    timezone difference between local time and UTC

    NOTA BENE
    The 'timezone' might not be available on all platforms.

    SEE ALSO
    time


    NAME
    log - Natural logarithm

    SYNTAX
    float log(float f);

    DESCRIPTION
    Return the natural logarithm of f.

    SEE ALSO
    pow and exp


    NAME
    lower_case - convert a string to lower case

    SYNTAX
    string lower_case(string s);

    DESCRIPTION
    Returns a string with all capital letters converted to lower case.

    SEE ALSO
    upper_case


    NAME
    m_delete - remove an index from a mapping

    SYNTAX
    mapping m_delete(mapping map, mixed index);

    DESCRIPTION
    Removes the entry with index index from mapping map destructively. Returns the changed mapping. If the mapping does not have an entry with index index, nothing is done. Note that m_delete changes map destructively and only returns the mapping for compatibility reasons.

    SEE ALSO
    mappingp


    NAME
    mappingp - is the argument a mapping?

    SYNTAX
    int mappingp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a mapping, zero otherwise.

    SEE ALSO
    intp, programp, arrayp, stringp, objectp, multisetp, floatp and functionp


    NAME
    master - return the master object

    SYNTAX
    object master();

    DESCRIPTION
    Master is added by the master object to make it easier to access it.


    NAME
    mkdir - make directory

    SYNTAX
    int mkdir(string dirname);

    DESCRIPTION
    Create a directory, return zero if it fails and nonzero if it successful.

    SEE ALSO
    rm and cd


    NAME
    mkmapping - make a mapping from two arrays

    SYNTAX
    mapping mkmapping(mixed *ind, mixed *val);

    DESCRIPTION
    Makes a mapping ind[x]:val[x], 0<=x<sizeof(ind). ind and val must have the same size. This is the inverse operation of indices and values.

    SEE ALSO
    indices and values


    NAME
    mkmultiset - make a multiset

    SYNTAX
    multiset mkmultiset(mixed *a)

    DESCRIPTION
    This function creates a multiset from an array.

    EXAMPLE
    > mkmultiset( ({1,2,3}) );
    Result: (< /* 3 elements */
    1,
    2,
    3
    >)

    SEE ALSO
    aggregate_multiset


    NAME
    mktime - convert date and time to seconds

    SYNTAX
    int mktime(mapping tm)
    or
    int mktime(int sec, int min, int hour, int mday, int mon, int year, int isdst, int tz)

    DESCRIPTION
    This function converts information about date and time into an integer which contains the number of seconds since the beginning of 1970. You can either call this function with a mapping containing the following elements:

    yearThe number of years since 1900
    monThe month
    mdayThe day of the month.
    hourThe number of hours past midnight
    minThe number of minutes after the hour
    secThe number of seconds after the minute
    isdstIf this is 1, daylight savings time is assumed
    tmThe timezone (-12 <= tz <= 12)

    Or you can just send them all on one line as the second syntax suggests.

    SEE ALSO
    time


    NAME
    multisetp - is the argument a multiset?

    SYNTAX
    int multisetp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a multiset, zero otherwise.

    SEE ALSO
    intp, programp, arrayp, stringp, objectp, mappingp, floatp and functionp


    NAME
    mv - move a file (may handle directories as well)

    SYNTAX
    int mv(string from,string to);

    DESCRIPTION
    Rename or move a file between directories. If the destination file already exists, it will be overwritten. Returns 1 on success, 0 otherwise.

    SEE ALSO
    rm


    NAME
    next_object - get next object

    SYNTAX
    object next_object(object o);
    or
    object next_object();

    DESCRIPTION
    All objects are stored in a linked list, next_object() returns the first object in this list, and next_object(o) the next object in the list after o.

    EXAMPLES
    /* This example calls shutting_down() in all cloned objects */
    object o;
    for(o=next_object();o;o=next_object(o))
    o->shutting_down();

    SEE ALSO
    clone and destruct


    NAME
    object_program - get the program associated with the object

    SYNTAX
    program object_program(object o);

    DESCRIPTION
    This function returns the program from which o was cloned. If o is not an object or has been destructed o zero is returned.

    SEE ALSO
    clone


    NAME
    objectp - is the argument an object?

    SYNTAX
    int objectp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is an object, zero otherwise.

    SEE ALSO
    intp, programp, floatp, stringp, arrayp, mappingp, multisetp and functionp


    NAME
    pow - Raise a number to the power of another.

    SYNTAX
    float pow(float n, float x);

    DESCRIPTION
    Return n raised to the power of x.

    SEE ALSO
    exp and log


    NAME
    programp - is the argument a program?

    SYNTAX
    int programp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a program, zero otherwise.

    SEE ALSO
    intp, multisetp, arrayp, stringp, objectp, mappingp, floatp and functionp


    NAME
    putenv - put environment variable

    SYNTAX
    void putenv(string varname, string value);

    DESCRIPTION
    This function sets the environment variable varname to value.

    SEE ALSO
    getenv and exece


    NAME
    query_host_name - return the name of the host we are running on

    SYNTAX
    string query_host_name();

    DESCRIPTION
    This function returns the name of the machine the interpreter is running on. This is the same thing that the command hostname prints.


    NAME
    query_num_arg - find out how many arguments were given

    SYNTAX
    int query_num_arg();

    DESCRIPTION
    query_num_arg returns the number of arguments given when this function was called. This is only useful for varargs functions.

    SEE ALSO
    call_function


    NAME
    random - return a random number

    SYNTAX
    int random(int max);

    DESCRIPTION
    This function returns a random number in the range 0 - max-1.

    SEE ALSO
    random_seed


    NAME
    random_seed - seed random generator

    SYNTAX
    void random_seed(int seed);

    DESCRIPTION
    This function sets the initial value for the random generator.

    EXAMPLE
    Pike v1.0E-13 Running Hilfe v1.2 (Hubbe's Incremental Pike Front-End)
    > random_seed(17);
    Result: 0
    > random(1000);
    Result: 732
    > random(1000);
    Result: 178
    > random(1000);
    Result: 94
    > random_seed(17);
    Result: 0
    > random(1000);
    Result: 732
    > random(1000);
    Result: 178
    > random(1000);
    Result: 94
    >

    SEE ALSO
    random


    NAME
    remove_call_out - remove a call out from the call out queue

    SYNTAX
    int remove_call_out(function f);
    or
    int remove_call_out(function id);

    DESCRIPTION
    This function finds the first call to the function f in the call out queue and removes it. The time left to that call out will be returned. If no call out was found, zero_type(remove_call_out(f)) will return 1. You can also give a call out id as argument. (as returned by call_out)

    SEE ALSO
    call_out_info, call_out and find_call_out


    NAME
    remove_include_path - remove a directory to search for include files

    SYNTAX
    void remove_include_path(string path);

    DESCRIPTION
    This function removes a directory from the list of directories to search for include files. It is the opposite of add_include_path.

    SEE ALSO
    add_include_path and #include


    NAME
    remove_module_path - remove a directory to search for modules

    SYNTAX
    void remove_module_path(string path);

    DESCRIPTION
    This function removes a directory from the list of directories to search for modules. It is the opposite of add_module_path. For more information about modules, see chapter 8 "Modules".

    SEE ALSO
    add_module_path


    NAME
    remove_program_path - remove a directory to search for modules

    SYNTAX
    void remove_program_path(string path);

    DESCRIPTION
    This function removes a directory from the list of directories to search for program. It is the opposite of add_program_path. For more information about programs, see section 4.2.4 "program".

    SEE ALSO
    add_program_path


    NAME
    replace - generic replace function

    SYNTAX
    string replace(string s, string from, string to);
    or
    string replace(string s, array(string) from, array(string) to);
    or
    array replace(array a, mixed from, mixed to);
    or
    mapping replace(mapping a, mixed from, mixed to);

    DESCRIPTION
    This function can do several kinds replacement operations, the different syntaxes do different things as follow:

    string replace(string s, string from, string to);

    When given strings as second and third argument, a copy of
    s with every occurrence of 'from' replaced with 'to' is returned.

    string replace(string s, array(string) from, array(string) to);

    When given arrays of strings as second and third argument,
    every occurrence of from[0] in s is replaced by to[0],
    from[1] is replaced by to[1] and so on...

    array replace(array a, mixed from, mixed to);
    mapping replace(mapping a, mixed from, mixed to);

    When the first argument is an array or mapping, the values in
    a are searched for values equal to from, which are replaced by
    to destructively.


    NAME
    replace_master - replace the master object

    SYNTAX
    void replace_master(object o);

    DESCRIPTION
    This function replaces the master object with the argument you specify. This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is probably a good idea to have your master inherit the original master and only re-define certain functions.

    NAME
    reverse - reverse a string, array or int

    SYNTAX
    string reverse(string s);
    or
    array reverse(array a);
    or
    int reverse(int i);

    DESCRIPTION
    This function reverses a string, char by char, an array, value by value or an int, bit by bit and returns the result. Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.

    SEE ALSO
    sscanf


    NAME
    rm - remove file or directory

    SYNTAX
    int rm(string f);

    DESCRIPTION
    Remove a file or directory, return 0 if it fails. Nonzero otherwise.

    SEE ALSO
    mkdir


    NAME
    rows - select a set of rows from an array

    SYNTAX
    array rows(mixed data, mixed *index)

    DESCRIPTION
    This function is exactly equivalent to:

    map_array(index,lambda(mixed x,mixed y) { return y[x]; },data)

    Except of course it is a lot shorter and faster. That is, it indexes data on every index in the array index and returns an array with the results.

    SEE ALSO
    column


    NAME
    rusage - return resource usage

    SYNTAX
    int *rusage();

    DESCRIPTION
    This function returns an array of ints describing how much resources the interpreter process has used so far. This array will have at least 29 elements, of which those values not available on this system will be zero. The elements are as follows:

    0: user time 1: system time 2: maxrss 3: idrss 4: isrss 5: minflt 6: minor page faults 7: major page faults 8: swaps 9: block input op. 10: block output op. 11: messages sent 12: messages received 13: signals received 14: voluntary context switches 15: involuntary context switches 16: sysc 17: ioch 18: rtime 19: ttime 20: tftime 21: dftime 22: kftime 23: ltime 24: slptime 25: wtime 26: stoptime 27: brksize 28: stksize

    Don't ask me to explain these values, read your system manuals for more information. (Note that all values may not be present though)

    SEE ALSO
    time


    NAME
    search - search for a value in a string or array

    SYNTAX
    int search(string haystack, string needle, [ int start ]);
    or
    int search(mixed *haystack, mixed needle, [ int start ]);
    or
    mixed search(mapping haystack, mixed needle, [ mixed start ]);

    DESCRIPTION
    Search for needle in haystack. Return the position of needle in haystack or -1 if not found. If the optional argument start is present search is started at this position. Note that when haystack is a string needle must be a string, and the first occurrence of this string is returned. However, when haystack is an array, needle is compared only to one value at a time in haystack.

    When the haystack is a mapping, search tries to find the index connected to the data needle. That is, it tries to lookup the mapping backwards. If needle isn't present in the mapping, zero is returned, and zero_type() will return 1 for this zero.

    SEE ALSO
    indices, values and zero_type


    NAME
    signal - trap signals

    SYNTAX
    void signal(int sig, function(int:void) callback);
    or
    void signal(int sig);

    DESCRIPTION
    This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc. I advice you not to. Pike should not receive any such signals and if it does it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.

    The callback will receive the signal number as the only argument. See the document for the function 'kill' for a list of signals.

    If no second argument is given, the signal handler for that signal is restored to the default handler.

    If the second argument is zero, the signal will be completely ignored.

    SEE ALSO
    kill, signame and signum


    NAME
    signame - get the name of a signal

    SYNTAX
    string signame(int sig);

    DESCRIPTION
    Returns a string describing the signal.

    EXAMPLE
    > signame(9);
    Result: SIGKILL

    SEE ALSO
    kill, signum and signal


    NAME
    signum - get a signal number given a descriptive string

    SYNTAX
    int signum(string sig);

    DESCRIPTION
    This function is the opposite of signame.

    EXAMPLE
    > signum("SIGKILL");
    Result: 9

    SEE ALSO
    signame, kill and signal


    NAME
    sin - Trigonometrical sine

    SYNTAX
    float sin(float f);

    DESCRIPTION
    Returns the sinus value for f.

    SEE ALSO
    asin and cos


    NAME
    sizeof - return the size of an array, string, multiset or mapping

    SYNTAX
    int sizeof(string|multiset|mapping|array|object a);

    DESCRIPTION
    This function returns the number of indexes available in the argument given to it. It replaces older functions like strlen, m_sizeof and size.


    NAME
    sleep - let interpreter doze off for a while

    SYNTAX
    void sleep(int s);

    DESCRIPTION
    This function makes the program stop for s seconds. Only signal handlers can interrupt the sleep. Other callbacks are not called during sleep.

    SEE ALSO
    signal


    NAME
    sort - sort an array destructively

    SYNTAX
    mixed *sort(array(mixed) index, array(mixed) ... data);

    DESCRIPTION
    This function sorts the array 'index' destructively. That means that the array itself is changed and returned, no copy is created. If extra arguments are given, they are supposed to be arrays of the same size. Each of these arrays will be modified in the same way as 'index'. Ie. if index 3 is moved to position 0 in 'index' index 3 will be moved to position 0 in all the other arrays as well.

    Sort can sort strings, integers and floats in ascending order. Arrays will be sorted first on the first element of each array.

    Sort returns its first argument.

    SEE ALSO
    reverse


    NAME
    sprintf - print the result from sprintf

    SYNTAX
    string sprintf(string format,mixed arg,....);

    DESCRIPTION
    The format string is a string containing a description of how to output the data in the rest of the arguments. This string should generally speaking have one %<modifiers><operator> (examples: %s, %0d, %-=20s) for each of the rest arguments.

    Modifiers:

    0 Zero pad numbers (implies right justification)
    ! Toggle truncation
    ' ' (space) pad positive integers with a space
    + pad positive integers with a plus sign
    - left adjusted within field size (default is right)
    | centered within field size
    = column mode if strings are greater than field size
    / Rough line break (break at exactly field size instead of between words)
    # table mode, print a list of '\n' separated word (top-to-bottom order)
    $ Inverse table mode (left-to-right order)
    n (where n is a number or *) a number specifies field size
    .n set precision
    :n set field size & precision
    ;n Set column width
    * if n is a * then next argument is used for precision/field size
    'X' Set a pad string. ' cannot be a part of the pad_string (yet)
    ~ Get pad string from argument list.
    < Use same arg again
    ^ repeat this on every line produced
    @ do this format for each entry in argument array
    > Put the string at the bottom end of column instead of top
    _ Set width to the length of data

    Operators:

    %% percent
    %d signed decimal int
    %u unsigned decimal int (doesn't really exist in Pike)
    %o unsigned octal int
    %x lowercase unsigned hexadecimal int
    %X uppercase unsigned hexadecimal int
    %c char (or short with %2c, %3c gives 3 bytes etc.)
    %f float
    %g heuristically chosen representation of float
    %e exponential notation float
    %s string
    %O any type (debug style)
    %n nop
    %t type of argument
    %<modifiers>{format%} do a format for every index in an array.

    EXAMPLES
    Pike v0.1 Running Hilfe v1.2 (Incremental Pike Front end)
    > int screen_width=70;
    Result: 70
    > mixed sample;
    > write(sprintf("fish: %c\n", 65));
    fish: A
    Result: 0
    > write(sprintf("Hello green friends\n"));
    Hello green friends
    Result: 0
    > write(sprintf("num: %d\n", 10));
    num: 10
    Result: 0
    > write(sprintf("num: %+10d\n", 10));
    num: +10
    Result: 0
    > write(sprintf("num: %010d\n", 5*2));
    num: 0000000010
    Result: 0
    > write(sprintf("num: %|10d\n", 20/2));
    num: 10
    Result: 0
    > write(sprintf("%|*s\n",screen_width,"THE NOT END"));
    THE NOT END
    Result: 0
    > write(sprintf("%|=*s\n",screen_width, "fun with penguins\n"));
    fun with penguins
    Result: 0
    > write(sprintf("%-=*O\n",screen_width,({ "fish", 9, "gumbies", 2 })));
    ({ /* 4 elements */
    "fish",
    9,
    "gumbies",
    2
    })
    Result: 0
    > write(sprintf("%-=*s\n", screen_width,
    "This will wordwrap the specified string within the "+
    "specified field size, this is useful say, if you let "+
    "users specify their screen size, then the room "+
    "descriptions will automagically word-wrap as appropriate.\n"+
    "slosh-n's will of course force a new-line when needed.\n"));
    This will wordwrap the specified string within the specified field
    size, this is useful say, if you let users specify their screen size,
    then the room descriptions will automagically word-wrap as
    appropriate.
    slosh-n's will of course force a new-line when needed.
    Result: 0
    > write(sprintf("%-=*s %-=*s\n", screen_width/2,
    "Two columns next to each other (any number of columns will "+
    "of course work) independently word-wrapped, can be useful.",
    screen_width/2-1,
    "The - is to specify justification, this is in adherence "+
    "to std sprintf which defaults to right-justification, "+
    "this version also supports center and right justification."));
    Two columns next to each other (any The - is to specify justification,
    number of columns will of course this is in adherence to std
    work) independently word-wrapped, sprintf which defaults to
    can be useful. right-justification, this version
    also supports center and right
    justification.
    Result: 0
    > write(sprintf("%-$*s\n", screen_width,
    "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
    "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
    "be forced\nby specifying a\nprecision.\nThe most obvious\n"+
    "use is for\nformatted\nls output."));
    Given a list of slosh-n
    separated 'words', this option
    creates a table out of them
    the number of columns be forced
    by specifying a precision. The most obvious
    use is for formatted ls output.
    Result: 0
    > write(sprintf("%-#*s\n", screen_width,
    "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+
    "creates a\ntable out\nof them\nthe number of\ncolumns\n"+
    "be forced\nby specifying a\nprecision.\nThe most obvious\n"+
    "use is for\nformatted\nls output."));
    Given a creates a by specifying a
    list of table out precision.
    slosh-n of them The most obvious
    separated the number of use is for
    'words', columns formatted
    this option be forced ls output.
    Result: 0
    > sample = ({ "first column: bing", "second column: womble" });
    Result: ({ /* 2 elements */
    "first column: bing",
    "second column: womble"
    })
    > write(sprintf("%-=*s\n%-=@*s\n", screen_width,
    "Another bizarre option is the @ operator, it applies the "+
    "format string it is in to each element of the array:",
    screen_width/sizeof(sample),
    sample));
    Another bizarre option is the @ operator, it applies the format string
    it is in to each element of the array:
    first column: bing second column: womble
    Result: 0
    > write(sprintf("Better use these instead: %{gurksallad: %s\n%}\n",
    sample));
    Better use these instead: gurksallad: first column: bing
    gurksallad: second column: womble

    Result: 0
    > write(sprintf("Of course all the simple printf options "+
    "are supported:\n %s: %d %x %o %c\n",
    "65 as decimal, hex, octal and a char",
    65, 65, 65, 65));
    Of course all the simple printf options are supported:
    65 as decimal, hex, octal and a char: 65 41 101 A
    Result: 0
    > write(sprintf("%|*s\n",screen_width, "THE END"));
    THE END
    Result: 0
    > quit
    Exiting.

    SEE ALSO
    sscanf


    NAME
    sqrt - Square root

    SYNTAX
    float sqrt(float f);
    or
    int sqrt(int i);

    DESCRIPTION
    Returns the square root of f, or in the second case, the square root truncated to the closest lower integer.

    SEE ALSO
    pow, log, exp and floor


    NAME
    strerror - return a string describing an error

    SYNTAX
    string strerror(int errno);

    DESCRIPTION
    This function returns a description of an error code. The error code is usually obtained from the file->errno() call.

    NOTA BENE
    This function may not be available on all platforms.


    NAME
    stringp - is the argument a string?

    SYNTAX
    int stringp(mixed arg);

    DESCRIPTION
    Returns 1 if arg is a string, zero otherwise.

    SEE ALSO
    intp, multisetp, arrayp, programp, objectp, mappingp, floatp and functionp


    NAME
    strlen - Return the length of a string

    SYNTAX
    int strlen(string s);

    DESCRIPTION
    This function is equal to sizeof.

    SEE ALSO
    sizeof


    NAME
    tan - Trigonometrical tangent

    SYNTAX
    float tan(float f);

    DESCRIPTION
    Returns the tangent value for f.

    SEE ALSO
    atan, sin and cos


    NAME
    this_object - return the object we are evaluating in currently

    SYNTAX
    object this_object();

    DESCRIPTION
    This function returns the object we are currently evaluating in.


    NAME
    throw - throw a value to catch or global error handling

    SYNTAX
    void throw(mixed value);

    DESCRIPTION
    This function throws a value to a waiting catch. If no catch is waiting global error handling will send the value to handle_error in the master object. If you throw an array with where the first index contains an error message and the second index is a backtrace, (the output from backtrace() that is) then it will be treated exactly like a real error by overlying functions.

    SEE ALSO
    catch


    NAME
    time - return the current time

    SYNTAX
    int time();
    or
    int time(1);

    DESCRIPTION
    This function returns the number of seconds since 1 Jan 1970. The function ctime() converts this integer to a readable string.

    The second syntax does not call the system call time() as often, but is only updated in the backed. (when Pike code isn't running)

    SEE ALSO
    time


    NAME
    trace - change debug trace level

    SYNTAX
    int trace(int t);

    DESCRIPTION
    This function affects the debug trace level. (also set by the -t command line option) The old level is returned. Trace level 1 or higher means that calls to Pike functions are printed to stderr, level 2 or higher means calls to builtin functions are printed, 3 means every opcode interpreted is printed, 4 means arguments to these opcodes are printed as well. See the command lines options for more information


    NAME
    typeof - check return type of expression

    SYNTAX
    typeof ( expression )

    DESCRIPTION
    This is a not really a function even if it looks like it, it returns a human readable (almost) representation of the type that the expression would return without actually evaluating it. The representation is in the form of a string.

    EXAMPLE
    > typeof(`sizeof);
    Result: function(object | mapping | array | multiset | string : int)
    > typeof(sizeof(({})));
    Result: int
    >


    NAME
    ualarm - set an alarm clock for delivery of a signal

    SYNTAX
    int ualarm(int useconds);

    DESCRIPTION
    ualarm arranges for a SIGALRM signal to be delivered to the process in useconds micro seconds.

    If useconds is zero, no new alarm is scheduled.

    In any event any previously set alarm is canceled.

    RETURN VALUE
    ualarm returns the number of microseconds seconds remaining
    until any previously scheduled alarm was due to be delivered, or
    zero if there was no previously scheduled alarm.

    SEE ALSO
    signal


    NAME
    upper_case - convert a string to upper case

    SYNTAX
    string upper_case(string s);

    DESCRIPTION
    Returns a copy of the string s with all lower case character converted to upper case character.

    SEE ALSO
    lower_case


    NAME
    values - return an array of all possible values from indexing

    SYNTAX
    mixed *values(string|multiset|mapping|array|object foo);

    DESCRIPTION
    Values return an array of all values you can get when indexing the value foo. For strings, an array of int with the ascii values of the characters in the string is returned. For a multiset, an array filled with ones is return. For mappings, objects and arrays, the returned array may contain any kind of value.

    SEE ALSO
    indices


    NAME
    version - return version info

    SYNTAX
    string version();

    DESCRIPTION
    This function returns a brief information about the Pike version.

    EXAMPLE
    > version();
    Result: Pike v0.3


    NAME
    write - write text to stdout

    SYNTAX
    int write(string text);

    DESCRIPTION
    Added by the master, it directly calls write in a Stdio.stdout.

    SEE ALSO
    Stdio.werror


    NAME
    zero_type - return the type of zero

    SYNTAX
    int zero_type(mixed a);

    DESCRIPTION
    There are many types of zeros out there, or at least there are two. One is returned by normal functions, and one returned by mapping lookups and find_call_out() when what you looked for wasn't there. The only way to separate these two kinds of zeros is zero_type. When doing a find_call_out or mapping lookup, zero_type on this value will return 1 if there was no such thing present in the mapping, or no such call_out could be found. If the argument to zero_type is a destructed object or a function in a destructed object, 2 will be returned. Otherwise zero_type will return zero.

    If the argument is not an int, zero will be returned.

    SEE ALSO
    find_call_out

    Appendix A, Terms and jargon

    HTTP
    Hyper-Text Transfer Protocol, the protocol used by WWW to transfer HTML from the server to the client. Based on TCP.
    WWW
    World Wide Web, popularly known as 'the Internet' :)
    TCP
    Transmission Control Protocol, the Internet standard for computer communication
    ASCII
    American Standard Code for Information Interchange. Standard set by the American Standards Authority for encoding English letters, numbers , some symbols and control characters in 7 bits. There are also some "semi-standard" systems which add other characters by using 8 bits, which are also loosely called ASCII.
    UNIX
    A group of operating systems. Some noteworthy Unixes are: Solaris, Linux, HP-UX, Digital Unix, SunOs, BSD and Unixware.
    clone
    To create an object from a program. Or to use C++ jargon: to instantiate a class.
    command line
    The line you write to execute a program
    command line option
    The words after the program name on the command line.
    constant
    1) A value written directly in the code, such as 1 or "foo". 2) A value defined with add_constant.
    identifier
    The name of a variable, function, class or constant.
    interpreter
    An interpreter interprets byte-code instruction by instruction. In this context 'the interpreter' is usually the Pike binary.
    iteration
    Iteration is when the program is executing a loop. Each time the loop is called is also called one iteration.
    object
    An object is what you get if you call a program. Objects contain variables and a reference to the program from which they were cloned. Same as 'instance' in C++.
    program
    1) An executable file 2) A builtin Pike data type. Programs are almost the same as classes in C++ and contain the actual compiled code.
    recursion
    Recursion is an alternative to iteration. Recursion occurs when a function calls itself.
    stderr
    Standard error. The error channel. This is where errors are supposed to be written. It is usually the screen, but can be redirected to a file or another program. See the manual page for sh(1) for more details.
    stdin
    Standard input. Usually the keyboard, but can also be from a file or another program. See the manual page for sh(1) for more details.
    stdout
    Standard output. This is usually the screen but can be redirected to a file or another program. See the manual page for sh(1) for more details.

    Appendix B, Register program

    Here is a complete listing of the example program from chapter 2.
    #!/usr/local/bin/pike

    mapping records(string:array(string)) = ([
        "Star Wars Trilogy" : ({
            "Fox Fanfare",
            "Main Title",
            "Princess Leia's Theme",
            "Here They Come",
            "The Asteroid Field",
            "Yoda's Theme",
            "The Imperial March",
            "Parade of th Ewoks",
            "Luke and Leia",
            "Fight with Tie Fighters",
            "Jabba the Hut",
            "Darth Vader's Death",
            "The Forest Battle",
            "Finale",
        })
    ]);

    void list_records()
    {
        int i;
        array(string) record_names=sort(indices(records));

        write("Records:\n");
        for(i=0;i<sizeof(record_names);i++)
            write(sprintf("%3d: %s\n", i+1, record_names[i]));
    }

    void show_record(int num)
    {
        int i;
        array(string) record_names=sort(indices(records));
        string name=record_names[num-1];
        string songs=records[name];
        
        write(sprintf("Record %d, %s\n",num,name));
        for(i=0;i<sizeof(songs);i++)
            write(sprintf("%3d: %s\n", i+1, songs[i]));
    }

    void add_record()
    {
        string record_name=readline("Record name: ");
        records[record_name]=({});
        write("Input song names, one per line. End with '.' on its own line.\n");
        while(1)
        {
            string song;
            song=readline(sprintf("Song %2d: ",sizeof(records[record_name])+1));
            if(song==".") return;
            records[record_name]+=({song});
        }
    }

    void save(string file_name)
    {
        string name, song;
        object o;
        o=Stdio.File();

        if(!o->open(file_name,"wct"))
        {
            write("Failed to open file.\n");
            return;
        }

        foreach(indices(records),name)
        {
            o->write("Record: "+name+"\n");
            foreach(records[name],song)
                o->write("Song: "+song+"\n");
        }

        o->close();
    }

    void load(string file_name)
    {
        object o;
        string name="ERROR";
        string file_contents,line;

        o=Stdio.File();
        if(!o->open(file_name,"r"))
        {
            write("Failed to open file.\n");
            return;
        }

        file_contents=o->read();
        o->close();

        records=([]);

        foreach(file_contents/"\n",line)
        {
            string cmd, arg;
            if(sscanf(line,"%s: %s",cmd,arg))
            {
                switch(lower_case(cmd))
                {
                    case "record":
                        name=arg;
                        records[name]=({});
                        break;

                    case "song":
                        records[name]+=({arg});
                        break;
                }
            }
        }
    }

    void delete_record(int num)
    {
        array(string) record_names=sort(indices(records));
        string name=record_names[num-1];

        m_delete(records,name);
    }

    void find_song(string title)
    {
        string name, song;
        int hits;

        title=lower_case(title);

        foreach(indices(records),name)
        {
            foreach(records[name],song)
            {
                if(search(lower_case(song), title) != -1)
                {
                    write(name+"; "+song+"\n");
                    hits++;
                }
            }
        }

        if(!hits) write("Not found.\n");
    }

    int main(int argc, array(string) argv)
    {
        string cmd;
        while(cmd=readline("Command: "))
        {
            string args;
            sscanf(cmd,"%s %s",cmd,args);

            switch(cmd)
            {
                case "list":
                    if((int)args)
                    {
                        show_record((int)args);
                    }else{
                        list_records();
                    }
                    break;

                case "quit":
                 exit(0);

                case "add":
                    add_record();
                    break;

                case "save":
                    save(args);
                    break;

                case "load":
                    load(args);
                    break;

                case "delete":
                    delete_record((int)args);
                    break;

                case "search":
                    find_song(args);
                    break;
            }
        }
    }

    Appendix C, Reserved words

    These are words that have special meaning in Pike and can not be used as variable or function names.

    array break case catch continue default do else float for foreach function gauge if inherit inline int lambda mapping mixed multiset nomask object predef private program protected public return sscanf static string switch typeof varargs void while

    Appendix D, BNF for Pike

    BNF is short for "Backus Naur Form". It is a precise way of describing syntax. This is the BNF for Pike:
    program::={ definition }
    definition::=import | inheritance | function_declaration | function_definition | variables | constant | class_def
    import::=modifiers import constant_identifier ";"
    inheritance::=modifiers inherit program_specifier [ ":" identifier ] ";"
    function_declaration::=modifiers type identifier "(" arguments ")" ";"
    function_definition::=modifiers type identifier "(" arguments ")" block
    variables::=modifiers type variable_names ";"
    variable_names::=variable_name { "," variable_name }
    variable_name::={ "*" } identifier [ "=" expression2 ]
    constant::=modifiers constant constant_names ";"
    constant_names::=constant_name { "," constant_name }
    constant_name::=identifier "=" expression2
    class_def::=modifiers class [ ";" ]
    class::=class [ identifier ] "{" program "}"
    modifiers::= { static | private | nomask | public | protected | inline }
    block::="{" { statement } "}"
    statement::=expression2 ";" | cond | while | do_while | for | switch | case | default | return | block | foreach | break | continue | ";"
    cond::=if statement [ else statement ]
    while::=while "(" expression ")" statement
    do_while::=do statement while "(" expression ")" ";"
    for::=for "(" [ expression ] ";" [ expression ] ";" [ expression ] ")" statement
    switch::=switch "(" expression ")" block
    case::=case expression [ ".." expression ] ":"
    default::=default ":"
    foreach::=foreach "(" expression ":" expression6 ")" statement
    break::=break ";"
    continue::=continue ";"
    expression::=expression2 { "," expression2 }
    expression2::={ lvalue ( "=" | "+=" | "*=" | "/=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "%=" ) } expression3
    expression3::=expression4 '?' expression3 ":" expression3
    expression4::={ expression5 ( "||" | "&&" | "|" | "^" | "&" | "==" | "!=" | ">" | "<" | ">=" | "<=" | "<<" | ">>" | "+" | "*" | "/" | "%" ) } expression5
    expression5::=expression6 | "(" type ")" expression5 | "--" expression6 | "++" expression6 | expression6 "--" | expression6 "++" | "~" expression5 | "-" expression5
    expression6::=string | number | float | catch | gauge | typeof | sscanf | lambda | class | constant_identifier | call | index | mapping | multiset | array | parenthesis | arrow
    number::=digit { digit } | "0x" { digits } | "'" character "'"
    float::=digit { digit } "." { digit }
    catch::=catch ( "(" expression ")" | block )
    gauge::=gauge ( "(" expression ")" | block )
    sscanf::=sscanf "(" expression2 "," expression2 { "," lvalue } ")"
    lvalue::=lambda expression6 | type identifier
    lambda::=lambda "(" arguments ")" block
    constant_identifier::=identifier { "." identifier }
    call::=expression6 "(" expression_list ")"
    index::=expression6 "[" expression [ ".." expression ] "]"
    array::="({" expression_list "})"
    multiset::="(<" expression_list ">)"
    mapping::="([" [ expression : expression { "," expression ":" expression } ] [ "," ] "])"
    arrow::=expression6 "->" identifier
    parenthesis::="(" expression ")"
    expression_list::= [ splice_expression { "," splice_expression } ] [ "," ]
    splice_expression::=[ "@" ] expression2
    type::= ( int | string | float | program | object [ "(" program_specifier ")" ] | mapping [ "(" type ":" type ")" | array [ "(" type ")" ] | multiset [ "(" type ")" ] | function [ function_type ] ) { "*" }
    function_type::="(" [ type { "," type } [ "..." ] ")"
    arguments::=[ argument { "," argument } ] [","]
    argument::=type [ "..." ] [ identifier ]
    program_specifier::=string_constant | constant_identifier
    string::=string_literal { string_literal }
    identifier::=letter { letter | digit } | "`+" | "`/" | "`%" | "`*" | "`&" | "`|" | "`^" | "`~" | "`<" | "`<<" | "`<=" | "`>" | "`>>" | "`>=" | "`==" | "`!=" | "`!" | "`()" | "`-" | "`->" | "`->=" | "`[]" | "`[]="
    letter::="a"-"z" | "A"-"Z" | "_"
    digit::="0"-"9"

    Appendix E, How to install Pike

    To install Pike, you need a C compiler, a couple of Mb of disk space, the source for Pike, and a bit of patience. The latest version of Pike is always available from
    the Pike home page. Lists of mirror sites and binary releases should also be available there. Pike should compile and install nicely on almost any UNIX platform. It has been tested on the following: After obtaining the Pike source you need to unpack it. To unpack Pike you need gzip, which is available from any GNU mirror site. You also need tar, which is a part of UNIX. If you got Pike-v0.5.tar.gz, simply unpack it by typing:
    	$ gunzip -d Pike-v0.5.tar.gz
    	$ tar xvf Pike-v0.5.tar
    
    Now you have a directory called Pike-v0.5. Please read the README file in the new directory since newer versions can contain information not available at the time this book was written.

    Now, to compile Pike, the following three commands should be enough.

    	$ cd Pike-v0.5/src
    	$ ./configure --prefix=/dir/to/install/pike
    	$ make
    
    They will (in order) change directory to the source directory. Configure will then find out what features are available on your system and construct makefiles. You will see a lot of output after you run configure. Do not worry, that is normal. It is usually not a good idea to install Pike anywhere but in /usr/local (the default) since Pike scripts written by other people will usually assume that's where Pike is. However, if you do not have write access to /usr/local you will have to install Pike somewhere else on your system.

    After that make will actually compile the program. After compilation it is a good idea to do make verify to make sure that Pike is 100% compatible with your system. Make verify will take a while to run and use a lot of CPU, but it is worth it to see that your compilation was successful. After doing that you should run make install to install the Pike binaries, libraries and include files in the directory you selected earlier.

    You are now ready to use Pike.

    Index

    `

    `&
    Image.image.`&
    `*
    Image.colortable.`*
    Image.image.`*
    `+
    Image.colortable.`+
    Image.image.`+
    `-
    Image.colortable.`-
    Image.image.`-
    ``*
    Image.colortable.``*
    `|
    Image.image.`|

    A

    acos
    add
    Image.colortable.add
    add_constant
    add_efun
    Simulate.add_efun
    add_include_path
    add_layers
    Image.image.add_layers
    add_module_path
    add_program_path
    aggregate
    aggregate_list
    Simulate.aggregate_list
    aggregate_mapping
    aggregate_multiset
    alarm
    all
    Yp.YpDomain.all
    Yp.YpMap.all
    all_constants
    all_efuns
    Simulate.all_efuns
    allocate
    apply_matrix
    Image.image.apply_matrix
    Array
    filter
    map
    search_array
    sort_array
    sum_arrays
    uniq
    arrayp
    asin
    atan
    autocrop
    Image.image.autocrop

    B

    backtrace
    baseline
    Image.font.baseline
    bind
    Yp.YpDomain.bind
    body_parts
    MIME.Message.body_parts
    boundary
    MIME.Message.boundary
    box
    Image.image.box
    broadcast
    Thread.Condition.broadcast

    C

    call_function
    call_out
    call_out_info
    capitalize
    String.capitalize
    cast
    Gmp.mpz.cast
    Image.colortable.cast
    Image.image.cast
    MIME.Message.cast
    catch
    cd
    ceil
    change_color
    Image.image.change_color
    charset
    MIME.Message.charset
    chroot
    circle
    Image.image.circle
    clear
    Image.image.clear
    clone
    Image.image.clone
    close
    Gdbm.close
    color
    Image.image.color
    colortable
    Image.colortable
    column
    combine_path
    compile_file
    compile_string
    Condition
    Thread.Condition
    copy
    Image.image.copy
    copy_value
    cos
    create
    Gdbm.create
    Gmp.mpz.create
    Gz.deflate.create
    Gz.inflate.create
    Image.colortable.create
    Image.image.create
    MIME.Message.create
    Regexp.create
    Thread.Fifo.create
    crypt
    ctime
    cubicles
    Image.colortable.cubicles

    D

    dct
    Image.image.dct
    decode
    Image.PNM.decode
    MIME.decode
    decode_base64
    MIME.decode_base64
    decode_qp
    MIME.decode_qp
    decode_uue
    MIME.decode_uue
    decode_value
    decode_word
    MIME.decode_word
    default_yp_domain
    Yp.default_yp_domain
    define
    deflate
    Gz.deflate
    Gz.deflate.deflate
    delete
    Gdbm.delete
    describe_backtrace
    destruct
    digits
    Gmp.mpz.digits
    disp_params
    MIME.Message.disp_params
    disposition
    MIME.Message.disposition
    distancesq
    Image.image.distancesq
    _do_call_outs

    E

    else
    elseif
    encode
    Image.GIF.encode
    Image.PNM.encode
    MIME.encode
    encode_base64
    MIME.encode_base64
    encode_binary
    Image.PNM.encode_binary
    encode_P6
    Image.PNM.encode_P6
    encode_qp
    MIME.encode_qp
    encode_trans
    Image.GIF.encode_trans
    encode_uue
    MIME.encode_uue
    encode_value
    encode_word
    MIME.encode_word
    end_block
    Image.GIF.end_block
    endif
    equal
    errno
    error
    exceptions
    exec
    Process.exec
    exece
    exit
    exp
    explode
    Simulate.explode

    F

    fetch
    Gdbm.fetch
    Fifo
    Thread.Fifo
    file_stat
    filter
    Array.filter
    filter_array
    Simulate.filter_array
    find_all_options
    Getopt.find_all_options
    find_call_out
    find_option
    Getopt.find_option
    firstkey
    Gdbm.firstkey
    floatp
    floor
    floyd_steinberg
    Image.colortable.floyd_steinberg
    font
    Image.font
    fork
    frompnm
    Image.image.frompnm
    fromppm
    Image.image.fromppm
    full
    Image.colortable.full
    function_name
    function_object
    functionp

    G

    gauge
    gc
    gcd
    Gmp.mpz.gcd
    _gce_block
    Image.GIF._gce_block
    Gdbm
    close
    create
    delete
    fetch
    firstkey
    nextkey
    reorganize
    store
    sync
    generate_boundary
    MIME.generate_boundary
    get_args
    Getopt.get_args
    get_dir
    get_filename
    MIME.Message.get_filename
    get_function
    Simulate.get_function
    getcwd
    getdata
    MIME.Message.getdata
    getegid
    getencoded
    MIME.Message.getencoded
    getenv
    geteuid
    getgid
    gethostbyaddr
    gethostbyname
    gethostname
    Getopt
    find_all_options
    find_option
    get_args
    getpgrp
    getpid
    getpixel
    Image.image.getpixel
    getppid
    getuid
    GIF
    Image.GIF
    gif_add
    Image.image.gif_add
    gif_add*
    Image.image.gif_add*
    gif_add_fs
    Image.image.gif_add_fs
    gif_add_fs_nomap
    Image.image.gif_add_fs_nomap
    gif_add_nomap
    Image.image.gif_add_nomap
    gif_begin
    Image.image.gif_begin
    gif_end
    Image.image.gif_end
    gif_netscape_loop
    Image.image.gif_netscape_loop
    glob
    Gmp
    mpz
    cast
    create
    digits
    gcd
    powm
    probably_prime_p
    size
    sqrt
    grey
    Image.image.grey
    guess_subtype
    MIME.guess_subtype
    Gz
    deflate
    create
    deflate
    inflate
    create
    inflate

    H

    hardlink
    hash
    header_block
    Image.GIF.header_block
    headers
    MIME.Message.headers
    height
    Image.font.height
    hsv_to_rgb
    Image.image.hsv_to_rgb

    I

    if
    image
    Image.image
    Image
    colortable
    `*
    `+
    `-
    ``*
    add
    cast
    create
    cubicles
    floyd_steinberg
    full
    map
    nodither
    ordered
    randomcube
    randomgrey
    reduce
    spacefactors
    font
    baseline
    height
    load
    set_xspacing_scale
    set_yspacing_scale
    text_extents
    write
    GIF
    encode
    encode_trans
    end_block
    _gce_block
    header_block
    netscape_loop_block
    render_block
    _render_block
    image
    `&
    `*
    `+
    `-
    `|
    add_layers
    apply_matrix
    autocrop
    box
    cast
    change_color
    circle
    clear
    clone
    color
    copy
    create
    dct
    distancesq
    frompnm
    fromppm
    getpixel
    gif_add
    gif_add*
    gif_add_fs
    gif_add_fs_nomap
    gif_add_nomap
    gif_begin
    gif_end
    gif_netscape_loop
    grey
    hsv_to_rgb
    invert
    line
    map_closest
    map_fast
    map_fs
    mirrorx
    mirrory
    modify_by_intensity
    noise
    paste
    paste_alpha
    paste_alpha_color
    paste_mask
    polyfill
    read_lsb_grey
    read_lsb_rgb
    rgb_to_hsv
    rotate
    rotate_ccw
    rotate_cw
    rotate_expand
    scale
    select_colors
    select_from
    setcolor
    setpixel
    skewx
    skewx_expand
    skewy
    skewy_expand
    threshold
    togif
    togif_fs
    toppm
    tuned_box
    turbulence
    write_lsb_grey
    write_lsb_rgb
    xsize
    ysize
    PNM
    decode
    encode
    encode_binary
    encode_P6
    implode
    Simulate.implode
    implode_nicely
    String.implode_nicely
    include
    index
    _indices
    Yp.YpMap._indices
    indices
    inflate
    Gz.inflate
    Gz.inflate.inflate
    initgroups
    intp
    invert
    Image.image.invert
    is_partial
    MIME.Message.is_partial

    K

    kill

    L

    l_sizeof
    Simulate.l_sizeof
    line
    Image.image.line
    listp
    Simulate.listp
    load
    Image.font.load
    load_module
    localtime
    lock
    Thread.Mutex.lock
    log
    lower_case

    M

    m_delete
    m_indices
    Simulate.m_indices
    m_sizeof
    Simulate.m_sizeof
    m_values
    Simulate.m_values
    map
    Array.map
    Image.colortable.map
    Yp.YpDomain.map
    Yp.YpMap.map
    map_array
    Simulate.map_array
    map_closest
    Image.image.map_closest
    map_fast
    Image.image.map_fast
    map_fs
    Image.image.map_fs
    map_regexp
    Simulate.map_regexp
    mappingp
    master
    match
    Regexp.match
    Yp.YpDomain.match
    Yp.YpMap.match
    member_array
    Simulate.member_array
    _memory_usage
    MIME
    decode
    decode_base64
    decode_qp
    decode_uue
    decode_word
    encode
    encode_base64
    encode_qp
    encode_uue
    encode_word
    generate_boundary
    guess_subtype
    Message
    body_parts
    boundary
    cast
    charset
    create
    disp_params
    disposition
    get_filename
    getdata
    getencoded
    headers
    is_partial
    params
    setboundary
    setcharset
    setdata
    setdisp_param
    setencoding
    setparam
    subtype
    transfer_encoding
    type
    parse_headers
    quote
    reconstruct_partial
    tokenize
    mirrorx
    Image.image.mirrorx
    mirrory
    Image.image.mirrory
    mkdir
    mklist
    Simulate.mklist
    mkmapping
    mkmultiset
    mktime
    modify_by_intensity
    Image.image.modify_by_intensity
    mpz
    Gmp.mpz
    multisetp
    Mutex
    Thread.Mutex
    mv

    N

    netscape_loop_block
    Image.GIF.netscape_loop_block
    new
    _next
    next_object
    nextkey
    Gdbm.nextkey
    nodither
    Image.colortable.nodither
    noise
    Image.image.noise

    O

    object_program
    objectp
    openlog
    order
    Yp.YpDomain.order
    Yp.YpMap.order
    ordered
    Image.colortable.ordered

    P

    params
    MIME.Message.params
    parse_headers
    MIME.parse_headers
    paste
    Image.image.paste
    paste_alpha
    Image.image.paste_alpha
    paste_alpha_color
    Image.image.paste_alpha_color
    paste_mask
    Image.image.paste_mask
    PI
    Simulate.PI
    PNM
    Image.PNM
    polyfill
    Image.image.polyfill
    popen
    Process.popen
    pow
    powm
    Gmp.mpz.powm
    pragma
    preprocessor
    _prev
    previous_object
    Simulate.previous_object
    probably_prime_p
    Gmp.mpz.probably_prime_p
    Process
    exec
    popen
    spawn
    system
    programp
    putenv

    Q

    query_host_name
    Simulate.query_host_name
    query_num_arg
    Queue
    Thread.Queue
    quote
    MIME.quote

    R

    random
    random_seed
    randomcube
    Image.colortable.randomcube
    randomgrey
    Image.colortable.randomgrey
    read
    Thread.Fifo.read
    Thread.Queue.read
    read_lsb_grey
    Image.image.read_lsb_grey
    read_lsb_rgb
    Image.image.read_lsb_rgb
    readlink
    reconstruct_partial
    MIME.reconstruct_partial
    reduce
    Image.colortable.reduce
    _refs
    Regexp
    create
    match
    split
    remove_call_out
    remove_include_path
    remove_module_path
    remove_program_path
    render_block
    Image.GIF.render_block
    _render_block
    Image.GIF._render_block
    reorganize
    Gdbm.reorganize
    replace
    replace_master
    reverse
    rgb_to_hsv
    Image.image.rgb_to_hsv
    rm
    rotate
    Image.image.rotate
    rotate_ccw
    Image.image.rotate_ccw
    rotate_cw
    Image.image.rotate_cw
    rotate_expand
    Image.image.rotate_expand
    rows
    rusage

    S

    scale
    Image.image.scale
    search
    search_array
    Array.search_array
    select_colors
    Image.image.select_colors
    select_from
    Image.image.select_from
    server
    Yp.YpDomain.server
    Yp.YpMap.server
    set_xspacing_scale
    Image.font.set_xspacing_scale
    set_yspacing_scale
    Image.font.set_yspacing_scale
    setboundary
    MIME.Message.setboundary
    setcharset
    MIME.Message.setcharset
    setcolor
    Image.image.setcolor
    setdata
    MIME.Message.setdata
    setdisp_param
    MIME.Message.setdisp_param
    setegid
    setencoding
    MIME.Message.setencoding
    seteuid
    setgid
    setparam
    MIME.Message.setparam
    setpixel
    Image.image.setpixel
    setuid
    signal
    Thread.Condition.signal
    signame
    signum
    Simulate
    add_efun
    aggregate_list
    all_efuns
    explode
    filter_array
    get_function
    implode
    l_sizeof
    listp
    m_indices
    m_sizeof
    m_values
    map_array
    map_regexp
    member_array
    mklist
    PI
    previous_object
    query_host_name
    strstr
    sum
    this_function
    sin
    size
    Gmp.mpz.size
    Thread.Fifo.size
    Thread.Queue.size
    _sizeof
    Yp.YpMap._sizeof
    sizeof
    skewx
    Image.image.skewx
    skewx_expand
    Image.image.skewx_expand
    skewy
    Image.image.skewy
    skewy_expand
    Image.image.skewy_expand
    sleep
    sort
    sort_array
    Array.sort_array
    spacefactors
    Image.colortable.spacefactors
    spawn
    Process.spawn
    split
    Regexp.split
    sprintf
    sqrt
    Gmp.mpz.sqrt
    sscanf
    stderr
    Stdio.stderr
    stdin
    Stdio.stdin
    Stdio
    stderr
    stdin
    stdout
    stdout
    Stdio.stdout
    store
    Gdbm.store
    strerror
    String
    capitalize
    implode_nicely
    strmult
    stringp
    strlen
    strmult
    String.strmult
    strstr
    Simulate.strstr
    subtype
    MIME.Message.subtype
    sum
    Simulate.sum
    sum_arrays
    Array.sum_arrays
    symlink
    sync
    Gdbm.sync
    system
    Process.system
    System

    T

    table-of-contents
    tan
    text_extents
    Image.font.text_extents
    this_function
    Simulate.this_function
    this_object
    Thread
    Condition
    broadcast
    signal
    wait
    Fifo
    create
    read
    size
    write
    Mutex
    lock
    trylock
    Queue
    read
    size
    write
    threshold
    Image.image.threshold
    throw
    time
    togif
    Image.image.togif
    togif_fs
    Image.image.togif_fs
    tokenize
    MIME.tokenize
    toppm
    Image.image.toppm
    trace
    transfer_encoding
    MIME.Message.transfer_encoding
    trylock
    Thread.Mutex.trylock
    tuned_box
    Image.image.tuned_box
    turbulence
    Image.image.turbulence
    type
    MIME.Message.type
    typeof

    U

    ualarm
    uLPC
    uname
    undef
    uniq
    Array.uniq
    upper_case

    V

    _values
    Yp.YpMap._values
    values
    _verify_internals
    version

    W

    wait
    Thread.Condition.wait
    write
    Image.font.write
    Thread.Fifo.write
    Thread.Queue.write
    write_lsb_grey
    Image.image.write_lsb_grey
    write_lsb_rgb
    Image.image.write_lsb_rgb

    X

    xsize
    Image.image.xsize

    Y

    Yp
    default_yp_domain
    YpDomain
    all
    bind
    map
    match
    order
    server
    YpMap
    all
    _indices
    map
    match
    order
    server
    _sizeof
    _values
    YpDomain
    Yp.YpDomain
    YpMap
    Yp.YpMap
    ysize
    Image.image.ysize

    Z

    zero_type