Select Git revision
-
Fredrik Hübinette (Hubbe) authored
Rev: src/global.h:1.22 Rev: src/interpret.c:1.81 Rev: src/language.yacc:1.96 Rev: src/las.c:1.62 Rev: src/lex.c:1.53 Rev: src/peep.c:1.24 Rev: src/peep.in:1.15 Rev: src/testsuite.in:1.105
Fredrik Hübinette (Hubbe) authoredRev: src/global.h:1.22 Rev: src/interpret.c:1.81 Rev: src/language.yacc:1.96 Rev: src/las.c:1.62 Rev: src/lex.c:1.53 Rev: src/peep.c:1.24 Rev: src/peep.in:1.15 Rev: src/testsuite.in:1.105
tutorial.wmml 443.63 KiB
<!--
<head>
<title>Pike tutorial</title>
</head>
-->
<!--
TODO: Add a section about casts
-->
<firstpage>
<p>
<center>
<h1>
Programming, using and understanding
<p>
<img src=pike.gif>
<p>
<font size=+7>Pike</font>
<p>
</h1>
<h2>by Fredrik Hübinette</h2>
</center>
</firstpage>
<preface title="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 it 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
<a href="http://www.emit.com.pl/ian.html">Ian Carr-de Avelon</a> and
<a href="mailto:hedda@idonix.se">Henrik Wallin</a>
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.
</preface>
<table-of-contents title="Table of contents">
<introduction title="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.
<section title="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.
<p>
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.
<!-- FIXME (finish this overview) -->
</section>
<anchor name=uLPC>
<section title="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.
<p>
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.
</section>
</anchor>
<section title="A comparison with other languages">
<dl>
<dt> Python
<dd> 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.
<dt> C++
<dd> 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++.
<dt> Lisp and Scheme
<dd> Internally Pike has a lot in common with simple interpreted Lisp and
Scheme implementations. They are all stack based, byte-compiled,
interpreted languages. Pike is also
a 'one-cell' language, just like Scheme.
<dt> Pascal
<dd> Pike has nothing in common with Pascal.
<dt> Tcl/Tk
<dd> 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.
<!-- The idea from the beginning was similar but the implementation is very different.-->
</dl>
</section>
<section title="What is Pike">
Pike is:
<ul>
<li> A programming language
<li> Object oriented
<li> Interpreted
<li> Fast
<li> Dynamic
<li> High-level
<li> similar to C++
<li> easy to extend
<li> (a fish)
</ul>
Pike has:
<ul>
<li> Garbage collection
<li> Advanced string functions
<li> 6 years of development behind it
<li> Advanced data types such as associative arrays
<li> Support for bignums
<li> Builtin socket support
</ul>
</section>
<section title="How to read this manual">
This manual uses a couple of different typefaces to describe different
things:
<dl>
<dt><i>italics</i>
<dd>Italics is used as a placeholder for other things. If it says <i>a word</i>
in the text it means that you should put your own word there.
<dt><b>bold</b>
<dd>Bold is just used to emphasize that this word is not merely what it sounds
like. It is actually a <b>term</b>.
<dt><tt>fixed size</tt>
<dd>Fixed size is used to for examples and text directly from the computer.
</dl>
Also, please beware that the word <b>program</b> is also a builtin Pike
data type.
</section>
</introduction>
<chapter title="Getting started">
<p>
First you need to have Pike installed on your computer. See <ref to=install>
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.
<p>
<section title="Your first Pike program">
<example language=pike>
int main()
{
write("hello world\n");
return 0;
}
</example>
Let's call this file hello_world.pike, and then we try to run it:
<p>
<pre>
$ pike hello_world.pike
hello world
$
</pre>
Pretty simple, Let's see what everything means:
<example language=pike>
int main()
</example>
This begins the function <tt>main</tt>. Before the function name the type of value
it returns is declared, in this case <tt>int</tt> 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 <tt>main</tt> 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 <i>name</i> of the function, the <i>parameters</i>, 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 <tt>main</tt>;
<p>
<example language=pike>
{
write("hello world\n");
return 0;
}
</example>
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.
<p>
<example language=pike>
write("hello world\n");
</example>
The first statement is a call to the builtin function <tt>write</tt>. This will
execute the code in the function <tt>write</tt> with the arguments as input data.
In this case, the constant string <tt>hello world\n</tt> is sent.
Well, not quite. The <tt>\n</tt> combination corresponds to the newline
character.
<tt>write</tt> then writes this string to stdout when executed. Stdout is the standard Unix output channel, usually the screen.
<p>
<example language=pike>
return 0;
</example>
This statement exits the function and returns the value zero. Any statements
following the return statements will not be executed.
<p>
</section>
<section title="Improving hello_world.pike">
Typing <tt>pike hello_world.pike</tt> 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:
<p>
<example language=pike>
#!/usr/local/bin/pike
int main()
{
write("hello world\n");
return 0;
}
</example>
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:
<p>
<pre>
$ chmod +x hello_world.pike
$ ./hello_world.pike
hello world
$
</pre>
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.
<p>
</section>
<section title="Further improvements">
Now, wouldn't it be nice if it said <tt>Hello world!</tt> instead of <tt>hello world</tt> ?
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 <i>command line option</i> that will make it type the old
<tt>hello world</tt>. 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:
<p>
<example language=pike>
#!/usr/local/bin/pike
int main(int argc, array(string) argv)
{
if(argc > 1 && argv[1]=="--traditional")
{
write("hello world\n"); // old style
}else{
write("Hello world!\n"); // new style
}
return 0;
}
</example>
Let's run it:
<p>
<pre>
$ chmod +x hello_world.pike
$ ./hello_world.pike
Hello world!
$ ./hello_world.pike --traditional
hello world
$
</pre>
What is new in this version, then?
<example language=pike>
int main(int argc, array(string) argv)
</example>
In this version the space between the parenthesis has been filled.
What it means is that <tt>main</tt> now takes two arguments.
One is called <tt>argc</tt>, and is of the type <tt>int</tt>.
The other is called <tt>argv</tt> and is a an array of strings.
<p>
The arguments to <tt>main</tt> are taken from the command line when the
Pike program is executed. The first argument, <tt>argc</tt>, is how many
words were written on the command line (including the command itself) and
<tt>argv</tt> is an array formed by these words.
<p>
<example language=pike>
if(argc > 1 && argv[1] == "--traditional")
{
write("hello world\n"); // old style
}else{
write("Hello world!\n"); // new style
}
</example>
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:
<p>
<example language=pike>
argc > 1 && argv[1] == "--traditional"
</example>
Loosely translated, this means: argc is greater than one, and the second
element in the array argv is equal to the string <tt>--traditional</tt>. 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.
<p>
Also note the comments:
<p>
<example language=pike>
write("hello world\n"); // old style
</example>
The <tt>//</tt> begins a comment which continues to the end of the line.
Comments will be ignored 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, i.e. <tt>/* ... */</tt>, which can extend over several lines. The <tt>//</tt> comment only extends to the end of the line.
<p>
</section>
<section title="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 <b>control structures</b> to make Pike
execute pieces of code in more interesting orders than from top to bottom.
<p>
We have already seen an example of the <tt>if</tt> statement:
<example language=pike meta=expression,statement1,statement2>
if( expression )
statement1;
else
statement2;
</example>
<!-- FIXME: should if have a capital letter or not? -->
<tt>if</tt> simply evaluates the expression and if the result is true it
executes <i>statement1</i>, otherwise it executes <i>statement2</i>. If you have no need for
statement2 you can leave out the whole else<!-- FIXME: tt/italics --> part like this:
<example language=pike meta=expression,statement1>
if( expression )
statement1;
</example>
In this case <i>statement1</i> is evaluated if <i>expression</i> is true, otherwise
nothing is evaluated.
<p>
<b>Note for beginners: go back to our first example and make sure you
understand what <tt>if</tt> does.</b>
<p>
Another very simple control structure is the <tt>while</tt> statement:
<example language=pike meta=expression,statement>
while( expression )
statement;
</example>
This statement evaluates <i>expression</i> and if it is found to be true it
evaluates <i>statement</i>. After that it starts over and evaluates <i>expression</i>
again. This continues until <i>expression</i> is no longer true. This type of
control structure is called a <b>loop </b> and is fundamental to all
interesting programming.
<p>
</section>
<section title="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:
<example language=pike meta=modifiers,type,varname1,varname2,statements>
modifiers type name(type varname1, type varname2, ...)
{
statements
}
</example>
The <i>modifiers</i> are optional. See <ref to=modifiers> for more details about
modifiers. The <i>type </i> specifies what kind of data the function returns.
For example, the word <tt>int</tt> would signify that the function returns
an integer number. The <i>name </i> 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 <i> statements </i> between the brackets are the function
body. Those statements will be executed whenever the function is called.
<p>
<b>Example:</b>
<example language=pike>
int sqr(int x) { return x*x; }
</example>
This line defines a function called <tt>sqr</tt> to take one argument of the
type <tt>int</tt> and also returns an <tt>int</tt>. The code itself returns
the argument multiplied by itself. To call this function from somewhere in the code
you could simply put: <tt>sqr(17)</tt> and that would return the integer value
289.
<p>
As the example above shows, <tt>return</tt> is used to specify the
return value of a function. The value after <tt>return</tt> must be of the
type specified before the function name. If the function is specified to
return <tt>void</tt>, nothing at all should be written after <tt>return</tt>.
Note that when a return statement is executed, the function will finish
immediately. Any statements following the return will be ignored.
<p>
There are many more control structures, they will all be described in a
later chapter devoted only to control structures.
<p>
</section>
<section title="True and false">
Throughout this chapter the words <b>true</b> and <b>false</b> 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 explain in a later chapter.)
<p>
</section>
<section title="Data Types">
As you saw in our first examples we have to indicate the type of value returned by a function or contained in a variable. We used integers (<tt>int</tt>), strings (<tt>string</tt>), and arrays (with the * notation).
The others are <tt>mapping</tt>, <tt>mixed</tt>, <tt>void</tt>, <tt>float</tt>, <tt>multiset</tt>, <tt>function</tt>, <tt>object</tt> and <tt>program</tt>.
Neither <tt>mixed</tt> nor <tt>void</tt> are really types, <tt>void</tt> signifies that no value should be returned and <tt>mixed</tt> that the return value can be of any type, or that the variable can contain any type of value.
<tt>Function</tt>, <tt>object</tt> and <tt>program</tt> are all types related to object orientation. We will not discuss the last three in any great detail here,
<dl>
<dt>Int
<dd>The integer type stores a signed integer. It is 32 bit or 64 depending
on architecture.
<dt>Float
<dd>This variable type stores a floating point number.
<dt>Array
<dd>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:
<example language=pike>
arr=({1,2,3});
</example>
Or, if you have already created an array, you can change the values
in the array like this:
<example language=pike meta=arr,ind,data>
arr [ ind ] = data;
</example>
This sets entry number <i>ind</i> in the array <i>arr</i> to <i>data</i>.
<i>ind</i> 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 <tt>array</tt> in
front of the variable name we want:
<example language=pike>
array i;
</example>
We can also declare several array variables on the same line:
<example language=pike>
array i, j;
</example>
If we want to specify that the variable should hold an array of strings,
we would write:
<example language=pike>
array (string) i;
</example>
<dt>String
<dd>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:
<table>
<tr><td><li>\n</td><td>newline</td></tr>
<tr><td><li>\r</td><td>carriage return</td></tr>
<tr><td><li>\t</td><td>tab</td></tr>
<tr><td><li>\b</td><td>backspace</td></tr>
<tr><td><li>\"</td><td>" (quotation character)</td></tr>
<tr><td><li>\\</td><td>\ (literal backslash)</td></tr>
</table>
<dt>Mapping
<dd>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:
<example language=pike>
mapping(string:string) map=(["five":"good", "ten":"excellent"]);
</example>
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.
<dt>Multiset
<dd>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.
</dl>
</section>
</chapter>
<chapter title="A more elaborate example">
<!-- FIXME: explain things AFTER showing the code? -->
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.
<example language=pike>
#!/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"
})
]);
</example>
We want to be able to get a simple list of the records in our database. The function <tt>list_records</tt> just goes through the mapping <tt>records</tt> and puts the indices, i.e. the record names, in an array of strings, record_names. By using the builtin function <tt>sort</tt> 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 <tt>for</tt> 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 <tt>sizeof</tt> gives the number of items in an array. The printout is formatted through the use of <tt>sprintf</tt> which works more or less like the C function of the same name.
<example language=pike>
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]));
}
</example>
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 (<tt>num</tt>) we gave as an argument to this function. Next we put the songs of this record in the array <tt>songs</tt> and print the record name followed by the songs, each song on a separate line.
<example language=pike>
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]));
}
</example>
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.
<example language=pike>
int main(int argc, array (string) argv)
{
if(argc <= 1)
{
list_records();
} else {
show_record((int) argv[1]);
}
}
</example>
<section title="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 <tt>main()</tt> function to accept "commands".
<p>
<section title="add_record()">
Using the builtin function <tt>readline()</tt> we wait for input which will be put into the variable <tt>record_name</tt>. The argument to <tt>readline()</tt> 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 <tt>while</tt> to check whether we should continue inputting songs.
The <tt>while(1)</tt> means "loop forever", because 1 is always <b>true</b>.
This program does not in fact loop forever, because it uses <tt>return</tt>
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 <tt>+=</tt> operator. It is the same as saying
<tt>records[record_name]=records[record_name]+({song})</tt>.
<example language=pike>
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});
}
}
</example>
</section>
<section title="main()">
The main function now does not care about any command line arguments.
Instead we use <tt>readline()</tt> to prompt the user for instructions
and arguments. The available instructions are "add", "list" and "quit".
What you enter into the variables <tt>cmd</tt> and <tt>args</tt> is checked in the
<tt>switch()</tt> 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 <tt>switch()</tt> the argument (in this case <tt>cmd</tt>) is checked in the <tt>case</tt> statements. The first case where the expression equals <tt>cmd</tt> 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 as in 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 <tt>break</tt> instruction tells the program to jump out of the <tt>switch()</tt> block.
"add" of course turns control over to the function described above.
If the command given is "quit" the <tt>exit(0)</tt> statement stops the execution of the program and returns 0 (zero) to the operating system, telling it that everything was ok.
<example language=pike>
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;
}
}
}
</example>
</section>
</section>
<section title="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 <tt>Stdio.File</tt>.
To Pike, a program is a data type which contains code, functions and variables.
A program can be <i>cloned</i> which means that Pike creates a data area
in memory for the program, places a reference to the program in the data area, and initializes it to act on the data in question. The methods (i.e. functions in the object) and variables in the object Stdio.File enable us to perform actions on the associated data file.
The methods we need to use are open, read, write and close. See <ref to=io>
for more details. <!-- Does this link work? -->
<p>
<section title="save()">
First we clone a <tt>Stdio.File</tt> program to the object <tt>o</tt>.
Then we use it to open the file whose<!-- FIXME: which instead of 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, <tt>foreach</tt>, to go through the mapping <tt>records</tt> 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.<br>
Finally, remember to close the file.
<example language=pike>
void save(string file_name)
{
string name, song;
Stdio.File 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();
}
</example>
</section>
<section title="load()">
The <tt>load</tt> function begins much the same, except we open the file named <tt>file</tt> for reading instead.
When receiving data from the file we put it in the string <tt>file_contents</tt>.
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 <tt>file_contents</tt> 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 <tt>foreach</tt> statement we can take the string <tt>file_contents</tt> apart piece by piece, putting each piece back in its proper place in the mapping records.
<example language=pike>
void load(string file_name)
{
string name="ERROR";
string file_contents,line;
Stdio.File 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;
}
}
}
}
</example>
</section>
<section title="main() revisited">
<tt>main()</tt> 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.
<example language=pike>
case "save":
save(args);
break;
case "load":
load(args);
break;
</example>
<p>
</section>
</section>
<section title="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.
<p>
<section title="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 <tt>list_records</tt> function).
Then we find the name of the record of the number <tt>num</tt> and use the builtin function <tt>m_delete()</tt> to remove that entry from <tt>records</tt>.
<example language=pike>
void delete_record(int num)
{
array(string) record_names=sort(indices(records));
string name=record_names[num-1];
m_delete(records,name);
}
</example>
</section>
<section title="search()">
Searching for songs is quite easy too. To count the number of hits we declare the variable <tt>hits</tt>. 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 <tt>search()</tt>, 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 <tt>search()</tt> 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.
<example language=pike>
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");
}
</example>
</section>
<section title="main() again">
Once again <tt>main()</tt> is left unchanged, except for yet another two case statements used to call the <tt>search()</tt> and <tt>delete</tt> functions, respectively. Note that you must provide an argument to delete or it will not work properly.
<example language=pike>
case "delete":
delete_record((int)args);
break;
case "search":
find_song(args);
break;
</example>
</section>
</section>
<section title="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 <ref to=register_program>. Read it, study it and enjoy!
<p>
</section>
<section title="Simple exercises">
<exercises>
<exercise>
Make a program which writes hello world 10 times.
</exercise>
<exercise>
Modify hello_world.pike to write the first argument to the program.
</exercise>
<exercise>
Make a program that writes a hello_world program to stdout
when executed.
</exercise>
<exercise>
Modify the register program to store data about programs and diskettes
instead of songs and records.
</exercise>
<exercise>
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.
</exercise>
<exercise>
Add code to the register program to check that the arguments to
<tt>show_record</tt> and <tt>delete_records</tt> are numbers. Also
make sure that the number isn't less than one or bigger than the
available number of records.
</exercise>
<exercise>
Rewrite the register program and put all the code in main().
</exercise>
</exercises>
</section>
</chapter>
<chapter title="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.
<section title="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.
<p>
<section title="if">
The simplest one is called the <b>if statement</b>. It can be written anywhere
where a statement is expected and it looks like this:
<example language=pre meta=expression,statement1,statement2>
if( expression )
statement1;
else
statement2;
</example>
Please note that there is no semicolon after the parenthesis or after the
<tt>else</tt>. Step by step, <tt>if</tt> does the following:
<ol>
<li>First it evaluates <i>expression</i>.<br>
<li>If the result was <b>false</b> go to point 5.
<li>Execute <i>statement1</i>.
<li>Jump to point 6.
<li>Execute <i>statement2</i>.
<li>Done.
</ol>
This is actually more or less how the interpreter executes the if statement.
In short, <i>statement1</i> is executed if <i>expression</i> is <b>true</b>
otherwise <i>statement2</i> is executed. If you are interested in
having something executed if the expression is false you can drop the
whole else part like this:
<example language=pike meta=expression,statement1>
if( expression )
statement1;
</example>
If on the other hand you are not interested in evaluating something if the
expression is <b>false</b> you should use the <b>not</b> operator to negate
the true/false value of the expression. See chapter 5 for more information
about the <b>not</b> operator. It would look like this:
<example language=pike meta=expression,statement2>
if( ! expression )
statement2 ;
</example>
Any of the statements here and in the rest of this chapter can
also be a <b>block</b> 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;
<example language=pike meta=expression,statement>
if ( ! expression )
{
statement;
statement;
statement;
}
</example>
</section>
<section title="switch">
A more sophisticated condition control structure is the <b>switch
statement</b>.
A switch lets you select one of many choices depending on the value of an
expression and it can look something like this:
<example language=pike meta=expression,constant1,constant2,constant3,constant4,expressions1,expressions2,expressions3,expressions5>
switch ( expression )
{
case constant1:
statement1;
break;
case constant2:
statement2;
break;
case constant3 .. constant4:
statement3;
break;
default:
statement5;
}
</example>
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 <tt>case</tt> 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 <tt>case</tt> statement. When a <tt>break</tt> 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.
<p>
One of the case statements in the above example differs in that it is
a <b>range</b>. In this case, any value between <i>constant3</i> and
<i>constant4</i> will cause Pike to jump to <i>statement3</i>. Note
that the ranges are inclusive, so the values <i>constant3</i> and
<i>constant4</i> are also valid.
</section>
</section>
<section title="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.
<section title="while">
<tt>While</tt> is the simplest of the loop control structures. It looks
just like an <tt>if</tt> statement without the else part:
<example language=pike meta=expression,statement>
while ( expression )
statement;
</example>
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:
<example language=pike>
int e=1;
while(e<5)
{
show_record(e);
e=e+1;
}
</example>
This would call show_record with the values 1, 2, 3 and 4.
</section>
<section title="for">
<tt>For</tt> is simply an extension of <tt>while</tt>. It provides an
even shorter and more compact way of writing loops. The syntax looks
like this:
<example language=pike meta=initializer_statement,expression,increment_expression,statement>
for ( initializer_statement ; expression ; incrementor_expression )
statement ;
</example>
For does the following steps:
<ol>
<li> Executes the the <i>initializer_statement</i>. The initializer statement
is executed only once and is most commonly used to initialize the loop
variable.
<li> Evaluates <i>expression</i>
<li> If the result was false it exits the loop and continues with the
program after the loop.
<li> Executes <i>statement</i>.
<li> Executes the <i>increment_expression</i>.
<li> Starts over from 2.
</ol>
This means that the example in the while section can be written like this:
<example language=pike>
for(int e=1; e<5; e=e+1)
show_record(e);
</example>
</section>
<section title="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.
<example language=pike meta=statement,expression>
do
statement;
while ( expression );
</example>
As usual, the <i>statement</i> can also be a block of statements, and then
you do not need a semicolon after it. To clarify, this statement executes
<i>statement</i> first, and then evaluates the <i>expression</i>. If the
expression is <b>true</b> 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:
<!-- Can someone come up with a better example? -->
<example language=pike>
do {
modem->write("ATDT441-9109\n"); // Dial 441-9109
} while(modem->gets()[..6]] != "CONNECT");
</example>
This example assumes you have written something that can communicate with
the modem by using the functions <tt>write</tt> and <tt>gets</tt>.
</section>
<section title="foreach">
<tt>Foreach</tt> is unique in that it does not have an explicit test expression
evaluated for each iteration in the loop. Instead, <tt>foreach</tt> executes
the statement once for each element in an array. <tt>Foreach</tt> looks like
this:
<example language=pike meta=array_expression,variable,statement>
foreach ( array_expression, variable )
statement ;
</example>
We have already seen an example of <tt>foreach</tt> in the <tt>find_song</tt>
function in chapter 2. What foreach does is:
<ol>
<li> It evaluates the <i>array_expression</i> which must return an array.
<li> If the array is empty, exit the loop.
<li> It then assigns the first element from the array to the <i>variable</i>.
<li> Then it executes the <i>statement</i>.
<li> If there are more elements in the array, the next one is assigned to
the <i>variable</i>, otherwise exit the loop.
<li> Go to point 4.
</ol>
<tt>Foreach</tt> is not really necessary, but it is faster and clearer than
doing the same thing with a <tt>for</tt> loop, as shown here:
<example language=pike meta=array_expression,variable,statement>
array tmp1= array_expression;
for ( tmp2 = 0; tmp2 < sizeof(tmp1); tmp2++ )
{
variable = tmp1 [ tmp2 ];
statement;
}
</example>
<p>
</section>
</section>
<section title="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:
<section title="break">
<tt>Break</tt><!-- FIXME: liten bokstav? --> exits a loop or switch statement immediately and continues
executing after the loop. <tt>Break</tt> can not be used outside of a loop or
switch. It is quite useful in conjunction with <tt>while(1)</tt> to
construct command parsing loops for instance:
<example language=pike>
while(1)
{
string command=readline("> ");
if(command=="quit") break;
do_command(command);
}
</example>
</section>
<section title="continue">
<tt>Continue</tt> does almost the same thing as <tt>break</tt>, 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 <tt>while</tt> loop, this
means it jumps up to the top again. For a <tt>for</tt> loop, it jumps to the
incrementor expression. For a <tt>do-while</tt> loop it jumps down to the
expression at the end. To continue our example above, <tt>continue</tt> can be used
like this:
<example language=pike>
while(1)
{
string command=readline("> ");
if(strlen(command) == 0) continue;
if(command=="quit") break;
do_command(command);
}
</example>
This way, <tt>do_command</tt> will never be called with an empty string as
argument.
</section>
<section title="return">
<tt>Return</tt> 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 <tt>return</tt>. Of course the type of the return value
must match the type in the function declaration. If your function declaration
is <tt>int main()</tt> the value after <tt>return</tt> must be an <b>int</b>.
For instance, if we wanted to make a program that always returns an error
code to the system, just like the UNIX command <tt>false</tt> this is how
it would be done:
<example language=pike>
#!/usr/local/bin/pike
int main()
{
return 1;
}
</example>
This would return the error code <tt>1</tt> to the system when the program
is run.
</section>
</section>
<section title=Exercises>
<exercises>
<exercise>
End all functions in the examples in chapter two with a return statement.
</exercise><exercise>
Change all <tt>foreach</tt> loops to <tt>for</tt> or <tt>while</tt> loops.
</exercise><exercise>
Make the <tt>find_song</tt> function in chapter 2 return when the first
matching song is found.
</exercise><exercise>
Make the <tt>find_song</tt> function write the number of the record
the song is on.
</exercise><exercise>
If you failed to get the program to work properly in the last exercise
of chapter 2, try it again now.
</exercise><exercise>
Make a program that writes all the numbers from 1 to 1000.
</exercise><exercise>
Modify the program in the previous exercise to NOT write numbers divisible by 3, 7 or 17.
</exercise><exercise>
Make a program that writes all the prime numbers between 1 and 1000.
</exercise>
</exercises>
</section>
</chapter>
<chapter title="Data types" name=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: <b>basic types</b>, and
<b>pointer types</b>. The difference is that basic types are copied when
assigned to a variable. With pointer types, merely the pointer is copied,
that way you get two variables pointing to the same thing.
<p>
<section title="Basic types">
The basic types are <tt>int</tt>, <tt>float</tt> and <tt>string</tt>.
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.
<section title="int">
<tt>Int</tt> 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 <tt>int</tt> might be larger
than 32 bits. Since they are integers, no decimals are allowed. An integer
constant can be written in several ways:
<example language=pike>
78 // decimal number
0116 // octal number
0x4e // hexadecimal number
'N' // Ascii character
</example>
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 <tt>N</tt> which just happens to be 78 in ASCII.
<p>
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++.
<p>
All the arithmetic, bitwise and comparison operators can be used on integers.
Also note these functions:
<dl>
<dt><tt>int intp(mixed <i>x</i>)</tt>
<dd> This function returns 1 if <i>x</i> is an int, 0 otherwise.
<dt><tt>int random(int <i>x</i>)</tt>
<dd>This function returns a random number greater or equal to zero and smaller than <i>x</i>.
<dt><tt>int reverse(int <i>x</i>)</tt>
<dd>This function reverses the order of the bits in <i>x</i> and returns the new number. It is not very useful.
<dt><tt>int sqrt(int <i>x</i>)</tt>
<dd>This computes the square root of <i>x</i>. The value is always rounded down.
</dl>
</section>
<section title="float">
<!-- FIXME: Du borde skriva något om att float och int inte är kompatibla och ingen
implicit casting sker som i C++ -->
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 <tt>float</tt>. 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:
<example language=pike>
3.14159265358979323846264338327950288419716939937510 // Pi
1.0e9 // A billion
1.0e-9 // A billionth
</example>
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
<tt>float</tt> might have higher accuracy than that. In the exponential form,
<tt>e</tt> means "times 10 to the power of", so <tt>1.0e9</tt> is equal to
"1.0 times 10 to the power of 9".
<p>
All the arithmetic and comparison operators can be used on floats.
Also, these functions operates on floats:
<dl>
<dt>trigonometric functions
<dd> The trigonometric functions are: <tt>sin</tt>, <tt>asin</tt>,
<tt>cos</tt>, <tt>acos</tt>, <tt>tan</tt> and <tt>atan</tt>.
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.
<dt><tt>float log(float <i>x</i>)</tt>
<dd>This function computes the natural logarithm of <i>x</i>,
<dt><tt>float exp(float <i>x</i>)</tt>
<dd>This function computes <b>e</b> raised to the power of <i>x</i>.
<dt><tt>float pow(float <i>x</i>, float <i>y</i>)</tt>
<dd>This function computes <i>x</i> raised to the power of <i>y</i>.
<dt><tt>float sqrt(float <i>x</i>)</tt>
<dd>This computes the square root of <i>x</i>.
<dt><tt>float floor(float <i>x</i>)</tt>
<dd>This function computes the largest integer value less than or equal to <i>x</i>. Note that the value is returned as a <tt>float</tt>, not an <tt>int</tt>.
<dt><tt>float ceil(float <i>x</i>)</tt>,
<dd>This function computes the smallest integer value greater than or equal to <i>x</i> and returns it as a <tt>float</tt>.
</dl>
</section>
<section title="string">
A <tt>string</tt> can be seen as an array of values from 0 to 2³²-1.
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 <b>shared</b>,
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:
<example language=pike>
"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
"\x4e" // N (4e is the hexadecimal ASCII value for N)
"\d78" // N (78 is the decimal ACII value for N)
"hello world\116\t\n\r\b\0\"\\" // All of the above
"\xff" // the character 255
"\xffff" // the character 65536
"\xffffff" // the character 16777215
"\116""3" // 'N' followed by a '3'
</example>
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, <tt>\t</tt> is the sequence to produce
a tab character, <tt>\\</tt> is used when you want one backslash and
<tt>\"</tt> is used when you want a double quote (<tt>"</tt>) to be a part
of the string instead of ending it.
Also, <tt>\<i>XXX</i></tt> where <i>XXX</i> is an
octal number from 0 to 37777777777 or <tt>\x<i>XX</i></tt> where <i>XX</i>
is 0 to ffffffff lets you write any character you want in the
string, even null characters. From version 0.6.105, you may also use
<tt>\d<i>XXX</i></tt> where <i>XXX</i> is 0 to 2³²-1. If you write two constant
strings after each other, they will be concatenated into one string.
<p>
You might be surprised to see that individual characters can have values
up to 2³²-1 and wonder how much memory that use. Do not worry, Pike
automatically decides the proper amount of memory for a string, so all
strings with character values in the range 0-255 will be stored with
one byte per character. You should also beware that not all functions
can handle strings which are not stored as one byte per character, so
there are some limits to when this feature can be used.
<p>
Although strings are a form of arrays, they are immutable. This means that
there is no way to change an individual character within a string without
creating a new string. This may seem strange, but keep in mind that strings
are shared, so if you would change a character in the string <tt>"foo"</tt>,
you would change *all* <tt>"foo"</tt> everywhere in the program.
<p>
However, the Pike compiler will allow you to to write code like you could
change characters within strings, the following code is valid and works:
<example language=pike>
string s="hello torld";
s[6]='w';
</example>
However, you should be aware that this does in fact create a new string and
it may need to copy the string <i>s</i> to do so. This means that the above
operation can be quite slow for large strings. You have been warned.
Most of the time, you can use <tt>replace</tt>, <tt>sscanf</tt>, <tt>`/</tt>
or some other high-level string operation to avoid having to use the above
construction too much.
<p>
All the comparison operators plus the operators listed here can be used on strings:
<dl>
<dt> Summation
<dd> Adding strings together will simply concatenate them.
<tt>"foo"+"bar"</tt> becomes <tt>"foobar"</tt>.
<dt> Subtraction
<dd> Subtracting one string from another will remove all occurrences
of the second string from the first one. So
<tt>"foobarfoogazonk" - "foo"</tt> results in <tt>"bargazonk"</tt>.
<dt> Indexing
<dd> Indexing will let you get the ASCII value of any character in a string.
The first index is zero.
<dt> Range
<dd> The range operator will let you copy any part of the string into a
new string. Example: <tt>"foobar"[2..4]</tt> will return <tt>"oba"</tt>.
<dt> Division
<dd> Division will let you divide a string at every occurrence of a word or
character. For instance if you do <tt>"foobargazonk" / "o"</tt> the
result would be <tt>({"f","","bargaz","nk"})</tt>. It is also possible
to divide the string into strings of length N by dividing the string
by N. If N is converted to a float before dividing, the reminder of
the division will be included in the result.
<dt> Multiplication
<dd> The inverse of the division operator can be accomplished by multiplying
an array with a string. So if you evaluate
<tt>({"f","","bargaz","nk"}) * "o"</tt> the result would be
<tt>"foobargazonk"</tt>.
<dt> Modulo
<dd> To complement the division operator, you can do <tt>string</tt> % <tt>int</tt>.
This operator will simply return the part of the string that was not
included in the array returned by <tt>string</tt> / <tt>int</tt>
</dl>
<p>
Also, these functions operates on strings:
<dl>
<dt><tt>string String.capitalize(string <i>s</i>)</tt>
<dd>Returns <i>s</i> with the first character converted to upper case.
<dt><tt>string lower_case(string <i>s</i>)</tt>
<dd>Returns <i>s</i> with all the upper case characters converted to lower case.
<dt><tt>string replace(string <i>s</i>, string <i>from</i>, string <i>to</i>)</tt>
<dd>This function replaces all occurrences of the string <i>from</i> in <i>s</i> with <i>to</i> and returns the new string.
<dt><tt>string reverse(string <i>s</i>)</tt>
<dd>This function returns a copy of <i>s</i> with the last byte from <i>s</i>
first, the second last in second place and so on.
<dt><tt>int search(string <i>haystack</i>, string <i>needle</i>)</tt>
<dd>This function finds the first occurrence of <i>needle</i> in <i>haystack</i> and returns where it found it.
<dt><tt>string sizeof(string <i>s</i>)</tt>
<dd>Same as <tt>strlen(<i>s</i>)</tt>, returns the length of the string.
<dt><tt>int stringp(mixed <i>s</i>)</tt>
<dd>This function returns 1 if <i>s</i> is a string, 0 otherwise.
<dt><tt>string strlen(string <i>s</i>)</tt>
<dd>Returns the length of the string <i>s</i>.
<dt><tt>string upper_case(string <i>s</i>)</tt>
<dd>This function returns <i>s</i> with all lower case characters converted
to upper case.
</dl>
</section>
</section>
<section title="Pointer types">
The basic types are, as the name implies, very basic. They are the foundation,
most of the pointer types are merely interesting ways to store the basic
types. The pointer types are <tt>array</tt>, <tt>mapping</tt>,
<tt>multiset</tt>, <tt>program</tt>, <tt>object</tt> and <tt>function</tt>.
They are all <b>pointers</b> 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.
<section title="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 <b>elements</b> and are accessible
through the index operator. To write a constant array you enclose the
values you want in the array with <tt>({ })</tt> like this:
<example language=pike>
({ }) // 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
</example>
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.
<p>
<center>
<image xfig=array><br>
fig 4.1
</center>
<p>
Operators and functions usable with arrays:
<dl>
<dt> indexing ( <tt><i>arr</i> [ <i>c</i> ]</tt> )
<dd> Indexing an array retrieves or sets a given element in the array.
The index <i>c</i> has to be an integer. To set an index, simply put
the whole thing on the left side of an assignment, like this:
<tt><i>arr</i> [ <i>c</i> ] = <i>new_value</i></tt>
<dt> range ( <tt><i>arr</i> [ <i>from</i> .. <i>to</i> ]</tt> )
<dd> The range copies the elements <i>from</i>, <i>from</i>+1, , <i>from</i>+2 ... <i>to</i> into a new array. The new array will have the size <i>to</i>-<i>from</i>+1.
<dt> comparing (<tt><i>a</i> == <i>b</i></tt> and <tt><i>a</i> != <i>b</i></tt>)
<dd> The equal operator returns 1 if <i>a</i> and <i>b</i> are the <b>same</b> arrays. It is not enough that they have the same size and same data. They must
be the same array. For example: <tt>({1}) == ({1})</tt> would return 0, while
<tt>array(int) a=({1}); return a==a;</tt> would return 1. Note that you cannot
use the operators <tt>></tt>, <tt>>=</tt>, <tt><</tt> or <tt><=</tt> on arrays.
<dt> Summation (<tt><i>a</i> + <i>b</i></tt>)
<dd> As with strings, summation concatenates arrays. <tt>({1})+({2})</tt> returns <tt>({1,2})</tt>.
<dt> Subtractions (<tt><i>a</i> - <i>b</i></tt>)
<dd> Subtracting one array from another returns a copy of
<i>a</i> with all the elements that are also present in <i>b</i> removed.
So <tt>({1,3,8,3,2}) - ({3,1})</tt> returns <tt>({8,2})</tt>.
<dt> Intersection (<tt><i>a</i> & <i>b</i></tt>)
<dd> Intersection returns an array with all values that are present in both
<i>a</i> and <i>b</i>. The order of the elements will be the same as
the the order of the elements in <i>a</i>. Example:
<tt>({1,3,7,9,11,12}) & ({4,11,8,9,1})</tt> will return:
<tt>({1,9,11})</tt>.
<dt> Union (<tt><i>a</i> | <i>b</i></tt>)
<dd> Union works almost as summation, but it only concatenates elements not
already present in <i>a</i>. So, <tt>({1,2,3}) | ({1,3,5})</tt> will
return <tt>({1,2,3,5})</tt>.
<dt> Xor (<tt><i>a</i> ^ <i>b</i></tt>)
<dd> This is also called symmetric difference. It returns an array with all
elements present in <i>a</i> or <i>b</i> but the element must NOT
be present in both. Example: <tt>({1,3,5,6}) ^ ({4,5,6,7})</tt> will
return <tt>({1,3,4,7})</tt>.
<dt> Division (<tt><i>a</i> / <i>b</i></tt>)
<dd> This will split the array <i>a</i> into an array of arrays. If <i>b</i> is
another array, <i>a</i> will be split at each occurance of that array.
If <i>b</i> is an integer or float, <i>a</i> will be split between
every <i>b</i>th element. Examples: <tt>({1,2,3,4,5})/({2,3})</tt> will
return <tt>({ ({1}), ({4,5}) })</tt> and <tt>({1,2,3,4})/2</tt> will
return <tt>({ ({1,2}), ({3,4}) })</tt>.
<dt> Modulo (<tt><i>a</i> % <i>b</i></tt>)
<dd> This operation is valid only if <i>b</i> is an integer. It will return
the part of the array that was not included by dividing <i>a</i> by
<i>b</i>.
<dt><tt>array aggregate(mixed ... <i>elems</i>)</tt>
<dd> This function does the same as the <tt>({ })</tt> operator; it creates an
array from all arguments given to it. In fact, writing <tt>({1,2,3})</tt>
is the same as writing <tt>aggregate(1,2,3)</tt>.
<dt><tt>array allocate(int <i>size</i>)</tt>
<dd>This function allocates a new array of size <tt>size</tt>. All the elements
in the new array will be zeroes.
<dt><tt>int arrayp(mixed <i>a</i>)</tt>
<dd>This function returns 1 if <i>a</i> is an array, 0 otherwise.
<dt><tt>array column(array(mixed) <i>a</i>, mixed <i>ind</i>)</tt>
<dd>This function goes through the array <i>a</i> and indexes every element
in it on <i>ind</i> and builds an array of the results. So if you have
an array <i>a</i> in which each element is a also an array. This function
will take a cross section, by picking out element <i>ind</i> from each
of the arrays in <i>a</i>. Example:
<tt>column( ({ ({1,2,3}), ({4,5,6}), ({7,8,9}) }), 2)</tt> will return
<tt>({3,6,9})</tt>.
<dt><tt>int equal(mixed <i>a</i>, mixed <i>b</i>)</tt>
<dd> This function returns 1 if if <i>a</i> and <i>b</i> 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.
<dt><tt>array Array.filter(array <i>a</i>, mixed <i>func</i>, mixed ... <i>args</i>)</tt>
<dd> <tt>filter</tt> returns every element in <i>a</i> for which <i>func</i> returns <b>true</b> when called with that element as first argument, and <i>args</i> for the second, third, etc. arguments.
<dt><tt>array Array.map(array <i>a</i>, mixed <i>func</i>, mixed ... <i>args</i>)</tt>
<dd> This function works similar to <tt>Array.filter</tt> but returns the results
of the function <i>func</i> instead of returning the elements from <i>a</i> for which <i>func</i> returns <b>true</b>.
<dt><tt>array replace(array <i>a</i>, mixed <i>from</i>, mixed <i>to</i>)</tt>
<dd>This function will create a copy of <i>a</i> with all elements equal to
<i>from</i> replaced by <i>to</i>.
<dt><tt>array reverse(array <i>a</i>)</tt>
<dd><tt>Reverse</tt> will create a copy of <i>a</i> with the last element first, the last but one second, and so on.
<dt><tt>array rows(array <i>a</i>, array <i>indexes</i>)</tt>
<dd>This function is similar to <tt>column</tt>. It indexes <i>a</i> with
each element from <i>indexes</i> and returns the results in an array.
For example: <tt>rows( ({"a","b","c"}), ({ 2,1,2,0}) ) </tt> will return
<tt>({"c","b","c","a"})</tt>.
<dt><tt>int search(array <i>haystack</i>, mixed <i>needle</i>)</tt>
<dd>This function returns the index of the first occurrence of an element
equal (tested with <tt>==</tt>) to <i>needle</i> in the array
<i>haystack</i>.
<dt><tt>int sizeof(mixed <i>arr</i>)</tt>
<dd>This function returns the number of elements in the array <i>arr</i>.
<dt><tt>array sort(array <i>arr</i>, array ... <i>rest</i>)</tt>
<dd>This function sorts <i>arr</i> 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 <i>arr</i>. See
<ref to=functions> for more details.
<dt><tt>array uniq(array <i>a</i>)</tt>
<dd>This function returns a copy of the array <i>a</i> with all duplicate
elements removed. Note that this function can return the elements
in any order.
</dl>
</section>
<section title="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:
<p>
<center>
<image xfig=mapping><br>
fig 4.2
</center>
<p>
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 <i>m</i> and we index it like this:
<tt><i>m</i> [ <i>i</i> ]</tt> the lookup function will quickly find the index
<i>i</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:
<example language=pike>
([ ]) // 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
</example>
<p>
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.
<p>
The following operators and functions are important:
<dl>
<dt> indexing ( <tt><i>m</i> [ <i>ind</i> ]</tt> )
<dd> As discussed above, indexing is used to retrieve, store and add values
to the mapping.
<dt> addition, subtraction, union, intersection and xor
<dd> All these operators works exactly as on arrays, with the difference that
they operate on the indices. In those cases when the value can come from
either mapping, it will be taken from the right side of the operator.
This makes it easier to add new values to a mapping with <tt>+=</tt>.
Some examples:<br>
<tt>([1:3, 3:1]) + ([2:5, 3:7])</tt> returns <tt>([1:3, 2:5, 3:7 ])</tt><br>
<tt>([1:3, 3:1]) - ([2:5, 3:7])</tt> returns <tt>([1:3])</tt><br>
<tt>([1:3, 3:1]) | ([2:5, 3:7])</tt> returns <tt>([1:3, 2:5, 3:7 ])</tt><br>
<tt>([1:3, 3:1]) & ([2:5, 3:7])</tt> returns <tt>([3:7])</tt><br>
<tt>([1:3, 3:1]) ^ ([2:5, 3:7])</tt> returns <tt>([1:3, 2:5])</tt><br>
<dt> same ( <tt><i>a</i> == <i>b</i></tt> )
<dd> Returns 1 if <i>a</i> is <b>the same</b> mapping as <i>b</i>, 0 otherwise.
<dt> not same ( <tt><i>a</i> != <i>b</i></tt> )
<dd> Returns 0 if <i>a</i> is <b>the same</b> mapping as <i>b</i>, 1 otherwise.
<dt><tt>array indices(mapping <i>m</i>)</tt>
<dd><tt>Indices</tt> returns an array containing all the indices in the mapping <i>m</i>.
<dt><tt>void m_delete(mapping <i>m</i>, mixed <i>ind</i>)</tt>
<dd>This function removes the index-value pair with the index <i>ind</i> from the mapping <i>m</i>.
<dt><tt>int mappingp(mixed <i>m</i>)</tt>
<dd>This function returns 1 if <i>m</i> is a mapping, 0 otherwise.
<dt><tt>mapping mkmapping(array <i>ind</i>, array <i>val</i>)</tt>
<dd>This function constructs a mapping from the two arrays <i>ind</i> and
<i>val</i>. Element 0 in <i>ind</i> and element 0 in <i>val</i> becomes
one index-value pair. Element 1 in <i>ind</i> and element 1 in <i>val</i>
becomes another index-value pair, and so on..
<dt><tt>mapping replace(mapping <i>m</i>, mixed <i>from</i>, mixed <i>to</i>)</tt>
<dd>This function creates a copy of the mapping <i>m</i> with all values equal to <i>from</i> replaced by <i>to</i>.
<dt><tt>mixed search(mapping <i>m</i>, mixed <i>val</i>)</tt>
<dd>This function returns the index of the 'first' index-value pair which has the value <i>val</i>.
<dt><tt>int sizeof(mapping <i>m</i>)</tt>
<dd><tt>Sizeof</tt> returns how many index-value pairs there are in the mapping.
<dt><tt>array values(mapping <i>m</i>)</tt>
<dd>This function does the same as <tt>indices</tt>, but returns an array with all the values instead. If <tt>indices</tt> and <tt>values</tt> 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 <tt>mkmapping</tt> to rebuild the mapping <i>m</i> again.
<dt><tt>int zero_type(mixed t)</tt>
<dd>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 <tt>zero_type(<i>m</i> [ <i>ind</i> ])</tt> returns 1, it means that the value was not present
in the mapping. If the value was present in the mapping, <tt>zero_type</tt> will return something else than 1.
</dl>
</section>
<section title="multiset">
A multiset is almost the same thing as a mapping. The difference is that there
are no values:
<p>
<center>
<image xfig=multiset><br>
fig 4.3
</center>
<p>
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: <tt><i>mset</i>[ <i>ind</i> ] = <i>val</i></tt> the index <i>ind</i>
will be added to the multiset <i>mset</i> if <i>val</i> is <b>true</b>.
Otherwise <i>ind</i> will be removed from the multiset instead.
<p>
Writing a constant multiset is similar to writing an array:
<example language=pike>
(< >) // Empty multiset
(< 17 >) // Multiset with one index: 17
(< "", 1, 3.0, 1 >) // Multiset with 3 indices
</example>
Note that you can actually have more than one of the same index in a multiset. This is
normally not used, but can be practical at times.
</section>
<section title="program" name=programs>
Normally, when we say <b>program</b> we mean something we can execute from
a shell prompt. However, Pike has another meaning for the same word. In Pike
a <tt>program</tt> is the same as a <b>class</b> in C++. A <tt>program</tt>
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 <tt>program</tt> does not hold space
to store any data however.
All the information in a <tt>program</tt> 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 <tt>object</tt>
which is the next data type we will discuss.
<p>
<center>
<image xfig=program><br>
fig 4.4
</center>
Writing a <tt>program</tt> is easy, in fact, every example we have tried so
far has been a <tt>program</tt>. To load such a program into memory, we can
use <tt>compile_file</tt> which takes a file name, compiles the file
and returns the compiled program. It could look something like this:
<example language=pike>
program p = compile_file("hello_world.pike");
</example>
You can also use the <b>cast</b> operator like this:
<example language=pike>
program p = (program) "hello_world";
</example>
This will also load the program <tt>hello_world.pike</tt>, the only difference
is that it will cache the result so that next time you do <tt>(program)"hello_world"</tt> you will receive the _same_ program. If you call
<tt>compile_file("hello_world.pike")</tt> repeatedly you will get a new program
each time.
<p>
There is also a way to write programs inside programs with the help of the
<tt>class</tt> keyword:
<example language=pike meta="class_name,inherits,variables,functions">
class class_name {
inherits, variables and functions
}
</example>
The <tt>class</tt> keyword can be written as a separate entity
outside of all functions, but it is also an expression which returns the
<tt>program</tt> written between the brackets. The <i>class_name</i> is
optional. If used you can later refer to that <tt>program</tt> by the name
<i>class_name</i>.
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 <b>structs</b>
(or records if you program Pascal).
Let's look at an example:
<example language=pike>
class record {
string title;
string artist;
array(string) songs;
}
array(record) records = ({});
void add_empty_record()
{
records+=({ record() });
}
void show_record(record rec)
{
write("Record name: "+rec->title+"\n");
write("Artist: "+rec->artist+"\n");
write("Songs:\n");
foreach(rec->songs, string song)
write(" "+song+"\n");
}
</example>
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
<tt>program</tt> called <tt>record</tt> which has three identifiers.
In <tt>add_empty_record</tt> a new object is created
by calling <tt>record</tt>. This is called <b>cloning</b> and it
allocates space to store the variables defined in the <tt>class record</tt>.
<tt>Show_record</tt> takes one of the records created in
<tt>add_empty_record</tt> and shows the contents of it. As you can see, the arrow operator
is used to access the data allocated in <tt>add_empty_record</tt>.
If you do not understand this section I suggest you go on and read the
next section about <tt>objects</tt> and then come back and read this
section again.
<p>
<dl>
<dt> cloning
<dd> To create a data area for a <tt>program</tt> you need to instantiate or
<b>clone</b> the program. This is accomplished by using a pointer
to the <tt>program</tt> as if it was a function and call it. That
creates a new object and calls the function <tt>create</tt> in the
new object with the arguments. It is also possible to use the
functions <tt>new()</tt> and <tt>clone()</tt> which do exactly the
same thing except you can use a string to specify what program you
want to clone.
<dt> compiling
<dd> All programs are generated by compiling a string. The string may of
course be read from a file. For this purpose there are three functions:
<example language=pike meta=p,filename>
program compile(string p);
program compile_file(string filename);
program compile_string(string p, string filename);
</example>
<tt>compile_file</tt> simply reads the file given as argument, compiles
it and returns the resulting program. <tt>compile_string</tt> instead
compiles whatever is in the string <i>p</i>. The second argument,
<i>filename</i>, is only used in debug printouts when an error occurs
in the newly made program. Both <tt>compile_file</tt> and
<tt>compile_string</tt> calls <tt>compile</tt> to actually compile
the string after calling <tt>cpp</tt> on it.
<dt> casting
<dd> Another way of compiling files to program is to use the <b>cast</b>
operator. Casting a string to the type <tt>program</tt> 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.
<dt> <tt>int programp(mixed <i>p</i>)</tt>
<dd> This function returns 1 if <i>p</i> is a program, 0 otherwise.
<dt> comparisons
<dd> As with all data types <tt>==</tt> and <tt>!=</tt> can be used to
see if two programs are the same or not.
</dl>
<p>
The following operators and functions are important:
<dl>
<dt> cloning ( <tt><i>p</i> ( <i>args</i> )</tt> )
<dd> Creates an object from a program. Discussed in the next section.
<dt> indexing ( <tt><i>p</i> [ <i>string</i> ]</tt>, or
<tt><i>p</i> -> <i>identifier</i></tt> )
<dd> Retreives the value of the named constant from a program.
<dt> <tt>array(string) indices(program <i>p</i>)</tt>
<dd> Returns an array with the names of all non-static constants in the
program.
<dt> <tt>array(mixed) values(program <i>p</i>)</tt>
<dd> Returns an array with the values of all non-static constants in the
program.
</dl>
</section>
<section title="object">
Although programs are absolutely necessary for any application you might
want to write, they are not enough. A <tt>program</tt> doesn't have anywhere
to store data, it just merely outlines how to store data. To actually store
the data you need an <tt>object</tt>. 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 <tt>program</tt> outlines where in the object
different variables are stored.
<center>
<image xfig=object><br>
fig 4.5
</center>
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:
<example language=pike>
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(record) records = ({});
void add_empty_record()
{
records+=({ record() });
}
void show_record(object rec)
{
rec->show();
}
</example>
Here we can clearly see how the function <tt>show</tt> prints the
contents of the variables in that object. In essence, instead of accessing
the data in the object with the <tt>-></tt> 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 <tt>record</tt>
stores its data, but we do not have to change anything outside of
the <tt>record</tt> program.
<p>
Functions and operators relevant to objects:
<dl>
<dt> indexing
<dd> 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 <tt>-></tt> operator is actually the same as indexing.
This means that <tt>o->foo</tt> is the same as <tt>o["foo"]</tt>
<dt> cloning
<dd> As discussed in the section about programs, cloning a program can be done
in two different ways:
<ol>
<li> Use a pointer to the program as a function and call it.
<li> Use the functions <tt>new</tt> or <tt>clone</tt>. (They are the same function.)
</ol>
Whenever you clone an object, all the global variables will be
initialized. After that the function <tt>create</tt> will be called
with any arguments you call the program with.
<dt> <tt>void destruct(object <i>o</i>)</tt>
<dd> This function invalidates all references to the object <i>o</i> and
frees all variables in that object. This function is also called when
<i>o</i> runs out of references. If there is a function named
<tt>destroy</tt> in the object, it will be called before the actual
destruction of the object.
<dt> <tt>array(string) indices(object <i>o</i>)</tt>
<dd> This function returns a list of all identifiers in the object <i>o</i>.
<dt> <tt>program object_program(object <i>o</i>)</tt>
<dd> This function returns the program from which <i>o</i> was cloned.
<dt> <tt>int objectp(mixed <i>o</i>)</tt>
<dd> This function returns 1 if <i>o</i> is an object, 0 otherwise.
Note that if <i>o</i> has been destructed, this function will return 0.
<dt> <tt>object this_object()</tt>
<dd> This function returns the object in which the interpreter is currently
executing.
<dt> <tt>array values(object <i>o</i>)</tt>
<dd> This function returns the same as <tt>rows(o,indices(o))</tt>.
That means it returns all the values of the identifiers in the
object <i>o</i>.
<dt> comparing
<dd> As with all data types <tt>==</tt> and <tt>!=</tt> can be used to
check if two objects are the same or not.
</dl>
</section>
<section title="function">
When indexing an object on a string, and that string is the name of a function
in the object a <tt>function</tt> is returned. Despite its name, a
<tt>function</tt> is really a <b>function pointer</b>.
<center>
<image xfig=function><br>
fig 4.6
</center>
When the function pointer is called, the interpreter sets
<tt>this_object()</tt> 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:
<example language=pike>
int foo() { return 1; }
function bar() { return foo; }
int gazonk() { return foo(); }
int teleledningsanka() { return bar()(); }
</example>
In this example, the function bar returns a pointer to the function
<tt>foo</tt>. No indexing is necessary since the function <tt>foo</tt> is
located in the same object. The function <tt>gazonk</tt> simply calls
<tt>foo</tt>. However, note that the word <tt>foo</tt> in that function
is an expression returning a function pointer that is then called. To
further illustrate this, <tt>foo</tt> has been replaced by <tt>bar()</tt>
in the function <tt>teleledningsanka</tt>.
<p>
For convenience, there is also a simple way to write a function inside another
function. To do this you use the <tt>lambda</tt> keyword. The
syntax is the same as for a normal function, except you write
<tt>lambda</tt> instead of the function name:
<example language=pike meta=types,statements>
lambda ( types ) { statements }
</example>
The major difference is that this is an expression that can be used inside
an other function. Example:
<example language=pike>
function bar() { return lambda() { return 1; }; )
</example>
This is the same as the first two lines in the previous example, the keyword
<tt>lambda</tt> allows you to write the function inside <tt>bar</tt>.
<p>
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.
<p>
This is what you can do with a function pointer.
<dl>
<dt> calling ( <i>f</i> ( mixed ... <i>args</i> ) )
<dd> As mentioned earlier, all function pointers can be called. In this example
the function <i>f</i> is called with the arguments <i>args</i>.
<dt> <tt>string function_name(function <i>f</i>)</tt>
<dd> This function returns the name of the function <i>f</i> is pointing at.
<dt> <tt>object function_object(function <i>f</i>)</tt>
<dd> This function returns the object the function <i>f</i> is located in.
<dt> <tt>int functionp(mixed <i>f</i>)</tt>
<dd> This function returns 1 if <i>f</i> is a <tt>function</tt>, 0 otherwise.
If <i>f</i> is located in a destructed object, 0 is returned.
<dt> <tt>function this_function()</tt>
<dd> This function returns a pointer to the function it is called from.
This is normally only used with <b>lambda</b> functions because they
do not have a name.
</dl>
</section>
</section>
<section title="Sharing data">
As mentioned in the beginning of this chapter, the assignment operator
(<tt>=</tt>) 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:
<example language=pike>
int main(int argc, array(string) argv)
{
array(string) tmp;
tmp=argv;
argv[0]="Hello world.\n";
write(tmp[0]);
}
</example>
This program will of course write <tt>Hello world.</tt>
<p>
Sometimes you want to create a copy of a mapping, array or object. To
do so you simply call <tt>copy_value</tt> 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.
<p>
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:
<tt>copy_of_arr = arr + ({});</tt> If you need to copy a mapping you use
an empty mapping, and for a multiset you use an empty multiset.
</section>
<section title="Writing data types">
When declaring a variable, you also have to specify what type of variable
it is. For most types, such as <tt>int</tt> and <tt>string</tt> this is
very easy. But there are much more interesting ways to declare variables
than that, let's look at a few examples:
<example language=pike>
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 from int to string
mapping(string:int) x;
// x implements Stdio.File
Stdio.File x;
// x implements 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:array(string)))) x;
</example>
As you can see there are some interesting ways to specify types.
Here is a list of what is possible:
<dl>
<dt> <tt>mixed</tt>
<dd> This means that the variable can contain any type, or the
function return any value
<dt> <tt>array( <i>type</i> )</tt>
<dd> This means an array of elements with the type <i>type</i>.
<dt> <tt><i>type</i> *</tt>
<dd> This also means an array of elements with the type <i>type</i>.
<dt> <tt>mapping( <i>key type</i> : <i>value type</i> )</tt>
<dd> This is a mapping where the keys are of type <i>key type</i> and the
values of <i>value type</i>.
<dt> <tt>multiset ( <i>type</i> )</tt>
<dd> This means a multiset containing values of the type <i>type</i>.
<dt> <tt>object ( <i>program</i> )</tt>
<dd> This means an object which 'implements' the specified program. The
<i>program</i> 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 <tt>inherit</tt> for more information
about this casting. The compiler will assume that any function
or variable accessed in this object has the same type information
as that function or variable has in <i>program</i>.
<dt> <tt><i>program</i></tt>
<dd> This too means 'an object which implements <i>program</i>'.
<i>program</i> can be a class or a constant.
<dt> <tt>function( <i>argument types</i> : <i>return type</i> )</tt>
<dd> This is a function taking the specified arguments and returning
<i>return type</i>. The <i>argument types</i> is a comma separated
list of types that specify the arguments. The argument list can also
end with <tt>...</tt> to signify that there can be any amount of the
last type.
<dt> <tt><i>type1</i> | <i>type2</i></tt>
<dd> This means either <i>type1</i> or <i>type2</i>
<dt> <tt>void</tt>
<dd> 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: <tt>function(int|void:void)</tt> this means a
function that may or may not take an integer argument and does not
return a value.
</dl>
</section>
<!-- FIXME: insert some things for the reader to do here -->
</chapter>
<chapter title="Operators" name=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 <b>operators</b> 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.
<section title="Arithmetic operators">
The arithmetic operators are the simplest ones, since they work just like
you remember from math in school. The arithmetic operators are:
<center>
<p>
<table border=1>
<tr> <th>Function</th> <th>Syntax</th> <th>Identifier</th> <th>Returns</th></tr>
<tr><anchor name=`+> <td>Addition</td> <td><tt>a + b</tt></td> <td><tt>`+</tt></td> <td>the sum of a and b</td></anchor></tr>
<tr><anchor name=`-> <td>Subtraction</td> <td><tt>a - b</tt></td> <td><tt>`-</tt></td> <td>b subtracted from a</td></anchor></tr>
<tr> <td>Negation</td> <td><tt>- a</tt></td> <td><tt>`-</tt></td> <td>minus a</td></tr>
<tr><anchor name=`*> <td>Multiplication</td> <td><tt>a * b</tt></td> <td><tt>`*</tt></td> <td>a multiplied by b</td></anchor></tr>
<tr><anchor name=`/> <td>Division</td> <td><tt>a / b</tt></td> <td><tt>`/</tt></td> <td>a divided by b</td></anchor></tr>
<tr><anchor name=`%> <td>Modulo</td> <td><tt>a % b</tt></td> <td><tt>`%</tt></td> <td>the remainder of a division between a and b</td></anchor></tr>
</table>
</center>
<p>
The third column, "Identifier" is the name of the function that actually
evaluates the operation. For instance, <tt>a + b</tt> can also be written
as <tt>`+(a, b)</tt>. I will show you how useful this can be at the end
of this chapter.
<p>
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 <b>modulo</b> operator. The modulo operator returns the
remainder from an integer division. It is the same as calculating
<tt>a - floor(a / b) * b</tt>. <tt>floor</tt> rounds the value down to
closest lower integer value. Note that the call to <tt>floor</tt> 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,
<tt>8 / 3</tt> would return <tt>2</tt>.
<p>
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.
<p>
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:
<center>
<table border=1>
<tr>
<th>Operation</th><th>Returned type</th><th>Returned value</th>
</tr>
<tr>
<td><tt><i>int</i> + <i>int</i></tt></td><td>int</td><td>the sum of the two values</td>
</tr>
<tr>
<td><tt><i>float</i> + <i>int</i><br>
<i>int</i> + <i>float</i><br>
<i>float</i> + <i>float</i></tt></td><td>float</td><td>the sum of the two values</td>
</tr>
<tr>
<td><tt><i>string</i> + <i>string</i><br>
<i>int</i> + <i>string</i><br>
<i>float</i> + <i>string</i><br>
<i>string</i> + <i>int</i><br>
<i>string</i> + <i>float</i></tt></td><td>string</td><td>In this case, any int or float is first converted to a string. Then the two strings are concatenated and the resulting string is returned.</td>
</tr>
<tr>
<td><tt><i>array</i> + <i>array</i></tt></td><td>array</td><td>The two arrays are concatenated into a new array and that new array is returned.</td>
</tr>
<tr>
<td><tt><i>mapping</i> + <i>mapping</i></tt></td><td>mapping</td><td>A 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.</td>
</tr>
<tr>
<td><tt><i>multiset</i> + <i>multiset</i></tt></td><td>multiset</td><td>A multiset with all the indices from both multisets is returned.</td>
</tr>
<tr>
<td><tt><i>int</i> - <i>int</i></tt></td><td>int</td><td>The right value subtracted from the left.</td>
</tr>
<tr>
<td><tt><i>float</i> - <i>int</i><br>
<i>int</i> - <i>float</i><br>
<i>float</i> - <i>float</i></tt></td><td>float</td><td>The right value subtracted from the left.</td>
</tr>
<tr>
<td><tt><i>string</i> - <i>string</i></tt></td><td>string</td><td>A copy of the left string with all occurrences of the right string removed.</td>
</tr>
<tr>
<td><tt><i>array</i> - <i>array</i></tt></td><td>array</td><td>A copy of the left array with all elements present in the right array removed. Example: <tt>({2,1,4,5,3,6,7}) - ({3,5,1})</tt> will return <tt>({2,4,6,7})</tt>.</td>
</tr>
<tr>
<td><tt><i>mapping</i> - <i>mapping</i></tt></td><td>mapping</td><td>A new mapping with all index-value pairs from the left mapping, except those indices that are also present in the right mapping.</td>
</tr>
<tr>
<td><tt><i>multiset</i> - <i>multiset</i></tt></td><td>multiset</td><td>A copy of the left multiset without any index present in the left multiset.</td>
</tr>
<tr>
<td><tt>- <i>int</i></tt></td><td>int</td><td>Same as 0 - <i>int</i>.</td>
</tr>
<tr>
<td><tt>- <i>float</i></tt></td><td>float</td><td>Same as 0 - <i>float</i>.</td>
</tr>
<tr>
<td><tt><i>int</i> * <i>int</i></tt></td><td>int</td><td>the product of the two values</td>
</tr>
<tr>
<td><tt><i>float</i> * <i>int</i><br>
<i>int</i> * <i>float</i><br>
<i>float</i> * <i>float</i></tt></td><td>float</td><td>the product of the two values</td>
</tr>
<tr>
<td><tt><i>array(string)</i> * <i>string</i></tt></td><td>string</td><td>All the strings in the array are concatenated with the string on the right in between each string. Example: <tt>({"foo","bar"})*"-"</tt> will return <tt>"foo-bar".</tt></td>
</tr>
<tr>
<td><tt><i>array(array)</i> * <i>array</i></tt></td><td>array</td><td>All the arrays in the left array are concatenated with the array on the right in between each array. Example: <tt>({ ({"foo"}) ,({"bar"})})*({"-"})</tt> will return <tt>({ "foo","-","bar" })</tt>.</td>
</tr>
<tr>
<td><tt><i>string</i> * <i>int</i></tt></td><td>string</td><td>This operation will concatenate the string N times. Example: <tt>"foo"*3</tt> will return <tt>"foofoofoo"</tt>.</td>
</tr>
<tr>
<td><tt><i>array</i> * <i>int</i></tt></td><td>string</td><td>This operation will concatenate the array N times. Example: <tt>({"foo"})*3</tt> will return <tt>({"foo","foo","foo"})</tt>.</td>
</tr>
<tr>
<td><tt><i>int</i> / <i>int</i></tt></td><td>int</td><td>The right integer divided by the left integer rounded towards minus infinity.</td>
</tr>
<tr>
<td><tt><i>float</i> / <i>int</i><br>
<i>int</i> / <i>float</i><br>
<i>float</i> / <i>float</i></tt></td><td>float</td><td>The right value divided by the left value.</td>
</tr>
<tr>
<td><tt><i>string</i> / <i>string</i></tt></td><td>array(string)</td><td>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:
<tt>"foo-bar"/"-"</tt> will return <tt>({"foo","bar"})</tt></td>
</tr>
<tr>
<td><tt><i>string</i> / <i>int</i></tt></td><td>array(string)</td><td>This will split the string into pieces. The size of the pieces is given by the integer. Only complete pieces will be included in the result, the 'reminder' is discarded. Example:
<tt>"foo-bar"/2</tt> will return <tt>({"fo","o-","ba"})</tt></td>
</tr>
<tr>
<td><tt><i>string</i> / <i>float</i></tt></td><td>array(string)</td><td>This is similar to dividing a string with an integer, but it allows fraction-sized segments and the reminder will always be included. Example:
<tt>"foo-bar"/2.5</tt> will return <tt>({"fo","o-b","ar"})</tt></td>
</tr>
<tr>
<td><tt><i>array</i> / <i>int</i></tt></td><td>array(array)</td><td>This is similar to dividing a string with an integer, but splits an array. Example:
<tt>({1,2,3,4,5,6,7})/2</tt> will return <tt>({({1,2}),({3,4}),({5,6})})</tt></td>
</tr>
<tr>
<td><tt><i>array</i> / <i>float</i></tt></td><td>array(array)</td><td>You should be able to predict what this does by now. :) Example:
<tt>({1,2,3,4,5,6,7,8})/2.5</tt> will return <tt>({({1,2}),({3,4,5}),({6,7}),({8})})</tt></td>
</tr>
<tr>
<td><tt><i>int</i> % <i>int</i></tt></td><td>int</td><td>The remainder of a division. If <tt>a</tt> and <tt>b</tt> are integers, <tt>a%b</tt> is the same as <tt>a-(a/b)*b</tt></td>
</tr>
<tr>
<td><tt>
<i>float</i> % <i>float</i><br>
<i>int</i> % <i>float</i><br>
<i>float</i> % <i>int</i></tt></td><td>float</td><td>The remainder of a division. If <tt>a</tt> and <tt>b</tt> are floats, <tt>a%b</tt> is the same as <tt>a-floor(a/b)*b</tt></td>
</tr>
<tr>
<td><tt>
<i>string</i> % <i>int</i></tt></td><td>string</td><td>The remainder of a string division. Example: <tt>"foo-bar"%2</tt> will return <tt>"r"</tt></td>
</tr>
<tr>
<td><tt>
<i>array</i> % <i>int</i></tt></td><td>string</td><td>The remainder of an array division. Example: <tt>({1,2,3,4,5,6,7})%2</tt> will return <tt>({7})</tt></td>
</tr>
</table>
</center>
</section>
<section title="Comparison operators">
The arithmetic operators would be hard to use for anything interesting
without the ability to compare the results to each other.
For this purpose there are six comparison operators:
<center>
<p>
<table border=1>
<tr> <th>Function</th> <th>Syntax</th> <th>Identifier</th> <th>Returns</th></tr>
<tr><anchor name=`==> <td>Same</td> <td><tt>a == b</tt></td> <td><tt>`==</tt></td> <td>1 if a is the same value as b, 0 otherwise</td></anchor></tr>
<tr><anchor name=`!=> <td>Not same</td> <td><tt>a != b</tt></td> <td><tt>`!=</tt></td> <td>0 if a is the same value as b, 1 otherwise</td></anchor></tr>
<tr><anchor name="`>"> <td>Greater than</td> <td><tt>a > b</tt></td> <td><tt>`> </tt></td><td>1 if a is greater than b, 0 otherwise</td></anchor></tr>
<tr><anchor name="`>="> <td>Greater than or equal to</td><td><tt>a >= b</tt></td><td><tt>`>=</tt></td><td>1 if a is greater to or equal to b, 0 otherwise</td></anchor></tr>
<tr><anchor name="`<"> <td>Lesser than</td> <td><tt>a < b</tt></td> <td><tt>`< </tt></td><td>1 if a is lesser than b, 0 otherwise</td></anchor></tr>
<tr><anchor name="`<="> <td>Lesser than or equal to</td> <td><tt>a <= b</tt></td><td><tt>`<=</tt></td><td>1 if a is lesser than or equal to b, 0 otherwise</td></anchor></tr>
</table>
<p>
</center>
The <tt>==</tt> and <tt>!=</tt> operators can be used on any type. For two
values to be <b>same</b> they must be the same type. Therefore 1 and 1.0 are
not <b>same</b>. Also, for two values of <b>pointer types</b> 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.
<p>
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 values of the environment variables <tt>LC_CTYPE</tt> and
<tt>LC_LANG</tt> are respected.
</section>
<section title="Logical operators">
Logical operators are operators that operate with truth values. In Pike any value
except zero is considered <b>true</b>. 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:
<center>
<p>
<table border=1>
<tr><th>Function</th> <th>Syntax</th> <th>Returns</th></tr>
<tr><td>And</td> <td><tt>a && b</tt></td> <td>If a is false, a is returned and b is not evaluated. Otherwise, b is returned.</td></tr>
<tr><td>Or</td> <td><tt>a || b</tt></td> <td>If a is true, a is returned and b is not evaluated. Otherwise, b is returned.</td></tr>
<tr><td>Not</td> <td><tt>! a</tt></td> <td>Returns 0 if a is true, 1 otherwise.</td></tr>
<tr><td>If-else</td> <td><tt>a ? b : c</tt></td> <td>If a is true, b is returned and c is not evaluated. Otherwise c is returned and b is not evaluated.</td></tr>
</table>
</center>
</section>
<section title="Bitwise/set operators">
These operators are used to manipulate bits as members in sets.
They can also manipulate arrays, multisets and mappings as sets.
<center>
<p>
<table border=1>
<tr> <th>Function</th> <th>Syntax</th> <th>Identifier</th> <th>Returns</th></tr>
<tr><anchor name="`<<"> <td>Shift left</td> <td><tt>a << b</tt></td> <td><tt>`<<</tt></td> <td>Multiplies a by 2 b times.</td></anchor></tr>
<tr><anchor name="`>>"> <td>Shift right</td> <td><tt>a >> b</tt></td> <td><tt>`>></tt></td> <td>Divides a by 2 b times.</td></anchor></tr>
<tr><anchor name=`~> <td>Inverse (not)</td> <td><tt>~ a</tt></td> <td><tt>`~</tt></td> <td>Returns -1-a.</td></anchor></tr>
<tr><anchor name=`&> <td>Intersection (and)</td> <td><tt>a & b</tt></td> <td><tt>`&</tt></td> <td>All elements present in both a and b.</td></anchor></tr>
<tr><anchor name=`|> <td>Union (or)</td> <td><tt>a | b</tt></td> <td><tt>`|</tt></td> <td>All elements present in a or b.</td></anchor></tr>
<tr><anchor name=`^> <td>Symmetric difference (xor)</td><td><tt>a ^ b</tt></td> <td><tt>`^</tt></td> <td>All elements present in a or b, but not present in both.</td></anchor></tr>
</table>
<p>
</center>
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 work I suggest you go look it up in some other
programming book or just don't use these operators on integers.
<p>
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:
<tt>({7,6,4,3,2,1}) & ({1, 23, 5, 4, 7})</tt> will return
<tt>({7,4,1})</tt>. 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 operation on a mapping
however, only the indices are considered. The values are just copied with
the indices. 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: <tt>([1:2]) | ([1:3])</tt> will return <tt>([1:3])</tt>.
</section>
<section title="Indexing">
The index and range operators are used to retrieve information from a
complex data type.
<center>
<p>
<table border=1>
<tr> <th>Function</th> <th>Syntax</th> <th>Identifier</th> <th>Returns</th></tr>
<tr><anchor name=`[]> <td>Index</td> <td><tt>a [ b ]</tt></td> <td><tt>`[]</tt></td> <td>Returns the index b from a.</td></anchor></tr>
<tr><anchor name="`->"> <td>Lookup</td> <td><tt>a -><i>identifier</i></tt></td><td><tt>`-></tt></td><td>Looks up the identifier. Same as a["<i>identifier</i>"].</td></anchor></tr>
<tr><anchor name=`[]=> <td>Assign index</td> <td><tt>a [ b ] = c</tt></td> <td><tt>`[]=;</tt></td><td>Sets the index b in a to c.</td></anchor></tr>
<tr><anchor name="`->="><td>Assign index</td> <td><tt>a -><i>identifier</i> = c</tt></td><td><tt>`->=</tt></td><td>Sets the index "<i>identifier</i>" in a to c.</td></anchor></tr>
<tr><anchor name=`[..]> <td>Range</td> <td><tt>a [ b .. c ]</tt></td> <td><tt>`[..]</tt></td> <td>Returns a slice of a starting at the index b and ending at c.</td></anchor></tr>
<tr> <td>Range</td> <td><tt>a [ .. c ]</tt></td> <td><tt>`[..]</tt></td> <td>Returns a slice of a starting at the beginning of a and ending at c.</td></tr>
<tr> <td>Range</td> <td><tt>a [ b .. ]</tt></td> <td><tt>`[..]</tt></td> <td>Returns a slice of a from the index b to the end of a.</td></tr>
</table>
<p>
</center>
The index operator can be written in two different ways. It can be
written as <tt><i>ob</i> [ <i>index</i> ]</tt> or
<tt><i>ob</i>-><i>identifier</i></tt>. However, the latter syntax is
equal to <tt><i>ob</i> [ "<i>identifier</i>" ]</tt>.
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:
<p>
<center>
<table border=1>
<tr>
<th>Operation</th> <th>Returns</th>
</tr>
<tr>
<td><tt><i>string</i>[<i>int</i>]</tt></td><td>Returns the ascii value of the Nth character in the string.</td>
</tr>
<tr>
<td><tt><i>array</i>[<i>int</i>]</tt></td><td>Return the element in the array corresponding to the integer.</td>
</tr>
<tr>
<td><tt><i>array</i>[<i>int</i>]=<i>mixed</i></tt></td><td>Sets the element in the array to the mixed value.</td>
</tr>
<tr>
<td><tt>
<i>mapping</i>[<i>mixed</i>]<br>
<i>mapping</i>-><i>identifier</i>
</tt></td><td>Returns the value associated with the index, 0 if it is not found.</td>
</tr>
<tr>
<td><tt>
<i>mapping</i>[<i>mixed</i>]=<i>mixed</i><br>
<i>mapping</i>-><i>identifier</i>=<i>mixed</i>
</tt></td><td>Associate the second mixed value with the first mixed value.</td>
</tr>
<tr>
<td><tt>
<i>multiset</i>[<i>mixed</i>]<br>
<i>multiset</i>-><i>identifier</i>
</tt></td><td>Returns 1 if the index (the value between the brackets) is present in the multiset, 0 otherwise.</td>
</tr>
<tr>
<td><tt>
<i>multiset</i>[<i>mixed</i>]=<i>mixed</i><br>
<i>multiset</i>-><i>identifier=<i>mixed</i></i>
</tt></td><td>If the mixed value is <b>true</b> the index is added to the multiset. Otherwise the index is removed from the multiset.</td>
</tr>
<tr>
<td><tt>
<i>object</i>[<i>string</i>]<br>
<i>object</i>-><i>identifier</i><br>
</tt></td><td>Returns the value of the named identifier in the object.</td>
</tr>
<tr>
<td><tt>
<i>object</i>[<i>string</i>]=<i>mixed</i><br>
<i>object</i>-><i>identifier</i>=<i>mixed</i><br>
</tt></td><td>Set the given identifier in the object to the mixed value. Only works if the identifier references a variable in the object.</td>
</tr>
<tr>
<td><tt>
<i>program</i>[<i>string</i>]<br>
<i>program</i>-><i>identifier</i><br>
</tt></td><td>Returns the value of the named constant identifier
in the program.</td>
</tr>
<tr>
<td><tt><i>string</i>[<i>int</i>..<i>int</i>]</tt></td><td>Returns a piece of the string.</td>
</tr>
<tr>
<td><tt><i>array</i>[<i>int</i>..<i>int</i>]</tt></td><td>Returns a slice of the array.</td>
</tr>
</table>
</center>
<p>
When indexing an <tt>array</tt> or <tt>string</tt> 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 <tt> arr[-i] </tt> is the
same as <tt>arr[sizeof(arr)-i]</tt>. 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
<tt><i>a</i>[<i>b</i>..<i>c</i>]</tt> will be treated as follows:
<ul>
<li> If <i>b</i> is less than zero, the range will begin at the start
of the array as if <i>b</i> had been zero.
<li> If <i>b</i> is greater or equal to sizeof(<i>a</i>) an empty array/string
will be returned.
<li> If <i>c</i> is less than <i>b</i>, an empty array/string will be
returned.
<li> If <i>c</i> is greater or equal to sizeof(<i>a</i>) the range will
continue to the end of the array/string.
<li> No errors are generated in any of the above cases.
</ul>
</section>
<!-- FIXME: tell more about indexing and ranges -->
<section title="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:
<example language=pike meta=variable,expression>
variable = expression;
</example>
The <i>variable</i> 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 <i>variable</i> to <i>expression</i>. Note that the above
is also an expression which returns the value of the <i>expression</i>.
This can be used in some interesting ways:
<example language=pike meta=variable1,variable2,expression>
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);
</example>
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 <tt>if(<i>variable</i> == <i>expression</i>)</tt> 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:
<p>
<center>
<table border=1>
<tr><th>Syntax</th> <th>Same as</th> <th>Function</th></tr>
<tr><td><tt><i>variable</i> += <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> + <i>expression</i></td><td>Add <i>expression</i> to <i>variable</i></td></tr>
<tr><td><tt><i>variable</i> -= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> - <i>expression</i></td><td>Subtract <i>expression</i> from <i>variable</i></td></tr>
<tr><td><tt><i>variable</i> *= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> * <i>expression</i></td><td>Multiply <i>variable</i> with <i>expression</i></td></tr>
<tr><td><tt><i>variable</i> /= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> / <i>expression</i></td><td>Divide <i>variable</i> by <i>expression</i></td></tr>
<tr><td><tt><i>variable</i> %= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> % <i>expression</i></td><td>Modulo <i>variable</i> by <i>expression</i></td></tr>
<tr><td><tt><i>variable</i> <<= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> << <i>expression</i></td><td>Shift <i>variable</i> <i>expression</i> bits left</td></tr>
<tr><td><tt><i>variable</i> >>= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> >> <i>expression</i></td><td>Shift <i>variable</i> <i>expression</i> bits right</td></tr>
<tr><td><tt><i>variable</i> |= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> | <i>expression</i></td><td>Or <i>variable</i> with <i>expression</i></td></tr>
<tr><td><tt><i>variable</i> &= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> & <i>expression</i></td><td>And <i>variable</i> with <i>expression</i></td></tr>
<tr><td><tt><i>variable</i> ^= <i>expression</i></tt></td><td> <i>variable</i> = <i>variable</i> ^ <i>expression</i></td><td>Xor <i>variable</i> with <i>expression</i></td></tr>
</table>
</center>
<p>
<anchor name=lvalues>
In all of the above expressions <i>variable</i> can actually be any of type
of assignable values. Assignable values are also known as <b>lvalues</b> and
here is a list of <b>lvalues</b>:
<p>
<center>
<table border=1>
<tr><th>Lvalue type</th><th>Syntax</th><th>Valid assignment type</th></tr>
<tr><td> a local or global variable </td><td> <i>identifier</i> </td> <td>same as variable</td></tr>
<tr><td> an element in an array </td><td> <i>array</i> [ <i>int</i> ]</td><td>any type</td></tr>
<tr><td> an element in an string </td><td> <i>string</i> [ <i>int</i> ]</td><td>integer</td></tr>
<tr><td> an element in a mapping </td><td> <i>mapping</i>[<i>mixed</i>] or <i>mapping</i>-><i>identifier</i> </td><td>any type</td></tr>
<tr><td> an element in a multiset </td><td> <i>multiset</i>[<i>mixed</i>] or <i>multiset</i>-><i>identifier</i> </td><td>true / false</td></tr>
<tr><td> a variable in an object </td><td> <i>object</i>[<i>string</i>] or <i>object</i>-><i>identifier</i> </td> <td>same type as named variable</td></tr>
<tr><td> a list of lvalues </td><td> [ <i>lvalue</i>, <i>lvalue</i> ] </td><td> an array, first value in the array will be assigned to the first lvalue in the list, second value in the array to the second value in the list etc. </td></tr>
</table>
</center>
</anchor>
</section>
<section title="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.
<center>
<p>
<table border=1>
<tr><th>Function</th> <th>Syntax</th> <th>Identifier</th><th>Returns</th></tr>
<tr><anchor name=`()><td>Calling</td><td><tt>a ( <i>args</i> )</tt></td><td><tt>`()</tt></td><td>Calls the function a.</td></anchor></tr>
<tr><td>splice</td> <td><tt>@ <i>a</i></tt></td> <td>none</td> <td>Sends each element in the array a as an individual argument to a function call.</td></tr>
<tr><td>Increment</td> <td><tt>++ a</tt></td> <td>none</td> <td>Increments a and returns the new value of a.</td></tr>
<tr><td>Decrement</td> <td><tt>-- a</tt></td> <td>none</td> <td>Decrements a and returns the new value of a.</td></tr>
<tr><td>Post increment</td><td><tt>a ++</tt></td> <td>none</td> <td>Increments a and returns the old value of a.</td></tr>
<tr><td>Post decrement</td><td><tt>a --</tt></td> <td>none</td> <td>Decrements a and returns the old value of a.</td></tr>
<tr><td>casting</td> <td><tt>(<i>type</i>) a</tt></td><td>none</td> <td>Tries to convert a into a value of the specified type.</td></tr>
<tr><td>Null</td> <td><tt>a, b</tt></td> <td>none</td> <td>Evaluates a and b, then returns b.</td></tr>
</table>
<p>
</center>
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.
<!-- In fact, <tt>({ foo, bar, gazonk }) (1, 2, 3)</tt> is the same as <tt>map(({ foo, bar, gazonk }), call_function, 1, 2, 3)</tt>. -->
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 <tt>clone</tt> is
implemented like this:
<p>
<example language=pike>
object clone(mixed p, mixed ... args) { ( (program)p )(@args); }
</example>
<p>
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.
<p>
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
(<tt>++<i>a</i></tt>) 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 (<tt><i>a</i>++</tt>) it will instead return the
value of the variable before it was incremented/decremented.
<p>
<anchor name=cast>
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:
<p>
<center>
<table border=1>
<tr><th>casting from</th><th>to</th><th>operation</th></tr>
<tr><td>int</td><td>string</td><td>Convert the int to ASCII representation</td></tr>
<tr><td>float</td><td>string</td><td>Convert the float to ASCII representation</td></tr>
<tr><td>string</td><td>int</td><td>Convert decimal, octal or hexadecimal number to an int. Note that this will only work with decimal numbers in future versions.</td></tr>
<tr><td>string</td><td>float</td><td>Convert ASCII number to a float.</td></tr>
<tr><td>string</td><td>program</td><td>String is a filename, compile the file and return the program. Results are cached.</td></tr>
<tr><td>string</td><td>object</td><td>This first casts the string to a program, (see above) and then clones the result. Results are cached.</td></tr>
<tr><td>object</td><td><i>type</i></td><td>This calls the function 'cast' with a string containing the type as an argument.</td></tr>
<tr><td>string</td><td>array</td><td>Same as doing <tt>values(<i>string</i>)</tt></td></tr>
<tr><td>array(int)</td><td>string</td><td>This does the inverse of the operation above. Ie. it constructs a string from an array of integers.</td></tr>
<tr><td>array</td><td>array(<i>type</i>)</td><td>This recursively casts all values in the array to <i>type</i>.</td></tr>
<tr><td>mapping</td><td>array</td><td>Same as <tt>Array.transpose(({indices(<i>mapping</i>),values(<i>mapping</i>))</tt>. Example: <tt>(array)([1:2,3:4])</tt> will return <tt>({ ({1,2}), ({3,4}) })</tt> </td></tr>
<tr><td>multiset</td><td>array</td><td>Same as doing <tt>indices(<i>multiset</i>)</tt>.</td></tr>
<tr><td>int</td><td>float</td><td>Returns a float with the same value as the integer.</td></tr>
<tr><td>float</td><td>int</td><td>Returns the integer closest to the float.</td></tr>
<tr><td>function</td><td>object</td><td>Same as <tt>function_object(<i>function</i>)</tt>.</td></tr>
</table>
</center>
<p>
You can also use the cast operator to tell the compiler things.
If <tt>a</tt> is a variable of type mixed containing an int, then the
expression <tt>(int)a</tt> can be used instead of <tt>a</tt> and that will
tell the compiler that the type of that expression is <tt>int</tt>.
</anchor>
<p>
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.
<p>
</section>
<section title="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 with lower. The following table shows
the relative priority of all the operators in descending order:
<p>
<center>
<table border=1 halign=center>
<tr><th>Operators</th></tr>
<tr><td><center><tt>(a) a() a[b] a->b a[b..c] ({}) ([]) (<>)</tt></center></td></tr>
<tr><td><center><tt>!a ~a (type)a ++a --a</tt></center></td></tr>
<tr><td><center><tt>a++ a--</tt></center></td></tr>
<tr><td><center><tt>a*b a/b a%b</tt></center></td></tr>
<tr><td><center><tt>a+b a-b</tt></center></td></tr>
<tr><td><center><tt>a>>b a<<b</tt></center></td></tr>
<tr><td><center><tt>a>b a>=b a<b a<=b</tt></center></td></tr>
<tr><td><center><tt>a==b a!=b</tt></center></td></tr>
<tr><td><center><tt>a&b</tt></center></td></tr>
<tr><td><center><tt>a^b</tt></center></td></tr>
<tr><td><center><tt>a|b</tt></center></td></tr>
<tr><td><center><tt>&&</tt></center></td></tr>
<tr><td><center><tt>||</tt></center></td></tr>
<tr><td><center><tt>a?b:c</tt></center></td></tr>
<tr><td><center><tt>=</tt></center></td></tr>
<tr><td><center><tt>@a</tt></center></td></tr>
<tr><td><center><tt>,</tt></center></td></tr>
</table>
</center>
<p>
Examples:
<center>
<table border=1>
<tr><th>The expression</th><th>is evaluated in this order:</th></tr>
<tr><td><tt> 1+2*2 </tt></td><td><tt> 1+(2*2) </tt></td></tr>
<tr><td><tt> 1+2*2*4 </tt></td><td><tt> 1+((2*2)*4) </tt></td></tr>
<tr><td><tt> (1+2)*2*4 </tt></td><td><tt> ((1+2)*2)*4 </tt></td></tr>
<tr><td><tt> 1+4,c=2|3+5 </tt></td><td><tt> (1+4),(c=((2|3)+5)) </tt></td></tr>
<tr><td><tt> 1+5 & 4 == 3 </tt></td><td><tt> (1+(5 & 4)) == 3 </tt></td></tr>
<tr><td><tt> c=1,99 </tt></td><td><tt> (c=1),99 </tt></td></tr>
<tr><td><tt> !a++ + ~--a()</tt></td><td><tt> (!(a++)) + (~((--a)())) </tt></td></tr>
</table>
</center>
</section>
<section title="Operator functions">
As mentioned earlier <tt>a + b</tt> can just as well be written as
<tt>`+(a, b)</tt>. Together with the function <tt>map</tt> 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:
<dl>
<dt> <tt>map(arr, `-)</tt>
<dd> This will return an array with each element negated.
<dt> <tt>map(text/"\n",`/," ")</tt>
<dd> This will divide a text into lines, each line will then be mapped
through <tt>`/</tt> and divided into an array of words.
<dt> <tt>`+(0, @arr)</tt>
<dd> This will add all the integers in the array <tt>arr</tt> together.
<dt> <tt>int abs(int a) { return ( a>0 ? `+ : `-)(a); }</tt>
<dd> This is a rather absurd but working function which will return the
absolute value of a.
</dl>
</section>
</chapter>
<chapter title="Object orientation">
As mentioned 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
oriented programming.
<section title="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
Pike-ish terms to C++-ish terms:
<dl>
<dt> a <i>class</i> <dd> a class
<dt> a <i>clone</i> <dd> an instance of a class
<dt> to <i>clone</i> <dd> to create an instance
<dt> an <i>object</i> <dd> an instance of a class
<dt> a <i>program</i> <dd> a class
</dl>
</section>
<section title="The approach">
Think of the data type <tt>program</tt> 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.
<!-- FIXME: do something about the following sentence? -->
Now we have a running system with
many running programs, each performing only the task it was designed for.
<p>
This analogy has one major flaw, when running programs in UNIX they actually
run simultaneously. UNIX is <i>multitasking</i>, 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 <b>threads</b> as will be
discussed in a later chapter.
</section>
<section title="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.
<p>
In my experience, the advantages of object oriented programming are:
<dl>
<dt>Modular programming made easy
<dd>Using <b>The approach</b> makes it easy to divide a project into smaller
pieces, these pieces are usually easier to write than the whole.
<dt>Local data scope
<dd>This is a very nifty thing with object oriented programs. If your program
uses several files, windows, stacks, TCP connections or whatever, you
simply write a <tt>program</tt> that handles one such file, window,
stack or TCP connection. If correctly written, you can then just create
many clones of that program.
<dt>Using the same interface to different objects
<dd>I can write a function that take 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 <tt>write</tt> method) and send that to the function
that outputs the data.
</dl>
Most of these things can be done without object orientation, but it is
object orientation that makes them easy.
</section>
<section title="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
<b>program</b> then cloned and then main() is called in that clone. All
this is done by the <b>master object</b>, which is compiled and cloned before
before all other objects. What the <b>master object</b> actually does is:
<example language=pike>
program scriptclass=compile_file(argv[0]); // Load script
object script=scriptclass(); // clone script
int ret=script->main(sizeof(argv), argv); // call main()
</example>
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.
<p>
If you don't want to put each program in a separate file, you can use the
<tt>class</tt> keyword to write all your classes in one file. We have
already seen an example how this in <ref to=types>, but let's go over it in
more detail. The syntax looks like this:
<example language=pike meta=class_name,class_definition>
class class_name {
class_definition
}
</example>
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 <i>class_name</i> and leave the class unnamed. The
<i>class definition</i> is simply the functions and programs you want to add
to the class.
<p>
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:
<example language=pike>
class foo {};
constant foo = class {};
</example>
Because classes are defined as constants, it is possible to use a class defined
inside classes you define later, like this:
<example language=pike>
class foo
{
int test() { return 17; }
};
class bar
{
program test2() { return foo; }
};
</example>
<!-- FIXME: tell more -->
</section>
<section title="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 <tt>inherit</tt> is all about.
Let's say I want to change the <tt>hello_world</tt> program to write a version number
before it writes hello world, using <tt>inherit</tt> I could do this like
this:
<example language=pike>
inherit "hello_world";
int main(int argc, array(string) argv)
{
write("Hello world version 1.0\n");
return ::main(argc,argv);
}
</example>
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 <tt>::</tt>
in front of the function name. The argument to inherit can be one of the following:
<dl>
<dt> A string
<dd> This will have the same effect as casting the string to a program and then
doing inherit on this program.
<dt> A constant containing a program.
<dd> Any constant from this program, module or inherited program that contains a
program can be inherited.
<dt> A class name
<dd> A class defined with the <tt>class</tt> keyword is in fact added as a constant,
so the same rule as above applies.
</dl>
<p>
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:
<center>
<image xfig=inherit><br>
</center>
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 inherits with the <tt>::</tt>
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.
</section>
<section title="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 get 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:
<example language=pike>
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 the third inherit
test1::read(); // Read data from the fourth inherit
test2::main(0,({})); // Call main in the fifth inherit
::read(); // Read data from all inherits
}
</example>
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 <tt>read</tt> without any <tt>::</tt> 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.
<p>
If you leave the inherit name blank and just call <tt>::read</tt> Pike will
call all inherited read() functions. If there is more than one inherited
read function the results will be returned in an array.
<p>
Let's look at another example:
<example language=pike>
#!/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);
}
}
</example>
This short piece of code works a lot like the UNIX command <tt>cat</tt>.
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.
</section>
<section title="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.
</section>
<section title="Modifiers" name=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
<b>modifiers</b>. 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:
<dl>
<dt><tt>static</tt>
<dd>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.
<dt><tt>final</tt>
<dd>This prevents other objects from re-defining this identifier in
programs that inherit this program.
<dt><tt>local</tt>
<dd>This makes the identifier 'local' meaning that even if
it is overloaded in an inheriting program, this program will still
use this identifer.
<dt><tt>private</tt>
<dd>This prevents inheriting programs from accessing this identifier.
Note that inheriting program can still re-define the identifier.
Also note that <tt>private</tt> does not imply <tt>static</tt>.
<dt><tt>public</tt>
<dd>This is the opposite of <tt>private</tt>. This is the default for
all identifiers. <tt>public</tt> can be used to override the effects
of a private inherit.
<dt><tt>protected</tt>
<dd>Reserved for future use.
</dl>
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, <tt>private inherit</tt> means that
the identifiers from this inherit will not be available to program inheriting
this program. <tt>static private inherit</tt> will also hide those identifiers
from the index and arrow operators, making the inherit available only to the
code in this program.
</section>
<section title="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.
<p>
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 <tt>==</tt> and <tt>!</tt> 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
<ref to=operators> for information on which operators can operate on objects
without operator overloading.
<center>
<table border=1>
<tr><th>Operation</th><th>Will call</th><th>Or</th></tr>
<tr><td>a+b</td><td>a->`+(b)</td><td>b->``+(a)</td></tr>
<tr><td>a+b+c+d</td><td>a->`+(b,c,d)</td><td>(b->(a))+c+d</td></tr>
<tr><td>a-b</td><td>a->`-(b)</td><td>b->``-(a)</td></tr>
<tr><td>a&b</td><td>a->`&(b)</td><td>b->``&(a)</td></tr>
<tr><td>a|b</td><td>a->`|(b)</td><td>b->``|(a)</td></tr>
<tr><td>a^b</td><td>a->`^(b)</td><td>b->``^(a)</td></tr>
<tr><td>a>>b</td><td>a->`>>(b)</td><td>b->``>>(a)</td></tr>
<tr><td>a<<b</td><td>a->`<<(b)</td><td>b->``<<(a)</td></tr>
<tr><td>a*b</td><td>a->`*(b)</td><td>b->``*(a)</td></tr>
<tr><td>a*b*c*d</td><td>a->`*(b,c,d)</td><td>b->`*(a)*c*d</td></tr>
<tr><td>a/b</td><td>a->`/(b)</td><td>b->``/(a)</td></tr>
<tr><td>a%b</td><td>a->`%(b)</td><td>b->``%(a)</td></tr>
<tr><td>~a</td><td>a->`~()</td></tr>
<tr><td>a==b</td><td>a->`==(b)</td><td>b->`==(a)</td></tr>
<tr><td>a!=b</td><td>!( a->`==(b) )</td><td>!( b->`==(a) )</td></tr>
<tr><td>a<b</td><td>a->`<(b)</td><td>b->`>(a)</td></tr>
<tr><td>a>b</td><td>a->`>(b)</td><td>b->`<(a)</td></tr>
<tr><td>a<=b</td><td>!( b->`>(a) )</td><td>!( a->`<(b) )</td></tr>
<tr><td>a>=b</td><td>!( b->`<(a) )</td><td>!( a->`>(b) )</td></tr>
<tr><td>(int)a</td><td>a->cast("int")</td></tr>
<tr><td>!a</td><td>a->`!()</td></tr>
<tr><td>if(a) { ... } </td><td>!( a->`!() )</td></tr>
<tr><td>a[b]</td><td>a->`[](b)</td></tr>
<tr><td>a[b]=c</td><td>a->`[]=(b,c)</td></tr>
<tr><td>a->foo</td><td>a->`->("foo")</td></tr>
<tr><td>a->foo=b</td><td>a->`->=("foo",b)</td></tr>
<tr><td>sizeof(a)</td><td>a->_sizeof()</td></tr>
<tr><td>indices(a)</td><td>a->_indices()</td></tr>
<tr><td>values(a)</td><td>a->_values()</td></tr>
<tr><td>a(b)</td><td>a->`()(b)</td></tr>
</table>
</center>
<p>
Here is a really silly example of a program that will write 10
to stdout when executed.
<example language=pike>
#!/usr/local/bin/pike
class three {
int `+(int foo) { return 3+foo; }
};
int main()
{
write(sprintf("%d\n",three()+7));
}
</example>
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.
</section>
<section title="Simple exercises">
<exercises>
<exercise>
Make a program that clones 10 hello world and then runs main() in
each one of them.
</exercise><exercise>
Modify the register program to use an object for each record.
</exercise><exercise>
Modify the register program to use the following search function:
<example language=pike>
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");
}
</example>
</exercise>
</exercises>
<!-- FIXME add more examples above -->
</section>
</chapter>
<chapter title="Miscellaneous functions" name=misc>
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.
<anchor name=sscanf>
<section title="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:
<example language=pike meta=str,fmt,lvalue>
int sscanf(string str, string fmt, lvalue ...)
</example>
The string <i>str</i> will be matched against the format string <i>fmt</i>.
<i>fmt</i> can contain strings
separated by %d,%s,%c and %f. Every % corresponds to one <i>lvalue</i>.
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.
<p>
Whenever a percent is found in the format string, a match is according
to the following table:
<table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> %d </td><td> reads an integer </td></tr>
<tr valign=top><td> %o </td><td> reads an octal integer </td></tr>
<tr valign=top><td> %x </td><td> reads a hexadecimal integer </td></tr>
<tr valign=top><td> %D </td><td> reads an integer that is either octal (leading zero), hexadecimal (leading 0x) or decimal. </td></tr>
<tr valign=top><td> %f </td><td> reads a float </td></tr>
<tr valign=top><td> %c </td><td> matches one char and returns it as an integer </td></tr>
<tr valign=top><td> %2c </td><td> matches two chars and returns them as an integer (short) </td></tr>
<tr valign=top><td> %4F </td><td> matches four chars and returns them as a float (IEEE single precision) </td></tr>
<tr valign=top><td> %8F </td><td> matches eigth chars and returns them as a float (IEEE double precision) </td></tr>
<tr valign=top><td> %s </td><td> 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. </td></tr>
<tr valign=top><td> %5s </td><td> gives a string of 5 characters (5 can be any number) </td></tr>
<tr valign=top><td> %[set] </td><td> 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'. </td></tr>
<tr valign=top><td> %{format%} </td><td> Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue. </td></tr>
</table>
<p>If a * is put between the percent and the operator, the operator
will only match its argument, not assign any variables.
<p>
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.
<p>
Let's look at a couple of examples:
<example language=pike>
// 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);
</example>
<p>
<encaps>SEE ALSO</encaps>: <link to=sprintf>sprintf</link>
</section>
</anchor>
<anchor name=catch>
<anchor name=exceptions>
<section title="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:
<example language=pike meta=statements>
catch { statements }
</example>
If an error occurs, catch will return a description of the error.
The description of the error has the following format:
<example language=pike>
({
"error description",
backtrace()
})
</example>
If no error occurs, catch will return zero. You may emulate your own errors
using the function throw, described in <ref to=functions>.
<p>
Example:
<example language=pike>
int x,y;
// This might generate "division by zero"
mixed error=catch { x/=y; };
</example>
</section>
</anchor>
</anchor>
<anchor name=gauge>
<section title="gauge">
The syntax for gauge is the same as the syntax for catch:
<example language=pike meta=statements>
gauge { statements }
</example>
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.
</section>
</anchor>
<anchor name=typeof>
<section title="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:
<example language=pike>
typeof( exit(1) )
</example>
This will return the string <tt>"void"</tt> since exit is a function that
returns void.
It will not execute the function <tt>exit</tt> and exit the process as you
might expect.
<p>
If you want to know the type after evaluation, use
<tt>sprintf("%t", expr)</tt>.
</section>
</anchor>
</chapter>
<chapter title="Modules" name=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.
<p>
here is a list of the basic Pike modules:
<dl>
<dt>Stdio
<dd>This module contains file I/O routines.
<dt>Array
<dd>This module contains functions that operate on arrays.
<dt>Calendar
<dd>Support for different calendar and date formats.
<dt>Crypto *
<dd>Cryptography routines.
<dt>Gdbm *
<dd>This module contains support for Gdbm databases.
<dt>Getopt
<dd>Routines to parse command line options
<dt>Gmp *
<dd>Support for large numbers.
<dt>Gz *
<dd>Deflate packing algorithms.
<dt>Image
<dd>Image manipulation routines.
<dt>LR
<dd>LALR(1) parser generator.
<dt>Msql *
<dd>Sql database support for the mini-SQL database server.
<dt>MIME
<dd>Support for coding and decoding MIME.
<dt>Mysql *
<dd>Sql database support for the mySQL database server.
<dt>Process
<dd>Functions to start and control other processes.
<dt>Protocols
<dd>Support for HTTP, NNTP, SMNT, DNS, TELNET and other protocols.
<dt>Regexp
<dd>Regexp matching routines.
<dt>Simulate
<dd>Routines to emulate old Pike routines.
<dt>String
<dd>Routines that operate on strings.
<dt>Sql *
<dd>Support for ASN1, PKCS and other standards.
<dt>Standards
<dd>Generic SQL database support.
<dt>System
<dd>Support for system specific functions.
<dt>Thread *
<dd>Thread support functions.
<dt>Tools
<dd>Complete programs available to use from within scripts.
<dt>Yp *
<dd>Network Information System support.
</dl>
<p>
* These modules might not be available depending on how Pike was compiled
and whether support for these functions exist on your system.<br>
<p>
<section title="How to use modules">
A module is a bunch of functions, programs or other modules collected in
one symbol. For instance, the module <tt>Stdio</tt> contains the objects
<tt>stdin</tt>, <tt>stdout</tt> and <tt>stderr</tt>. To access these objects
you can write <tt>Stdio.stdin</tt>, <tt>Stdio.stdout</tt> or
<tt>Stdio.stderr</tt> anywhere in your program where an object of that type
is acceptable. If you use <tt>Stdio</tt> a lot you can put
<tt>import Stdio;</tt> 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 <tt>stdin</tt> instead of <tt>Stdio.stdin</tt>.
It is also possible to import all modules in a directory with <tt>import</tt>
by putting the directory name in doublequtes. So, to import all modules in
the current directory, you would use <tt>import ".";</tt>.
</section>
<section title="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.
<p>
When you use <tt>Stdio</tt> Pike will look for that module:
<ol>
<li> In imported directories.
<li> In directories added with add_module_path()
<li> In directories specified with -M on the command line.
<li> In directories in the environment variable PIKE_MODULE_PATH
<li> In the directory with builtin modules, usually /usr/local/lib/pike/modules/
</ol>
For each of these directories, Pike will do the following:
<ol>
<li> If there is a file called Stdio.pmod.pike, Pike will load this
Pike program, clone it and use that as a module.
<li> If there is a file called Stdio.pmod.so, Pike will load this
with load_module(), clone it and use that as a module.
<li> 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 <tt>module</tt> in that directory, all identifiers
from that module will overload any modules actually present in the
directory.
</ol>
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.
</section>
<section title="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.
<p>
You can also use the . operator without an identifier preceeding it to
access modules in the same directory as the program itself. For instance,
<tt>.my_module.foo</tt> would mean 'the identifier <tt>foo</tt> in the module
<tt>my_module</tt> in this directory.
</section>
<section title="How to write a module">
Here is an example of a simple module:
<example language=pike>
constant PI = 3.14159265358979323846264338327950288419716939937510;
float cos2(float f) { return pow(cos(f),2.0); }
</example>
if we save this short file as <tt>Trig.pmod</tt> we can now use this
module like this:
<example language=pike>
int main()
{
write(sprintf("%f\n",.Trig.cos2(.Trig.PI));
}
</example>
or like this:
<example language=pike>
import .Trig;
int main()
{
write(sprintf("%f\n",cos2(PI));
}
</example>
</section>
<section title="Simple exercises">
<exercises>
<exercise>
Save the hello_world.pike program as hello_world.pike.pmod, then make
a program that loads this module and calls its main().
</exercise><exercise>
Make a directory called <tt>Programs.pmod</tt>
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.
</exercise><exercise>
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 <tt>hello_world</tt>.
</exercise><exercise>
Try putting <tt>Programs.pmod</tt> in another directory and then try to
run the programs from the last two examples.
</exercise>
</exercises>
</section>
</chapter>
<chapter title="File I/O" name=io>
<module name=Stdio>
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 <tt>Stdio</tt>.
<section title="Stdio.File">
<class name=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. <tt>Stdio.File</tt> is completely
written in C. What follows is a description of all the functions in
<tt>Stdio.File</tt>.
<method name=create title="init file struct">
<man_syntax>
object(Stdio.File) Stdio.File();<br>
object(Stdio.File) Stdio.File(string <I>fd</I>);<br>
object(Stdio.File) Stdio.File(string <i>file</i>, string <i>mode</i>);<br>
</man_syntax>
<man_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.
<p>
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.
<p>
Alternatively, you can clone a File with "stdin", "stdout" or
"stderr" as argument. This will open the specified standard
stream.
</man_description>
<man_see>clone, Stdio.File->open</man_see>
</method>
<method name=open title="open a file">
<man_syntax>
int open(string <I>filename</I>, string <I>how</I>);<br>
</man_syntax>
<man_description>
Open a file for read, write or append. The variable <i>how</i> should
contain one or more of the following letters:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> 'r' </td><td> open file for reading </td></tr>
<tr valign=top><td> 'w' </td><td> open file for writing </td></tr>
<tr valign=top><td> 'a' </td><td> open file for append (use with 'w') </td></tr>
<tr valign=top><td> 't' </td><td> truncate file at open (use with 'w') </td></tr>
<tr valign=top><td> 'c' </td><td> create file if it doesn't exist (use with 'w') </td></tr>
<tr valign=top><td> 'x' </td><td> fail if file already exist (use with 'c') </td></tr>
</table>
<p><i>How</i> should _always_ contain at least one of 'r' or 'w'.
<p>Returns 1 on success, 0 otherwise.
</man_description>
<man_see>Stdio.File->close</man_see>
</method>
<method name=close title="close a file">
<man_syntax>
int close(string <I>how</I>);<br>
int close();<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->open</man_see>
</method>
<method name=read title="read data from a file or stream">
<man_syntax>
string read(int <I>nbytes</I>);<br>
string read(int <I>nbytes</I>, int <I>notall</I>);<br>
string read();<br>
</man_syntax>
<man_description>
Read tries to read <i>nbytes</i> bytes from the file, and return it as a
string. If something goes wrong, zero is returned.
<p>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.
<p>
If no arguments are given, read will read to the end of the file/stream.
</man_description>
<man_see>Stdio.File->read_oob,Stdio.File->write</man_see>
</method>
<method name=read_oob title="read out-of-band data from a stream">
<man_syntax>
string read_oob(int <I>nbytes</I>);<br>
string read_oob(int <I>nbytes</I>, int <I>notall</I>);<br>
string read_oob();<br>
</man_syntax>
<man_description>
Tries to read <i>nbytes</i> bytes of out-of-band data from the stream,
and returns it as a string. If something goes wrong, zero is returned.
<p>
If a one is given as a second argument to <tt>read_oob()</tt>, only
as many bytes of out-of-band data as are currently available will be
returned.
<p>
If no arguments are given, <tt>read_oob</tt> will read to the end of
the stream.
</man_description>
<man_note>
This function is only available if the option '--with-oob' was specified
when Pike was compiled.
<p>
It is not guaranteed that all out-of-band data sent from the other end
will be received. Most streams only allow for a single byte of out-of-band
data at a time.
</man_note>
<man_see>Stdio.File->read,Stdio.File->write_oob</man_see>
</method>
<method name=write title="write data to a file or stream">
<man_syntax>
int write(string <I>data</I>);<br>
</man_syntax>
<man_description>
Write data to file or stream and return how many bytes that were
actually written. -1 is returned if something went wrong and no
bytes were written.
</man_description>
<man_see>Stdio.File->read,Stdio.File->write_oob</man_see>
</method>
<method name=write_oob title="write out-of-band data to a stream">
<man_syntax>
int write_oob(string <I>data</I>);<br>
</man_syntax>
<man_description>
Writes out-of-band data to a stream and returns how many bytes that were
actually written. -1 is returned if something went wrong and no
bytes were written.
</man_description>
<man_note>
This function is only available if the option '--with-oob' was specified
when Pike was compiled.
<p>
It is not guaranteed that all out-of-band data will be received at the
other end. Most streams only allow for a single byte of out-of-band data
at a time. Some streams will send the rest of the data as ordinary data.
</man_note>
<man_see>Stdio.File->read_oob,Stdio.File->write</man_see>
</method>
<method name=seek title="seek to a position in a file">
<man_syntax>
int seek(int <I>pos</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->tell</man_see>
</method>
<method name=tell title="tell where we are in a file">
<man_syntax>
int tell();<br>
</man_syntax>
<man_description>
Returns the current position in the file.
</man_description>
<man_see>Stdio.File->seek</man_see>
</method>
<method name=truncate title="truncate a file">
<man_syntax>
int truncate(int length);<br>
</man_syntax>
<man_description>
Truncates a file to that length.
Returns 1 if ok, 0 if failed.
</man_description>
<man_see>Stdio.File->open</man_see>
</method>
<method name=stat title="do file_stat on an open file">
<man_syntax>
array(int) stat();<br>
</man_syntax>
<man_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.
</man_description>
<man_see>file_stat</man_see>
</method>
<method name=errno title="what was last error?">
<man_syntax>
int errno();<br>
</man_syntax>
<man_description>
Returns the error code for the last command on this file.
Error code is normally cleared when a command is successful.
</man_description>
</method>
<method name=set_buffer title="set internal socket buffer">
<man_syntax>
void set_buffer(int <I>bufsize</I>, string <I>mode</I>);<br>
void set_buffer(int <I>bufsize</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->open_socket, Stdio.Port->accept</man_see>
</method>
<method name=set_nonblocking title="make stream nonblocking">
<man_syntax>
void set_nonblocking(function(mixed, string:void) read_callback,<br>
<dl><dt><dd>function(mixed:void) write_callback,<br>
function(mixed:void) close_callback);<br>
</dl>
or<br>
void set_nonblocking(function(mixed, string:void) read_callback,<br>
<dl><dt><dd>function(mixed:void) write_callback,<br>
function(mixed:void) close_callback,<br>
function(mixed, string:void) read_oob_callback,<br>
function(mixed:void) write_oob_callback);<br>
</dl>
or<br>
void set_nonblocking();<br>
</man_syntax>
<man_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.
<p>
When out-of-band data arrives on the stream, read_oob_callback will
be called with some or all of this data. When the stream allows
out-of-band data to be sent, write_oob_callback is called so that
you can write out-of-band data to it.
<p>
All callbacks will have the id of file as first argument when called.
<p>
If no arguments are given, the callbacks are not changed. The
stream is just set to nonblocking mode.
</man_description>
<man_note>
Out-of-band data is only supported if Pike was compiled with the option
'--with-oob'.
</man_note>
<man_see>Stdio.File->set_blocking,Stdio.File->set_id</man_see>
</method>
<method name=set_read_callback title="set the read callback">
<man_syntax>
void set_read_callback(function read_callback)<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->set_nonblocking</man_see>
</method>
<method name=set_write_callback title="set the write callback">
<man_syntax>
void set_write_callback(function write_callback)<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->set_nonblocking</man_see>
</method>
<method name=set_close_callback title="set the close callback">
<man_syntax>
void set_close_callback(function close_callback)<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->set_nonblocking</man_see>
</method>
<method name=set_blocking title="make stream blocking">
<man_syntax>
void set_blocking();<br>
</man_syntax>
<man_description>
This function sets a stream to blocking mode. i.e. all reads and writes
will wait until data has been written before returning.
</man_description>
<man_see>Stdio.File->set_nonblocking</man_see>
</method>
<method name=set_id title="set id of this file">
<man_syntax>
void set_id(mixed <I>id</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->query_id</man_see>
</method>
<method name=query_id title="get id of this file">
<man_syntax>
mixed query_id();<br>
</man_syntax>
<man_description>
This function returns the id of this file.
</man_description>
<man_see>Stdio.File->set_id</man_see>
</method>
<method name=query_read_callback title="return the read callback function">
<man_syntax>
function query_read_callback();<br>
</man_syntax>
<man_description>
This function returns the read_callback, which is set with
set_nonblocking or set_read_callback.
</man_description>
<man_see>Stdio.File->set_nonblocking, Stdio.File->set_read_callback</man_see>
</method>
<method name=query_write_callback title="return the write callback function">
<man_syntax>
function query_write_callback();<br>
</man_syntax>
<man_description>
This function returns the write_callback, which is set with
set_nonblocking or set_write_callback.
</man_description>
<man_see>Stdio.File->set_nonblocking, Stdio.File->set_write_callback</man_see>
</method>
<method name=query_close_callback title="return the close callback function">
<man_syntax>
function query_close_callback();<br>
</man_syntax>
<man_description>
This function returns the close_callback, which is set with
set_nonblocking or set_close_callback.
</man_description>
<man_see>Stdio.File->set_nonblocking, Stdio.File->set_close_callback</man_see>
</method>
<method name=dup title="duplicate a file">
<man_syntax>
object(Stdio.File) dup();<br>
</man_syntax>
<man_description>
This function returns a clone of Stdio.File with all variables
copied from this file. Note that all variables, even id, is copied.
</man_description>
<man_see>Stdio.File->assign</man_see>
</method>
<method name=dup2 title="duplicate a file over another">
<man_syntax>
int dup2(object(Stdio.File) <I>to</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_example>
<example language=pike>
/* Redirect stdin to come from the file 'foo' */
object o=Stdio.File();
o->open("foo","r");
o->dup2(Stdio.File("stdin"));
</example>
</man_example>
<man_see>Stdio.File->assign, Stdio.File->dup</man_see>
</method>
<method name=assign title="assign a file">
<man_syntax>
void assign(object <I>f</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->dup</man_see>
</method>
<method name=open_socket title="open a socket">
<man_syntax>
int open_socket(int|void port, string|void address);<br>
</man_syntax>
<man_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.
<p>
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.
</man_description>
<man_see>Stdio.File->connect, Stdio.File->set_nonblocking</man_see>
</method>
<method name=connect title="connect a socket to something">
<man_syntax>
int connect(string <I>IP</I>,int <I>port</I>);<br>
</man_syntax>
<man_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.
<p>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.
</man_description>
<man_see>Stdio.File->query_address</man_see>
</method>
<method name=query_address title="get addresses">
<man_syntax>
string query_address();<br>
string query_address(1);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File->connect</man_see>
</method>
<method name=pipe title="create a two-way pipe">
<man_syntax>
object pipe();<br>
</man_syntax>
<man_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.
</man_description>
<man_see>fork</man_see>
</method>
<method name=set_close_on_exec title="set / clear the close on exec flag">
<man_syntax>
void set_close_on_exec(int <I>onoff</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>exece</man_see>
</method>
<!-- FIX ME might be good to have a plain and simple example of Stdio.File here -->
<p>
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 <tt>File::</tt> even if that is not strictly
necessary.
<example language=pike>
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());
}
</example>
</class>
</section>
<section title="Stdio.FILE">
<class name=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:
<hr noshade size=1>
<method name=gets title="get one line">
<man_syntax>
string gets();<br>
</man_syntax>
<man_description>
This function returns one line from the FILE, it returns zero if
no more lines are available.
</man_description>
</method>
<method name=printf title="formatted print">
<man_syntax>
string printf(string <I>format</I>, mixed ... <I>data</I>);<br>
</man_syntax>
<man_description>
This function does approximately the same as:
write(sprintf(format,@data))
</man_description>
<man_see>sprintf</man_see>
</method>
<method name=ungets title="put a string back in the buffer">
<man_syntax>
string ungets(string <I>s</I>);<br>
</man_syntax>
<man_description>
This function puts a string back in the input buffer. The string
can then be read with read, gets or getchar.
</man_description>
</method>
<method name=getchar title="get one character from the input stream">
<man_syntax>
int getchar();<br>
</man_syntax>
<man_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.
</man_description>
</method>
<!-- FIX ME, example of how to use Stdio.FILE here -->
</class>
</section>
<anchor name=Stdio.stdin>
<anchor name=Stdio.stdout>
<anchor name=Stdio.stderr>
<section title="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 <tt>Stdio.stdin</tt>,
<tt>Stdio.stdout</tt> and <tt>Stdio.stderr</tt> respectively. Standard
input is a clone of <tt>Stdio.FILE</tt>, which means you can use the line
oriented functions. <tt>Stdio.stdout</tt> and <tt>Stdio.stderr</tt> are
simply clones of <tt>Stdio.File</tt>.
<p>
Example:
<example language=pike>
int main()
{
int line;
while(string s=Stdio.stdin.gets())
write(sprintf("%5d: %s\n",line++,s));
}
</example>
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 <tt>Stdio.stdout.write</tt> instead
of just <tt>write</tt> because they are the same function.
</section>
</anchor>
</anchor>
</anchor>
<section title="Stdio.Terminfo">
<module name="Terminfo">
<function name=Stdio.Terminfo.getFallbackTerm title="get fallback terminal">
<man_syntax>
object(Stdio.Terminfo.Terminfo)|object(Stdio.Terminfo.Termcap) getFallbackTerm(string <I>term</I>);
</man_syntax>
<man_description>
Returns an object describing the fallback terminal for the
terminal <I>term</I>. This is usually equvivalent to
<tt>Stdio.Terminfo.getTerm("dumb")</tt>.
</man_description>
<man_see>
Stdio.Terminfo.getTerm
</man_see>
</function>
<hr noshade size=1>
<function name=Stdio.Terminfo.getTerm title="get terminal description">
<man_syntax>
object(Stdio.Terminfo.Terminfo)|object(Stdio.Terminfo.Termcap) getTerm();<br>
or<br>
object(Stdio.Terminfo.Terminfo)|object(Stdio.Terminfo.Termcap) getTerm(string <I>term</I>);
</man_syntax>
<man_description>
Returns an object describing the terminal <I>term</I>. If <I>term</I>
is not specified, it will default to <tt>getenv("TERM")</tt> or if
that fails to <tt>"dumb"</tt>.
<p>
Lookup of terminal information will first be done in the systems
terminfo database, and if that fails in the termcap database. If
neither database exists, a hardcoded entry for <tt>"dumb"</tt> will be used.
</man_description>
<man_see>
Stdio.Terminfo.getTerminfo, Stdio.Terminfo.getTermcap, Stdio.getFallbackTerm
</man_see>
</function>
<hr noshade size=1>
<function name=Stdio.Terminfo.getTermcap title="get termcap description">
<man_syntax>
object(Stdio.Terminfo.Termcap) getTermcap(string <I>term</I>);<br>
</man_syntax>
<man_description>
Return the terminal description of <I>term</I> from the systems
termcap database. Returns 0 if not found.
</man_description>
<man_see>
Stdio.Terminfo.getTerm, Stdio.Terminfo.getTerminfo
</man_see>
</function>
<hr noshade size=1>
<function name=Stdio.Terminfo.getTerminfo title="get terminfo description">
<man_syntax>
object(Stdio.Terminfo.Terminfo) getTerminfo(string <I>term</I>);<br>
</man_syntax>
<man_description>
Return the terminal description of <I>term</I> from the systems
terminfo database. Returns 0 if not found.
</man_description>
<man_see>
Stdio.Terminfo.getTerm, Stdio.Terminfo.getTermcap
</man_see>
</function>
<hr noshade size=1>
<section title="Stdio.Terminfo.Termcap">
<class name="Termcap">
Termcap terminal decription object.
<method name=create title="initialize termcap object">
<man_syntax>
object(Stdio.Terminfo.Termcap) Termcap(string <I>cap</I>);<br>
or<br>
object(Stdio.Terminfo.Termcap) Termcap(string <I>cap</I>, object <I>tcdb</I>);<br>
or<br>
object(Stdio.Terminfo.Termcap) Termcap(string <I>cap</I>, object <I>tcdb</I>, int <I>maxrecurse</I>);
</man_syntax>
</method>
<method name=tputs title="put termcap string">
</method>
</class>
</section>
<hr noshade size=1>
<section title="Stdio.Terminfo.Terminfo">
<class name="Terminfo">
Terminfo terminal description object.
</class>
</section>
<hr noshade size=1>
<!-- FIXME: More documentation here. -->
</module>
</section>
<section title="Stdio.Readline">
<class name="Readline">
<hr noshade size=1>
<method name=create title="init readline">
<man_syntax>
object(Stdio.Readline) Stdio.Readline();<br>
or<br>
object(Stdio.Readline) Stdio.Readline(object <I>infd</I>);<br>
or<br>
object(Stdio.Readline) Stdio.Readline(object <I>infd</I>,<br keep_ws>
<dl><dt><dd>
object|string <I>interm</I>);<br>
</dl><br>
or<br>
object(Stdio.Readline) Stdio.Readline(object <I>infd</I>,<br keep_ws>
<dl><dt><dd>
object|string <I>interm</I>,<br keep_ws>
object <I>outfd</I>);<br>
</dl><br>
or<br>
object(Stdio.Readline) Stdio.Readline(object <I>infd</I>,<br keep_ws>
<dl><dt><dd>
object|string <I>interm</I>,<br keep_ws>
object <I>outfd</I>,<br keep_ws>
object|string <I>outterm</I>);<br>
</dl>
</man_syntax>
<man_description>
Creates a Readline object, that takes input from <I>infd</I>, and has output
on <I>outfd</I>.
<p>
<I>infd</I> defaults to <tt>Stdio.stdout</tt>.
<p>
<I>interm</I> defaults to <tt>Stdio.Terminfo.getTerm()</tt>.
<p>
<I>outfd</I> defaults to <I>infd</I>, unless <I>infd</I> is 0, in
which case <I>outfd</I> defaults to <tt>Stdio.stdout</tt>.
<p>
<I>outterm</I> defaults to <I>interm</I>.
</man_description>
</method>
<!-- FIXME: More documentation needed. -->
</class>
</section>
<section title="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.
<hr>
<function name=file_size title="return the size of a file in bytes">
<man_syntax>
int file_size(string <I>file</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.write_file, Stdio.read_bytes</man_see>
</function>
<function name=perror title="print error">
<man_syntax>
void perror(string <I>s</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.werror</man_see>
</function>
<function name=read_bytes title="read a number of bytes into a string from a file">
<man_syntax>
string read_bytes(string <I>file</I>,int <I>start</I>,int <I>len</I>);<br>
string read_bytes(string <I>file</I>,int <I>start</I>);<br>
string read_bytes(string <I>file</I>);<br>
</man_syntax>
<man_description>
Read <i>len</i> number of bytes from file <i>file</i> staring at byte <i>start</i> and
return it as a string. If <i>len</i> is omitted, the rest of the file
will be returned. If <i>start</i> is also omitted, the entire file will
be returned.
</man_description>
<man_see>Stdio.write_file</man_see>
</function>
<function name=read_file title="read a number of lines into a string from file">
<man_syntax>
string read_file(string <I>file</I>, int <I>start</I>, int <I>len</I>);<br>
string read_file(string <I>file</I>);<br>
</man_syntax>
<man_description>
Read <i>len</i> lines from the file <i>file</i> after skipping <i>start</i> lines
and return those lines as a string. If <i>start</i> and <i>len</i> are omitted
the whole file is read.
</man_description>
<man_see>Stdio.read_bytes, Stdio.write_file</man_see>
</function>
<function name=readline title="read a line from stdin">
<man_syntax>
string readline(string <I>prompt</I>);<br>
</man_syntax>
<man_description>
This function writes the string <i>prompt</i> 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.
</man_description>
<man_see>Stdio.File</man_see>
</function>
<function name=sendfile title="send contents from one file to another">
<man_syntax>
object sendfile(array(string) <I>headers</I>,<br>
<dl><dt><dd>
object <I>from</I>, int <I>offset</I>, int <I>len</I>,<br keep_ws>
array(string) <I>trailers</I>,<br keep_ws>
object <I>to</I>);<br>
</dl><br>
or<br>
object sendfile(array(string) <I>headers</I>,<br>
<dl><dt><dd>
object <I>from</I>, int <I>offset</I>, int <I>len</I>,<br keep_ws>
array(string) <I>trailers</I>,<br keep_ws>
object <I>to</I>,<br keep_ws>
function(int, mixed ...:void) <I>callback</I>,<br keep_ws>
mixed ... <I>args</I>);<br>
</dl>
</man_syntax>
<man_description>
Sends <I>headers</I> followed by <I>len</I> bytes starting at <I>offset</I>
from the file <I>from</I> followed by <I>trailers</I> to the file <I>to</I>.
When completed <I>callback</I> is called with the total number of bytes sent
as the first argument, followed by <I>args</I>.
<p>
Any of <I>headers</I>, <I>from</I> and <I>trailers</I> may be left out
by setting them to 0.
<p>
Setting <I>offset</I> to -1 means send from the current position in
<I>from</I>.
<p>
Setting <I>len</I> to -1 means send until <I>from</I>'s end of file is
reached.
</man_description>
<man_note>The sending is performed asynchronously, and may complete
before the function returns.
<p>
For <I>callback</I> to be called, the backend must be active (ie
<tt>main()</tt> must have returned -1).
<p>
In some cases, the backend must also be active for any sending to
be performed at all.
</man_note>
<man_see>Stdio.File->set_nonblocking</man_see>
</function>
<function name=werror title="write to stderr">
<man_syntax>
void werror(string <I>s</I>);<br>
</man_syntax>
<man_description>
Writes a message to stderr. Stderr is normally the console, even if
the process output has been redirected to a file or pipe.
</man_description>
</function>
<function name=write_file title="append a string to a file">
<man_syntax>
int write_file(string <i>file</i>, string <i>str</i>)<br>
</man_syntax>
<man_description>
Append the string <i>str</i> onto the file <i>file</i>. Returns number of bytes written.
</man_description>
<man_see>Stdio.read_bytes</man_see>
</function>
</section>
<section title="Listening to sockets">
<class name=Port>
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
<tt>Stdio.Port</tt>. <tt>Stdio.Port</tt> 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 <tt>Stdio.Port</tt>:
<hr>
<method name=bind title="open socket and bind it to a port">
<man_syntax>
int bind(int <I>port</I>);<br>
int bind(int <I>port</I>,function <I>accept_callback</I>);<br>
int bind(int <I>port</I>,function <I>accept_callback</I>, string <I>IP</I>);<br>
</man_syntax>
<man_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.
<p>
If the optional argument <i>IP</i> is given, bind will try to bind to
this IP name (or number).
</man_description>
<man_see>Stdio.Port->accept</man_see>
</method>
<method name=listen_fd title="listen to an already open port">
<man_syntax>
int listen_fd(int <I>fd</I>);<br>
int listen_fd(int <I>fd</I>,function <I>accept_callback</I>);<br>
</man_syntax>
<man_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 <i>fd</i> is an already open port.
</man_description>
<man_note>
This function is only for the advanced user, and is generally used
when sockets are passed to Pike at exec time.
</man_note>
<man_see>Stdio.Port->bind, Stdio.Port->accept</man_see>
</method>
<method name=create title="create and/or setup a port">
<man_syntax>
object(Stdio.Port) Stdio.Port("stdin")<br>
object(Stdio.Port) Stdio.Port("stdin",function <i>accept_callback</i>)<br>
object(Stdio.Port) Stdio.Port("stdin",function <i>accept_callback</i>)<br>
object(Stdio.Port) Stdio.Port(int <i>port</i>)<br>
object(Stdio.Port) Stdio.Port(int <i>port</i>,function <i>accept_callback</i>)<br>
object(Stdio.Port) Stdio.Port(int <i>port</i>,function <i>accept_callback</i>, string <i>ip</i>)<br>
</man_syntax>
<man_description>
When create is called with <tt>"stdin"</tt> 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.
</man_description>
<man_see>clone, Stdio.Port->bind</man_see>
</method>
<method name=set_id title="set the id of a port">
<man_syntax>
void set_id(mixed <I>id</I>);<br>
</man_syntax>
<man_description>
This function sets the id used for accept_callback by this port.
The default id is this_object().
</man_description>
<man_see>Stdio.Port->query_id</man_see>
</method>
<method name=query_id title="Return the id for this port.">
<man_syntax>
mixed query_id();<br>
</man_syntax>
<man_description>
This function returns the id for this port. The id is normally the
first argument to accept_callback.
</man_description>
<man_see>Stdio.Port->set_id</man_see>
</method>
<method name=errno title="return the last error">
<man_syntax>
int errno();<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.Port->errno</man_see>
</method>
<method name=accept title="accept a connection">
<man_syntax>
object accept();<br>
</man_syntax>
<man_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.
</man_description>
<man_see>Stdio.File</man_see>
</method>
</class>
</section>
<section title="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)
<p>
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.
<p>
<example language=pike>
#!/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;
</example>
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.
<p>
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.
<example language=pike>
/* 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
</example>
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/
<p>
Next we declare a class called output_class. Later we will clone one
instance of this class for each incoming HTTP connection.
<p>
<example language=pike>
class output_class
{
inherit Stdio.File : socket;
inherit Stdio.File : file;
</example>
Our new class inherits Stdio.File twice. To be able to separate them
they are then named 'socket' and 'file'.
<p>
<example language=pike>
int offset=0;
</example>
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).
<p>
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.
<example language=pike>
void write_callback()
{
int written;
string data;
</example>
The following line means: call seek in the inherited program 'file'.
<example language=pike>
file::seek(offset);
</example>
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.
<p>
<example language=pike>
data=file::read(BLOCK);
</example>
Read BLOCK (16060) bytes from the file. If there are less that that left to
read only that many bytes will be returned.
<p>
<example language=pike>
if(strlen(data))
{
</example>
If we managed to read something...
<p>
<example language=pike>
written=socket::write(data);
</example>
... we try to write it to the socket.
<p>
<example language=pike>
if(written >= 0)
{
offset+=written;
return;
}
</example>
Update offset if we managed to write to the socket without errors.
<p>
<example language=pike>
werror("Error: "+socket::errno()+".\n");
}
</example>
If something went wrong during writing, or there was nothing left to read
we destruct this instance of this class.
<p>
<example language=pike>
destruct(this_object());
}
</example>
That was the end of write_callback()
<p>
Next we need a variable to buffer the input received in. We initialize it
to an empty string.
<example language=pike>
string input="";
</example>
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.
<p>
<example language=pike>
void read_callback(mixed id,string data)
{
string cmd;
input+=data;
</example>
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.
<p>
<example language=pike>
if(sscanf(input,"%s %s%*[\012\015 \t]",cmd,input)>2)
{
</example>
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.
<p>
<example language=pike>
if(cmd!="GET")
{
werror("Only method GET is supported.\n");
destruct(this_object());
return;
}
</example>
If the first word isn't GET print an error message and terminate
this instance of the program. (and thus the connection)
<example language=pike>
sscanf(input,"%*[/]%s",input);
</example>
Remove the leading slash.
<p>
<example language=pike>
input=BASE+combine_path("/",input);
</example>
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.
<example language=pike>
if(!file::open(input,"r"))
{
</example>
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.
<p>
<example language=pike>
if(!file::open(NOFILE,"r"))
{
</example>
If this fails too. Write an error message and destruct this object.
<p>
<example language=pike>
werror("Couldn't find default file.\n");
destruct(this_object());
return;
}
}
</example>
Ok, now we set up the socket so we can write the data back.
<example language=pike>
socket::set_buffer(65536,"w");
</example>
Set the buffer size to 64 kilobytes.
<p>
<example language=pike>
socket::set_nonblocking(0,write_callback,0);
</example>
Make it so that write_callback is called when it is time to write more
data to the socket.
<p>
<example language=pike>
write_callback();
</example>
Jump-start the writing.
<example language=pike>
}
}
</example>
That was the end of read_callback().
<p>
This function is called if the connection is closed while we are reading
from the socket.
<example language=pike>
void selfdestruct() { destruct(this_object()); }
</example>
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.
<p>
<example language=pike>
void create(object f)
{
socket::assign(f);
</example>
We insert the data from the file f into 'socket'.
<p>
<example language=pike>
socket::set_nonblocking(read_callback,0,selfdestruct);
</example>
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.
<p>
<example language=pike>
}
</example>
End of create()
<p>
<example language=pike>
};
</example>
End of the new class.
<p>
Next we define the function called when someone connects.
<p>
<example language=pike>
void accept_callback()
{
object tmp_output;
</example>
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.
<p>
<example language=pike>
tmp_output=accept();
</example>
The function accept clones a Stdio.File and makes this equal to the
newly connected socket.
<p>
<example language=pike>
if(!tmp_output) return;
</example>
If it failed we just return.
<p>
<example language=pike>
output_class(tmp_output);
</example>
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.
<p>
<example language=pike>
destruct(tmp_output);
</example>
Destruct the object returned by accept(), output_class has already copied
the contents of this object.
<p>
<example language=pike>
}
</example>
Then there is main, the function that gets it all started.
<example language=pike>
int main(int argc, array(string) argv)
{
werror("Starting minimal httpd\n");
</example>
Write an encouraging message to stderr.
<example language=pike>
if(!bind(PORT, accept_callback))
{
werror("Failed to open socket (already bound?)\n");
return 17;
}
</example>
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.
<example language=pike>
return - 17; /* Keep going */
</example>
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)
<example language=pike>
}
</example>
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.
<p>
</section>
</module>
</chapter>
<module name=Thread>
<chapter title="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 <tt>#if constant(thread_create)</tt>.
Pike needs POSIX or UNIX thread support when compiled to support threads.
<p>
<section title="Starting a thread">
Starting a thread is very easy. You simply call <tt>thread_create</tt> with a function
pointer and any arguments it needs and that function will be executed in a
separate thread. The function <tt>thread_create</tt> will return immediately and both
the calling function and the called function will execute at the same time. Example:
<example language=pike>
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);
}
</example>
This may all seem very simple, but there are a few complications to
watch out for:
<dl>
<dt> Accessing unlocked data
<dd> Look at this code:
<example language=pike>
void mapadd(mapping m, int i, int j)
{
if(map[i])
map[i]+=({j});
else
map[i]=({j});
}
</example>
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 <tt>map[i]</tt> is zero and both threads will
then do <tt>map[i]=({j});</tt> and one value of <tt>j</tt> 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 <b>condition variables</b>, 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:
<example language=pike>
#!/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);
}
</example>
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.
<dt> Deadlocks
<dd> 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.
</dl>
</section>
<section title="Threads reference section">
This section describes all thread-related functions and classes.
<hr noshade size=1>
<function name=thread_create title="create a thread">
<man_syntax>
object thread_create(function <I>f</I>, mixed ... <I>args</I>);<br>
</man_syntax>
<man_description>
This function creates a new thread which will run simultaneously
to the rest of the program. The new thread will call the function
<i>f</i> with the arguments <i>args</i>. 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.
</man_description>
<man_note>
This function is only available on systems with POSIX or UNIX threads support.
</man_note>
<man_see>Thread.Mutex, Thread.Condition, Thread.this_thread</man_see>
</function>
<function name=this_thread title="return thread id">
<man_syntax>
object this_thread();<br>
</man_syntax>
<man_description>
This function returns the object that identifies this thread.
</man_description>
<man_see>Thread.thread_create</man_see>
</function>
<function name=all_threads title="return all thread ids">
<man_syntax>
array(object) all_threads();<br>
</man_syntax>
<man_description>
This function returns an array with the thread ids of all threads.
</man_description>
<man_see>Thread.thread_create</man_see>
</function>
<class name=Thread.Mutex title="mutex locks">
<man_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.
</man_description>
<man_note>
Mutex locks are only available on systems with POSIX or UNIX threads support.
<p>
In POSIX threads, mutex locks can only be unlocked by the same thread
that locked them. In Pike any thread can unlock a locked mutex.
</man_note>
<man_example>
<pre>
/* 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.
*/
</pre>
<example language=pike>
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;
}
</example>
</man_example>
</class>
<hr noshade size=1>
<method name=Thread.Mutex->lock title="lock the mutex">
<man_syntax>
object lock();
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Mutex->trylock title="try to lock the mutex">
<man_syntax>
object trylock();
</man_syntax>
<man_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.
</man_description>
</method>
<hr newpage noshade size=1>
<class name=Thread.Condition title="condition variables">
<man_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.
</man_description>
<man_note>
Condition variables are only available on systems with POSIX or UNIX threads
support.
</man_note>
<man_example>
<example language=pike>
// 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;
array 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();
}
</example>
</man_example>
<man_see>
Thread.Mutex
</man_see>
</class>
<hr noshade size=1>
<method name=Thread.Condition->wait title="wait for condition">
<man_syntax>
void wait();<br>
void wait(object <I>mutex_key</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
Thread.Mutex->lock
</man_see>
</method>
<hr noshade size=1>
<method name=Thread.Condition.signal title="signal a condition variable">
<man_syntax>
void signal();
</man_syntax>
<man_description>
Signal wakes up one of the threads currently waiting for the
condition.
</man_description>
<man_bugs>
It sometimes wakes up more than one thread.
</man_bugs>
</method>
<hr noshade size=1>
<method name=Thread.Condition->broadcast title="signal all waiting threads">
<man_syntax>
void broadcast();
</man_syntax>
<man_description>
This function wakes up all threads currently waiting for this
condition.
</man_description>
</method>
<hr noshade size=1>
<class name=Thread.Fifo title="first in, first out object">
<man_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.
</man_description>
<man_note>
Fifos are only available on systems with POSIX threads support.
</man_note>
<man_see>
Thread.Queue
</man_see>
</class>
<hr noshade size=1>
<method name=Thread.Fifo->create title="initialize the fifo">
<man_syntax>
void create(int <I>size</I>);<br>
object(Thread.Fifo) Thread.Fifo();<br>
object(Thread.Fifo) Thread.Fifo(int <i>size</i>);<br>
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Fifo->write title="queue a value">
<man_syntax>
void write(mixed <I>value</I>);
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Fifo->read title="read a value from the fifo">
<man_syntax>
mixed read();
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Fifo->size title="return number of values in fifo">
<man_syntax>
int size();
</man_syntax>
<man_description>
This function returns how many values are currently in the fifo. <!-- L}ter fel /hedda -->
</man_description>
</method>
<hr noshade size=1>
<class name=Thread.Queue title="a queue of values">
<man_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.
</man_description>
<man_note>
Queues are only available on systems with POSIX or UNIX threads support.
</man_note>
<man_see>
Thread.Fifo
</man_see>
<hr noshade size=1>
<method name=Thread.Queue->write title="queue a value">
<man_syntax>
void write(mixed <I>value</I>);
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Queue->read title="read a value from the queue">
<man_syntax>
mixed read();
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Thread.Queue->size title="return number of values in queue">
<man_syntax>
int queue->size();
</man_syntax>
<man_description>
This function returns how many values are currently in the queue.
</man_description>
</method>
</class>
<hr noshade size=1>
<class name=thread_local title="Thread local variable class">
<man_description>
This class allows you to have variables which are separate for each
thread that uses it. It has two methods: get and set. A value stored
in an instance of thread_local can only be retreived by that same thread.
</man_description>
<hr noshade size=1>
<method name=thread_local.set title="Set the thread_local value">
<man_syntax>
mixed set(mixed <i>value</i>);
</man_syntax>
<man_description>
This sets the value returned by the <tt>get</tt> method. Note that
this value can only be retreived by the same thread. Calling this method
does not affect the value returned by <tt>get</tt> when called by another
thread.
</man_description>
</method>
<hr noshade size=1>
<method name=thread_local.get title="Get the thread_local value">
<man_syntax>
mixed set(mixed <i>value</i>);
</man_syntax>
<man_description>
This returns the value prevoiusly stored in the thread_local by the
<tt>set</tt> method by this thread.
</man_description>
</method>
</class>
</section>
<section title="Threads example">
Let's look at an example of how to work with threads. This program is the same
minimal WWW server as in <ref to=io> 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:
<example language=pike>
#!/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);
}
</example>
<p>
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.
</section>
</chapter>
</module>
<chapter title="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 <tt>String</tt> and <tt>Array</tt>, but more are expected to
show up in the future.
<section title="String">
<module name="String" title="extra string functionality module">
The module <tt>String</tt> 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.
<hr noshade size=1>
<function name=String.fuzzymatch title="make a fuzzy compare of two strings">
<man_syntax>
int fuzzymatch(string word1, string word2);
</man_syntax>
<man_description>
This function compares two strings using a fuzzy matching
routine. The higher the resulting value, the better the strings match.
</man_description>
<man_example>
> fuzzymatch("cat", "hat");<br>
Result: 66<br>
> fuzzymatch("cat", "dog");<br>
Result: 0<br>
> fuzzymatch("United States", "United Nations");<br>
Result: 70
</man_example>
<man_note>
This function is only available in Pike 0.6.82 and later.
</man_note>
<man_see>
Array.diff, Array.diff_compare_table, Array.diff_longest_sequence
</man_see>
</function>
<hr noshade size=1>
<function name=String.implode_nicely title="make an English comma separated list">
<man_syntax>
string implode_nicely(array(string) words, string|void separator);
</man_syntax>
<man_description>
This function implodes a list of words to a readable string.
If the separator is omitted, the default is <tt>"and"</tt>.
</man_description>
<man_example>
> implode_nicely(({"green"}));<br>
Result: green<br>
> implode_nicely(({"green","blue"}));<br>
Result: green and blue<br>
> implode_nicely(({"green","blue","white"}));<br>
Result: green, blue and white<br>
> implode_nicely(({"green","blue","white"}),"or");<br>
Result: green, blue or white<br>
</man_example>
<man_see>
`*
</man_see>
</function>
<hr noshade size=1>
<function name=String.capitalize title="capitalize a string">
<man_syntax>
string capitalize(string str);
</man_syntax>
<man_description>
Convert the first character in str to upper case, and return the
new string.
</man_description>
<man_see>
lower_case, upper_case
</man_see>
</function>
<hr noshade size=1>
<function name=String.strmult title="multiply strings">
<man_syntax>
string strmult(string <I>s</I>, int <I>num</I>);
</man_syntax>
<man_description>
This function multiplies 's' by 'num'. The return value is the same
as appending 's' to an empty string 'num' times.
</man_description>
</function>
<function name=String.count title="count needles in a haystack string">
<man_syntax>
string count(string <i>haystack</i>, string <i>needle</i>);
</man_syntax>
<man_description>
This function counts the number of times the needle
can be found in haystack.
Intersections between needles are not counted, ie
count("....","..") is 2.
</man_description>
</function>
<hr noshade size=1>
</module>
</section>
<section title="Array">
<module name="Array" title="supplemental Array handling functions">
As with <tt>String</tt> these functions are Pike functions written to
supplement those written in C.
<hr noshade size=1>
<function name=Array.diff title="gives the difference of two arrays">
<man_syntax>
array(array(array)) diff(array <i>a</i>, array <i>b</i>);<br>
</man_syntax>
<man_description>
Calculates which parts of the arrays that are common to both, and which parts
that are not.
Returns an array with two elements, the first is an array of parts in
array <b>a</b>, and the second is an array of parts in array <b>b</b>.
</man_description>
<man_example><pre>
> Array.diff("Hello world!"/"","Help!"/"");
Result: ({ /* 2 elements */
({ /* 3 elements */
({ /* 3 elements */
"H",
"e",
"l"
}),
({ /* 8 elements */
"l",
"o",
" ",
"w",
"o",
"r",
"l",
"d"
}),
({ /* 1 elements */
"!"
})
}),
({ /* 3 elements */
({ /* 3 elements */
"H",
"e",
"l"
}),
({ /* 1 elements */
"p"
}),
({ /* 1 elements */
"!"
})
})
})
</pre></man_example>
<man_note>
This function is only available in Pike 0.6 and later.
</man_note>
<man_see>
Array.diff_compare_table, Array.diff_longest_sequence, String.fuzzymatch
</man_see>
</function>
<hr noshade size=1>
<function name=Array.diff_compare_table
title="gives the comparison-table used by Array.diff()">
<man_syntax>
array(array(int)) diff_compare_table(array <i>a</i>, array <i>b</i>);<br>
</man_syntax>
<man_description>
Returns an array which maps from index in <b>a</b> to corresponding
indices in <b>b</b>.
</man_description>
<man_example><pre>
> Array.diff_compare_table("Hello world!"/"","Help!"/"");
Result: ({ /* 12 elements */
({ /* 1 elements */
0
}),
({ /* 1 elements */
1
}),
({ /* 1 elements */
2
}),
({ /* 1 elements */
2
}),
({ }),
({ }),
({ }),
({ }),
({ }),
({ /* 1 elements */
2
}),
({ }),
({ /* 1 elements */
4
})
})
</pre></man_example>
<man_note>
This function is only available in Pike 0.6 and later.
</man_note>
<man_see>
Array.diff, Array.diff_longest_sequence, String.fuzzymatch
</man_see>
</function>
<hr noshade size=1>
<function name=Array.diff_longest_sequence
title="gives the longest common sequence of two arrays">
<man_syntax>
array(int) diff_longest_sequence(array <i>a</i>, array <i>b</i>);<br>
</man_syntax>
<man_description>
Gives the longest sequence of indices in <b>b</b> that have corresponding
values in the same order in <b>a</b>.
</man_description>
<man_example><pre>
> Array.diff_longest_sequence("Hello world!"/"","Help!"/"");
Result: ({ /* 4 elements */
0,
1,
2,
4
})</pre>
</man_example>
<man_note>
This function is only available in Pike 0.6 and later.
</man_note>
<man_see>
Array.diff, Array.diff_compare_table, String.fuzzymatch
</man_see>
</function>
<hr noshade size=1>
<function name=Array.everynth title="return every n:th element of an array">
<man_syntax>
array(mixed) Array.everynth(array(mixed) arr1, void|int nth, void|int start);
</man_syntax>
<man_description>
This function returns an array with every n:th element of an other
array. If nth is zero, every second element is returned.
</man_description>
<man_example>
> Array.everynth(({"1","2","3","4","5","6"}),2,1);<br>
<pre>
Result: ({ /* 3 elements */
"2",
"4",
"6"
})
</pre>
</man_example>
<man_note>
This function is only available in Pike 0.6.? and later.
</man_note>
<man_see>
Array.splice, `/
</man_see>
</function>
<hr noshade size=1>
<function name=Array.filter title="filter an array or mapping through a function">
<man_syntax>
array filter(array <I>arr</I>,function <I>fun</I>,mixed ... <I>args</I>);<br>
array filter(array(object) <I>arr</I>,string <I>fun</I>,mixed ... <I>args</I>);<br>
array filter(array(function) <I>arr</I>,-<I>1</I>,mixed ... <I>args</I>);<br>
</man_syntax>
<man_description>
First syntax:<br>
Filter array returns an array holding the items of arr for which
fun returns true.
<p>Second syntax:<br>
Filter array calls fun in all the objects in the array arr, and
return all objects that returned true.
<p>Third syntax:<br>
Filter array calls all function pointers in the array arr, and
return all that returned true.
</man_description>
<man_see>
Array.sum_arrays, Array.map
</man_see>
</function>
<hr noshade size=1>
<function name=Array.longest_ordered_sequence
title="find the longest ordered sequence of elements">
<man_syntax>
array(int) longest_ordered_sequence(array a);<br>
</man_syntax>
<man_description>
This function returns an array of the indices in the longest
ordered sequence of elements in the array.
</man_description>
<man_example>
<pre>
> array a = ({ 1,2,3,4,2,3,5,6 });
Result: ({ /* 8 elements */
1,
2,
3,
4,
2,
3,
5,
6
})
> array seq = Array.longest_ordered_sequence(a);
Result: ({ /* 6 elements */
0,
1,
4,
5,
6,
7
})
> rows(a,seq);
Result: ({ /* 6 elements */
1,
2,
2,
3,
5,
6
})
</pre>
</man_example>
<man_note>
This function is only available in Pike 0.6 and later.
</man_note>
<man_see>
Array.diff
</man_see>
</function>
<hr noshade size=1>
<function name=Array.map title="map an array or mapping over a function">
<man_syntax>
array map(array <I>arr</I>,function <I>fun</I>,mixed ... <I>args</I>);<br>
array map(array(object) <I>arr</I>,string <I>fun</I>,mixed ... <I>args</I>);<br>
array map(array(function) <I>arr</I>,-<I>1</I>,mixed ... <I>arg</I>);<br>
</man_syntax>
<man_description>
First syntax:<br>
Map array returns an array holding the items of arr mapped through
the function fun. i.e. arr[x]=fun(arr[x], @args) for all x.
<p>Second syntax:<br>
Map array calls function fun in all objects in the array arr.
i.e. arr[x]=arr[x]->fun(@ args);
<p>Third syntax:<br>
Map array calls the functions in the array arr:
arr[x]=arr[x]->fun(@ args);
</man_description>
<man_see>
Array.sum_arrays, Array.filter
</man_see>
</function>
<hr noshade size=1>
<function name=Array.permute title="Give a specified permutation of an array">
<man_syntax>
array permute(array in,int number);
</man_syntax>
<man_description>
<tt>permute</tt> gives you a selected permutation of an array.
The numbers of permutations equal sizeof(in)! (the factorial of
the size of the given array).
</man_description>
<man_example>
Array.permute( ({ 1,2,3 }), 0) -> ({1,2,3})
Array.permute( ({ 1,2,3 }), 3) -> ({1,3,2})
</man_example>
<man_see>
Array.shuffle
</man_see>
</function>
<hr noshade size=1>
<function name=Array.search_array title="search for something in an array">
<man_syntax>
int search_array(array <I>arr</I>,function <I>fun</I>,mixed <I>arg</I>, ...);<br>
int search_array(array(object) <I>arr</I>,string <I>fun</I>,mixed <I>arg</I>, ...);<br>
int search_array(array(function) <I>arr</I>,-<I>1</I>,mixed <I>arg</I>, ...);
</man_syntax>
<man_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.
</man_description>
<man_see>
Array.sum_arrays, Array.filter
</man_see>
</function>
<hr noshade size=1>
<function name=Array.shuffle title="Random-shuffle an array">
<man_syntax>
array shuffle(array in);
</man_syntax>
<man_description>
<tt>shuffle</tt> gives back the same elements, but by random order.
</man_description>
<man_example>
Array.shuffle( ({"this","is","an","ordered","array"}) )
-> ({"is","ordered","array","this","an"})
</man_example>
<man_see>
Array.permute
</man_see>
</function>
<hr noshade size=1>
<function name=Array.splice title="splice two or more arrays">
<man_syntax>
array(mixed) Array.splice(array(mixed) arr1, array(mixed) arr2, array(mixed) ...);
</man_syntax>
<man_description>
This function splice two or more arrays together. This means that
the the array becomes an array of the first element in the first
given array, the first argument in next array and so on for all
arrays. Then the second elements are added.
</man_description>
<man_example>
> Array.splice(({1,2,3}),({"1","2","3"}),({"a","b","c"}));<br>
<pre>
Result: ({ /* 9 elements */
1,
"1",
"a",
2,
"2",
"b",
3,
"3",
"c"
})
> Array.splice(({1,2,3}),({"1","2","3"}),({"a","b"}));
Result: ({ /* 9 elements */
1,
"1",
"a",
2,
"2",
"b",
})
</pre>
</man_example>
<man_note>
This function is only available in Pike 0.6.? and later.
</man_note>
<man_see>
`/, `*, `+, `-, Array.everynth
</man_see>
</function>
<hr noshade size=1>
<function name=Array.sum_arrays title="map any number of arrays over a function">
<man_syntax>
array sum_arrays(function <I>fun</I>,array <I>arr1</I>,...);
</man_syntax>
<man_description>
Works like this:
<p><tt>array sum_arrays(function fun,array arr1,...)<br>
{<br>
<dl><dt><dd>int e;<br>
array res=allocate(sizeof(arr1));<br>
for(e=0;e<sizeof(arr1);e++)<br>
{<br>
<dl><dt><dd>res[e]=fun(arr1[e],arr2[e],...);<br>
</dl>}<br>
return res;<br>
</dl>}<br>
</tt>
<p>Simple ehh?
</man_description>
<man_see>
Array.map, Array.filter, Array.search_array
</man_see>
</function>
<hr noshade size=1>
<function name=Array.sort_array title="sort an array">
<man_syntax>
array sort_array(array <I>arr</I>,function <I>fun</I>,mixed ... <I>args</I>);
</man_syntax>
<man_description>
This function sorts an array after a compare-function <i>fun</i>
which takes two arguments and should return 1 if the first argument
is larger then the second. The rest of the arguments <i>args</i> will be
sent as 3rd, 4th etc. argument to <i>fun</i>. If <i>fun</i> is omitted, `< is used
instead.
</man_description>
<man_see>
Array.map, sort
</man_see>
</function>
<hr noshade size=1>
<function name=Array.uniq title="remove elements that are duplicates">
<man_syntax>
array uniq(array <I>a</I>);
</man_syntax>
<man_description>
This function returns an copy of the array <i>a</i> with all duplicate
values removed. The order of the values in the result is undefined.
</man_description>
</function>
<hr noshade size=1>
</module>
</section>
</chapter>
<anchor name=Image>
<chapter title=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.
<p>
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.
<p>
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.
<p>
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'.
<p>
Let's look at an example of how this can be used:
<example language=pike>
#!/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.GIF.encode(image));
}
</example>
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.
<hr newpage>
<include file=Image.wmml>
</chapter>
</anchor>
<anchor name=Protocols>
<chapter title=Protocols>
The Protocol modules is some helper modules that makes it easier for
the pike programmer to use some of the protocols used on the internet.
<hr newpage>
<include file=protocols.wmml>
</chapter>
</anchor>
<chapter title="Other modules">
Pike also include a number of smaller modules. These modules implement support
for various algorithms, data structures and system routines.
<module name=System>
<section title="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.
<p>
Please note that these functions are available globally, you do not
need to <tt>import System</tt> to use these functions.
<hr noshade size=1>
<function name=chroot title="change the root directory" fullpath>
<man_syntax>
int chroot(string <I>newroot</I>);<br>
int chroot(object(File) <I>obj</I>);<br>
</man_syntax>
<man_description>
Changes the root directory for this process to the indicated
directory.
</man_description>
<man_note>
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.
<p>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.
</man_note>
</function>
<hr noshade size=1>
<function name=getegid title="get the effective group ID" fullpath>
<man_syntax>
int getegid();<br>
</man_syntax>
<man_description>
Get the effective group ID.
</man_description>
<man_see>
setuid, getuid, setgid, getgid, seteuid, geteuid, setegid
</man_see>
</function>
<hr noshade size=1>
<function name=geteuid title="get the effective user ID" fullpath>
<man_syntax>
int geteuid();<br>
</man_syntax>
<man_description>
Get the effective user ID.
</man_description>
<man_see>
setuid, getuid, setgid, getgid, seteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=getgid title="get the group ID" fullpath>
<man_syntax>
int getgid();<br>
</man_syntax>
<man_description>
Get the real group ID.
</man_description>
<man_see>
setuid, getuid, setgid, seteuid, geteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=getgroups title="get the supplemental group access list" fullpath>
<man_syntax>
array(int) getgroups();<br>
</man_syntax>
<man_description>
Get the current supplemental group access list for this process.
</man_description>
<man_note>
This function in not available in Pike 0.5 and earlier.
</man_note>
<man_see>
initgroups, setgroups, getgid, setgid, getegid, setegid
</man_see>
</function>
<hr noshade size=1>
<function name=gethostbyaddr title="gets information about a host given its address" fullpath>
<man_syntax>
array gethostbyaddr(string <I>addr</I>);<br>
</man_syntax>
<man_description>
Returns an array with information about the specified IP address.
<p>The returned array contains the same information as that returned
by gethostbyname().
</man_description>
<man_note>
This function only exists on systems that have the gethostbyaddr(2)
or similar system call.
</man_note>
<man_see>
gethostbyname
</man_see>
</function>
<hr noshade size=1>
<function name=gethostbyname title="gets information about a host given its name" fullpath>
<man_syntax>
array gethostbyname(string <I>hostname</I>);<br>
</man_syntax>
<man_description>
Returns an array with information about the specified host.
<p>The array contains three elements:
<p>The first element is the hostname.
<p>The second element is an array(string) of IP numbers for the host.
<p>The third element is an array(string) of aliases for the host.
</man_description>
<man_note>
This function only exists on systems that have the gethostbyname(2)
or similar system call.
</man_note>
<man_see>
gethostbyaddr
</man_see>
</function>
<hr noshade size=1>
<function name=gethostname title="get the name of this host" fullpath>
<man_syntax>
string gethostname();<br>
</man_syntax>
<man_description>
Returns a string with the name of the host.
</man_description>
<man_note>
This function only exists on systems that have the gethostname(2)
or uname(2) system calls.
</man_note>
</function>
<hr noshade size=1>
<function name=getpgrp title="get the process group ID" fullpath>
<man_syntax>
int getpgrp();<br>
int getpgrp(int <I>pid</I>);<br>
</man_syntax>
<man_description>
With no arguments or with <i>pid</i> equal to zero, returns the process
group ID of this process.
<p>If <i>pid</i> is specified, returns the process group ID of that process.
</man_description>
<man_see>
getpid, getppid
</man_see>
</function>
<hr noshade size=1>
<function name=getpid title="get the process ID" fullpath>
<man_syntax>
int getpid();<br>
</man_syntax>
<man_description>
Returns the process ID of this process.
</man_description>
<man_see>
getppid, getpgrp
</man_see>
</function>
<hr noshade size=1>
<function name=getppid title="get the parent process ID" fullpath>
<man_syntax>
int getppid();<br>
</man_syntax>
<man_description>
Returns the process ID of the parent process.
</man_description>
<man_see>
getpid, getpgrp
</man_see>
</function>
<hr noshade size=1>
<function name=getuid title="get the user ID" fullpath>
<man_syntax>
int getuid();<br>
</man_syntax>
<man_description>
Get the real user ID.
</man_description>
<man_see>
setuid, setgid, getgid, seteuid, geteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=hardlink title="create a hardlink" fullpath>
<man_syntax>
void hardlink(string <I>from</I>, string <I>to</I>);<br>
</man_syntax>
<man_description>
Creates a hardlink named <i>to</i> from the file <i>from</i>.
</man_description>
<man_see>
symlink, mv, rm
</man_see>
</function>
<hr noshade size=1>
<function name=initgroups title="initialize the group access list" fullpath>
<man_syntax>
void initgroups(string <I>username</I>, int <I>base_gid</I>);<br>
</man_syntax>
<man_description>
Initializes the group access list according to the system
group database. <i>base_gid</i> is also added to the group access
list.
</man_description>
<man_see>
setuid, getuid, setgid, getgid, seteuid, geteuid, setegid, getegid, getgroups, setgroups
</man_see>
</function>
<hr noshade size=1>
<function name=openlog title="initializes the connection to syslogd" fullpath>
<man_syntax>
void openlog(string <I>ident</I>, int <I>options</I>, <I>facility</I>);<br>
</man_syntax>
<man_description>
Initializes the connection to syslogd.
<p>The <i>ident</i> argument specifies an identifier to tag all log entries
with.
<p><i>options</i> is a bit field specifying the behavior of the message
logging. Valid options are:
<p><dl><dt><dd><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> LOG_PID </td><td> Log the process ID with each message. </td></tr>
<tr valign=top><td> LOG_CONS </td><td> Write messages to the console if they can't be sent to syslogd. </td></tr>
<tr valign=top><td> LOG_NDELAY </td><td> Open the connection to syslogd now and not later. </td></tr>
<tr valign=top><td> LOG_NOWAIT </td><td> Do not wait for subprocesses talking to syslogd. </td></tr>
</table>
</dl>
<p><i>facility</i> specifies what subsystem you want to log as. Valid
facilities are:
<p><dl><dt><dd><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> LOG_AUTH </td><td> Authorization subsystem </td></tr>
<tr valign=top><td> LOG_AUTHPRIV </td></tr>
<tr valign=top><td> LOG_CRON </td><td> Crontab subsystem </td></tr>
<tr valign=top><td> LOG_DAEMON </td><td> System daemons </td></tr>
<tr valign=top><td> LOG_KERN </td><td> Kernel subsystem (NOT USABLE) </td></tr>
<tr valign=top><td> LOG_LOCAL </td><td> For local use </td></tr>
<tr valign=top><td> LOG_LOCAL[1-7] </td><td> For local use </td></tr>
<tr valign=top><td> LOG_LPR </td><td> Line printer spooling system </td></tr>
<tr valign=top><td> LOG_MAIL </td><td> Mail subsystem </td></tr>
<tr valign=top><td> LOG_NEWS </td><td> Network news subsystem </td></tr>
<tr valign=top><td> LOG_SYSLOG </td></tr>
<tr valign=top><td> LOG_USER </td></tr>
<tr valign=top><td> LOG_UUCP </td><td> UUCP subsystem </td></tr>
</table>
</dl>
</man_description>
<man_note>
Only available on systems with syslog(3).
</man_note>
<man_bugs>
LOG_NOWAIT should probably always be specified.
</man_bugs>
<man_see>
syslog, closelog, setlogmask
</man_see>
</function>
<hr noshade size=1>
<function name=readlink title="read a symbolic link" fullpath>
<man_syntax>
string readlink(string <I>linkname</I>);<br>
</man_syntax>
<man_description>
Returns what the symbolic link <i>linkname</i> points to.
</man_description>
<man_see>
symlink
</man_see>
</function>
<hr noshade size=1>
<function name=setegid title="set the effective group ID" fullpath>
<man_syntax>
void setegid(int <I>uid</I>);<br>
</man_syntax>
<man_description>
Sets the effective group ID to <i>gid</i>.
</man_description>
<man_see>
setuid, getuid, setgid, getgid, seteuid, geteuid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=seteuid title="set the effective user ID" fullpath>
<man_syntax>
void seteuid(int <I>uid</I>);<br>
</man_syntax>
<man_description>
Sets the effective user ID to <i>uid</i>.
</man_description>
<man_see>
setuid, getuid, setgid, getgid, geteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=setgid title="set the group ID" fullpath>
<man_syntax>
void setgid(int <I>gid</I>);<br>
</man_syntax>
<man_description>
Sets the real group ID, effective group ID and saved group ID to <i>gid</i>.
</man_description>
<man_see>
setuid, getuid, getgid, seteuid, geteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=setgroups title="set the supplemental group access list" fullpath>
<man_syntax>
void getgroups(array(int) gids);<br>
</man_syntax>
<man_description>
Set the supplemental group access list for this process.
</man_description>
<man_note>
This function is not available in Pike 0.5 and earlier.
</man_note>
<man_see>
initgroups, getgroups, getgid, setgid, getegid, setegid
</man_see>
</function>
<hr noshade size=1>
<function name=setuid title="set the user ID" fullpath>
<man_syntax>
void setuid(int <I>uid</I>);<br>
</man_syntax>
<man_description>
Sets the real user ID, effective user ID and saved user ID to <i>uid</i>.
</man_description>
<man_see>
getuid, setgid, getgid, seteuid, geteuid, setegid, getegid
</man_see>
</function>
<hr noshade size=1>
<function name=symlink title="create a symbolic link" fullpath>
<man_syntax>
void symlink(string <I>from</I>, string <I>to</I>);<br>
</man_syntax>
<man_description>
Creates a symbolic link named <i>to</i> pointing to <i>from</i>.
</man_description>
<man_see>
hardlink, readlink, mv, rm
</man_see>
</function>
<hr noshade size=1>
<function name=uname title="get operating system information" fullpath>
<man_syntax>
mapping(string:string) <I>uname</I>();<br>
</man_syntax>
<man_description>
Returns a mapping describing the operating system.
<p>The mapping contains the following fields:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> </td><td> "sysname": </td><td> Operating system name </td></tr>
<tr valign=top><td> </td><td> "nodename": "release": "version": "machine": </td><td> Host name Release of this OS Version number of this OS Machine architecture </td></tr>
</table>
</man_description>
<man_note>
This function only exists on systems that have the uname(2)
system call.
</man_note>
</function>
</section>
</module>
<hr noshade size=1>
<module name=Process>
<section title="Process">
The Process module contains functions to start and control other programs from Pike.
<hr noshade size=1>
<function name=Process.popen title="pipe open">
<man_syntax>
string popen(string <I>cmd</I>);<br>
</man_syntax>
<man_description>
This function runs the command <i>cmd</i> as in a shell and returns the
output. See your Unix/C manual for details on popen.
</man_description>
</function>
<hr noshade size=1>
<function name=Process.system title="run an external program">
<man_syntax>
void system(string <I>cmd</I>);<br>
</man_syntax>
<man_description>
This function runs the external program <i>cmd</i> and waits until it
is finished. Standard /bin/sh completions/redirections/etc. can
be used.
</man_description>
<man_see>
Process.popen, Process.exec, Process.spawn
</man_see>
</function>
<hr noshade size=1>
<function name=Process.spawn title="spawn a process">
<man_syntax>
int spawn(string <I>cmd</I>);<br>
int spawn(string <I>cmd</I>, object <I>stdin</I>);<br>
int spawn(string <I>cmd</I>, object <I>stdin</I>, object <I>stdout</I>);<br>
int spawn(string <I>cmd</I>, object <I>stdin</I>, object <I>stdout</I>, object <I>stderr</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
Process.popen, fork, Process.exec, Stdio.File->pipe, Stdio.File->dup2
</man_see>
</function>
<hr noshade size=1>
<function name=exece title="execute a program">
<man_syntax>
int exece(string <I>file</I>, array(string) <I>args</I>);<br>
int exece(string <I>file</I>, array(string) <I>args</I>, mapping(string:string) <I>env</I>);<br>
</man_syntax>
<man_description>
This function transforms the Pike process into a process running
the program specified in the argument <i>file</i> with the argument <i>args</i>.
If the mapping <i>env</i> 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.
</man_description>
<man_note>
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.
</man_note>
<man_example>
exece("/bin/ls", ({"-l"}));<br>
exece("/bin/sh", ({"-c", "echo $HOME"}), (["HOME":"/not/home"]));<br>
</man_example>
<man_see>
fork, Stdio.File->pipe
</man_see>
</function>
<hr noshade size=1>
<function name=Process.exec title="simple way to use exece()">
<man_syntax>
int exec(string <I>file</I>, string ... <I>args</I>);<br>
</man_syntax>
<man_description>
This function destroys the Pike parser and runs the program
<i>file</i> 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.
</man_description>
<man_example>
exec("/bin/echo","hello","world");<br>
</man_example>
</function>
<class name=Process.Spawn
title="spawn off another program with control structure">
<man_syntax>
object Process.Spawn(string program,
void|array(string) args,
void|mapping(string:string) env,
void|string cwd); <br>
or
object Process.Spawn(string program,
void|array(string) args,
void|mapping(string:string) env,
void|string cwd,
array(void|object(Stdio.file)) fds,
void|array(void|object(Stdio.file)) fds_to_close);
</man_syntax>
<man_description>
Spawn off another program (<tt>program</tt>) and creates
the control structure. This does not spawn off a shell to
find the program, therefore must <tt>program</tt> be the full
path the the program.<p>
<tt>args</tt> is per default no argument(s),<p>
<tt>env</tt> is reset to the given mapping, or kept if the
argument is <tt>0</tt>.
<tt>fds</tt> is your stdin, stdout and stderr. Default
is local pipes (see <link to=Stdio.stdin>stdin</link> et al).
<tt>fds_to_close</tt> is file descriptors that are closed
in the forked branch when the program is executed (ie, the
other end of the pipes).
</man_description>
<variable name=stdin,stdout,stderr,fd title="pipes to the program">
<man_syntax>
object(Stdio.File) stdin;<br>
object(Stdio.File) stdout;<br>
object(Stdio.File) stderr;<br>
array(void|object(Stdio.File)) fd;<br>
</man_syntax>
<man_description>
Pipes to the spawned program (if set). fd[0]==stdin, etc.
</man_description>
</variable>
<variable name=pid title="spawned program pid">
<man_syntax>
int pid;
</man_syntax>
<man_description>
pid of the spawned program.
</man_description>
</variable>
<method name=wait title="wait for the spawned program to finish">
<man_syntax>
void wait();
</man_syntax>
<man_description>
Returns when the program has exited.
</man_description>
</method>
<method name=kill title="send a signal to the program">
<man_syntax>
int kill(int signal);
</man_syntax>
<man_description>
Sends a signal to the program.
</man_description>
</method>
</class>
</section>
</module>
<module name=Regexp>
<section title="Regexp">
Regexp is short for <b>Regular Expression</b>. 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.
<p>
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.
<table>
<tr><th> pattern </th><th>Matches</th></tr>
<tr><td> . </td><td> any one character </td></tr>
<tr><td> [abc] </td><td> a, b or c </td></tr>
<tr><td> [a-z] </td><td> any character a to z inclusive </td></tr>
<tr><td> [^ac] </td><td> any character except a and c </td></tr>
<tr><td> (x) </td><td> x (x might be any regexp) If used with split, this also puts the string matching x into the result array. </td></tr>
<tr><td> x* </td><td> zero or more occurrences of 'x' (x may be any regexp) </td></tr>
<tr><td> x+ </td><td> one or more occurrences of 'x' (x may be any regexp) </td></tr>
<tr><td> x|y </td><td> x or y. (x or y may be any regexp) </td></tr>
<tr><td> xy </td><td> xy (x and y may be any regexp) </td></tr>
<tr><td> ^ </td><td> beginning of string (but no characters) </td></tr>
<tr><td> $ </td><td> end of string (but no characters) </td></tr>
<tr><td> \< </td><td> the beginning of a word (but no characters) </td></tr>
<tr valign=top><td> \> </td><td> the end of a word (but no characters) </td></tr>
</table>
Let's look at a few examples:
<table>
<tr><th>Regexp</th><th>Matches</th></tr>
<tr><td>[0-9]+</td><td>one or more digits</td></tr>
<tr><td>[^ \t\n]</td><td>exactly one non-whitespace character</td></tr>
<tr><td>(foo)|(bar)</td><td>either 'foo' or 'bar'</td></tr>
<tr><td>\.html$</td><td>any string ending in '.html'</td></tr>
<tr><td>^\.</td><td>any string starting with a period</td></tr>
</table>
<p>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.
<p>
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.
<p>
You might wonder what regexps are good for, hopefully it should be more clear
when you read about the following functions:
<hr noshade size=1>
<method name=Regexp.create title="compile regexp">
<man_syntax>
void create();<br>
void create(string <i>regexp</i>);<br>
object(Regexp) Regexp();<br>
object(Regexp) Regexp(string <I>regexp</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
clone, Regexp->match
</man_see>
</method>
<hr noshade size=1>
<method name=Regexp.match title="match a regexp">
<man_syntax>
int match(string <i>s</i>)<br>
</man_syntax>
<man_description>
Return 1 if <i>s</i> matches the regexp bound to the object regexp,
zero otherwise.
</man_description>
<man_see>
Regexp->create, Regexp->split
</man_see>
</method>
<hr noshade size=1>
<method name=Regexp.split title="split a string according to a pattern">
<man_syntax>
array(string) split(string <i>s</i>)<br>
</man_syntax>
<man_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.
</man_description>
<man_bugs>
You can only have 40 sub-regexps.
</man_bugs>
<man_see>
Regexp->create, Regexp->match
</man_see>
</method>
<hr noshade size=1>
<!-- FIX ME: write and document Regexp->explode -->
</section>
</module>
<module name=Gmp>
<section title="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..
<p>
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.
<class name=Gmp.mpz title="bignum program">
<man_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.
<p>The mpz object implements all the normal integer operations.
(except xor) There are also some extra operators:
</man_description>
<man_note>
This module is only available if libgmp.a was available and
found when Pike was compiled.
</man_note>
</class>
<hr noshade size=1>
<method name=Gmp.mpz.create title="initialize a bignum">
<man_syntax>
object Mpz();<br>
object Mpz(int|object|float <I>i</I>);<br>
object Mpz(string <I>digits</I>, int <I>base</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
clone
</man_see>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.powm title="raise and modulo">
<man_syntax>
object powm(int|string|float|object <I>a</I>,int|string|float|object <I>b</I>);<br>
</man_syntax>
<man_description>
This function returns ( mpz ** <i>a</i> ) % <i>b</i>.
For example, <tt> Mpz(2)->powm(10,42); </tt> would return <tt>16</tt>
since 2 to the power of 10 is 1024 and 1024 modulo 42 is 16.
</man_description>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.sqrt title="square root">
<man_syntax>
object sqrt();<br>
</man_syntax>
<man_description>
This function returns the truncated integer part of the square
root of the value of mpz.
</man_description>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.probably_prime_p title="is this number a prime?">
<man_syntax>
int probably_prime_p();<br>
</man_syntax>
<man_description>
This function returns 1 if mpz is a prime, and 0 most of the time
if it is not.
</man_description>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.gcd title="greatest common divisor">
<man_syntax>
object gcd(object|int|float|string arg)<br>
</man_syntax>
<man_description>
This function returns the greatest common divisor for <i>arg</i> and mpz.
</man_description>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.cast title="cast to other type">
<man_syntax>
object cast( "string" | "int" | "float" );<br>
(string) mpz<br>
(int) mpz<br>
(float) mpz<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
cast
</man_see>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.digits title="convert mpz to a string">
<man_syntax>
string digits();<br>
string digits(int|void <I>base</I>);<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
Gmp.mpz->cast
</man_see>
</method>
<hr noshade size=1>
<method name=Gmp.mpz.size title="how long is a number">
<man_syntax>
string size();<br>
string size(int|void <I>base</I>);<br>
</man_syntax>
<man_description>
This function returns how long the mpz would be represented in the
specified base. The default base is 2.
</man_description>
<man_see>
Gmp.mpz->digits
</man_see>
</method>
</section>
</module>
<hr noshade size=1>
<module name=Gdbm>
<section title="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.
<p>
<!-- FIX ME, implement `[], `[]=, _sizeof, _indices and _values -->
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.
<hr noshade size=1>
<method name=Gdbm.gdbm->create title="open database">
<man_syntax>
int create();<br>
int create(string <I>file</I>);<br>
int create(string <I>file</I>, string <I>mode</I>);<br>
object(Gdbm) Gdbm();
object(Gdbm) Gdbm(string <i>file</i>);
object(Gdbm) Gdbm(string <i>file</i>, string <i>mode</i>);
</man_syntax>
<man_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:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> r </td><td> open database for reading </td></tr>
<tr valign=top><td> w </td><td> open database for writing </td></tr>
<tr valign=top><td> c </td><td> create database if it does not exist </td></tr>
<tr valign=top><td> t </td><td> overwrite existing database </td></tr>
<tr valign=top><td> f </td><td> fast mode </td></tr>
</table>
<p>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.
<p>The default mode is "rwc".
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->close title="close database">
<man_syntax>
void close();<br>
</man_syntax>
<man_description>
This closes the database.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->store title="store a value in the database">
<man_syntax>
int store(string <I>key</I>, string <I>data</I>);<br>
</man_syntax>
<man_description>
Associate the contents of <i>data</i> with the key <i>key</i>. If the key <i>key</i>
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.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->fetch title="fetch a value from the database">
<man_syntax>
string fetch(string <I>key</I>);<br>
</man_syntax>
<man_description>
Returns the data associated with the key <i>key</i> in the database.
If there was no such key in the database, zero is returned.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->delete title="delete a value from the database">
<man_syntax>
int delete(string <I>key</I>);<br>
</man_syntax>
<man_description>
Remove a key from the database. Note that no error will be generated
if the key does not exist.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->firstkey title="get first key in database">
<man_syntax>
string firstkey();<br>
</man_syntax>
<man_description>
Returns the first key in the database, this can be any key in the
database.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->nextkey title="get next key in database">
<man_syntax>
string nextkey(string <I>key</I>);<br>
</man_syntax>
<man_description>
This returns the key in database that follows the key <i>key</i>.
This is of course used to iterate over all keys in the database.
</man_description>
<man_example>
/* Write the contents of the database */<br>
for(key=gdbm->firstkey(); k; k=gdbm->nextkey(k))<br>
<dl><dt><dd>write(k+":"+gdbm->fetch(k)+"\n");<br>
</dl>
</man_example>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->reorganize title="reorganize database">
<man_syntax>
int reorganize();<br>
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Gdbm.gdbm->sync title="synchronize database">
<man_syntax>
void sync();<br>
</man_syntax>
<man_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.
</man_description>
</method>
</section>
</module>
<hr noshade size=1>
<module name=Getopt>
<section title="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 (<tt>-t</tt>), the long ones
consist of two dashes followed by a string of text (<tt>--test</tt>).
The short options can also be combined, which means that you can write
<tt>-tda</tt> instead of <tt>-t -d -a</tt>. Options can also require
arguments, in which case they cannot be combined. To write an option
with an argument you write <tt>-t <i>argument</i></tt> or <tt>-t<i>argument</i></tt> or <tt>--test=<i>argument</i></tt>.
<hr noshade size=1>
<function name=Getopt.find_option title="find command line options">
<man_syntax>
<p>mixed find_option(array(string) <i>argv</i>,<br>
<dl><dt><dd>string <i>shortform</i>,<br>
void|string <i>longform</i>,<br>
void|string <i>envvar</i>,<br>
void|mixed <i>def</i>,<br>
void|int <i>throw_errors</i>);<br>
</dl>
</man_syntax>
<man_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.
<p>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.
</man_description>
<man_note>
find_option modifies argv.<br>
This function reads options even if they are written after the first
non-option on the line.
</man_note>
<man_example>
<pre><example language=pike>
/* 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)
{
if(find_option(argv,"f","foo"))
werror("The FOO option was given.\n");
werror("The BAR option got the "+
find_option(argv,"b","bar","BAR_OPTION","default")+
" argument.\n");
}
</example></pre>
</man_example>
<man_see>
Getopt.get_args
</man_see>
</function>
<hr noshade size=1>
<function name=Getopt.find_all_options title="find command line options">
<man_syntax>
array find_all_options(array(string) <i>argv</i>, array <i>option</i>, int|void <i>posix_me_harder</i>, int|void <i>throw_errors</i>);<br>
</man_syntax>
<man_description>
This function does the job of several calls to <tt>find_option</tt>.
The main advantage of this is that it allows it to handle the
POSIX_ME_HARDER environment variable better. When the either
the argument <i>posix_me_harder</i> or the environment variable
POSIX_ME_HARDER is true, no arguments will be parsed after the first
non-option on the command line.
<p>
Each element in the array <i>options</i> should be an array on the
following form:
<p>
<dl>
<dt>({
<dd>string <i>name</i>,
<dd>int <i>type</i>,
<dd>string|array(string) <i>aliases</i>,
<dd>void|string|array(string) <i>env_var</i>,
<dd>void|mixed <i>default</i>
<dt>})
</dl>
Only the first three elements has to be included.
<dl>
<dt> <i>name</i>
<dd> Name is a tag used to identify the option in the output.
<dt> <i>type</i>
<dd> 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 <tt>--version</tt>. MAY_HAVE_ARG should be used
for options that may or may not need an argument.
<dt> <i>aliases</i>
<dd> 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 <i>aliases</i> so find_all_options can distinguish between
long and short options. Example: <tt>({"-tT","--test"})</tt>
This would make find_all_options look for <tt>-t</tt>,
<tt>-T</tt> and <tt>--test</tt>.
<dt> <i>env_var</i>
<dd> This is a string or an array of strings containing names of
environment variables that can be used instead of the
command line option.
<dt> <i>default</i>
<dd> 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.
</dl>
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:
<dl>
<dt>({
<dd>string <i>name</i>,
<dd>mixed <i>value</i>
<dt>})
</dl>
The <i>name</i> is the identifier from the input and <i>value</i> is the
value given to it from the argument, environment variable or <i>default</i>.
If no default is given, <i>value</i> will be 1.
</man_description>
<man_note>
find_all_options modifies argv.<br>
</man_note>
<man_example>
First let's take a look at input and output:
<pre>
> Getopt.find_all_options(({"test","-dd"}),
>> ({ ({ "debug", Getopt.NO_ARG, ({"-d","--debug"}), "DEBUG", 1}) }));
Result: ({
({ "debug", 1 }),
({ "debug", 1 })
})
</pre>
<p>
This is what it would look like in real code:
<example language=pike>
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);
}
</example>
</man_example>
<man_see>
Getopt.get_args
</man_see>
</function>
<hr noshade size=1>
<function name=Getopt.get_args title="get the non-option arguments">
<man_syntax>
array(string) get_args(array(string) <I>argv</I>,void|int <i>throw_errors</i>);<br>
</man_syntax>
<man_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.
</man_description>
<man_example>
<example language=pike>
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");
}
</example>
</man_example>
<man_see>
Getopt.find_option
</man_see>
</function>
</section>
</module>
<hr noshade size=1>
<module name=Gz>
<section title="Gz">
The Gz module contains functions to compress and uncompress strings using
the same algorithm as the program <tt>gzip</tt>. 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 <i>algorithm</i> 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.
<p>
<class name=Gz.deflate title="string packer">
<man_description>
Gz.inflate is a builtin program written in C. It interfaces the
packing routines in the libz library.
</man_description>
<man_note>
This program is only available if libz was available and found when
Pike was compiled.
</man_note>
<man_see>
Gz.inflate
</man_see>
</class>
<hr noshade size=1>
<method name=Gz.deflate.create title="initialize packer">
<man_syntax>
void create(int X)<br>
object(Gz.deflate) Gz.deflate(int X)<br>
</man_syntax>
<man_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.
<p>This function can also be used to re-initialize a Gz.deflate object
so it can be re-used.
</man_description>
</method>
<hr noshade size=1>
<method name=Gz.deflate->deflate title="pack data">
<man_syntax>
string deflate(string <I>data</I>, int <I>flush</I>);<br>
</man_syntax>
<man_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:
<p>
<table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> Gz.NO_FLUSH </td><td> Only data that doesn't fit in the internal buffers is returned. </td></tr>
<tr valign=top><td> Gz.PARTIAL_FLUSH </td><td> All input is packed and returned. </td></tr>
<tr valign=top><td> Gz.SYNC_FLUSH </td><td> All input is packed and returned. </td></tr>
<tr valign=top><td> Gz.FINISH </td><td> All input is packed and an 'end of data' marker is appended. </td></tr>
</table>
<p>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.
</man_description>
<man_see>
Gz.inflate->inflate
</man_see>
</method>
<hr noshade size=1>
<class name=Gz.inflate title="string unpacker">
<man_description>
Gz.inflate is a builtin program written in C. It interfaces the
packing routines in the libz library.
</man_description>
<man_note>
This program is only available if libz was available and found when
Pike was compiled.
</man_note>
<man_see>
Gz.deflate
</man_see>
</class>
<hr noshade size=1>
<method name=Gz.inflate.create title="initialize unpacker">
<man_syntax>
void create()<br>
object(Gz.inflate) Gz.inflate()<br>
</man_syntax>
<man_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.
</man_description>
</method>
<hr noshade size=1>
<method name=Gz.inflate->inflate title="unpack data">
<man_syntax>
string inflate(string <I>data</I>);<br>
</man_syntax>
<man_description>
This function performs gzip style decompression. It can inflate
a whole file at once or in blocks.
</man_description>
<man_example>
import Stdio;<br>
// whole file<br>
write(Gz.inflate()->inflate(stdin->read());<br>
<p>// streaming (blocks)<br>
function inflate=Gz.inflate()->inflate;<br>
while(string s=stdin->read(8192))<br>
<dl><dt><dd>write(inflate(s));<br>
</dl>
</man_example>
<man_see>
Gz.deflate->deflate
</man_see>
</method>
</section>
<method name=Gz.crc32 title="calculate checksum">
<man_syntax>
string crc32(string <I>data</I>,void|int start_value);<br>
</man_syntax>
<man_description>
This method is usable for calculating checksums, and presents
the standard ISO3309 Cyclic Redundancy Check.
</man_description>
<man_see>
Gz
</man_see>
</method>
</module>
<hr noshade size=1>
<module name=Yp title="Yellow Pages, also known as NIS">
<section title="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.
<hr noshade size=1>
<function name=Yp.default_yp_domain title="get the default Yp domain">
<man_syntax>
string default_yp_domain();
</man_syntax>
<man_description>
Returns the default yp-domain.
</man_description>
</function>
<hr noshade size=1>
<class name=Yp.YpDomain title="class representing an Yp domain">
<man_syntax>
object(Yp.YpDomain) Yp.YpDomain(string|void <i>domain</i>);
</man_syntax>
<man_description>
This creates a new YpDomain object.
<p>
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.
<p>
If no domain is given, the default domain will be used. (As returned
by Yp.default_yp_domain)
</man_description>
</class>
<hr noshade size=1>
<method name=Yp.YpDomain->bind title="bind this object to another domain">
<man_syntax>
void bind(string|void <i>domain</i>);
</man_syntax>
<man_description>
Re-bind the object to another (or the same) domain. If no domain is given,
the default domain will be used.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpDomain->match title="match a key in a map">
<man_syntax>
string match(string <i>map</i>, string <i>key</i>);
</man_syntax>
<man_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.
<p>
<i>arguments</i> is the map Yp-map to search in. This must be a full map
name, for example, you should use <tt>passwd.byname</tt> instead of
just <tt>passwd</tt>. <i>key</i> is the key to search for. The key
must match exactly, no pattern matching of any kind is done.
</man_description>
<man_example>
<example language=pike>
object dom = Yp.YpDomain();
write(dom->match("passwd.byname", "root"));
</example>
</man_example>
</method>
<hr noshade size=1>
<method name=Yp.YpDomain->all title="return the whole map">
<man_syntax>
mapping(string:string) all(string <i>map</i>);
</man_syntax>
<man_description>
Returns the whole map as a mapping. <i>map</i> is the YP-map to search in.
This must be the full map name, you have to use <tt>passwd.byname</tt>
instead of just <tt>passwd</tt>.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpDomain->map title="call a function for each entry in an Yp map">
<man_syntax>
void map(string <i>map</i>, function(string,string:void) <i>over</i>);
</man_syntax>
<man_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. <i>map</i> is the YP-map to search in.
This must be the full map name, as an
example, passwd.byname instead of just passwd.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpDomain->server title="find an Yp server">
<man_syntax>
string server(string <i>map</i>);
</man_syntax>
<man_description>
Returns the hostname of the server serving the map <i>map</i>. <i>map</i>
is the YP-map to search in. This must be the full map name, as an
example, passwd.byname instead of just passwd.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpDomain->order title="get the 'order' for specified map">
<man_syntax>
int order(string <i>map</i>);
</man_syntax>
<man_description>
Returns the 'order' number for the map <i>map</i>. This is usually a
time_t (see the global function time()). When the map is changed, this number
will change as well. <i>map</i> is
the YP-map to search in. This must be the full map name, as an
example, passwd.byname instead of just passwd.
</man_description>
</method>
<hr noshade size=1>
<class name=Yp.YpMap title="class representing one Yp map">
<man_syntax>
object(Yp.YpMap) Yp.Ypmap(string <i>map</i>, string|void <i>domain</i>);
</man_syntax>
<man_description>
This creates a new YpMap object.
<p>
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. <i>map</i> 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.
</man_description>
</class>
<hr noshade size=1>
<method name=Yp.YpMap->match title="find key in map">
<man_syntax>
string match(string <i>key</i>)<br>;
string <i>Yp.YpMap</i>[string <i>key</i>];<br>
</man_syntax>
<man_description>
Search for the key <i>key</i>. If there is no <i>key</i> in the map, 0
will be returned, otherwise the string matching the key will
be returned.
<i>key</i> must match exactly, no pattern
matching of any kind is done.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->all title="return the whole map as a mapping">
<man_syntax>
mapping(string:string) all();<br>
(mapping) <i>Yp.YpMap</i>;<br>
</man_syntax>
<man_description>
Returns the whole map as a mapping.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->map title="call a function for each entry in the map">
<man_syntax>
void map(function(string,string:void) <i>over</i>);
</man_syntax>
<man_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)'.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->server title="find what server servers this map">
<man_syntax>
string server();
</man_syntax>
<man_description>
Returns the hostname of the server serving this map.
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->order title="find the 'order' of this map">
<man_syntax>
int order();
</man_syntax>
<man_description>
Returns the 'order' number for this map. This is usually a
time_t (see the global function time())
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->_sizeof title="return the number of entries in the map">
<man_syntax>
int sizeof(<i>Yp.YpMap</i>);
</man_syntax>
<man_description>
Returns the number of entries in the map. This is equivalent to
<tt>sizeof((mapping)map);</tt>
</man_description>
</method>
<hr noshade size=1>
<method name=Yp.YpMap->_indices title="return the indices from the map">
<man_syntax>
array(string) indices(<i>Yp.YpMap</i>)<br>
</man_syntax>
<man_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.
</man_description>
<man_see>
Yp.YpMap->_values
</man_see>
</method>
<hr noshard size=1>
<method name=Yp.YpMap->_values title="return the values from the map">
<man_syntax>
array(string) values(<i>Yp.Ypmap</i>)
</man_syntax>
<man_description>
Returns the values of the map. If values is called first, indices must
be called immediately after. If indices is called first, it is the
other way around.
</man_description>
<man_see>
Yp.YpMap->_indices
</man_see>
</method>
<hr noshade size=1>
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.
<example language=pike>
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
}
</example>
</section>
</module>
<hr noshade size=1>
<module name=ADT.Table>
<section title="ADT.Table">
ADT.Table is a generic module for manipulating tables. Each table contains one
or several columns. Each column is associated with a name, the column name.
Optionally, one can provide a column type. The Table module can do a number
of operations on a given table, like computing the sum of a column, grouping,
sorting etc.<p>
All column references are case insensitive. A column can be referred to by
its position (starting from zero). All operations are non-destructive. That
means that a new table object will be returned after, for example, a sort.<p>
An example is available at the end of this section.
<hr noshade size=1>
<method name=ADT.Table.table->create title="create a table object">
<man_syntax>
void create(array(array) <i>table</i>, array(string) <i>column_names</i>, array(mapping)|void <i>column_types</i>);<br>
</man_syntax>
<man_description>
The table class takes two or three arguments:<p>
<ol>
<li></i>table</i> is a two-dimensional array consisting of one array of
columns per row. All rows must have the same number of columns as specified
in <i>column_names</i>.<p>
<li><i>column_names</i> is an array of column names associated with each
column in the table. References by column name are case insensitive. The
case used in <i>column_names</i> will be used when the table is displayed.
A column can also be referred to by its position, starting from zero.<p>
<li><i>column_types</i> is an optional array of mappings. The column type
information is only used when displaying the table. Currently, only the
keyword "type" is recognized. The type can be specified as "text" or
"num" (numerical). Text columns are left adjusted, whereas numerical
columns are right adjusted. If a mapping in the array is 0 (zero),
it will be assumed to be a text column. If <i>column_types</i> is
omitted, all columns will displayed as text. See
<link to=ADT.Table.ASCII.encode>ADT.Table.ASCII.encode</link> on how to
display a table.<p>
</ol>
</man_description>
<man_example>
<example language=pike>
object t = ADT.Table.table( ({ ({ "Blixt", "Gordon" }),
({ "Buck", "Rogers" }) }),
({ "First name", "Last name" }) );
</example>
</man_example>
<man_see>
ADT.Table.ASCII.encode
</man_see>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->_indices title="gives the column names">
<man_syntax>
array(string) _indices();<br>
</man_syntax>
<man_description>
This method returns the column names for the table. The case used when
the table was created will be returned.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->_values title="gives the table contents">
<man_syntax>
array(array) _values();<br>
</man_syntax>
<man_description>
This method returns the contents of a table as a two dimensional array. The
format is an array of rows. Each row is an array of columns.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->_sizeof title="gives the number of table rows">
<man_syntax>
int _sizeof();<br>
</man_syntax>
<man_description>
This method returns the number of rows in the table.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->reverse title="reverses the table rows">
<man_syntax>
object reverse();<br>
</man_syntax>
<man_description>
This method reverses the rows of the table and returns a new table object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->rename title="rename a column">
<man_syntax>
object rename(string|int <i>from</i>, string <i>to</i>);<br>
</man_syntax>
<man_description>
This method renames the column named <i>from</i> to <i>to</i> and
returns a new table object. Note that <i>from</i> can be the column
position.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->type title="fetch or set the type for a column">
<man_syntax>
mapping type(string|int <i>column</i>, mapping|void <i>type</i>);<br>
</man_syntax>
<man_description>
This method gives the type for the given column. If a second argument is
given, the old type will be replaced with <i>type</i>. The column type
is only used when the table is displayed. The format is as specified
in <link to=ADT.Table.table.create>create</link>.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->limit title="truncate the table">
<man_syntax>
object limit(int <i>n</i>);<br>
</man_syntax>
<man_description>
This method truncates the table to the first <i>n</i> rows and returns
a new object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->sort title="sort the table on one or several columns">
<man_syntax>
object sort(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
This method sorts the table in ascendent order on one or several columns
and returns a new table object. The left most column is sorted last. Note
that the sort is stable.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->rsort title="sort the table in reversed order on one or several columns">
<man_syntax>
object rsort(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
Like <link to=ADT.Table.table.sort>sort</link>, but the order is descendent.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->distinct title="keep unique rows only">
<man_syntax>
object distinct(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
This method groups by the given columns and returns a table with only
unique rows. When no columns are given, all rows will be unique. A new
table object will be returned.
</man_description>
</method>
<hr noshade size=1>
<method name=Table.table->sum title="computes the sum of equal rows">
<man_syntax>
object sum(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
This method sums all equal rows. The table will be grouped by the
columns not listed. The result will be returned as a new table object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->group title="group the table using functions">
<man_syntax>
object group(mapping(string|int:funcion) <i>fus</i>, mixed ... <i>arg</i>);<br>
object group(funcion <i>f</i>, array(string|int)|string|int <i>columns</i>, mixed ... <i>arg</i>);<br>
</man_syntax>
<man_description>
This method calls the function for each column each time a non uniqe row
will be joined. The table will be grouped by the columns not listed. The
result will be returned as a new table object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->map title="map columns over a function">
<man_syntax>
object map(funcion <i>fu</i>, string|int|array(int|string) <i>columns</i>, mixed ... <i>arg</i>);<br>
</man_syntax>
<man_description>
This method calls the function for all rows in the table. The value returned
will replace the values in the columns given as argument to map. If
the function returns an array, several columns will be replaced. Otherwise
the first column will be replaced. The result will be returned as a new
table object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->where title="filter the table through a function">
<man_syntax>
object where(array(string|int)|string|int <i>column1</i>, funcion <i>fu</i>, mixed ... <i>arg</i>);<br>
</man_syntax>
<man_description>
This method calls the function for each row. If the function returns zero,
the row will be thrown away. If the function returns something non-zero,
the row will be kept. The result will be returned as a new table object.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->select title="keep only the given columns">
<man_syntax>
object select(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
This method returns a new table object with the selected columns only.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->remove title="remove columns">
<man_syntax>
object remove(string|int <i>column1</i>, string|int <i>column2</i>, ...);<br>
</man_syntax>
<man_description>
Like <link to=ADT.Table.table.select>select</link>, but the given
columns will not be in the resulting table.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->encode title="represent the table as a binary string">
<man_syntax>
string encode();<br>
</man_syntax>
<man_description>
This method returns a binary string representation of the table. It is
useful when one wants to store a table, for example in a file.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->decode title="decode an encoded table">
<man_syntax>
string decode(string <i>table_string</i>);<br>
</man_syntax>
<man_description>
This method returns a table object from a binary string representation of
a table.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->col title="fetch a column">
<man_syntax>
array col(string|int <i>column</i>);<br>
</man_syntax>
<man_description>
This method returns the contents of a given column as an array.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->`[] title="fetch a column">
<man_syntax>
array `[](string|int <i>column</i>);<br>
</man_syntax>
<man_description>
Same as <link to=ADT.Table.table.col>col</link>.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->row title="fetch a row">
<man_syntax>
array row(int <i>row_number</i>);<br>
</man_syntax>
<man_description>
This method returns the contents of a given row as an array.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->`== title="compare two tables">
<man_syntax>
int `==(object <i>table</i>);<br>
</man_syntax>
<man_description>
This method compares two tables. They are equal if the contents
of the tables and the column names are equal. The column name
comparison is case insensitive.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->append_bottom title="concatenate two tables">
<man_syntax>
object append_bottom(object <i>table</i>);<br>
</man_syntax>
<man_description>
This method appends two tables. The table given as an argument will be
added at the bottom of the current table. Note, the column names must
be equal. The column name comparison is case insensitive.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.table->append_right title="concatenate two tables">
<man_syntax>
object append_right(object <i>table</i>);<br>
</man_syntax>
<man_description>
This method appends two tables. The table given as an argument will be
added on the right side of the current table. Note that the number of
rows in both tables must be equal.
</man_description>
</method>
<hr noshade size=1>
<method name=ADT.Table.ASCII.encode title="produces an ASCII formated table">
<man_syntax>
string encode(object <i>table</i>, mapping|void <i>options</i>);<br>
</man_syntax>
<man_description>
This method returns a table represented in ASCII suitable for human eyes.
<i>options</i> is an optional mapping. If the keyword "indent" is used
with a number, the table will be indented with that number of space
characters.
</man_description>
</method>
<hr noshade size=1>
<man_example>
<example language=pike>
array(string) fält = ({ "Frukt", "Leverantör", "Antal" });
array(mapping) typ = ({ 0, 0, ([ "type":"num" ]) });
array(array) tabell = ({ ({ "Avocado", "Frukt AB", 314 }),
({ "Banan", "Banankompaniet", 4276 }),
({ "Apelsin", "Frukt AB", 81 }),
({ "Banan", "Frukt AB", 1174 }),
({ "Apelsin", "General Food", 523 }) });
object t = .Table.table(tabell, fält, typ);
write("FRUKT & GRÖNT\n\n");
write(.Table.ASCII.encode(t, ([ "indent":4 ])));
write("\nLEVERANTÖRER\n\n");
write(.Table.ASCII.encode(t->select("leverantör", "antal")->
sum("antal")->rename("antal", "Summa antal")->
rsort("summa antal")));
write("\nLEVERANTÖRER\n\n"+
.Table.ASCII.encode(t->select("leverantör", "antal")->
sum("antal")->rename("antal", "Summa antal")->
where("summa antal", `>, 1000)->
rsort("summa antal")));
write("\nLEVERANSER\n\n");
write(.Table.ASCII.encode(t->select("frukt")->distinct("frukt")->
sort("frukt"), ([ "indent":4 ])));
</example>
</man_example>
</section>
</module>
<hr noshade size=1>
<module name=Yabu>
<section title="Yabu transaction database">
Yabu is a all purpose database, used to store data records associated with a
unique key. Yabu is very similar to mappings, however, records are
stored in files and not in memory. Also, Yabu features <i>tables</i>,
which is a way to handle several mapping-like structures in the same
database. A characteristic feature of Yabu is that it allows for
<i>transactions</i>. A transaction is a sequence of database commands
that will be accepted in whole, or not at all.<p>
Some effort has been made to make sure that Yabu is crash safe.
This means that the database should survive process kills, core
dumps and such -- although this is not something that can be absolutely
guaranteed. Also, all non-commited and pending transactions will
be cancelled in case of a crash.<p>
Yabu uses three types of objects, listed below:<p>
<ul>
<li>The <i>db</i> object is the main database object. It can create
table objects. The methods available in the db object are:
<link to=Yabu.db.table><tt>table</tt></link> (the <tt>[]</tt> operator),
<link to=Yabu.db.list_tables><tt>list_tables</tt></link>
(<tt>indices</tt>),
<link to=Yabu.db.sync><tt>sync</tt></link> and
<link to=Yabu.db.purge><tt>purge</tt></link>.
<li>The <i>table</i> object handles tables. It is used in order to
store and fetch records from the database. It can create transaction
objects. The methods available in the table object are:
<link to=Yabu.table.set><tt>set</tt></link> (the <tt>[]=</tt> operator),
<link to=Yabu.table.get><tt>get</tt></link> (the <tt>[]</tt> operator),
<link to=Yabu.table.list_keys><tt>list_keys</tt></link> (<tt>indices</tt>),
<link to=Yabu.table.delete><tt>delete</tt></link>,
<link to=Yabu.table.transaction><tt>transaction</tt></link> and
<link to=Yabu.table.purge><tt>purge</tt></link>.
<li>The <i>transaction</i> object handles transactions. It works
like the table object. The difference is that a sequence of commands
must end with <tt>commit</tt> or <tt>rollback</tt>. The methods available
in the table object are:
<link to=Yabu.table.set><tt>set</tt></link> (the <tt>[]=</tt> operator),
<link to=Yabu.table.get><tt>get</tt></link> (the <tt>[]</tt> operator),
<link to=Yabu.table.list_keys><tt>list_keys</tt></link> (<tt>indices</tt>),
<link to=Yabu.table.delete><tt>delete</tt></link>,
<link to=Yabu.transaction.commit><tt>commit</tt></link> and
<link to=Yabu.transaction.rollback><tt>rollback</tt></link>.
</ul><p>
A simple example is illustrated below.<p>
<man_example>
<example language=pike>
// Create a database called "my.database" in write/create mode.
object db = Yabu.db("my.database", "wc");
// Create a table called "fruit".
object table = db["fruit"];
// Store a record called "orange" with the value "yummy".
table["orange"] = "yummy";
// Store a record called "apple" with the value 42.
table["apple"] = 42;
</example>
</man_example><p>
Transactions are slightly more complex, but not much so. See example
below.
<man_example>
<example language=pike>
// Create a database called "my.database"
// in write/create/transaction mode.
object db = Yabu.db("my.database", "wct");
// Create a table called "fruit".
object table = db["fruit"];
// Create a transaction object for table "fruit".
object transaction = table->transaction();
// Store a record called "orange" with
// the value "yummy". Note that this record
// is only visible through the transaction object.
transaction["orange"] = "yummy";
// Store a record called "apple" with the value 42.
// As with "orange", this record is invisible
// for all objects except this transaction object.
transaction["apple"] = 42;
// Commit the records "orange" and "apple".
// These records are now a part of the database.
transaction->commit();
</example>
</man_example>
<hr noshade size=1>
<section title="The database">
The db object is the main Yabu database object. It is used to open
the database and it can create table objects.<p>
A Yabu database can operate in two basic modes:<p>
<ul>
<li> Read mode. In read mode, nothing in the database can be altered,
added nor deleted. All Yabu files will be opended in read mode, which
means that the database will be in the same state on the disk as it
was prior to the opening.
<li> Write mode. In write mode, records can be altered, added or deleted. In
combination with create mode, new tables can also be added. Transactions
can optionally be used with write mode. When compressed mode is enabled,
all records will be compressed before stored on to disk.
</ul>
Compressed databases opened without compress mode enabled will be handled
correctly in both modes, provided that the Gz module is available.
However, new records will no longer be compressed in write mode.<p>
<method name=Yabu.db->create title="Open a Yabu database">
<man_syntax>
void create(string <i>directory</i>, string <i>mode</i>);
</man_syntax>
<man_description>
Create takes two arguments:<p>
<ol>
<li><i>directory</i> is a string specifying the directory where Yabu will
store its files. Yabu will create the directory if it does not exist,
provided Yabu is opened in write and create mode (see below).<p>
<li><i>mode</i> is a string specifying the mode in which Yabu will
operate. There are five switches available:<p>
<ul>
<li>"r" - Read mode. No database entries can be altered and no files will
be modified.<p>
<li>"c" - Create mode. The database can create new tables. Create mode is
only used togheter with write mode.<p>
<li>"w" - Write mode. The database can be altered and the files will be
updates accordingly.<p>
<li>"t" - Transaction mode. The database now allows transactions.<p>
<li>"C" - Compress mode. Provided the <link to=Gz>Gz module</link> is
available, all records will be compressed before stored on to disk.<p>
</ul>
</ol>
</man_description>
<man_note>
It is very important not to open the same a database more than
once at a time. Otherwise there will be conflicts and most likely
strange failures and unpredictable behaviours. Yabu does not check
weather a database is already open or not.
</man_note>
<man_example>
<example language=pike>
// Open a database in create/write/transaction mode.
object db = Yabu.db("my.database", "cwt");
// Open a database in read mode.
object db = Yabu.db("my.database", "r");
// Open a database in create/write/compress mode.
object db = Yabu.db("my.database", "cwC");
</example>
</man_example>
<man_see>
Yabu.db->table,
Yabu.db->list_tables,
Yabu.db->sync,
Yabu.db->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.db->table title="Open a table">
<man_syntax>
object(table) table(string <i>table_name</i>);<br>
object(table) `[](string <i>table_name</i>);<br>
</man_syntax>
<man_description>
This method opens a table with <i>table_name</i>. If the table
does not exist, it will be created. A table object will be returned.
</man_description>
<man_see>
Yabu.db->list_tables,
Yabu.db->sync,
Yabu.db->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.db->list_tables title="List all tables">
<man_syntax>
array(string) list_tables();<br>
array(string) _indices();<br>
</man_syntax>
<man_description>
This method lists all available tables.
</man_description>
<man_see>
Yabu.db->table,
Yabu.db->sync,
Yabu.db->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.db->sync title="Synchronize database">
<man_syntax>
void sync();<br>
</man_syntax>
<man_description>
This method synchronizes the database on disk. Yabu stores some information
about the database in memory for performance reasons. Syncing is recommended
when one wants the information on disk to be updated with the current
information in memory.
</man_description>
<man_see>
Yabu.db->table,
Yabu.db->list_tables,
Yabu.db->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.db->purge title="Delete database">
<man_syntax>
void purge();<br>
</man_syntax>
<man_description>
This method deletes the whole database and all database files stored on disk.
</man_description>
<man_see>
Yabu.db->table,
Yabu.db->list_tables,
Yabu.db->sync
</man_see>
</method>
</section>
<hr noshade size=1>
<section title="Tables">
The table object is used to store and retrieve information from
a table. Table objects are created by the db class. A table object
can create a transaction object.
<method name=Yabu.table->set title="Store a record in a table">
<man_syntax>
mixed set(string key, mixed data);<br>
mixed `[]=(string key, mixed data);<br>
</man_syntax>
<man_description>
This method stores the contents of <i>data</i> as a record with the name
<i>key</i>. If a record with that name already exists, it will be
replaced. Records can only be added to the database in write mode.
</man_description>
<man_see>
Yabu.table->get,
Yabu.table->delete,
Yabu.table->list_keys,
Yabu.table->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.table->get title="Fetch a record from a table">
<man_syntax>
mixed get(string key);<br>
mixed `[](string key);<br>
</man_syntax>
<man_description>
This method fetches the data associated with the record name
<i>key</i>. If a record does not exist, zero is returned.
</man_description>
<man_see>
Yabu.table->set,
Yabu.table->delete,
Yabu.table->list_keys,
Yabu.table->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.table->list_keys title="List the records in a table">
<man_syntax>
array(string) list_keys();<br>
array(string) _indices();<br>
</man_syntax>
<man_description>
This method lists all record names in the table.
</man_description>
<man_see>
Yabu.table->set,
Yabu.table->get,
Yabu.table->delete,
Yabu.table->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.table->delete title="Delete a record in a table">
<man_syntax>
void delete(string <i>key</i>);<br>
</man_syntax>
<man_description>
This method deletes the record with the name <i>key</i>.
</man_description>
<man_see>
Yabu.table->set,
Yabu.table->get,
Yabu.table->list_keys,
Yabu.table->purge
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.table->purge title="Delete a table">
<man_syntax>
void purge();<br>
</man_syntax>
<man_description>
This method deletes the whole table and the table files on disk.
</man_description>
<man_see>
Yabu.table->set,
Yabu.table->get,
Yabu.table->list_keys,
Yabu.table->delete
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.table->transaction title="Begin a transaction">
<man_syntax>
object(transaction) transaction();<br>
</man_syntax>
<man_description>
A transaction is a sequence of table commands that will be accepted in
whole, or not at all. If the program for some reason crashes or makes
an abrupt exit during a transaction, the transaction is cancelled.<p>
This method returns a transaction object.
</man_description>
<man_see>
Yabu.transaction->commit,
Yabu.transaction->rollback
</man_see>
</method>
</section>
<hr noshade size=1>
<section title="Transactions">
Transactions make it possible to alter, add or delete several database
records and guarantee that all changes, or no changes, will be accepted
by the database. A transaction object is basically a table object with
a few restrictions and additions, listed below:<p>
<ul>
<li>Purge is not available in a transaction object.
<li>Commit. In order to make all changes take affect, commit must be
issued at the end of a transaction sequence. Changes done by a
transaction object will never take affect before commit,
even if the database is shut down, the program crashes etc.
<li>Rollback. A rollback cancels all changes made by the transaction object.
</ul><p>
Rollbacks always succeeds. However, with commit that is not always
the case. A commit will fail if:<p>
<ul>
<li>A record that is altered by the transaction object is altered
again by something else, before commit. This is called a conflict,
and will result in an error upon commit.
</ul><p>
<method name=Yabu.transaction->commit title="Commit a transaction">
<man_syntax>
void commit();<br>
</man_syntax>
<man_description>
This method commits the changes made in a transaction. If a record affected
by the transaction is altered during the transaction, a conflict will
arise and an error is thrown.
</man_description>
<man_see>
Yabu.table->transaction,
Yabu.transaction->rollback
</man_see>
</method>
<hr noshade size=1>
<method name=Yabu.transaction->rollback title="Rollback a transaction">
<man_syntax>
void rollback();<br>
</man_syntax>
<man_description>
This method cancels a transaction. All changes made in the transaction
are lost.
</man_description>
<man_see>
Yabu.table->transaction,
Yabu.transaction->commit
</man_see>
</method>
</section>
</section>
</module>
<hr noshade size=1>
<module name=MIME>
<section title="MIME">
<a href="http://www.roxen.com/rfc/rfc1521.txt">RFC1521</a>, the
<b>Multipurpose Internet Mail Extensions</b> memo, defines a
structure which 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 <a href="http://www.roxen.com/rfc/rfc822.txt">RFC822</a>,
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:
<dl>
<dt>Headers
<dd><ul>
<li>A MIME-Version header must be present to signal MIME compatibility
<li>A Content-Type header should be present to describe the nature of the
data in the message body. Seven major types are defined, and an extensive
number of subtypes are available. The header can also contain attributes
specific to the type and subtype.
<li>A Content-Transfer-Encoding may be present to notify that the data of
the body is encoded in some particular encoding.
</ul>
<dt>Body
<dd><ul>
<li>Raw data to be interpreted according to the Content-Type header
<li>Can be encoded using one of several Content-Transfer-Encodings to
allow transport over non 8bit clean channels
</ul>
</dl>
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.
<p>
The Message class does not make any interpretation of the body data, unless
the content type is <tt>multipart</tt>. A multipart message contains several
individual messages separated by boundary strings. The <tt>create</tt>
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 <tt>body_parts</tt> 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:
<img src=multipart.gif>
<hr newpage>
<section title="Global functions">
<function name=MIME.decode title="Remove transfer encoding">
<man_syntax>
string decode(string <i>data</i>, string <i>encoding</i>);
</man_syntax>
<man_description>
Extract raw data from an encoded string suitable for transport between systems.
The encoding can be any of
<tt><ul>
<li>7bit
<li>8bit
<li>base64
<li>binary
<li>quoted-printable
<li>x-uue
<li>x-uuencode
</ul></tt>
The encoding string is not case sensitive.
</man_description>
<man_see>
MIME.encode
</man_see>
</function>
<hr newpage>
<function name=MIME.decode_base64 title="Decode <tt>base64</tt> transfer encoding">
<man_syntax>
string decode_base64(string <i>encoded_data</i>);
</man_syntax>
<man_description>
This function decodes data encoded using the <tt>base64</tt> transfer encoding.
</man_description>
<man_see>
MIME.encode_base64
</man_see>
</function>
<hr newpage>
<function name=MIME.decode_qp title="Decode <tt>quoted-printable</tt> transfer encoding">
<man_syntax>
string decode_qp(string <i>encoded_data</i>);
</man_syntax>
<man_description>
This function decodes data encoded using the <tt>quoted-printable</tt>
(a.k.a. quoted-unreadable) transfer encoding.
</man_description>
<man_see>
MIME.encode_qp
</man_see>
</function>
<hr newpage>
<function name=MIME.decode_uue title="Decode <tt>x-uue</tt> transfer encoding">
<man_syntax>
string decode_uue(string <i>encoded_data</i>);
</man_syntax>
<man_description>
This function decodes data encoded using the <tt>x-uue</tt> transfer encoding.
It can also be used to decode generic UUEncoded files.
</man_description>
<man_see>
MIME.encode_uue
</man_see>
</function>
<hr newpage>
<function name=MIME.decode_word title="De-scramble RFC1522 encoding">
<man_syntax>
array(string) decode_word(string <i>word</i>);
</man_syntax>
<man_description>
Extracts the textual content and character set from an <i>encoded word</i>
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.
</man_description>
<man_example>
<example language=pike>
> 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"
})
})
</example>
</man_example>
<man_see>
MIME.encode_word
</man_see>
</function>
<hr newpage>
<function name=MIME.encode title="Apply transfer encoding">
<man_syntax>
string encode(string <i>data</i>, string <i>encoding</i>,<br>
<dl><dt><dd>void|string <i>filename</i>,<br>
void|int <i>no_linebreaks</i>);<br>
</dl>
</man_syntax>
<man_description>
Encode raw data into something suitable for transport to other systems.
The encoding can be any of
<tt><ul>
<li>7bit
<li>8bit
<li>base64
<li>binary
<li>quoted-printable
<li>x-uue
<li>x-uuencode
</ul></tt>
The encoding string is not case sensitive. For the <tt>x-uue</tt> encoding,
an optional filename string may be supplied. If a nonzero value is passed
as <i>no_linebreaks</i>, the result string will not contain any linebreaks
(base64 and quoted-printable only).
</man_description>
<man_see>
MIME.decode
</man_see>
</function>
<hr newpage>
<function name=MIME.encode_base64 title="Encode string using <tt>base64</tt> transfer encoding">
<man_syntax>
string encode_base64(string <i>data</i>, void|int <i>no_linebreaks</i>);
</man_syntax>
<man_description>
This function encodes data using the <tt>base64</tt> transfer encoding.
If a nonzero value is passed as <i>no_linebreaks</i>, the result string
will not contain any linebreaks.
</man_description>
<man_see>
MIME.decode_base64
</man_see>
</function>
<hr newpage>
<function name=MIME.encode_qp title="Encode string using <tt>quoted-printable</tt> transfer encoding">
<man_syntax>
string encode_qp(string <i>data</i>, void|int <i>no_linebreaks</i>);
</man_syntax>
<man_description>
This function encodes data using the <tt>quoted-printable</tt>
(a.k.a. quoted-unreadable) transfer encoding. If a nonzero value is passed as <i>no_linebreaks</i>, the result string will not contain any linebreaks.
</man_description>
<man_note>
Please do not use this function. QP is evil, and there's no
excuse for using it.
</man_note>
<man_see>
MIME.decode_qp
</man_see>
</function>
<hr newpage>
<function name=MIME.encode_uue title="Encode string using <tt>x-uue</tt> transfer encoding">
<man_syntax>
string encode_uue(string <i>encoded_data</i>, void|string <i>filename</i>);
</man_syntax>
<man_description>
This function encodes data using the <tt>x-uue</tt> 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.
</man_description>
<man_see>
MIME.decode_uue
</man_see>
</function>
<hr newpage>
<function name=MIME.encode_word title="Encode word according to RFC1522">
<man_syntax>
string encode_word(array(string) <i>word</i>, string <i>encoding</i>);
</man_syntax>
<man_description>
Create an <i>encoded word</i> 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 <tt>"base64"</tt> or
<tt>"quoted-printable"</tt> (or either <tt>"b"</tt> or <tt>"q"</tt> 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.
</man_description>
<man_example>
<pre>
> MIME.encode_word( ({ "Quetzalcoatl", "iso-8859-1" }), "base64" );
Result: =?iso-8859-1?b?UXVldHphbGNvYXRs?=
> MIME.encode_word( ({ "Foo", 0 }), "base64" );
Result: Foo
</pre>
</man_example>
<man_see>
MIME.decode_word
</man_see>
</function>
<hr newpage>
<function name=MIME.generate_boundary title="Create a suitable boundary string for multiparts">
<man_syntax>
string generate_boundary();
</man_syntax>
<man_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 <tt>base64</tt>, <tt>quoted-printable</tt>, or <tt>x-uue</tt> encoded data.
It is also unlikely to appear in normal text. This function is used by
the cast method of the <tt>Message</tt> class if no boundary string is
specified.
</man_description>
</function>
<hr newpage>
<function name=MIME.guess_subtype title="Provide a reasonable default for the subtype field">
<man_syntax>
string guess_subtype(string <i>type</i>);
</man_syntax>
<man_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:
<table border=1>
<tr><th>type</th><th>subtype</th></tr>
<tr><td>text</td><td>plain</td></tr>
<tr><td>message</td><td>rfc822</td></tr>
<tr><td>multipart</td><td>mixed</td></tr>
</table>
</man_description>
</function>
<hr newpage>
<function name=MIME.parse_headers title="Separate a bytestream into headers and body">
<man_syntax>
array(mapping(string:string)|string) parse_headers(string <i>message</i>);
</man_syntax>
<man_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.
<p>
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.
</man_description>
</function>
<hr newpage>
<function name=MIME.quote title="Create an RFC822 header field from lexical elements">
<man_syntax>
string quote(array(string|int) <i>lexical_elements</i>);
</man_syntax>
<man_description>
This function is the inverse of the <link to=MIME.tokenize>tokenize</link> function.
A header field value is constructed from a sequence of lexical elements.
Characters (<tt>int</tt>s) are taken to be special-characters, whereas
strings are encoded as atoms or quoted-strings, depending on whether
they contain any special characters.
</man_description>
<man_example>
<pre>
> MIME.quote( ({ "attachment", ';', "filename", '=', "/usr/dict/words" }) );
Result: attachment;filename="/usr/dict/words"
</pre>
</man_example>
<man_note>
There is no way to construct a domain-literal using this function.
Neither can it be used to produce comments.
</man_note>
<man_see>
MIME.tokenize
</man_see>
</function>
<hr newpage>
<function name=MIME.reconstruct_partial title="Join a fragmented message to its original form">
<man_syntax>
int|object reconstruct_partial(array(object) <i>collection</i>);
</man_syntax>
<man_description>
This function will attempt to reassemble a fragmented message from its
parts. The array <i>collection</i> should contain <tt>MIME.Message</tt>
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.
<p>
Should the function succeed in reconstructing the original message, a
new <tt>MIME.Message</tt> 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:
<ul>
<li>If an empty <i>collection</i> is passed in, or one that contains messages
which are not of type <tt>message/partial</tt>, or parts of different
fragmented messages, the function returns 0.
<li>If more fragments are needed to reconstruct the entire message, the
number of additional messages needed is returned.
<li>If more fragments are needed, but the function can't tell exactly how
many, -1 is returned.
</ul>
</man_description>
<man_see>
MIME.Message->is_partial
</man_see>
</function>
<hr newpage>
<function name=MIME.tokenize title="Separate an RFC822 header field into lexical elements">
<man_syntax>
array(string|int) tokenize(string <i>header</i>);
</man_syntax>
<man_description>
A structured header field, as specified by RFC822, is constructed from
a sequence of lexical elements. These are:
<ul>
<li>individual special characters
<li>quoted-strings
<li>domain-literals
<li>comments
<li>atoms
</ul>
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. <tt>int</tt>s). Quoted-strings,
domain-literals and atoms will be decoded and returned as strings.
Comments are not returned in the array at all.
</man_description>
<man_example>
<pre>
> MIME.tokenize("multipart/mixed; boundary=\"foo/bar\" (Kilroy was here)");
Result: ({ /* 7 elements */
"multipart",
47,
"mixed",
59,
"boundary",
61,
"foo/bar"
})
</pre>
</man_example>
<man_note>
As domain-literals are returned as strings, there is no way to tell the
domain-literal <tt>[127.0.0.1]</tt> from the quoted-string
<tt>"[127.0.0.1]"</tt>. Hopefully this won't cause any problems.
Domain-literals are used seldom, if at all, anyway...
<p>
The set of special-characters is the one specified in RFC1521 (i.e. <tt>"<",
">", "@", ",", ";", ":", "\", "/", "?", "="</tt>), and not the one
specified in RFC822.
</man_note>
<man_see>
MIME.quote
</man_see>
</function>
<hr newpage>
</section>
<section title="The MIME.Message class">
<class name=MIME.Message title="The MIME.Message class">
This class is used to hold a decoded MIME message.
<section title="Public fields">
<hr newpage>
<variable name=MIME.Message->body_parts title="Multipart sub-messages">
<man_syntax>
array(object) msg->body_parts;
</man_syntax>
<man_description>
If the message is of type <tt>multipart</tt>, this is an array containing one
Message object for each part of the message. If the message is not a
multipart, this field is <tt>0</tt>.
</man_description>
<man_see>
MIME.Message->type, MIME.Message->boundary
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->boundary title="Boundary string for multipart messages">
<man_syntax>
string msg->boundary;
</man_syntax>
<man_description>
For multipart messages, this <tt>Content-Type</tt> 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.
</man_description>
<man_see>
MIME.Message->setboundary
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->charset title="Character encoding for text bodies">
<man_syntax>
string msg->charset;
</man_syntax>
<man_description>
One of the possible parameters of the <tt>Content-Type</tt> header is the
charset attribute. It determines the character encoding used in bodies of
type text. If there is no <tt>Content-Type</tt> header, the value of this
field is <tt>"us-ascii"</tt>.
</man_description>
<man_see>
MIME.Message->type
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->disposition title="Multipart subpart disposition">
<man_syntax>
string msg->disposition;
</man_syntax>
<man_description>
The first part of the <tt>Content-Disposition</tt> header, hinting on how
this part of a multipart message should be presented in an interactive
application. If there is no <tt>Content-Disposition</tt> header, this
field is <tt>0</tt>.
</man_description>
</variable>
<hr newpage>
<variable name=MIME.Message->disp_params title="Content-Disposition parameters">
<man_syntax>
mapping(string:string) msg->disp_params;
</man_syntax>
<man_description>
A mapping containing all the additional parameters to the
<tt>Content-Disposition</tt> header.
</man_description>
<man_see>
MIME.Message->setdisp_param, MIME.Message->get_filename
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->headers title="All header fields of the message">
<man_syntax>
mapping(string:string) msg->headers;
</man_syntax>
<man_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 <b>not</b> be accessed through
this mapping. These fields are currently:
<ul>
<li><tt>content-type</tt>
<li><tt>content-disposition</tt>
<li><tt>content-length</tt>
<li><tt>content-transfer-encoding</tt>
</ul>
The contents of these fields can be accessed and/or modified through a set
of variables and methods available for this purpose.
</man_description>
<man_see>
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
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->params title="Content-Type parameters">
<man_syntax>
mapping(string:string) msg->params;
</man_syntax>
<man_description>
A mapping containing all the additional parameters to the
<tt>Content-Type</tt> header. Some of these parameters have fields of their
own, which should be accessed instead of this mapping wherever applicable.
</man_description>
<man_see>
MIME.Message->charset, MIME.Message->boundary, MIME.Message->setparam
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->subtype title="The subtype attribute of the Content-Type header">
<man_syntax>
string msg->subtype;
</man_syntax>
<man_description>
The <tt>Content-Type</tt> header contains a type, a subtype, and optionally
some parameters. This field contains the subtype attribute extracted from the
header. If there is no <tt>Content-Type</tt> header, the value of this field
is <tt>"plain"</tt>.
</man_description>
<man_see>
MIME.Message->type, MIME.Message->params
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->transfer_encoding title="Body encoding method">
<man_syntax>
string msg->transfer_encoding;
</man_syntax>
<man_description>
The contents of the <tt>Content-Transfer-Encoding</tt> header. If no
<tt>Content-Transfer-Encoding</tt> header is given, this field is <tt>0</tt>.
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.
</man_description>
<man_see>
MIME.Message->setencoding
</man_see>
</variable>
<hr newpage>
<variable name=MIME.Message->type title="The type attribute of the Content-Type header">
<man_syntax>
string msg->type;
</man_syntax>
<man_description>
The <tt>Content-Type</tt> header contains a type, a subtype, and optionally
some parameters. This field contains the type attribute extracted from the
header. If there is no <tt>Content-Type</tt> header, the value of this field
is <tt>"text"</tt>.
</man_description>
<man_see>
MIME.Message->subtype, MIME.Message->params
</man_see>
</variable>
<hr newpage>
</section>
<section title="Public methods">
<hr newpage>
<method name=MIME.Message->cast title="Encode message into byte stream">
<man_syntax>
string (string )<i>MIME.Message</i>;
</man_syntax>
<man_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
<link to=MIME.generate_boundary>generate_boundary</link>.
</man_description>
<man_example>
<example language=pike>
> 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==
</example>
</man_example>
<man_see>
MIME.Message->create
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->create title="Create a Message object">
<man_syntax>
object MIME.Message(void | string <i>message</i>,<br>
<dl><dt><dd>void | mapping(string:string) <i>headers</i>,<br>
void | array(object) <i>parts</i>);<br>
</dl>
</man_syntax>
<man_description>
There are several ways to call the constructor of the Message class;
<ul>
<li>With zero arguments, you will get a dummy message without either headers
or body. Not very useful.
<li>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.
<li>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.
</ul>
</man_description>
<man_example>
<example languag=pike>
> 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
</example>
</man_example>
<man_see>
MIME.Message->cast
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->getdata title="Obtain raw body data">
<man_syntax>
string getdata();
</man_syntax>
<man_description>
This method returns the raw data of the message body entity. The
<link to=MIME.Message.type>type</link> and <link to=MIME.Message.subtype>subtype</link> attributes
indicate how this data should be interpreted.
</man_description>
<man_see>
MIME.Message->getencoded
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->getencoded title="Obtain encoded body data">
<man_syntax>
string getencoded();
</man_syntax>
<man_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.
</man_description>
<man_see>
MIME.Message->getdata
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->get_filename title="Get supplied filename for body data">
<man_syntax>
string get_filename();
</man_syntax>
<man_description>
This method tries to find a suitable filename should you want to save the
body data to disk. It will examine the <tt>filename</tt> attribute of the
<tt>Content-Disposition</tt> header, and failing that the <tt>name</tt>
attribute of the <tt>Content-Type</tt> header. If neither attribute is set,
the method returns 0.
</man_description>
<man_note>
An interactive application should always query the user for the actual
filename to use. This method may provide a reasonable default though.
</man_note>
</method>
<hr newpage>
<method name=MIME.Message->is_partial title="Identify <tt>message/partial</tt> message">
<man_syntax>
array(string|int) is_partial();
</man_syntax>
<man_description>
If this message is a part of a fragmented message (i.e. has a Content-Type
of <tt>message/partial</tt>), 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.
</man_description>
<man_see>
MIME.reconstruct_partial
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setboundary title="Set boundary parameter">
<man_syntax>
void setboundary(string <i>boundary</i>);
</man_syntax>
<man_description>
Sets the <tt>boundary</tt> parameter of the <tt>Content-Type</tt> header.
This is equivalent of calling
<tt>msg->setparam("boundary", <i>boundary</i>)</tt>.
</man_description>
<man_see>
MIME.Message->setparam
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setcharset title="Set charset parameter">
<man_syntax>
void setcharset(string <i>charset</i>);
</man_syntax>
<man_description>
Sets the <tt>charset</tt> parameter of the <tt>Content-Type</tt> header.
This is equivalent of calling
<tt>msg->setparam("charset", <i>charset</i>)</tt>.
</man_description>
<man_see>
MIME.Message->setparam
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setdata title="Replace body data">
<man_syntax>
void setdata(string <i>data</i>);
</man_syntax>
<man_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
<link to=MIME.Message.type>type</link> and <link to=MIME.Message.subtype>subtype</link> attributes.
Do not use this method unless you know what you are doing.
</man_description>
<man_see>
MIME.Message->getdata
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setdisp_param title="Set Content-Disposition parameters">
<man_syntax>
void setdisp_param(string <i>param</i>, string <i>value</i>);
</man_syntax>
<man_description>
Set or modify the named parameter of the <tt>Content-Disposition</tt> header.
A common parameters is e.g. <tt>filename</tt>. It is not allowed to modify
the <tt>Content-Disposition</tt> header directly, please use this
function instead.
</man_description>
<man_see>
MIME.Message->setparam, MIME.Message->get_filename
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setencoding title="Set transfer encoding for message body">
<man_syntax>
void setencoding(string <i>encoding</i>);
</man_syntax>
<man_description>
Select a new transfer encoding for this message. The
<tt>Content-Transfer-Encoding</tt> header will be modified accordingly,
and subsequent calls to <tt>getencoded</tt> will produce data encoded using
the new encoding. See <link to=MIME.encode>encode</link> for a list of valid
encodings.
</man_description>
<man_see>
MIME.Message->getencoded
</man_see>
</method>
<hr newpage>
<method name=MIME.Message->setparam title="Set Content-Type parameters">
<man_syntax>
void setparam(string <i>param</i>, string <i>value</i>);
</man_syntax>
<man_description>
Set or modify the named parameter of the <tt>Content-Type</tt> header.
Common parameters include <tt>charset</tt> for text messages, and
<tt>boundary</tt> for multipart messages. It is not allowed to modify
the <tt>Content-Type</tt> header directly, please use this function instead.
</man_description>
<man_see>
MIME.Message->setcharset, MIME.Message->setboundary,
MIME.Message->setdisp_param
</man_see>
</method>
<hr newpage>
</section>
</class>
</section>
</section>
</module>
<section title="Simulate">
<module name=Simulate title="Compatibility functions">
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.
<p>
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:
<hr newpage>
<function name=Simulate.member_array title="find first occurrence of a value in an array">
<man_syntax>
int member_array(mixed <I>item</I>, array <I>arr</I>);
</man_syntax>
<man_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
<tt>search(<i>arr</i>, <i>item</i>)</tt>.
</man_description>
</function>
<hr newpage>
<function name=Simulate.previous_object title="return the calling object">
<man_syntax>
object previous_object();
</man_syntax>
<man_description>
Returns an object pointer to the object that called current function,
if any.
</man_description>
<man_see>
backtrace
</man_see>
</function>
<hr newpage>
<function name=Simulate.this_function title="return a function pointer to the current function">
<man_syntax>
function this_function();
</man_syntax>
<man_description>
Returns a function pointer to the current function, useful for
making recursive lambda-functions.
</man_description>
<man_see>
backtrace
</man_see>
</function>
<hr newpage>
<function name=Simulate.get_function title="fetch a function from an object">
<man_syntax>
function get_function(object <I>o</I>, string <I>name</I>);
</man_syntax>
<man_description>
Defined as: return o[name];
</man_description>
</function>
<hr newpage>
<function name=Simulate.map_regexp title="filter an array through a regexp">
<man_syntax>
array(string) map_regexp(array(string) <I>arr</I>, string <I>reg</I>);
</man_syntax>
<man_description>
Returns those strings in arr that matches the regexp in reg.
</man_description>
<man_see>
Regexp
</man_see>
</function>
<hr newpage>
<constant name=Simulate.PI title="pi">
<man_syntax>
PI;
</man_syntax>
<man_description>
This is not a function, it is a constant roughly equal to the mathematical
constant Pi.
</man_description>
</constant>
<hr newpage>
<function name=Simulate.all_efuns title="return all 'efuns'">
<man_syntax>
mapping all_efuns();
</man_syntax>
<man_description>
This function is the same as all_constants.
</man_description>
<man_see>
all_constants
</man_see>
</function>
<hr newpage>
<function name=Simulate.explode title="explode a string on a delimeter">
<man_syntax>
string explode(string <I>s</I>, string <I>delimiter</I>);
</man_syntax>
<man_description>
This function is really the same as the division operator.
It simly divides the string <i>s</i> into an array by splitting
<i>s</i> at every occurance of <i>delimeter</i>.
</man_description>
<man_see>
Simulate.implode
</man_see>
</function>
<hr newpage>
<function name=Simulate.filter_array title="filter an array through a function">
<man_syntax>
array filter_array(array <I>arr</I>,function <I>fun</I>,mixed ... <I>args</I>);<br>
array filter_array(array(object) <I>arr</I>,string <I>fun</I>,mixed ... <I>args</I>);<br>
array filter_array(array(function) <I>arr</I>,-<I>1</I>,mixed ... <I>args</I>);<br>
</man_syntax>
<man_description>
Filter array is the same function as Array.filter.
</man_description>
<man_see>
Array.filter
</man_see>
</function>
<hr newpage>
<function name=Simulate.implode title="implode an array of strings">
<man_syntax>
string implode(array(string) <I>a</I>, string <I>delimiter</I>);
</man_syntax>
<man_description>
This function is the inverse of explode. It concatenates all the
strings in a with a delimiter in between each.
<p>This function is the same as multiplication.
</man_description>
<man_example>
> implode( ({ "foo","bar","gazonk"}), "-" );<br>
Result: foo-bar-gazonk<br>
> ({ "a","b","c" })*" and ";<br>
Result: a and b and c<br>
> <br>
</man_example>
<man_see>
Simulate.explode
</man_see>
</function>
<hr newpage>
<function name=Simulate.m_indices title="return all indices from a mapping">
<man_syntax>
array m_indices(mapping <I>m</I>);
</man_syntax>
<man_description>
This function is equal to indices.
</man_description>
<man_see>
indices
</man_see>
</function>
<hr newpage>
<function name=Simulate.m_sizeof title="return the size of a mapping">
<man_syntax>
int m_sizeof(mapping <I>m</I>);
</man_syntax>
<man_description>
This function is equal to sizeof.
</man_description>
<man_see>
sizeof
</man_see>
</function>
<hr newpage>
<function name=Simulate.m_values title="return all values from a mapping">
<man_syntax>
array m_values(mapping <I>m</I>);
</man_syntax>
<man_description>
This function is equal to values.
</man_description>
<man_see>
values
</man_see>
</function>
<hr newpage>
<function name=Simulate.map_array title="map an array over a function">
<man_syntax>
array map_array(array <I>arr</I>,function <I>fun</I>,mixed ... <I>args</I>);<br>
array map_array(array(object) <I>arr</I>,string <I>fun</I>,mixed ... <I>args</I>);<br>
array map_array(array(function) <I>arr</I>,-<I>1</I>,mixed ... <I>arg</I>);
</man_syntax>
<man_description>
This function is the same as Array.map.
</man_description>
<man_see>
Array.map
</man_see>
</function>
<hr newpage>
<function name=Simulate.strstr title="find a string inside a string">
<man_syntax>
int strstr(string <I>str1</I>,string <I>str2</I>);
</man_syntax>
<man_description>
Returns the position of <i>str2</i> in <i>str1</i>, if <i>str2</i> can't be found in <i>str1</i>
-1 is returned.
</man_description>
<man_see>
sscanf, Simulate.explode, search
</man_see>
</function>
<hr newpage>
<function name=Simulate.sum title="add values together">
<man_syntax>
int sum(int ... <I>i</I>);<br>
float sum(float ... <I>f</I>);<br>
string sum(string|float|int ... <I>p</I>);<br>
array sum(array ... <I>a</I>);<br>
mapping sum(mapping ... <I>m</I>);<br>
list sum(multiset ... <I>l</I>);<br>
</man_syntax>
<man_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.
</man_description>
</function>
<hr newpage>
<function name=Simulate.add_efun title="add an efun or constant">
<man_syntax>
void add_efun(string func_name, mixed function)<br>
void add_efun(string func_name)
</man_syntax>
<man_description>
This function is the same as add_constant.
</man_description>
<man_see>
Simulate.add_constant
</man_see>
</function>
<hr newpage>
<function name=Simulate.l_sizeof title="return the size of a multiset">
<man_syntax>
int l_sizeof(multiset <I>m</I>);
</man_syntax>
<man_description>
This function is equal to sizeof.
</man_description>
<man_see>
sizeof
</man_see>
</function>
<hr newpage>
<function name=Simulate.listp title="is the argument a list? (multiset)">
<man_syntax>
int listp(mixed <I>l</I>);
</man_syntax>
<man_description>
This function is the same as multisetp.
</man_description>
<man_see>
Simulate.multisetp
</man_see>
</function>
<hr newpage>
<function name=Simulate.mklist title="make a multiset">
<man_syntax>
multiset mklist(array <I>a</I>);
</man_syntax>
<man_description>
This function creates a multiset from an array.
</man_description>
<man_example>
<example languag=pike>
> mklist( ({1,2,3}) );
Result: (< /* 3 elements */
1,
2,
3
>)
</example>
</man_example>
<man_see>
aggregate_multiset
</man_see>
</function>
<hr newpage>
<function name=Simulate.aggregate_list title="aggregate a multiset">
<man_syntax>
multiset aggregate_list(mixed ... <I>args</I>);
</man_syntax>
<man_description>
This function is exactly the same as aggregate_multiset.
</man_description>
<man_see>
aggregate_multiset
</man_see>
</function>
<hr newpage>
<function name=Simulate.query_host_name title="return the name of the host we are running on">
<man_syntax>
string query_host_name();
</man_syntax>
<man_description>
This function returns the name of the machine the interpreter is
running on. This is the same thing that the command 'hostname'
prints.
</man_description>
</function>
<!-- Simulate.explode saknas -->
</module>
</section>
<hr newpage>
<!-- FIX ME priority_queue and heap should be placed inside Structs
<h2>Structs</h2>
<h2>Msql</h2>
<h2>Mysql</h2>
<h2>Sql</h2>
<h2>LR</h2>
-->
<include file=Mysql.wmml>
<include file=crypto.wmml>
<section title=Calendar>
<include file=Calendar.wmml>
</section>
<section title=Parser>
<include file=Parser.wmml>
</section title=Parser>
</chapter>
<chapter title="The preprocessor">
<anchor name=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.
<p>
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:
<hr noshade size=1>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#!<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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
<p>#!/usr/local/bin/pike
<p>
</dl>
<hr noshade size=1>
<anchor name=define>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#define<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
The simplest way to use define is to write
<p><dl><dt><dd>#define <identifier> <replacement string><br>
</dl>
<p>which will cause all subsequent occurrences of 'identifier' to be
replaced with the replacement string.
<p>Define also has the capability to use arguments, thus a line like
<p><dl><dt><dd>#define <identifier>(arg1, arg2) <replacement string><br>
</dl>
<p>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.
<p>
<dt><encaps>BUGS</encaps><dd>
Note that it is not a good idea to do something like this:
<p>#define foo bar // a comment
<p>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.
<dt><encaps>EXAMPLE</encaps><dd>
<example language=pike>
#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));
}
</example>
<p>
</dl>
</anchor>
<hr noshade size=1>
<anchor name=undef>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#undef<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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.
<p>
<dt><encaps>EXAMPLES</encaps><dd>
<tt>#define foo bar<br>
#undef foo<br>
#define foo(bar) gazonk bar<br>
#undef foo<br>
<br>
</tt>
<p>
</dl>
</anchor>
<hr noshade size=1>
<anchor name=if>
<anchor name=elseif>
<anchor name=else>
<anchor name=endif>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#if<br>
#elif<br>
#elseif<br>
#else<br>
#endif<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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.
<p>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.
<p>
Also, two special functions can be used, <tt>defined()</tt> and <tt>constant()</tt>.
<tt>defined(<i>identifier</i>)</tt> expands to 1 if <i>identifier</i> is defined and
0 otherwise. <tt>constant(<i>identifier</i>)</tt> expands to 1 if <i>identifier</i> is
an predefined constant (with add_constant), 0 otherwise.
<p>
<dt><encaps>EXAMPLES</encaps><dd>
<tt>#if 1<br>
<dl><dt><dd>write("foo");<br>
</dl>#else<br>
<dl><dt><dd>write("bar");<br>
</dl>#endif<br>
<p>#if defined(FOO)<br>
<dl><dt><dd>write(FOO);<br>
</dl>#elif defined(BAR)<br>
<dl><dt><dd>write(BAR);<br>
</dl>#else<br>
<dl><dt><dd>write("default");<br>
</dl>#endif<br>
<p>#if !constant(write_file)<br>
inherit "simulate.pike"<br>
#endif<br>
<br>
</tt>
<p>
</dl>
</anchor>
</anchor>
</anchor>
</anchor>
<hr noshade size=1>
<anchor name=error>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#error<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
This directive causes a compiler error, it can be used to notify
the user that certain functions are missing and similar things.
<p>
<dt><encaps>EXAMPLES</encaps><dd>
<tt>#if !constant(write_file)<br>
#error write_file function is missing<br>
#endif<br>
<br>
</tt>
<p>
</dl>
</anchor>
<hr noshade size=1>
<anchor name=include>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#include<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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.
<p>
<dt><encaps>EXAMPLES</encaps><dd>
<tt>#include "foo.h"<br>
<br>
</tt>
<p>
</dl>
</anchor>
<hr noshade size=1>
<anchor name=line>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#line<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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.
<p>This can also be used when generating Pike from something else, to
tell the compiler where the code originally originated from.
<p>
<dt><encaps>EXAMPLES</encaps><dd>
<tt>#line 4 "foo.cf" /* The next line was generated from 4 in foo.cf */<br>
<br>
</tt>
<p>
</dl>
</anchor>
<hr noshade size=1>
<anchor name=pragma>
<dl>
<dt><encaps>DIRECTIVE</encaps><dd>
<tt>#pragma<br>
</tt>
<p>
<dt><encaps>DESCRIPTION</encaps><dd>
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.
<p>
</dl>
</anchor>
</anchor>
</chapter>
<chapter title="All the builtin functions" name=functions>
This chapter is a reference for all the builtin functions in Pike.
They are listed in alphabetical order.
<HR NEWPAGE>
<function name=_disable_threads title="temporarily disable threads" fullpath>
<man_syntax>
object _disable_threads();
</man_syntax>
<man_description>
This function first posts a notice to all threads that it is time to stop.
It then waits until all threads actually *have* stopped, and then then
returns an object. All other threads will be blocked from running until
that object has been freed/destroyed. This function can completely block
Pike if used incorrectly. Use with extreme caution.
</man_description>
</function>
<HR NEWPAGE>
<function name=_exit title="Really exit" fullpath>
<man_syntax>
void _exit(int <i>returncode</I>);
</man_syntax>
<man_description>
This function does the same as <tt>exit</tt>, but doesn't bother to clean
up the Pike interpreter before exiting. This means that no destructors
will be called, caches will not be flushed, file locks might not be released,
and databases might not be closed properly. Use with extreme caution.
</man_description>
<man_see>
exit
</man_see>
</function>
<HR NEWPAGE>
<function name=_locate_references title="locate where an object is referenced from">
<man_syntax>
mapping(string:int) _locate_references(string|array|mapping|multiset|function|object|program <i>o</i>);
</man_syntax>
<man_description>
This function is mostly intended for debugging. It will search through
all data structures in Pike looking for <i>o</i> and print the
locations on stderr. <i>o</i> can be anything but <tt>int</tt> or
<tt>float</tt>.
</man_description>
</function>
<HR NEWPAGE>
<function name=_memory_usage title="check memory usage">
<man_syntax>
mapping(string:int) _memory_usage();
</man_syntax>
<man_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.
</man_description>
<man_see>
_verify_internals
</man_see>
</function>
<HR NEWPAGE>
<function name=_next title="find the next object/array/whatever">
<man_syntax>
mixed _next(mixed <I>p</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
next_object, _prev
</man_see>
</function>
<HR NEWPAGE>
<function name=_prev title="find the previous object/array/whatever">
<man_syntax>
mixed _next(mixed <I>p</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
_next
</man_see>
</function>
<HR NEWPAGE>
<function name=_refs title="find out how many references a pointer type value has">
<man_syntax>
int _refs(string|array|mapping|multiset|function|object|program <I>o</I>);
</man_syntax>
<man_description>
This function checks how many references the value <i>o</i> 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.
</man_description>
<man_see>
_next, _prev
</man_see>
</function>
<HR NEWPAGE>
<function name=_verify_internals title="check Pike internals">
<man_syntax>
void _verify_internals();
</man_syntax>
<man_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.
</man_description>
</function>
<HR NEWPAGE>
<function name=acos title="trigonometrical inverse cosine">
<man_syntax>
float acos(float <I>f</I>);
</man_syntax>
<man_description>
Return the arcus cosine value for <i>f</i>.
The result will be in radians.
</man_description>
<man_see>
cos, asin
</man_see>
</function>
<HR NEWPAGE>
<function name=add_constant title="add new predefined functions or constants">
<man_syntax>
void add_constant(string <I>name</I>, mixed <I>value</I>);<br>
void add_constant(string <I>name</I>);
</man_syntax>
<man_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.
<p>
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.
</man_description>
<man_example>
add_constant("true",1);<br>
add_constant("false",0);<br>
add_constant("PI",4.0);<br>
add_constant("sqr",lambda(mixed x) { return x * x; });<br>
add_constant("add_constant");<br>
</man_example>
<man_see>
all_constants
</man_see>
</function>
<HR NEWPAGE>
<function name=add_include_path title="add a directory to search for include files">
<man_syntax>
void add_include_path(string <I>path</I>);
</man_syntax>
<man_description>
This function adds another directory to the search for include files.
This is the same as the command line option <tt>-I</tt>. Note that
the added directory will only be searched when using < > to
quote the included file.
</man_description>
<man_see>
remove_include_path, #include
</man_see>
</function>
<HR NEWPAGE>
<function name=add_module_path title="add a directory to search for modules">
<man_syntax>
void add_module_path(string <I>path</I>);
</man_syntax>
<man_description>
This function adds another directory to the search for modules.
This is the same as the command line option <tt>-M</tt>. For more
information about modules, see <ref to=modules>.
</man_description>
<man_see>
remove_module_path
</man_see>
</function>
<HR NEWPAGE>
<function name=add_program_path title="add a directory to search for modules">
<man_syntax>
void add_program_path(string <I>path</I>);
</man_syntax>
<man_description>
This function adds another directory to the search for programs.
This is the same as the command line option <tt>-P</tt>. For more
information about programs, see <ref to=programs>.
</man_description>
<man_see>
remove_program_path
</man_see>
</function>
<HR NEWPAGE>
<function name=aggregate title="construct an array">
<man_syntax>
array aggregate(mixed ... <I>elems</I>);<br>
({ elem1, elem2, ... });
</man_syntax>
<man_description>
Construct an array with the arguments as indices. This function
could be written in Pike as:
<p>array aggregate(mixed ... elems) { return elems; }
</man_description>
<man_note>
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 array(int) a=allocate(10); will do.
</man_note>
<man_see>
sizeof, arrayp, allocate
</man_see>
</function>
<HR NEWPAGE>
<function name=aggregate_mapping title="construct a mapping">
<man_syntax>
mapping aggregate_mapping(mixed ... <I>elems</I>);<br>
([ key1:val1, key2:val2, ... ]);
</man_syntax>
<man_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.
</man_description>
<man_see>
sizeof, mappingp, mkmapping
</man_see>
</function>
<HR NEWPAGE>
<function name=aggregate_multiset title="construct a multiset">
<man_syntax>
multiset aggregate_multiset(mixed ... <I>elems</I>);<br>
(< elem1, elem2, ... >);
</man_syntax>
<man_description>
Construct a multiset with the arguments as indices. This function
could be written in Pike as:
<p>multiset aggregate(mixed ... elems) { return mkmultiset(elems); }
<p>The only problem is that mkmultiset is implemented using
aggregate_multiset...
</man_description>
<man_see>
sizeof, multisetp, mkmultiset
</man_see>
</function>
<HR NEWPAGE>
<function name=alarm title="set an alarm clock for delivery of a signal">
<man_syntax>
int alarm(int <I>seconds</I>);
</man_syntax>
<man_description>
<tt>alarm</tt> arranges for a SIGALRM signal to be delivered to the
process <!-- hedda: Menar du process eller thread? Lite mer förklaring, tack. hubbe: det st}r process, vad tror du jag menar??? -->in <i>seconds</i> seconds.
<p>
If <i>seconds</i> is zero, no new alarm is scheduled.
<p>
In any event any previously set alarm is canceled.
<p>
<dt><encaps>RETURN VALUE</encaps><dd>
<tt>alarm</tt> 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.
</man_description>
<man_see>
signal
</man_see>
</function>
<HR NEWPAGE>
<function name=all_constants title="return all predefined constants">
<man_syntax>
mapping (string:mixed) <I>all_constant</I>();
</man_syntax>
<man_description>
Returns a mapping containing all constants, indexed on the names of the
constant, and with the value of the efun as argument.
</man_description>
<man_see>
add_constant
</man_see>
</function>
<HR NEWPAGE>
<function name=allocate title="allocate an array">
<man_syntax>
array allocate(int <I>size</I>);
</man_syntax>
<man_description>
Allocate an array of size elements and initialize them to zero.
</man_description>
<man_example>
array a=allocate(17);
</man_example>
<man_note>
Arrays are dynamically allocated there is no need to declare them
like <tt>int a[10]=allocate(10);</tt> (and it is not possible either) like
in C, just <tt>array(int) a=allocate(10);</tt> will do.
</man_note>
<man_see>
sizeof, aggregate, arrayp
</man_see>
</function>
<HR NEWPAGE>
<function name=arrayp title="is the argument an array?">
<man_syntax>
int arrayp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is an array, zero otherwise.
</man_description>
<man_see>
allocate, intp, programp, floatp, stringp, objectp, mappingp, multisetp,
functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=array_sscanf title="sscanf to an array">
<man_syntax>
array array_sscanf(string <i>data</i>, string <i>format</i>);
</man_syntax>
<man_description>
This function works just like <tt>sscanf</tt>, but returns the matched
results in an array instead of assigning them to lvalues. This is often
useful for user-defined sscanf strings.
</man_description>
<man_see>
sscanf, `/
</man_see>
</function>
<HR NEWPAGE>
<function name=asin title="trigonometrical inverse sine">
<man_syntax>
float asin(float <I>f</I>);
</man_syntax>
<man_description>
Returns the arcus sinus value for <i>f</i>.
</man_description>
<man_see>
sin, acos
</man_see>
</function>
<HR NEWPAGE>
<function name=atan title="trigonometrical inverse tangent">
<man_syntax>
float atan(float <I>f</I>);
</man_syntax>
<man_description>
Returns the arcus tangent value for <i>f</i>.
</man_description>
<man_see>
tan, asin, acos
</man_see>
</function>
<HR NEWPAGE>
<function name=basename title="get the base of a filename">
<man_syntax>
string basename(string <i>filename</i>);
</man_syntax>
<man_description>
This function returns the base of a filename, for instance the base of
<tt>"/home/hubbe/bin/pike"</tt> would be <tt>"pike"</tt>.
</man_description>
<man_see>
dirname, explode_path
</man_see>
</function>
<HR NEWPAGE>
<function name=backtrace title="get a description of the call stack">
<man_syntax>
array(array) backtrace();
</man_syntax>
<man_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:
<p>({<br>
<dl><dt><dd><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> file, </td><td> /* a string with the filename if known, else zero */ </td></tr>
<tr valign=top><td> line, </td><td> /* an integer containing the line if known, else zero */ </td></tr>
<tr valign=top><td> function, </td><td> /* The function pointer to the called function */ </td></tr>
<tr valign=top><td> mixed|void ..., </td><td> /* The arguments the function was called with */ </td></tr>
</table>
</dl>})<br>
<p>The current call frame will be last in the array, and the one above
that the last but one and so on.
</man_description>
<man_see>
catch, throw
</man_see>
</function>
<HR NEWPAGE>
<function name=cpp title="run the preprocessor on a string">
<man_syntax>
string cpp ( string <i>source</i>, string <i>filename</i>);
</man_syntax>
<man_description>
This function runs the Pike preprocessor on a string. The second argument
<i>filename</i> will be used for inserting <tt>#line</tt> statements into
the result.
</man_description>
<man_see>
compile, compile_string, compile_file
</man_see>
</function>
<HR NEWPAGE>
<function name=call_function title="call a function with arguments">
<man_syntax>
mixed call_function(function <I>fun</I>,mixed ... <I>args</I>);<br>
mixed fun ( mixed ... <I>args</I> );
</man_syntax>
<man_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.
</man_description>
<man_see>
backtrace, Simulate.get_function
</man_see>
</function>
<HR NEWPAGE>
<function name=call_out title="make a delayed call to a function">
<man_syntax>
mixed call_out(function <I>f</I>, int <I>delay</I>, mixed ... <I>args</I>);
</man_syntax>
<man_description>
Call_out places a call to the function <i>f</i> with the argument <i>args</i>
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.
</man_description>
<man_see>
remove_call_out, find_call_out, call_out_info
</man_see>
</function>
<HR NEWPAGE>
<function name=call_out_info title="get info about all call outs">
<man_syntax>
array(array) call_out_info();
</man_syntax>
<man_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:
<p>({<br>
<dl><dt><dd><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> time_left, </td><td> /* an int */ </td></tr>
<tr valign=top><td> caller, </td><td> /* the object that made the call out */ </td></tr>
<tr valign=top><td> function, </td><td> /* the function to be called */ </td></tr>
<tr valign=top><td> arg1, </td><td> /* the first argument, if any */ </td></tr>
<tr valign=top><td> arg2, </td><td> /* the second argument, if any */ </td></tr>
<tr valign=top><td> ... </td><td> /* and so on... */ </td></tr>
</table>
</dl>})<br>
</man_description>
<man_see>
call_out, find_call_out, remove_call_out
</man_see>
</function>
<HR NEWPAGE>
<function name=_do_call_outs title="do all pending call_outs">
<man_syntax>
void _do_call_out();
</man_syntax>
<man_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.
<p>
As a side-effect, this function sets the value returned by
<tt>time(1)</tt> to the current time.
</man_description>
<man_see>
call_out, find_call_out, remove_call_out
</man_see>
</function>
<HR NEWPAGE>
<function name=catch>
<man_syntax>
catch { commands };<br>
catch ( expression );
</man_syntax>
<man_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 })
</man_description>
<man_see>
throw
</man_see>
</function>
<HR NEWPAGE>
<function name=cd title="change directory">
<man_syntax>
int cd(string <I>s</I>);
</man_syntax>
<man_description>
Change the current directory for the whole Pike process, return
1 for success, 0 otherwise.
</man_description>
<man_see>
getcwd
</man_see>
</function>
<HR NEWPAGE>
<function name=ceil title="truncate a number upward">
<man_syntax>
float ceil(float <I>f</I>);
</man_syntax>
<man_description>
Return the closest integer value higher or equal to <i>f</i>.
</man_description>
<man_note>
<tt>ceil()</tt> does <b>not</b> return an int, merely an integer value stored in a float.
</man_note>
<man_see>
floor
</man_see>
</function>
<HR NEWPAGE>
<function name=clone title="clone an object from a program">
<man_syntax>
object clone(program <I>p</I>,mixed ... <I>args</I>);
</man_syntax>
<man_description>
<tt>clone()</tt> creates an object from the program <i>p</i>. Or in C++ terms:
It creates an instance of the class <i>p</i>. This clone will first have
all global variables initialized, and then <tt>create()</tt> will be called
with <i>args</i> as arguments.
</man_description>
<man_see>
new, destruct, compile_string, compile_file
</man_see>
</function>
<HR NEWPAGE>
<function name=new title="clone an object from a program">
<man_syntax>
object new(program <I>p</I>,mixed ... <I>args</I>);
</man_syntax>
<man_description>
<tt>new()</tt> creates an object from the program <i>p</i>. Or in C++ terms:
It creates an instance of the class <i>p</i>. This clone will first have
all global variables initialized, and then <tt>create()</tt> will be called
with <i>args</i> as arguments.
</man_description>
<man_see>
clone, destruct, compile_string, compile_file
</man_see>
</function>
<HR NEWPAGE>
<function name=column title="extract a column">
<man_syntax>
array column(array data,mixed index)
</man_syntax>
<man_description>
This function is exactly equivalent to:
<example language=pike>
map_array(data, lambda(mixed x,mixed y) { return x[y]; }, index)
</example>
Except of course it is a lot shorter and faster.
That is, it indices every index in the array data on the value of
the argument index and returns an array with the results.
</man_description>
<man_example>
<pre>
> column( ({ ({1,2}), ({3,4}), ({5,6}) }), 1)
Result: ({2, 4, 6})
</pre>
</man_example>
<man_see>
rows
</man_see>
</function>
<HR NEWPAGE>
<function name=combine_path title="concatenate paths">
<man_syntax>
string combine_path(string <I>absolute</I>, string <I>relative</I>);
</man_syntax>
<man_description>
Concatenate a relative path to an absolute path and remove any
"//", "/.." or "/." to produce a straightforward absolute path
as a result.
</man_description>
<man_example>
> combine_path("/foo/bar/","..");<br>
Result: /foo<br>
> combine_path("/foo/bar/","../apa.c");<br>
Result: /foo/apa.c<br>
> combine_path("/foo/bar","./sune.c");<br>
Result: /foo/bar/sune.c<br>
</man_example>
<man_see>
getcwd
</man_see>
</function>
<HR NEWPAGE>
<function name=compile title="compile a string to a program">
<man_syntax>
program compile(string <I>program</I>);
</man_syntax>
<man_description>
<tt>compile</tt> takes a piece of Pike code as a string and
compiles it into a clonable program. Note that <i>prog</i> must contain
the complete source for a program. You can not compile a single expression
or statement. Also note that <tt>compile</tt> does not preprocess the
program. To preprocess the program you can use <tt>compile_string</tt> or
call the preprocessor manually by calling <tt>cpp</tt>.
</man_description>
<man_see>
clone, compile_string, compile_file, cpp
</man_see>
</function>
<HR NEWPAGE>
<function name=compile_file title="compile a file to a program">
<man_syntax>
program compile_file(string <I>filename</I>);
</man_syntax>
<man_description>
This function will compile the file <i>filename</i> to a Pike program that can
later be used for cloning. It is the same as doing
<tt>compile_string(Stdio.read_file(<i>filename</i>),<i>filename</i>)</tt>.
</man_description>
<man_see>
clone, compile_string
</man_see>
</function>
<HR NEWPAGE>
<function name=compile_string title="compile a string to a program">
<man_syntax>
program compile_string(string <I>prog</I>, string <I>name</I>);
</man_syntax>
<man_description>
Equal to <tt>compile(cpp(<i>prog</i>, <i>name</i>));</tt>
</man_description>
<man_see>
compile_string, clone
</man_see>
</function>
<HR NEWPAGE>
<function name=copy_value title="copy a value recursively">
<man_syntax>
mixed copy_value(mixed <I>value</I>);
</man_syntax>
<man_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 ==)
</man_description>
<man_see>
equal
</man_see>
</function>
<HR NEWPAGE>
<function name=cos title="trigonometrical cosine">
<man_syntax>
float cos(float <I>f</I>);
</man_syntax>
<man_description>
Returns the cosine value for <i>f</i>.
</man_description>
<man_see>
acos, sin
</man_see>
</function>
<HR NEWPAGE>
<function name=crypt title="crypt a password">
<man_syntax>
string crypt(string <I>password</I>);<br>
int crypt(string <I>typed_password</I>, string <I>crypted_password</I>);
</man_syntax>
<man_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.
</man_description>
<man_example>
To crypt a password use:<br>
<dl><dt><dd>crypted_password = crypt(typed_password);<br>
</dl>To see if the same password was used again use:<br>
<dl><dt><dd>matched = crypt(typed_password, crypted_password);<br>
</dl>
</man_example>
</function>
<HR NEWPAGE>
<function name=ctime title="convert time int to readable date string">
<man_syntax>
string ctime(int <I>current_time</I>);
</man_syntax>
<man_description>
Convert the output from a previous call to time() into a readable
string containing the current year, month, day and time.
</man_description>
<man_example>
> ctime(time());<br>
Result: Wed Jan 14 03:36:08 1970<br>
</man_example>
<man_see>
time, localtime, mktime, gmtime
</man_see>
</function>
<HR NEWPAGE>
<function name=decode_value title="code a value into a string">
<man_syntax>
mixed decode_value(string <I>coded_value</I>);
</man_syntax>
<man_description>
This function takes a string created with encode_value() and converts
it back to the value that was coded.
</man_description>
<man_see>
encode_value
</man_see>
</function>
<HR NEWPAGE>
<function name=describe_backtrace title="make a backtrace readable">
<man_syntax>
string describe_backtrace(array(array) <I>backtrace</I>);
</man_syntax>
<man_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()
</man_description>
<man_see>
backtrace
</man_see>
</function>
<HR NEWPAGE>
<function name=destruct title="destruct an object">
<man_syntax>
void destruct(object <I>o</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
clone
</man_see>
</function>
<HR NEWPAGE>
<function name=dirname title="find the directory part of a path">
<man_syntax>
string dirname(string <i>path</i>);
</man_syntax>
<man_description>
This function returns the directory part of a path. For example, the
directory part of <tt>"/home/hubbe/bin/pike"</tt> would be <tt>"/home/hubbe/bin"</tt>.
</man_description>
<man_see>
basename, explode_path
</man_see>
</function>
<HR NEWPAGE>
<function name=encode_value title="code a value into a string">
<man_syntax>
string encode_value(mixed <I>value</I>);
</man_syntax>
<man_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.
<p>
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.
</man_description>
<man_see>
decode_value, sprintf
</man_see>
</function>
<HR NEWPAGE>
<function name=equal title="check if two values are equal or not">
<man_syntax>
int equal(mixed <I>a</I>, mixed <I>b</I>);
</man_syntax>
<man_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.
</man_description>
<man_example>
> ({ 1 }) == ({ 1 });<br>
Result: 0<br>
> equal( ({ 1 }), ({ 1 }) );<br>
Result: 1<br>
> <br>
</man_example>
<man_see>
copy_value
</man_see>
</function>
<HR NEWPAGE>
<function name=errno title="return system error number">
<man_syntax>
int errno();
</man_syntax>
<man_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.
</man_description>
<man_see>
Stdio.File->errno, strerror
</man_see>
</function>
<HR NEWPAGE>
<function name=exece>
<man_syntax>
int exece(string <I>file</I>, array(string) <I>args</I>);<br>
int exece(string <I>file</I>, array(string) <I>args</I>, mapping(string:string) <I>env</I>);
</man_syntax>
<man_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.
</man_description>
<man_note>
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.
</man_note>
<man_example>
exece("/bin/ls", ({"-l"}));<br>
exece("/bin/sh", ({"-c", "echo $HOME"}), (["HOME":"/not/home"]));<br>
</man_example>
<man_see>fork, Stdio.File->pipe</man_see>
</function>
<HR NEWPAGE>
<function name=explode_path fullpath title="exit Pike interpreter">
<man_syntax>
array(string) explode_path(string <I>path</I>);
</man_syntax>
<man_description>
This function divides a path into its components. This might seem like
it could be done by dividing the string on <tt>"/"</tt>, but that would
not work on other operating systems.
</man_description>
<man_example>
> explode_path("/home/hubbe/bin/pike");
Result: ({ "home", "hubbe", "bin", "pike" })
</man_example>
</function>
<HR NEWPAGE>
<function name=exit fullpath title="exit Pike interpreter">
<man_syntax>
void exit(int <I>returncode</I>);
</man_syntax>
<man_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.
</man_description>
</function>
<HR NEWPAGE>
<function name=exp title="natural exponent">
<man_syntax>
float exp(float <I>f</I>);
</man_syntax>
<man_description>
Return the natural exponent of <i>f</i>.
</man_description>
<man_see>
pow, log
</man_see>
</function>
<HR NEWPAGE>
<function name=file_stat title="stat a file" fullpath>
<man_syntax>
array(int) file_stat(string <I>file</I>);<br>
array(int) file_stat(string <I>file</I>, <I>1</I>);<br>
array(int) file->stat();
</man_syntax>
<man_description>
file_stat returns an array of integers describing some properties<br>
about the file. Currently file_stat returns 7 entries:<br>
<data_description type=array(int)>
<elem value=mode>file mode, protection bits etc. etc. </elem>
<elem value=size>file size for regular files, <br>
-2 for dirs,<br>
-3 for links,<br>
-4 for otherwise </elem>
<elem value=atime>last access time </elem>
<elem value=mtime>last modify time </elem>
<elem value=ctime>last status time change </elem>
<elem value=uid>The user who owns this file</elem>
<elem value=gid>The group this file belongs to</elem>
</data_description>
If you give 1 as a second argument, file_stat does not follow links.<br>
You can never get -3 as size if you don't give a second argument.<br>
<p>If there is no such file or directory, zero is returned.
</man_description>
<man_see>get_dir</man_see>
</function>
<HR NEWPAGE>
<function name=file_truncate title="truncate a file" fullpath>
<man_syntax>
int file_truncate(string <I>file</I>,int <I>length</I>);<br>
</man_syntax>
<man_description>
Truncates a file to that length.
Returns 1 if ok, 0 if failed.
</man_description>
</function>
<HR NEWPAGE>
<function name=find_call_out title="find a call out in the queue">
<man_syntax>
int find_call_out(function <I>f</I>);<br>
int find_call_out(mixed <I>id</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
call_out, remove_call_out, call_out_info
</man_see>
</function>
<HR NEWPAGE>
<function name=floatp title="is the argument a float?">
<man_syntax>
int floatp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a float, zero otherwise.
</man_description>
<man_see>
intp, programp, arrayp, stringp, objectp, mappingp, multisetp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=floor title="truncate a number downward">
<man_syntax>
float floor(float <I>f</I>);
</man_syntax>
<man_description>
Return the closest integer value lower or equal to <i>f</i>.
</man_description>
<man_note>
floor() does <b>not</b> return an int, merely an integer value stored in a float.
</man_note>
<man_see>
ceil
</man_see>
</function>
<HR NEWPAGE>
<function name=fork title="fork the process in two">
<man_syntax>
int fork();
</man_syntax>
<man_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.
</man_description>
<man_note>
This function cause endless bugs if used without proper care.
<p>
Some operating systems have problems if this function is used together
with threads.
</man_note>
<man_see>
Process.exec, Stdio.File->pipe
</man_see>
</function>
<HR NEWPAGE>
<function name=function_name title="return the name of a function, if known">
<man_syntax>
string function_name(function <I>f</I>);
</man_syntax>
<man_description>
This function returns the name of the function <i>f</i>. If the function is
a pre-defined function in the driver, zero will be returned.
</man_description>
<man_see>
function_object, Simulate.get_function
</man_see>
</function>
<HR NEWPAGE>
<function name=function_object title="return what object a function is in">
<man_syntax>
object function_object(function <I>f</I>);
</man_syntax>
<man_description>
Function_object will return the object the function <i>f</i> is in. If the
function is a predefined function from the driver, zero will be
returned.
</man_description>
<man_see>
function_name, Simulate.get_function
</man_see>
</function>
<HR NEWPAGE>
<function name=functionp title="is the argument a function?">
<man_syntax>
int functionp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a function, zero otherwise.
</man_description>
<man_see>
intp, programp, arrayp, stringp, objectp, mappingp, multisetp, floatp
</man_see>
</function>
<HR NEWPAGE>
<function name=gc title="do garbage collection">
<man_syntax>
int gc();
</man_syntax>
<man_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.)
</man_description>
</function>
<HR NEWPAGE>
<function name=get_dir title="read a directory">
<man_syntax>
array(string) get_dir(string <I>dirname</I>);
</man_syntax>
<man_description>
Returns an array of all filenames in the directory <i>dirname</i>, or zero if
no such directory exists.
</man_description>
<man_see>
mkdir, cd
</man_see>
</function>
<HR NEWPAGE>
<function name=get_profiling_info title="get profiling information">
<man_syntax>
array(int|mapping(string:array(int))) get_profiling_info(program <I>prog</I>);
</man_syntax>
<man_description>
Returns an array with two elements, the first of which is the number of
times the program <tt>prog</tt> has been cloned.<br>
The second element is a <tt>mapping(string:array(int))</tt> from function
name to an <tt>array(int)</tt> with two elements. The first element of
this array is the number of times the function has been called, while
the second element is the total time (in milliseconds) spent in the
function so far.
</man_description>
<man_note>
This function is only available if Pike was compiled with the option
'--with-profiling'.
</man_note>
<man_see>
</man_see>
</function>
<HR NEWPAGE>
<function name=getcwd title="return current working directory">
<man_syntax>
string getcwd();
</man_syntax>
<man_description>
getcwd returns the current working directory.
</man_description>
<man_see>
cd
</man_see>
</function>
<HR NEWPAGE>
<function name=getenv title="get an environment variable">
<man_syntax>
string getenv(string <I>varname</I>);
</man_syntax>
<man_description>
Returns the value of the environment variable with the name <i>varname</i>,
if no such environment variable exists, zero is returned.
</man_description>
<man_note>
This function is provided by master.pike.
</man_note>
</function>
<HR NEWPAGE>
<function name=getpid title="get the process id of this process">
<man_syntax>
int getpid();
</man_syntax>
<man_description>
This returns the pid of this process. Useful for sending
signals to yourself.
</man_description>
<man_see>
kill, fork, signal
</man_see>
</function>
<HR NEWPAGE>
<function name=glob title="match strings against globs" fullpath>
<man_syntax>
int glob(string <I>glob</I>, string <I>str</I>);
or<br>
array(string) glob(string <I>glob</I>, array(string) <I>arr</I>);<br>
</man_syntax>
<man_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 <i>str</i> matches <i>glob</i>. When given an array as
second argument, an array containing all matching strings is returned.
</man_description>
<man_see>sscanf, Regexp</man_see>
</function>
<HR NEWPAGE>
<function name=gmtime title="break down time() into intelligible components">
<man_syntax>
mapping(string:int) gmtime(int <I>time</I>);
</man_syntax>
<man_description>
This function works like <tt>localtime</tt> but the result is
not adjusted for the local time zone.
</man_description>
<man_see>
localtime, time, ctime, mktime
</man_see>
</function>
<HR NEWPAGE>
<function name=hash title="hash a string">
<man_syntax>
int hash(string <I>s</I>);<br>
int hash(string <I>s</I>, int <I>max</I>);
</man_syntax>
<man_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.
</man_description>
</function>
<HR NEWPAGE>
<function name=indices title="return an array of all index possible for a value">
<man_syntax>
array indices(string|array|mapping|multiset|object <I>foo</I>);
</man_syntax>
<man_description>
<tt>indices</tt> returns an array of all values you can use as index when
indexing <i>foo</i>. 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.
</man_description>
<man_see>
values
</man_see>
</function>
<HR NEWPAGE>
<function name=is_absolute_path title="Is the given pathname relative or not?">
<man_syntax>
int is_absolute_path(string <I>path</I>);
</man_syntax>
<man_description>
Returns 1 if <i>path</i> is an absolute path, 0 otherwise.
</man_description>
<man_see>
</man_see>
</function>
<HR NEWPAGE>
<function name=intp title="is the argument an int?">
<man_syntax>
array intp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is an int, zero otherwise.
</man_description>
<man_see>
arrayp, programp, floatp, stringp, objectp, mappingp, multisetp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=kill title="send signal to other process">
<man_syntax>
int kill(int pid, int signal);
</man_syntax>
<man_description>
Kill sends a signal to another process. If something goes wrong
-1 is returned, 0 otherwise.
<p>Some signals and their supposed purpose:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> SIGHUP </td><td> Hang-up, sent to process when user logs out </td></tr>
<tr valign=top><td> SIGINT </td><td> Interrupt, normally sent by ctrl-c </td></tr>
<tr valign=top><td> SIGQUIT </td><td> Quit, sent by ctrl-\ </td></tr>
<tr valign=top><td> SIGILL </td><td> Illegal instruction </td></tr>
<tr valign=top><td> SIGTRAP </td><td> Trap, mostly used by debuggers </td></tr>
<tr valign=top><td> SIGABRT </td><td> Aborts process, can be caught, used by Pike whenever something goes seriously wrong. </td></tr>
<tr valign=top><td> SIGBUS </td><td> Bus error </td></tr>
<tr valign=top><td> SIGFPE </td><td> Floating point error (such as division by zero) </td></tr>
<tr valign=top><td> SIGKILL </td><td> Really kill a process, cannot be caught </td></tr>
<tr valign=top><td> SIGUSR1 </td><td> Signal reserved for whatever you want to use it for. </td></tr>
<tr valign=top><td> SIGSEGV </td><td> Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike. </td></tr>
<tr valign=top><td> SIGUSR2 </td><td> Signal reserved for whatever you want to use it for. </td></tr>
<tr valign=top><td> SIGALRM </td><td> Signal used for timer interrupts. </td></tr>
<tr valign=top><td> SIGTERM </td><td> Termination signal </td></tr>
<tr valign=top><td> SIGSTKFLT </td><td> Stack fault </td></tr>
<tr valign=top><td> SIGCHLD </td><td> Child process died </td></tr>
<tr valign=top><td> SIGCONT </td><td> Continue suspended </td></tr>
<tr valign=top><td> SIGSTOP </td><td> Stop process </td></tr>
<tr valign=top><td> SIGSTP </td><td> Suspend process </td></tr>
<tr valign=top><td> SIGTTIN </td><td> tty input for background process </td></tr>
<tr valign=top><td> SIGTTOU </td><td> tty output for background process </td></tr>
<tr valign=top><td> SIGXCPU </td><td> Out of CPU </td></tr>
<tr valign=top><td> SIGXFSZ </td><td> File size limit exceeded </td></tr>
<tr valign=top><td> SIGPROF </td><td> Profile trap </td></tr>
<tr valign=top><td> SIGWINCH </td><td> Window change signal </td></tr>
</table>
<p>Note that you have to use signame to translate the name of a signal
to its number.
</man_description>
<man_see>
signal, signum, signame, fork
</man_see>
</function>
<HR NEWPAGE>
<function name=load_module title="load a binary module">
<man_syntax>
int load_module(string <I>module_name</I>);
</man_syntax>
<man_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.
<p>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.
<p>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.
</man_description>
<man_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.
</man_bugs>
</function>
<HR NEWPAGE>
<function name=localtime title="break down time() into intelligible components">
<man_syntax>
mapping(string:int) localtime(int <I>time</I>);
</man_syntax>
<man_description>
Given a time represented as second since 1970, as returned by the
function time(), this function returns a mapping with the following
components:
<data_description type=mapping>
<elem type=int(0..59) name=sec >seconds over the minute </elem>
<elem type=int(0..59) name=min >minutes over the hour </elem>
<elem type=int(0..59) name=hour >what hour in the day </elem>
<elem type=int(1..31) name=mday >day of the month </elem>
<elem type=int(0..11) name=mon >what month </elem>
<elem type=int(0..) name=year >years since 1900 </elem>
<elem type=int(0..6) name=wday >day of week (0=Sunday) </elem>
<elem type=int(0..365) name=yday>day of year </elem>
<elem type=int(0..1) name=isdst>is daylight saving time </elem>
<elem type=int name=timezone>difference between local time and UTC </elem>
</data_description>
</man_description>
<man_note>
The 'timezone' might not be available on all platforms.
</man_note>
<man_see>
Calendar, gmtime, time, ctime, mktime
</man_see>
</function>
<HR NEWPAGE>
<function name=log title="natural logarithm">
<man_syntax>
float log(float <I>f</I>);
</man_syntax>
<man_description>
Return the natural logarithm of <i>f</i>.
</man_description>
<man_see>
pow, exp
</man_see>
</function>
<HR NEWPAGE>
<function name=lower_case title="convert a string to lower case">
<man_syntax>
string lower_case(string <I>s</I>);
</man_syntax>
<man_description>
Returns a string with all capital letters converted to lower case.
</man_description>
<man_see>
upper_case
</man_see>
</function>
<HR NEWPAGE>
<function name=m_delete title="remove an index from a mapping">
<man_syntax>
mapping m_delete(mapping <I>map</I>, mixed <I>index</I>);
</man_syntax>
<man_description>
Removes the entry with index <i>index</i> from mapping <i>map</i> destructively.
Returns the changed mapping. If the mapping does not have an
entry with index <i>index</i>, nothing is done.
Note that m_delete changes map destructively and only returns
the mapping for compatibility reasons.
</man_description>
<man_see>
mappingp
</man_see>
</function>
<HR NEWPAGE>
<function name=mappingp title="is the argument a mapping?">
<man_syntax>
int mappingp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a mapping, zero otherwise.
</man_description>
<man_see>
intp, programp, arrayp, stringp, objectp, multisetp, floatp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=master title="return the master object">
<man_syntax>
object master();
</man_syntax>
<man_description>
Master is added by the master object to make it easier to access it.
</man_description>
</function>
<HR NEWPAGE>
<function name=mkdir title="make directory">
<man_syntax>
int mkdir(string <I>dirname</I>);
</man_syntax>
<man_description>
Create a directory, return zero if it fails and nonzero if it successful.
</man_description>
<man_see>
rm, cd
</man_see>
</function>
<HR NEWPAGE>
<function name=mkmapping title="make a mapping from two arrays">
<man_syntax>
mapping mkmapping(array <I>ind</I>, array <I>val</I>);
</man_syntax>
<man_description>
Makes a mapping ind[x]:val[x], 0<=x<sizeof(ind).
<i>ind</i> and <i>val</i> must have the same size.
This is the inverse operation of <tt>indices</tt> and <tt>values</tt>.
</man_description>
<man_see>
indices, values
</man_see>
</function>
<HR NEWPAGE>
<function name=mkmultiset title="make a multiset">
<man_syntax>
multiset mkmultiset(array a);
</man_syntax>
<man_description>
This function creates a multiset from an array.
</man_description>
<man_example>
<example language=pike>
> mkmultiset( ({1,2,3}) );
Result: (< /* 3 elements */
1,
2,
3
>)
</example>
</man_example>
<man_see>
aggregate_multiset
</man_see>
</function>
<HR NEWPAGE>
<function name=mktime title="convert date and time to seconds">
<man_syntax>
int mktime(mapping tm)<br>
int mktime(int sec, int min, int hour, int mday, int mon, int year, int isdst, int tz)
</man_syntax>
<man_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:
<p>
<center>
<table>
<tr><td>year</td><td>The number of years since 1900</td></tr>
<tr><td>mon</td><td>The month</td></tr>
<tr><td>mday</td><td>The day of the month.</td></tr>
<tr><td>hour</td><td>The number of hours past midnight</td></tr>
<tr><td>min</td><td>The number of minutes after the hour</td></tr>
<tr><td>sec</td><td>The number of seconds after the minute</td></tr>
<tr><td>isdst</td><td>If this is 1, daylight savings time is assumed</td></tr>
<tr><td>tm</td><td>The timezone (-12 <= tz <= 12)</td></tr>
</table>
</center>
<p>
Or you can just send them all on one line as the second syntax suggests.
</man_description>
<man_see>
time, ctime, localtime, gmtime
</man_see>
</function>
<HR NEWPAGE>
<function name=multisetp title="is the argument a multiset?">
<man_syntax>
int multisetp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a multiset, zero otherwise.
</man_description>
<man_see>
intp, programp, arrayp, stringp, objectp, mappingp, floatp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=mv title="move a file (may handle directories as well)">
<man_syntax>
int mv(string <I>from</I>,string <I>to</I>);
</man_syntax>
<man_description>
Rename or move a file between directories. If the destination
file already exists, it will be overwritten. Returns 1 on success,
0 otherwise.
</man_description>
<man_see>
rm
</man_see>
</function>
<HR NEWPAGE>
<function name=next_object title="get next object">
<man_syntax>
object next_object(object <I>o</I>);<br>
object next_object();
</man_syntax>
<man_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.
</man_description>
<man_example>
<example language=pike>
/* This example calls shutting_down() in all cloned objects */
object o;
for(o=next_object();o;o=next_object(o))
o->shutting_down();<br>
</example>
</man_example>
<man_see>
clone, destruct
</man_see>
<man_note>
This function is not recommended to use.
</man_note>
</function>
<HR NEWPAGE>
<function name=object_program title="get the program associated with the object">
<man_syntax>
program object_program(object <I>o</I>);
</man_syntax>
<man_description>
This function returns the program from which <i>o</i> was cloned.
If <i>o</i> is not an object or has been destructed <i>o</i> zero is returned.
</man_description>
<man_see>
clone, new
</man_see>
</function>
<HR NEWPAGE>
<function name=objectp title="the argument an object?">
<man_syntax>
int objectp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is an object, zero otherwise.
</man_description>
<man_see>
intp, programp, floatp, stringp, arrayp, mappingp, multisetp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=pow title="raise a number to the power of another">
<man_syntax>
float pow(float <I>n</I>, float <I>x</I>);
</man_syntax>
<man_description>
Return <i>n</i> raised to the power of <i>x</i>.
</man_description>
<man_see>
exp, log
</man_see>
</function>
<HR NEWPAGE>
<function name=programp title="is the argument a program?">
<man_syntax>
int programp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a program, zero otherwise.
</man_description>
<man_see>
intp, multisetp, arrayp, stringp, objectp, mappingp, floatp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=putenv title="put environment variable">
<man_syntax>
void putenv(string <I>varname</I>, string <I>value</I>);
</man_syntax>
<man_description>
This function sets the environment variable <i>varname</i> to <i>value</i>.
</man_description>
<man_see>
getenv, exece
</man_see>
</function>
<HR NEWPAGE>
<function name=query_host_name title="return the name of the host we are running on">
<man_syntax>
string query_host_name();
</man_syntax>
<man_description>
This function returns the name of the machine the interpreter is
running on. This is the same thing that the command <tt>hostname</tt>
prints.
</man_description>
</function>
<HR NEWPAGE>
<function name=query_num_arg title="find out how many arguments were given">
<man_syntax>
int query_num_arg();
</man_syntax>
<man_description>
<tt>query_num_arg</tt> returns the number of arguments given when this
function was called. This is only useful for varargs functions.
</man_description>
<man_see>
call_function
</man_see>
</function>
<HR NEWPAGE>
<function name=random title="return a random number">
<man_syntax>
int random(int <I>max</I>);
</man_syntax>
<man_description>
This function returns a random number in the range 0 - max-1.
</man_description>
<man_see>
random_seed
</man_see>
</function>
<HR NEWPAGE>
<function name=random_seed title="seed random generator">
<man_syntax>
void random_seed(int <I>seed</I>);
</man_syntax>
<man_description>
This function sets the initial value for the random generator.
</man_description>
<man_example>
Pike v1.0E-13 Running Hilfe v1.2 (Hubbe's Incremental Pike Front-End)<br>
> random_seed(17);<br>
Result: 0<br>
> random(1000);<br>
Result: 732<br>
> random(1000);<br>
Result: 178<br>
> random(1000);<br>
Result: 94<br>
> random_seed(17);<br>
Result: 0<br>
> random(1000);<br>
Result: 732<br>
> random(1000);<br>
Result: 178<br>
> random(1000);<br>
Result: 94<br>
><br>
</man_example>
<man_see>
random
</man_see>
</function>
<HR NEWPAGE>
<function name=remove_call_out title="remove a call out from the call out queue">
<man_syntax>
int remove_call_out(function <I>f</I>);<br>
int remove_call_out(function <I>id</I>);
</man_syntax>
<man_description>
This function finds the first call to the function <i>f</i> 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)
</man_description>
<man_see>
call_out_info, call_out, find_call_out
</man_see>
</function>
<HR NEWPAGE>
<function name=remove_include_path title="remove a directory to search for include files">
<man_syntax>
void remove_include_path(string <I>path</I>);
</man_syntax>
<man_description>
This function removes a directory from the list of directories to search
for include files. It is the opposite of add_include_path.
</man_description>
<man_see>
add_include_path, #include
</man_see>
</function>
<HR NEWPAGE>
<function name=remove_module_path title="remove a directory to search for modules">
<man_syntax>
void remove_module_path(string <I>path</I>);
</man_syntax>
<man_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 <ref to=modules>.
</man_description>
<man_see>
add_module_path
</man_see>
</function>
<HR NEWPAGE>
<function name=remove_program_path title="remove a directory to search for modules">
<man_syntax>
void remove_program_path(string <I>path</I>);
</man_syntax>
<man_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 <ref to=programs>.
</man_description>
<man_see>
add_program_path
</man_see>
</function>
<HR NEWPAGE>
<function name=replace title="generic replace function">
<man_syntax>
string replace(string <I>s</I>, string <I>from</I>, string <I>to</I>);<br>
string replace(string <I>s</I>, array(string) <I>from</I>, array(string) <I>to</I>);<br>
array replace(array <I>a</I>, mixed <I>from</I>, mixed <I>to</I>);<br>
mapping replace(mapping <I>a</I>, mixed <I>from</I>, mixed <I>to</I>);
</man_syntax>
<man_description>
This function can do several kinds replacement operations, the
different syntaxes do different things as follow:
<dl>
<dt>string replace(string s, string from, string to);
<dd>When given strings as second and third argument, a copy of
s with every occurrence of 'from' replaced with 'to' is returned.
<dt>string replace(string s, array(string) from, array(string) to);
<dd>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...
<dt>array replace(array a, mixed from, mixed to);
<dt>mapping replace(mapping a, mixed from, mixed to);
<dd>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.
</dl>
</man_description>
</function>
<HR NEWPAGE>
<function name=replace_master title="replace the master object">
<man_syntax>
void replace_master(object <I>o</I>);
</man_syntax>
<man_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.
<!-- FIX ME, tell how to inherit the master -->
</man_description>
</function>
<HR NEWPAGE>
<function name=reverse title="reverse a string, array or int">
<man_syntax>
string reverse(string <I>s</I>);<br>
array reverse(array <I>a</I>);<br>
int reverse(int <I>i</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
sscanf
</man_see>
</function>
<HR NEWPAGE>
<function name=rm title="remove file or directory">
<man_syntax>
int rm(string <I>f</I>);
</man_syntax>
<man_description>
Remove a file or directory, return 0 if it fails. Nonzero otherwise.
</man_description>
<man_see>
mkdir
</man_see>
</function>
<HR NEWPAGE>
<function name=rows title="select a set of rows from an array">
<man_syntax>
array rows(mixed data, array index);
</man_syntax>
<man_description>
This function is exactly equivalent to:
<p>map_array(index,lambda(mixed x,mixed y) { return y[x]; },data)
<p>Except of course it is a lot shorter and faster.
That is, it indices data on every index in the array index and
returns an array with the results.
</man_description>
<man_see>
column
</man_see>
</function>
<HR NEWPAGE>
<function name=rusage title="return resource usage">
<man_syntax>
array(int) rusage();
</man_syntax>
<man_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:
<p>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
<p>Don't ask me to explain these values, read your system manuals for
more information. (Note that all values may not be present though)
</man_description>
<man_see>
time
</man_see>
</function>
<HR NEWPAGE>
<function name=search title="search for a value in a string or array">
<man_syntax>
int search(string <I>haystack</I>, string <I>needle</I>, [ int <I>start</I> ]);<br>
int search(array <I>haystack</I>, mixed <I>needle</I>, [ int <I>start</I> ]);<br>
mixed search(mapping <I>haystack</I>, mixed <I>needle</I>, [ mixed <I>start</I> ]);
</man_syntax>
<man_description>
Search for <i>needle</i> in <i>haystack</i>. Return the position of <i>needle</i> in
<i>haystack</i> or -1 if not found. If the optional argument <i>start</i> is present
search is started at this position. Note that when <i>haystack</i> is a string
<i>needle</i> must be a string, and the first occurrence of this string is
returned. However, when <i>haystack</i> is an array, <i>needle</i> is compared only
to one value at a time in <i>haystack</i>.
<p>
When the <i>haystack</i> is a mapping, <tt>search</tt> tries to find the index
connected to the data <i>needle</i>. That is, it tries to lookup the mapping
backwards. If <i>needle</i> isn't present in the mapping, zero is returned,
and zero_type() will return 1 for this zero.
</man_description>
<man_see>
indices, values, zero_type
</man_see>
</function>
<HR NEWPAGE>
<function name=signal title="trap signals">
<man_syntax>
void signal(int <I>sig</I>, function(int:void) <I>callback</I>);<br>
void signal(int <I>sig</I>);
</man_syntax>
<man_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.
<p>The callback will receive the signal number as the only argument.
See the document for the function 'kill' for a list of signals.
<p>If no second argument is given, the signal handler for that signal
is restored to the default handler.
<p>If the second argument is zero, the signal will be completely ignored.
</man_description>
<man_see>
kill, signame, signum
</man_see>
</function>
<HR NEWPAGE>
<function name=signame title="get the name of a signal">
<man_syntax>
string signame(int <I>sig</I>);
</man_syntax>
<man_description>
Returns a string describing the signal.
</man_description>
<man_example>
> signame(9);<br>
Result: SIGKILL<br>
</man_example>
<man_see>
kill, signum, signal
</man_see>
</function>
<HR NEWPAGE>
<function name=signum title="get a signal number given a descriptive string">
<man_syntax>
int signum(string <I>sig</I>);
</man_syntax>
<man_description>
This function is the opposite of signame.
</man_description>
<man_example>
> signum("SIGKILL");<br>
Result: 9<br>
</man_example>
<man_see>
signame, kill, signal
</man_see>
</function>
<HR NEWPAGE>
<function name=sin title="trigonometrical sine">
<man_syntax>
float sin(float <I>f</I>);
</man_syntax>
<man_description>
Returns the sinus value for <i>f</i>.
</man_description>
<man_see>
asin, cos
</man_see>
</function>
<HR NEWPAGE>
<function name=sizeof title="return the size of an array, string, multiset or mapping">
<man_syntax>
int sizeof(string|multiset|mapping|array|object <I>a</I>);
</man_syntax>
<man_description>
This function returns the number of indices available in the argument
given to it. It replaces older functions like strlen, m_sizeof and
size.
</man_description>
</function>
<HR NEWPAGE>
<function name=sleep title="let interpreter doze off for a while">
<man_syntax>
void sleep(int <I>s</I>);
</man_syntax>
<man_description>
This function makes the program stop for s seconds. Only signal
handlers can interrupt the sleep. Other callbacks are not called
during sleep.
</man_description>
<man_see>
signal
</man_see>
</function>
<HR NEWPAGE>
<function name=sort title="sort an array destructively">
<man_syntax>
array sort(array(mixed) <I>index</I>, array(mixed) ... <I>data</I>);
</man_syntax>
<man_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'. I.e. 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.
<p>Sort can sort strings, integers and floats in ascending order.
Arrays will be sorted first on the first element of each array.
<p>Sort returns its first argument.
</man_description>
<man_see>
reverse
</man_see>
</function>
<HR NEWPAGE>
<function name=sprintf title="print the result from sprintf">
<man_syntax>
string sprintf(string <I>format</I>,mixed <I>arg</I>,....);
</man_syntax>
<man_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.
<p>Modifiers:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> 0 </td><td> Zero pad numbers (implies right justification) </td></tr>
<tr valign=top><td> ! </td><td> Toggle truncation </td></tr>
<tr valign=top><td> ' ' (space) </td><td> pad positive integers with a space </td></tr>
<tr valign=top><td> + </td><td> pad positive integers with a plus sign </td></tr>
<tr valign=top><td> - </td><td> left adjusted within field size (default is right) </td></tr>
<tr valign=top><td> | </td><td> centered within field size </td></tr>
<tr valign=top><td> = </td><td> column mode if strings are greater than field size </td></tr>
<tr valign=top><td> / </td><td> Rough line break (break at exactly field size instead of between words) </td></tr>
<tr valign=top><td> # </td><td> table mode, print a list of '\n' separated word (top-to-bottom order) </td></tr>
<tr valign=top><td> $ </td><td> Inverse table mode (left-to-right order) </td></tr>
<tr valign=top><td> n </td><td> (where n is a number or *) a number specifies field size </td></tr>
<tr valign=top><td> .n </td><td> set precision </td></tr>
<tr valign=top><td> :n </td><td> set field size & precision </td></tr>
<tr valign=top><td> ;n </td><td> Set column width </td></tr>
<tr valign=top><td> * </td><td> if n is a * then next argument is used for precision/field size </td></tr>
<tr valign=top><td> 'X' </td><td> Set a pad string. ' cannot be a part of the pad_string (yet) </td></tr>
<tr valign=top><td> ~ </td><td> Get pad string from argument list. </td></tr>
<tr valign=top><td> < </td><td> Use same arg again </td></tr>
<tr valign=top><td> ^ </td><td> repeat this on every line produced </td></tr>
<tr valign=top><td> @ </td><td> do this format for each entry in argument array </td></tr>
<tr valign=top><td> > </td><td> Put the string at the bottom end of column instead of top </td></tr>
<tr valign=top><td> _ </td><td> Set width to the length of data </td></tr>
</table>
<p>Operators:
<p><table border=0 cellpadding=0 cellspacing=0>
<tr valign=top><td> %% </td><td> percent </td></tr>
<tr valign=top><td> %d </td><td> signed decimal int </td></tr>
<tr valign=top><td> %u </td><td> unsigned decimal int (doesn't really exist in Pike) </td></tr>
<tr valign=top><td> %o </td><td> unsigned octal int </td></tr>
<tr valign=top><td> %x </td><td> lowercase unsigned hexadecimal int </td></tr>
<tr valign=top><td> %X </td><td> uppercase unsigned hexadecimal int </td></tr>
<tr valign=top><td> %c </td><td> char (or short with %2c, %3c gives 3 bytes etc.) </td></tr>
<tr valign=top><td> %f </td><td> float </td></tr>
<tr valign=top><td> %g </td><td> heuristically chosen representation of float </td></tr>
<tr valign=top><td> %G </td><td> like %g, but uses uppercase E for exponent </td></tr>
<tr valign=top><td> %e </td><td> exponential notation float </td></tr>
<tr valign=top><td> %E </td><td> like %e, but uses uppercase E for exponent </td></tr>
<tr valign=top><td> %F </td><td> binary IEEE representation of float (%4F gives single precision, %8F gives double precision.) </td></tr>
<tr valign=top><td> %s </td><td> string </td></tr>
<tr valign=top><td> %O </td><td> any type (debug style) </td></tr>
<tr valign=top><td> %n </td><td> nop </td></tr>
<tr valign=top><td> %t </td><td> type of argument </td></tr>
<tr valign=top><td> %<modifiers>{format%} </td><td> do a format for every index in an array. </td></tr>
</table>
</man_description>
<man_example>
<pre>
<i>Pike v0.7 release 1 running Hilfe v2.0 (Incremental Pike Frontend)
> int screen_width=70;
Result: 70
> mixed sample;
> write(sprintf("fish: %c\n", 65));</i>
fish: A
<i>Result: 8
> write(sprintf("num: %d\n", 10));</i>
num: 10
<i>Result: 8
> write(sprintf("num: %+10d\n", 10));</i>
num: +10
<i>Result: 16
> write(sprintf("num: %010d\n", 5*2));</i>
num: 0000000010
<i>Result: 16
> write(sprintf("num: %|10d\n", 20/2));</i>
num: 10
<i>Result: 16
> write(sprintf("%|*s\n",screen_width,"THE NOT END"));</i>
THE NOT END
<i>Result: 71
> write(sprintf("%|=*s\n",screen_width, "fun with penguins\n"));</i>
fun with penguins
<i>Result: 71
> write(sprintf("%-=*O\n",screen_width,({ "fish", 9, "gumbies", 2 })));</i>
({ /* 4 elements */
"fish",
9,
"gumbies",
2
})
<i>Result: 426
> 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"));</i>
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.
<i>Result: 355
> 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.")); </i>
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.
<i>Result: 426
> 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."));</i>
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.
<i>Result: 312
> sample = ({"bing","womble","wuff","gul"});
Result: ({ /* 4 elements */
"bing",
"womble",
"wuff",
"gul"
})
> write(sprintf("This will apply the format strings between the\n"
"procent-braces to all elements in the array:\n"
"%{gurksallad: %s\n%}",
sample));</i>
This will apply the format strings between the
procent-braces to all elements in the array:
gurksallad: bing
gurksallad: womble
gurksallad: wuff
gurksallad: gul
<i>Result: 162
> 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));</i>
Of course all the simple printf options are supported:
65 as decimal, hex, octal and a char: 65 41 101 A
<i>Result: 106
> write(sprintf("%|*s\n",screen_width, "THE END"));</i>
THE END
<i>Result: 71
> quit
Exiting.</i>
</pre>
</man_example>
<man_see>
sscanf
</man_see>
</function>
<HR NEWPAGE>
<function name=sqrt title="square root">
<man_syntax>
float sqrt(float <I>f</I>);<br>
int sqrt(int <I>i</I>);
</man_syntax>
<man_description>
Returns the square root of <i>f</i>, or in the second case, the square root
truncated to the closest lower integer.
</man_description>
<man_see>
pow, log, exp, floor
</man_see>
</function>
<HR NEWPAGE>
<function name=strerror title="return a string describing an error">
<man_syntax>
string strerror(int <I>errno</I>);
</man_syntax>
<man_description>
This function returns a description of an error code. The error
code is usually obtained from the file->errno() call.
</man_description>
<man_note>
This function may not be available on all platforms.
</man_note>
</function>
<HR NEWPAGE>
<function name=stringp title="is the argument a string?">
<man_syntax>
int stringp(mixed <I>arg</I>);
</man_syntax>
<man_description>
Returns 1 if <i>arg</i> is a string, zero otherwise.
</man_description>
<man_see>
intp, multisetp, arrayp, programp, objectp, mappingp, floatp, functionp
</man_see>
</function>
<HR NEWPAGE>
<function name=string_to_unicode title="convert a string to an UTF16 stream">
<man_syntax>
string string_to_unicode(string <I>s</I>);
</man_syntax>
<man_description>
Converts a string into an UTF16 compiant byte-stream.
<p>
Throws an error if characters not legal in an UTF16 stream are encountered.
Valid characters are in the range 0x00000 - 0x10ffff, except for characters
0xfffe and 0xffff.
<p>
Characters in range 0x010000 - 0x10ffff are encoded using surrogates.
</man_description>
<man_note>
This function is only available in Pike 0.6.105 and later.
</man_note>
<man_see>
Locale.Charset.decode, string_to_utf8, unicode_to_string, utf8_to_string
</man_see>
</function>
<HR NEWPAGE>
<function name=string_to_utf8 title="convert a string to an UTF8 stream">
<man_syntax>
string string_to_utf8(string <I>s</I>);
string string_to_utf8(string <I>s</I>, int <I>extended</I>);
</man_syntax>
<man_description>
Converts a string into an UTF8 compilant byte-stream.
<p>
Throws an error if characters not valid in an UTF8 stream are encountered.
Valid characters are in the range 0x00000000 - 0x7fffffff.
<p>
If <tt>extended</tt> is 1, characters in the range 0x80000000-0xfffffffff
will also be accepted, and encoded using a non-standard UTF8 extension.
</man_description>
<man_note>
This function is only available in Pike 0.6.105 and later.
</man_note>
<man_see>
Locale.Charset.decode, string_to_unicode, unicode_to_string, utf8_to_string
</man_see>
</function>
<HR NEWPAGE>
<function name=strlen title="return the length of a string">
<man_syntax>
int strlen(string <I>s</I>);
</man_syntax>
<man_description>
This function is equal to sizeof.
</man_description>
<man_see>
sizeof
</man_see>
</function>
<HR NEWPAGE>
<function name=tan title="trigonometrical tangent">
<man_syntax>
float tan(float <I>f</I>);
</man_syntax>
<man_description>
Returns the tangent value for <i>f</i>.
</man_description>
<man_see>
atan, sin, cos
</man_see>
</function>
<HR NEWPAGE>
<function name=this_object title="return the object we are evaluating in currently">
<man_syntax>
object this_object();
</man_syntax>
<man_description>
This function returns the object we are currently evaluating in.
</man_description>
</function>
<HR NEWPAGE>
<function name=throw title="throw a value to catch or global error handling">
<man_syntax>
void throw(mixed <I>value</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
catch
</man_see>
</function>
<HR NEWPAGE>
<function name=time title="return the current time">
<man_syntax>
int time();<br>
int time(1);<br>
float time(int <I>t</I>);<br>
</man_syntax>
<man_description>
This function returns the number of seconds since 1 Jan 1970.
The function ctime() converts this integer to a readable string.
<p>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)
<p>
The third syntax can be used to measure time more preciely than one second.
It return how many seconds has passed since <I>t</i>. The precision of this
function varies from system to system.
</man_description>
<man_see>
ctime, localtime, mktime, gmtime
</man_see>
</function>
<HR NEWPAGE>
<function name=trace title="change debug trace level">
<man_syntax>
int trace(int <I>t</I>);
</man_syntax>
<man_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
</man_description>
</function>
<HR NEWPAGE>
<function name=typeof title="check return type of expression">
<man_syntax>
typeof ( expression );
</man_syntax>
<man_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.
</man_description>
<man_example>
> typeof(`sizeof);<br>
Result: function(object | mapping | array | multiset | string : int)<br>
> typeof(sizeof(({})));<br>
Result: int<br>
> <br>
</man_example>
</function>
<HR NEWPAGE>
<function name=ualarm title="set an alarm clock for delivery of a signal">
<man_syntax>
int ualarm(int <I>useconds</I>);
</man_syntax>
<man_description>
ualarm arranges for a SIGALRM signal to be delivered to the
process in useconds micro seconds.
<p>If useconds is zero, no new alarm is scheduled.
<p>In any event any previously set alarm is canceled.
</man_description>
<man_returns>
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.
</man_returns>
<man_see>
signal
</man_see>
</function>
<HR NEWPAGE>
<function name=unicode_to_string title="convert an UTF16 stream to a string">
<man_syntax>
string unicode_to_string(string <I>s</I>);
</man_syntax>
<man_description>
Converts an UTF16 byte-stream into a string.
</man_description>
<man_note>
This function does not decode surrogates.
<p>
This function is only available in Pike 0.6.105 and later.
</man_note>
<man_see>
Locale.Charset.decode, string_to_unicode, string_to_utf8, utf8_to_string
</man_see>
</function>
<HR NEWPAGE>
<function name=upper_case title="convert a string to upper case">
<man_syntax>
string upper_case(string <I>s</I>);
</man_syntax>
<man_description>
Returns a copy of the string <i>s</i> with all lower case character converted
to upper case character.
</man_description>
<man_see>
lower_case
</man_see>
</function>
<HR NEWPAGE>
<function name=utf8_to_string title="convert an UTF8 stream to a string">
<man_syntax>
string utf8_to_string(string <I>s</I>);
string utf8_to_string(string <I>s</I>, int <I>extended</I>);
</man_syntax>
<man_description>
Converts an UTF8 byte-stream into a string.
<p>
Throws an error if the stream is not a legal UFT8 byte-stream.
<p>
Accepts and decodes the extension used by
<link to=string_to_utf8>string_to_utf8()</link>, if <tt>extended</tt> is 1.
</man_description>
<man_note>
This function is only available in Pike 0.6.105 and later.
</man_note>
<man_see>
Locale.Charset.decode, string_to_unicode, string_to_utf8, unicode_to_string
</man_see>
</function>
<HR NEWPAGE>
<function name=values title="return an array of all possible values from indexing">
<man_syntax>
array values(string|multiset|mapping|array|object <I>foo</I>);
</man_syntax>
<man_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.
</man_description>
<man_see>
indices
</man_see>
</function>
<HR NEWPAGE>
<function name=version title="return version info">
<man_syntax>
string version();
</man_syntax>
<man_description>
This function returns a brief information about the Pike version.
</man_description>
<man_example>
<example language=pike>
> version();
Result: "Pike v0.7 release 1"
</example>
</man_example>
</function>
<HR NEWPAGE>
<function name=write title="write text to stdout">
<man_syntax>
int write(string <I>text</I>);
</man_syntax>
<man_description>
Added by the master, it directly calls write in a
<link to=Stdio.stdout>Stdio.stdout</link>.
</man_description>
<man_see>
Stdio.werror
</man_see>
</function>
<HR NEWPAGE>
<function name=zero_type title="return the type of zero">
<man_syntax>
int zero_type(mixed <I>a</I>);
</man_syntax>
<man_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.
<p>If the argument is not an int, zero will be returned.
</man_description>
<man_see>
find_call_out
</man_see>
</function>
</chapter>
<!--
<H1>XXX. Things to describe somewhere</H1>
<ul>
<li>garbage collection
<li>int ... args
<li>data storage (local vs. global variables)
<li>trace
<li>Pike command line
<li>hilfe
<li>socket->query_address()
<li> scope for class {}
<li>optimization
</ul>
<HR NEWPAGE>
<HR NEWPAGE>
<HR NEWPAGE>
<chapter title="Pike internals - how to extend Pike">
The rest of this book describes how Pike works and how to extend it with
your own functions written in C or C++. Even if you are not interested in
extending Pike, the information in this section can make you understand
Pike better and thus make you a better Pike programmer. From this point on
I will assume that the reader knows C or C++.
<p>
<section title="The master object">
Pike is a very dynamic language. Sometimes that is not enough, sometimes you
want to change the way Pike handles errors, loads modules or start scripts.
All this and much more can be changed by modifying the <b>master object</b>.
The <b>master object</b> is a Pike object like any other object, but it is
loaded before anything else and is expected to perform certain things for
the Pike executable. The Pike executable cannot function without a master
object to take care of these things. Here is a list of the methods needed
in the <b>master object</b>:
<dl>
<dt> <tt>program cast_to_program(string <i>program_name</i>, string <i>current_file</i>)</tt>
<dd> This function is called whenever someone performs a cast from a string
to a program.
<dt> <tt>program handle_inherit(string <i>program_name</i>, string <i>current_file</i>)</tt>
<dd> This is called whenever a Pike program which uses inherit with a string
argument is called. It is expected to return the program to inherit.
<dt> <tt>void handle_error(array <i>trace</i>)</tt>
<dd> This function is expected to write the error messages when a
run time error occurs. The argument is of the form
<tt>({"<i>error_description</i>", backtrace() })</tt>. If any error
occurs in this routine Pike will dump core.
<dt> <tt>program cast_to_program(string <i>program_name</i>, string <i>current_file</i>)</tt>
<dd> This function is called whenever someone performs a cast from a string
to an object.
<dt> <tt>mixed resolv(string <i>identifier</i>, string <i>current_file</i>)</tt>
<dd> This function is called whenever the compiler finds an unknown identifier
in a program. It is normally used for loading modules.
It is supposed to return <tt>([])[0]</tt> if the master doesn't know what
the value should be, and the value in question otherwise.
<dt> <tt>void _main(array(string) <i>argv</i>, array(string) <i>env</i>)</tt>
<dd> This function is supposed to start a Pike script. It receives all
the command line arguments in the first array and all environment
variables on the form <tt>"<i>var</i>=<i>value</i>"</tt>.
_main is called as soon as all modules and setup is done.
<dt> <tt>void compile_error(string <i>file</i>, int <i>line</i>, string <i>err</i>)</tt>
<dd> This function is called whenever a compile error is encountered. Normally
it just writes a message to stderr.
<dt> <tt>string handle_include(string <i>file</i>, string <i>current_file</i>, int <i>local_include</i>)</tt>
<dd> This function is used to locate include files. <i>file</i> is the file
name the user wants to include, and <i>local_include</i> is 1 if
the user used double quotes rather than lesser-than, greater-than to
quote the file name. Otherwise it is zero.
</dl>
<p>
Aside from the above functions, which are expected from the Pike binary,
the master object is also expected to provide functions used by Pike
scripts. The current master adds the following global functions:
<dl><dd>
add_include_path,
remove_include_path,
add_module_path,
remove_module_path,
add_program_path,
remove_program_path,
master,
describe_backtrace,
mkmultiset,
strlen,
new,
clone,
UNDEFINED,
write,
getenv and putenv.
</dl>
<p>
There are at least two ways to change the behavior of the master object.
(Except for editing it directly, which would cause other Pike scripts not
to run in most cases.) You can either copy the master object, modify it
and use the command line option <tt>-m</tt> to load your file instead of
the default master object. However, since there might be more functionality
added to the master object in the future I do not recommend this.
<p>
A better way is to write an object that inherits the master and then calls
replace_master with the new object as argument. This should be far more
future-safe. Although I can not guarantee that the interface between Pike
and the master object will not change in the future, so be careful if you
do this.
<p>
Let's look an example:
<example language=pike>
#!/usr/local/bin/pike
class new_master {
inherit "/master";
void create()
{
/* You need to copy the values from the old master to the new */
/* NOTE: At this point we are still using the old master */
object old_master = master();
object new_master = this_object();
foreach(indices(old_master), string varname)
{
/* The catch is needed since we can't assign constants */
catch { new_master[varname] = old_master[varname]; };
}
}
void handle_error(array trace)
{
Stdio.write_file("error log",describe_backtrace(trace));
}
};
int main(int argc, array(string) argv)
{
replace_master(new_master());
/* Run rest of program */
exit(0);
}
</example>
This example installs a master object which logs run time errors to file
instead of writing them to stderr.
<p>
</section>
<h2> Functional overview </h2>
<h2>Overview of the Pike source</h2>
<dl>
<dt> library files
<dd>
<dl>
<dt> callback
</dl>
<dt> compiler
<dt> backend
<dt> callback
<dt> constants
<dt> docode
<dt>
</dl>
<ul>
<li>Overview of the Pike source
<li>The master object
<li>The file structure of a module
<li>Data types from the inside
<li>Writing portable modules: autoconf
<li>Other useful functions
</ul>
</chapter>
-->
<include file=extending.wmml>
<appendix title="Terms and jargon">
<dl>
<dt> HTTP <dd> Hyper-Text Transfer Protocol, the protocol used by WWW to transfer HTML from the server to the client. Based on TCP.
<dt> WWW <dd> World Wide Web, popularly known as 'the Internet' :)
<dt> TCP <dd> Transmission Control Protocol, the Internet standard for computer communication
<dt> ASCII <dd> 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.
<dt> UNIX <dd> A group of operating systems. Some noteworthy Unixes are: Solaris, Linux, HP-UX, Digital Unix, SunOs, BSD and Unixware.
<dt> clone <dd> To create an object from a program. Or to use C++ jargon: to instantiate a class.
<dt> command line <dd> The line you write to execute a program
<dt> command line option <dd> The words after the program name on the <i>command line</i>.
<dt> constant <dd> 1) A value written directly in the code, such as <tt>1</tt> or <tt>"foo"</tt>. 2) A value defined with add_constant.
<dt> identifier <dd> The name of a variable, function, class or constant.
<dt> interpreter <dd> An interpreter <i>interprets </i> byte-code instruction by instruction. In this context 'the interpreter' is usually the Pike binary.
<dt> iteration <dd> Iteration is when the program is executing a loop. Each time the loop is called is also called one iteration.
<dt> object <dd> 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++.
<dt> program <dd> 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.
<dt> recursion <dd> Recursion is an alternative to iteration. Recursion occurs when a function calls itself.
<dt> stderr <dd> 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.
<dt> stdin <dd> 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.
<dt> stdout <dd> 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.
</dl>
</appendix>
<appendix title="Register program" name=register_program>
Here is a complete listing of the example program from
chapter 2.
<example language=pike>
#!/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];
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]));
}
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;
Stdio.File 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)
{
string name="ERROR";
string file_contents,line;
Stdio.File 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;
}
}
}
</example>
</appendix>
<appendix title="Reserved words">
These are words that have special meaning in Pike and can not be used
as variable or function names.
<p>
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>
<appendix title="BNF for Pike">
BNF is short for "Backus Naur Form". It is a precise way of describing syntax.
This is the BNF for Pike:
<table>
<tr valign=top><td>program</td><td>::=</td><td>{ definition }</td></tr>
<tr valign=top><td>definition</td><td>::=</td><td>import | inheritance | function_declaration | function_definition | variables | constant | class_def</td></tr>
<tr valign=top><td>import</td><td>::=</td><td>modifiers <b>import</b> ( constant_identifier | string ) ";" </td></tr>
<tr valign=top><td>inheritance</td><td>::=</td><td>modifiers <b>inherit</b> program_specifier [ ":" identifier ] ";" </td></tr>
<tr valign=top><td>function_declaration</td><td>::=</td><td>modifiers type identifier "(" arguments ")" ";"</td></tr>
<tr valign=top><td>function_definition</td><td>::=</td><td>modifiers type identifier "(" arguments ")" block </td></tr>
<tr valign=top><td>variables</td><td>::=</td><td>modifiers type variable_names ";"</td></tr>
<tr valign=top><td>variable_names</td><td>::=</td><td>variable_name { "," variable_name }</td></tr>
<tr valign=top><td>variable_name</td><td>::=</td><td>{ "*" } identifier [ "=" expression2 ]</td></tr>
<tr valign=top><td>constant</td><td>::=</td><td>modifiers <b>constant</b> constant_names ";" </td></tr>
<tr valign=top><td>constant_names</td><td>::=</td><td>constant_name { "," constant_name }</td></tr>
<tr valign=top><td>constant_name</td><td>::=</td><td>identifier "=" expression2</td></tr>
<tr valign=top><td>class_def</td><td>::=</td><td>modifiers <b>class</b> [ ";" ] </td></tr>
<tr valign=top><td>class</td><td>::=</td><td><b>class</b> [ identifier ] "{" program "}"</td></tr>
<tr valign=top><td>modifiers</td><td>::=</td><td> { <b>static</b> | <b>private</b> | <b>nomask</b> | <b>public</b> | <b>protected</b> | <b>inline</b> }</td></tr>
<tr valign=top><td>block</td><td>::=</td><td>"{" { statement } "}" </td></tr>
<tr valign=top><td>statement</td><td>::=</td><td>expression2 ";" | cond | while | do_while | for | switch | case | default | return | block | foreach | break | continue | ";" </td></tr>
<tr valign=top><td>cond</td><td>::=</td><td><b>if</b> statement [ <b>else</b> statement ]</td></tr>
<tr valign=top><td>while</td><td>::=</td><td><b>while</b> "(" expression ")" statement</td></tr>
<tr valign=top><td>do_while</td><td>::=</td><td><b>do</b> statement <b>while</b> "(" expression ")" ";" </td></tr>
<tr valign=top><td>for</td><td>::=</td><td><b>for</b> "(" [ expression ] ";" [ expression ] ";" [ expression ] ")" statement</td></tr>
<tr valign=top><td>switch</td><td>::=</td><td><b>switch</b> "(" expression ")" block</td></tr>
<tr valign=top><td>case</td><td>::=</td><td><b>case</b> expression [ ".." expression ] ":"</td></tr>
<tr valign=top><td>default</td><td>::=</td><td><b>default</b> ":"</td></tr>
<tr valign=top><td>foreach</td><td>::=</td><td><b>foreach</b> "(" expression ":" expression6 ")" statement</td></tr>
<tr valign=top><td>break</td><td>::=</td><td><b>break</b> ";"</td></tr>
<tr valign=top><td>continue</td><td>::=</td><td><b>continue</b> ";"</td></tr>
<tr valign=top><td>expression</td><td>::=</td><td>expression2 { "," expression2 }</td></tr>
<tr valign=top><td>expression2</td><td>::=</td><td>{ lvalue ( "=" | "+=" | "*=" | "/=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "%=" ) } expression3</td></tr>
<tr valign=top><td>expression3</td><td>::=</td><td>expression4 '?' expression3 ":" expression3 </td></tr>
<tr valign=top><td>expression4</td><td>::=</td><td>{ expression5 ( "||" | "&&" | "|" | "^" | "&" | "==" | "!=" | ">" | "<" | ">=" | "<=" | "<<" | ">>" | "+" | "*" | "/" | "%" ) } expression5</td></tr>
<tr valign=top><td>expression5</td><td>::=</td><td>expression6 | "(" type ")" expression5 | "--" expression6 | "++" expression6 | expression6 "--" | expression6 "++" | "~" expression5 | "-" expression5 </td></tr>
<tr valign=top><td>expression6</td><td>::=</td><td>string | number | float | catch | gauge | typeof | sscanf | lambda | class | constant_identifier | call | index | mapping | multiset | array | parenthesis | arrow </td></tr>
<tr valign=top><td>number</td><td>::=</td><td>digit { digit } | "0x" { digits } | "'" character "'" </td></tr>
<tr valign=top><td>float</td><td>::=</td><td>digit { digit } "." { digit }</td></tr>
<tr valign=top><td>catch</td><td>::=</td><td><b>catch</b> ( "(" expression ")" | block )</td></tr>
<tr valign=top><td>gauge</td><td>::=</td><td><b>gauge</b> ( "(" expression ")" | block )</td></tr>
<tr valign=top><td>sscanf</td><td>::=</td><td><b>sscanf</b> "(" expression2 "," expression2 { "," lvalue } ")" </td></tr>
<tr valign=top><td>lvalue</td><td>::=</td><td>expression6 | type identifier | "[" [ lvalue { "," lvalue } [ "," ] ] "]"</td></tr>
<tr valign=top><td>lambda</td><td>::=</td><td><b>lambda</b> "(" arguments ")" block</td></tr>
<tr valign=top><td>constant_identifier</td><td>::=</td><td>["."] identifier { "." identifier }</td></tr>
<tr valign=top><td>call</td><td>::=</td><td>expression6 "(" expression_list ")" </td></tr>
<tr valign=top><td>index</td><td>::=</td><td>expression6 "[" expression [ ".." expression ] "]"</td></tr>
<tr valign=top><td>array</td><td>::=</td><td>"({" expression_list "})"</td></tr>
<tr valign=top><td>multiset</td><td>::=</td><td>"(<" expression_list ">)"</td></tr>
<tr valign=top><td>mapping</td><td>::=</td><td>"([" [ expression : expression { "," expression ":" expression } ] [ "," ] "])"</td></tr>
<tr valign=top><td>arrow</td><td>::=</td><td>expression6 "->" identifier</td></tr>
<tr valign=top><td>parenthesis</td><td>::=</td><td>"(" expression ")"</td></tr>
<tr valign=top><td>expression_list</td><td>::=</td><td> [ splice_expression { "," splice_expression } ] [ "," ]</td></tr>
<tr valign=top><td>splice_expression</td><td>::=</td><td>[ "@" ] expression2</td></tr>
<tr valign=top><td>type</td><td>::=</td><td> ( <b>int</b> | <b>string</b> | <b>float</b> | <b>program</b> | <b>object</b> [ "(" program_specifier ")" ] | <b>mapping</b> [ "(" type ":" type ")" | <b>array</b> [ "(" type ")" ] | <b>multiset</b> [ "(" type ")" ] | <b>function</b> [ function_type ] ) { "*" }</td></tr>
<tr valign=top><td>function_type</td><td>::=</td><td>"(" [ type { "," type } [ "..." ] ")"</td></tr>
<tr valign=top><td>arguments</td><td>::=</td><td>[ argument { "," argument } ] [","]</td></tr>
<tr valign=top><td>argument</td><td>::=</td><td>type [ "..." ] [ identifier ]</td></tr>
<tr valign=top><td>program_specifier</td><td>::=</td><td>string_constant | constant_identifier</td></tr>
<tr valign=top><td>string</td><td>::=</td><td>string_literal { string_literal }</td></tr>
<tr valign=top><td>identifier</td><td>::=</td><td>letter { letter | digit } | "`+" | "`/" | "`%" | "`*" | "`&" | "`|" | "`^" | "`~" | "`<" | "`<<" | "`<=" | "`>" | "`>>" | "`>=" | "`==" | "`!=" | "`!" | "`()" | "`-" | "`->" | "`->=" | "`[]" | "`[]="</td></tr>
<tr valign=top><td>letter</td><td>::=</td><td>"a"-"z" | "A"-"Z" | "_"</td></tr>
<tr valign=top><td>digit</td><td>::=</td><td>"0"-"9"</td></tr>
</table>
</appendix>
<appendix title="How to install Pike" name=install>
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 <a href=http://pike.idonex.se>the Pike home page</a>.
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:
<ul>
<li> Solaris 2.4, 2.5, 2.5.1, 2.6
<li> Linux Red Hat, Slackware, Debian etc.
<li> Digital Unix (OSF/1)
<li> HP-UX 10
<li> AIX 4
<li> IRIX
<li> NetBSD 2.2.2
<li> SunOs 4.1.1, 4.1.3
<li> SCO UNIX
<li> Ultrix
</ul>
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.6.105.tar.gz, simply unpack it by
typing:
<pre>
$ gunzip -d Pike-v0.6.105.tar.gz
$ tar xvf Pike-v0.5.105.tar
</pre>
Now you have a directory called Pike-v0.6.53. Please read the README file
in the new directory since newer versions can contain information not
available at the time this book was written.
<p>
Now, to compile Pike, the following three commands should be enough.
<pre>
$ cd Pike-v0.6.105/src
$ ./configure --prefix=/dir/to/install/pike
$ make
</pre>
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.
<p>
After that <tt>make</tt> will actually compile the program. After compilation
it is a good idea to do <tt>make verify</tt> 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 <tt>make install</tt> to install
the Pike binaries, libraries and include files in the directory you selected
earlier.
<p>
You are now ready to use Pike.
</appendix>
<insert_added_appendices>
<index title=Index>