Previous chapter To contents Next chapter

Chapter 16, Builtin functions

This chapter is a reference for all the builtin functions in Pike. They are listed in alphabetical order.

FUNCTION
_disable_threads - temporarily disable threads

SYNTAX
object _disable_threads();

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.

FUNCTION
_do_call_outs - do all pending call_outs

SYNTAX
void _do_call_out();

DESCRIPTION
This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.

As a side-effect, this function sets the value returned by time(1) to the current time.

SEE ALSO
call_out, find_call_out and remove_call_out

FUNCTION
_exit - Really exit

SYNTAX
void _exit(int returncode);

DESCRIPTION
This function does the same as exit, 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.

SEE ALSO
exit

FUNCTION
_locate_references - locate where an object is referenced from

SYNTAX
mapping(string:int) _locate_references(string|array|mapping|multiset|function|object|program o);

DESCRIPTION
This function is mostly intended for debugging. It will search through all data structures in Pike looking for o and print the locations on stderr. o can be anything but int or float.

FUNCTION
_memory_usage - check memory usage

SYNTAX
mapping(string:int) _memory_usage();

DESCRIPTION
This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use. Try evaluating the function in hilfe to see precisely what it returns.

SEE ALSO
_verify_internals

FUNCTION
_next - find the next object/array/whatever

SYNTAX
mixed _next(mixed p);

DESCRIPTION
All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next object/array/mapping/string/etc in the linked list. It is mainly meant for debugging Pike but can also be used to control memory usage.

SEE ALSO
next_object and _prev

FUNCTION
_prev - find the previous object/array/whatever

SYNTAX
mixed _next(mixed p);

DESCRIPTION
This function returns the 'previous' object/array/mapping/etc in the linked list. It is mainly meant for debugging Pike but can also be used to control memory usage. Note that this function does not work on strings.

SEE ALSO
_next

FUNCTION
_refs - find out how many references a pointer type value has

SYNTAX
int _refs(string|array|mapping|multiset|function|object|program o);

DESCRIPTION
This function checks how many references the value o has. Note that the number of references will always be at least one since the value is located on the stack when this function is executed. _refs() is mainly meant for debugging Pike but can also be used to control memory usage.

SEE ALSO
_next and _prev

FUNCTION
_verify_internals - check Pike internals

SYNTAX
void _verify_internals();

DESCRIPTION
This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.

FUNCTION
abs - absolute value

SYNTAX
float abs(float f); int abs(int f); object abs(object f);

DESCRIPTION
Return the absolute value for f. f can be a Gmp-object.

FUNCTION
acos - trigonometrical inverse cosine

SYNTAX
float acos(float f);

DESCRIPTION
Return the arcus cosine value for f. The result will be in radians.

SEE ALSO
cos and asin

FUNCTION
add_constant - add new predefined functions or constants

SYNTAX
void add_constant(string name, mixed value);
void add_constant(string name);

DESCRIPTION
This function adds a new constant to Pike, it is often used to add builtin functions. All programs compiled after add_constant function is called can access 'value' by the name given by 'name'. If there is a constant called 'name' already, it will be replaced by by the new definition. This will not affect already compiled programs.

Calling add_constant without a value will remove that name from the list of constants. As with replacing, this will not affect already compiled programs.

EXAMPLE
add_constant("true",1);
add_constant("false",0);
add_constant("PI",4.0);
add_constant("sqr",lambda(mixed x) { return x * x; });
add_constant("add_constant");

SEE ALSO
all_constants

FUNCTION
add_include_path - add a directory to search for include files

SYNTAX
void add_include_path(string path);

DESCRIPTION
This function adds another directory to the search for include files. This is the same as the command line option -I. Note that the added directory will only be searched when using < > to quote the included file.

SEE ALSO
remove_include_path and #include

FUNCTION
add_module_path - add a directory to search for modules

SYNTAX
void add_module_path(string path);

DESCRIPTION
This function adds another directory to the search for modules. This is the same as the command line option -M. For more information about modules, see chapter 8 "Modules".

SEE ALSO
remove_module_path

FUNCTION
add_program_path - add a directory to search for modules

SYNTAX
void add_program_path(string path);

DESCRIPTION
This function adds another directory to the search for programs. This is the same as the command line option -P. For more information about programs, see section 4.2.4 "program".

SEE ALSO
remove_program_path

FUNCTION
aggregate - construct an array

SYNTAX
array aggregate(mixed ... elems);
({ elem1, elem2, ... });

DESCRIPTION
Construct an array with the arguments as indices. This function could be written in Pike as:

array aggregate(mixed ... elems) { return elems; }

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.

SEE ALSO
sizeof, arrayp and allocate

FUNCTION
aggregate_mapping - construct a mapping

SYNTAX
mapping aggregate_mapping(mixed ... elems);
([ key1:val1, key2:val2, ... ]);

DESCRIPTION
Groups the arguments together two and two to key-index pairs and creates a mapping of those pairs. The second syntax is always preferable.

SEE ALSO
sizeof, mappingp and mkmapping

FUNCTION
aggregate_multiset - construct a multiset

SYNTAX
multiset aggregate_multiset(mixed ... elems);
(< elem1, elem2, ... >);

DESCRIPTION
Construct a multiset with the arguments as indices. This function could be written in Pike as:

multiset aggregate(mixed ... elems) { return mkmultiset(elems); }

The only problem is that mkmultiset is implemented using aggregate_multiset...

SEE ALSO
sizeof, multisetp and mkmultiset

FUNCTION
alarm - set an alarm clock for delivery of a signal

SYNTAX
int alarm(int seconds);

DESCRIPTION
alarm arranges for a SIGALRM signal to be delivered to the process in seconds seconds.

If seconds is zero, no new alarm is scheduled.

In any event any previously set alarm is canceled.

RETURNS
alarm returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

SEE ALSO
signal

FUNCTION
all_constants - return all predefined constants

SYNTAX
mapping (string:mixed) all_constant();

DESCRIPTION
Returns a mapping containing all constants, indexed on the names of the constant, and with the value of the efun as argument.

SEE ALSO
add_constant

FUNCTION
allocate - allocate an array

SYNTAX
array allocate(int size);

DESCRIPTION
Allocate an array of size elements and initialize them to zero.

EXAMPLE
array a=allocate(17);

NOTE
Arrays are dynamically allocated there is no need to declare them like int a[10]=allocate(10); (and it is not possible either) like in C, just array(int) a=allocate(10); will do.

SEE ALSO
sizeof, aggregate and arrayp

FUNCTION
arrayp - is the argument an array?

SYNTAX
int arrayp(mixed arg);

DESCRIPTION
Returns 1 if arg is an array, zero otherwise.

SEE ALSO
allocate, intp, programp, floatp, stringp, objectp, mappingp, multisetp and functionp

FUNCTION
array_sscanf - sscanf to an array

SYNTAX
array array_sscanf(string data, string format);

DESCRIPTION
This function works just like sscanf, but returns the matched results in an array instead of assigning them to lvalues. This is often useful for user-defined sscanf strings.

SEE ALSO
sscanf and `/

FUNCTION
asin - trigonometrical inverse sine

SYNTAX
float asin(float f);

DESCRIPTION
Returns the arcus sinus value for f.

SEE ALSO
sin and acos

FUNCTION
atan - trigonometrical inverse tangent

SYNTAX
float atan(float f);

DESCRIPTION
Returns the arcus tangent value for f.

SEE ALSO
atan2, tan, asin and acos

FUNCTION
atan2 - trigonometrical inverse tangent

SYNTAX
float atan2(float f1, float f2);

DESCRIPTION
Returns the arcus tangent value for f1/f2.

SEE ALSO
atan, tan, asin and acos

FUNCTION
atexit - schedule a callback for when pike exits

SYNTAX
void atexit(function callback);

DESCRIPTION
This function puts the callback in a queue of callbacks to call when pike exits. Please note that atexit callbacks are not called if pike exits abnormally.

SEE ALSO
exit

FUNCTION
backtrace - get a description of the call stack

SYNTAX
array(array) backtrace();

DESCRIPTION
This function returns a description of the call stack at this moment. The description is returned in an array with one entry for each call in the stack. Each entry has this format:

({
     file, /* a string with the filename if known, else zero */
     line, /* an integer containing the line if known, else zero */
     function, /* The function pointer to the called function */
     mixed|void ..., /* The arguments the function was called with */
})

The current call frame will be last in the array, and the one above that the last but one and so on.

SEE ALSO
catch and throw

FUNCTION
basename - get the base of a filename

SYNTAX
string basename(string filename);

DESCRIPTION
This function returns the base of a filename, for instance the base of "/home/hubbe/bin/pike" would be "pike".

SEE ALSO
dirname and explode_path

FUNCTION
call_function - call a function with arguments

SYNTAX
mixed call_function(function fun,mixed ... args);
mixed fun ( mixed ... args );

DESCRIPTION
This function takes a function pointer as first argument and calls this function with the rest of the arguments as arguments. Normally, you will never have to write call_function(), because you will use the second syntax instead.

SEE ALSO
backtrace and Simulate.get_function

FUNCTION
call_out - make a delayed call to a function

SYNTAX
mixed call_out(function f, float|int delay, mixed ... args);

DESCRIPTION
Call_out places a call to the function f with the argument args in a queue to be called in about delay seconds. The return value identifies this call out. The return value can be sent to find_call_out or remove_call_out to remove the call out again.

SEE ALSO
remove_call_out, find_call_out and call_out_info

FUNCTION
call_out_info - get info about all call outs

SYNTAX
array(array) call_out_info();

DESCRIPTION
This function returns an array with one entry for each entry in the call out queue. The first in the queue will be in index 0. Each index contains an array that looks like this:

({

time_left, /* an int */
caller, /* the object that made the call out */
function, /* the function to be called */
arg1, /* the first argument, if any */
arg2, /* the second argument, if any */
... /* and so on... */
})

SEE ALSO
call_out, find_call_out and remove_call_out

FUNCTION
catch

SYNTAX
catch { commands };
catch ( expression );

DESCRIPTION
catch traps exceptions such as run time errors or calls to throw() and returns the argument given to throw. For a run time error, this value is ({ "error message", backtrace })

SEE ALSO
throw

FUNCTION
cd - change directory

SYNTAX
int cd(string s);

DESCRIPTION
Change the current directory for the whole Pike process, return 1 for success, 0 otherwise.

SEE ALSO
getcwd

FUNCTION
ceil - truncate a number upward

SYNTAX
float ceil(float f);

DESCRIPTION
Return the closest integer value higher or equal to f.

NOTE
ceil() does not return an int, merely an integer value stored in a float.

SEE ALSO
floor and round

FUNCTION
chmod - change mode of a file in the filesystem

SYNTAX
void chmod(string filename,int mode);

DESCRIPTION
Sets the protection mode of the given file. It will throw if it fails.

SEE ALSO
Stdio.File->open and errno

FUNCTION
clone - clone an object from a program

SYNTAX
object clone(program p,mixed ... args);

DESCRIPTION
clone() creates an object from the program p. Or in C++ terms: It creates an instance of the class p. This clone will first have all global variables initialized, and then create() will be called with args as arguments.

SEE ALSO
new, destruct, compile_string and compile_file

FUNCTION
column - extract a column

SYNTAX
array column(array data,mixed index)

DESCRIPTION
This function is exactly equivalent to:
map_array(data, lambda(mixed x,mixed y) { return x[y]; }, index)
Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.

EXAMPLE
	> column( ({ ({1,2}), ({3,4}), ({5,6}) }), 1)
	Result: ({2, 4, 6})

SEE ALSO
rows

FUNCTION
combine_path - concatenate paths

SYNTAX
string combine_path(string absolute, string relative);

DESCRIPTION
Concatenate a relative path to an absolute path and remove any "//", "/.." or "/." to produce a straightforward absolute path as a result.

EXAMPLE
> combine_path("/foo/bar/","..");
Result: /foo
> combine_path("/foo/bar/","../apa.c");
Result: /foo/apa.c
> combine_path("/foo/bar","./sune.c");
Result: /foo/bar/sune.c

SEE ALSO
getcwd and Stdio.append_path

FUNCTION
compile - compile a string to a program

SYNTAX
program compile(string program);

DESCRIPTION
compile takes a piece of Pike code as a string and compiles it into a clonable program. Note that prog must contain the complete source for a program. You can not compile a single expression or statement. Also note that compile does not preprocess the program. To preprocess the program you can use compile_string or call the preprocessor manually by calling cpp.

SEE ALSO
clone, compile_string, compile_file and cpp

FUNCTION
compile_file - compile a file to a program

SYNTAX
program compile_file(string filename);

DESCRIPTION
This function will compile the file filename to a Pike program that can later be used for cloning. It is the same as doing compile_string(Stdio.read_file(filename),filename).

SEE ALSO
clone and compile_string

FUNCTION
compile_string - compile a string to a program

SYNTAX
program compile_string(string prog, string name);

DESCRIPTION
Equal to compile(cpp(prog, name));

SEE ALSO
compile_string and clone

FUNCTION
copy_value - copy a value recursively

SYNTAX
mixed copy_value(mixed value);

DESCRIPTION
Copy value will copy the value given to it recursively. If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed. The resulting value will always be equal to the copied (tested with the efun equal), but they may not the the same value. (tested with ==)

SEE ALSO
equal

FUNCTION
cos - trigonometrical cosine

SYNTAX
float cos(float f);

DESCRIPTION
Returns the cosine value for f.

SEE ALSO
acos and sin

FUNCTION
cpp - run the preprocessor on a string

SYNTAX
string cpp ( string source, string filename);

DESCRIPTION
This function runs the Pike preprocessor on a string. The second argument filename will be used for inserting #line statements into the result.

SEE ALSO
compile, compile_string and compile_file

FUNCTION
crypt - crypt a password

SYNTAX
string crypt(string password);
int crypt(string typed_password, string crypted_password);

DESCRIPTION
This function crypts and verifies a short string. (normally only the first 8 characters are significant) The first syntax crypts the string password into something that is hopefully hard to decrypt, and the second function crypts the first string and verifies that the crypted result matches the second argument and returns 1 if they matched, 0 otherwise.

EXAMPLE
To crypt a password use:
crypted_password = crypt(typed_password);
To see if the same password was used again use:
matched = crypt(typed_password, crypted_password);

FUNCTION
ctime - convert time int to readable date string

SYNTAX
string ctime(int current_time);

DESCRIPTION
Convert the output from a previous call to time() into a readable string containing the current year, month, day and time.

EXAMPLE
> ctime(time());
Result: Wed Jan 14 03:36:08 1970

SEE ALSO
time, localtime, mktime and gmtime

FUNCTION
decode_value - decode a value from a string

SYNTAX
mixed decode_value(string coded_value);

DESCRIPTION
This function takes a string created with encode_value() or encode_value_canonic() and converts it back to the value that was coded.

SEE ALSO
encode_value and encode_value_canonic

FUNCTION
describe_backtrace - make a backtrace readable

SYNTAX
string describe_backtrace(array(array) backtrace);

DESCRIPTION
Returns a string containing a readable message that describes where the backtrace was made. The argument 'backtrace' should normally be the return value from a call to backtrace()

SEE ALSO
backtrace and describe_error

FUNCTION
describe_error - get the error message from a backtrace

SYNTAX
string describe_error(array(array) backtrace);

DESCRIPTION
Returns only the error message in a backtrace. If there is no message in it, a fallback message is returned.

SEE ALSO
backtrace and describe_backtrace

FUNCTION
destruct - destruct an object

SYNTAX
void destruct(object o);

DESCRIPTION
Destruct marks an object as destructed, all pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible. This will also call o->destroy.

SEE ALSO
clone

FUNCTION
dirname - find the directory part of a path

SYNTAX
string dirname(string path);

DESCRIPTION
This function returns the directory part of a path. For example, the directory part of "/home/hubbe/bin/pike" would be "/home/hubbe/bin".

SEE ALSO
basename and explode_path

FUNCTION
encode_value - code a value into a string

SYNTAX
string encode_value(mixed value);

DESCRIPTION
This function takes a value, and converts it to a string. This string can then be saved, sent to another Pike process, packed or used in any way you like. When you want your value back you simply send this string to decode_value() and it will return the value you encoded.

Almost any value can be coded, mappings, floats, arrays, circular structures etc. At present, objects, programs and functions cannot be saved in this way. This is being worked on.

SEE ALSO
decode_value, sprintf and encode_value_canonic

FUNCTION
encode_value_canonic - code a value into a string on canonical form

SYNTAX
string encode_value_canonic(mixed value)

DESCRIPTION
Takes a value and converts it to a string on canonical form, much like encode_value(). The canonical form means that if an identical value is encoded, it will produce exactly the same string again, even if it's done at a later time and/or in another Pike process. The produced string is compatible with decode_value().

Note that this function is more restrictive than encode_value() with respect to the types of values it can encode. It will throw an error if it can't encode to a canonical form.

SEE ALSO
encode_value and decode_value

FUNCTION
enumerate - create an array with an enumeration

SYNTAX
array(int) enumerate(int n);
array enumerate(int n,void|mixed step,void|mixed start,void|function operator);

DESCRIPTION
Create an enumeration, useful for initializing arrays or as first argument to map or foreach.

For instance, enumerate(4) gives ({0,1,2,3}).

Advanced use: the resulting array is caluculated like this:

array enumerate(int n,mixed step,mixed start,function operator)
{
   array res=({});
   for (int i=0; i<n; i++)
   {
      res+=({start});
      start=operator(start,step);
   }
   return res;
}

The default values is step=1, start=0, operator=add.

SEE ALSO
map and foreach

FUNCTION
equal - check if two values are equal or not

SYNTAX
int equal(mixed a, mixed b);

DESCRIPTION
This function checks if the values a and b are equal. For all types but arrays, multisets and mappings, this operation is the same as doing a == b. For arrays, mappings and multisets however, their contents are checked recursively, and if all their contents are the same and in the same place, they are considered equal.

EXAMPLE
> ({ 1 }) == ({ 1 });
Result: 0
> equal( ({ 1 }), ({ 1 }) );
Result: 1
>

SEE ALSO
copy_value

FUNCTION
errno - return system error number

SYNTAX
int errno();

DESCRIPTION
This function returns the system error from the last file operation. Note that you should normally use the function errno in the file object instead.

SEE ALSO
Stdio.File->errno and strerror

FUNCTION
exece

SYNTAX
int exece(string file, array(string) args);
int exece(string file, array(string) args, mapping(string:string) env);

DESCRIPTION
This function transforms the Pike process into a process running the program specified in the argument 'file' with the argument 'args'. If the mapping 'env' is present, it will completely replace all environment variables before the new program is executed. This function only returns if something went wrong during exece(), and in that case it returns zero.

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.

EXAMPLE
exece("/bin/ls", ({"-l"}));
exece("/bin/sh", ({"-c", "echo $HOME"}), (["HOME":"/not/home"]));

SEE ALSO
fork and Stdio.File->pipe

FUNCTION
explode_path - Split a path into components

SYNTAX
array(string) explode_path(string path);

DESCRIPTION
This function divides a path into its components. This might seem like it could be done by dividing the string on "/", but that would not work on other operating systems.

EXAMPLE
> explode_path("/home/hubbe/bin/pike"); Result: ({ "home", "hubbe", "bin", "pike" })

FUNCTION
exit - exit Pike interpreter

SYNTAX
void exit(int returncode);

DESCRIPTION
This function exits the whole Pike program with the return code given. Using exit() with any other value than 0 indicates that something went wrong during execution. See your system manuals for more information about return codes.

FUNCTION
exp - natural exponent

SYNTAX
float exp(float f);

DESCRIPTION
Return the natural exponent of f.

SEE ALSO
pow and log

FUNCTION
file_stat - stat a file

SYNTAX
array(int) file_stat(string file);
array(int) file_stat(string file, 1);
array(int) file->stat();

DESCRIPTION
file_stat returns an array of integers describing some properties
about the file. Currently file_stat returns 7 entries:
({
   int mode  [0] file mode, protection bits etc. etc. 
   int size  [1] file size for regular files, 
                   -2 for dirs,
                   -3 for links,
                   -4 for otherwise 
   int atime [2] last access time 
   int mtime [3] last modify time 
   int ctime [4] last status time change 
   int uid   [5] The user who owns this file
   int gid   [6] The group this file belongs to
})
If you give 1 as a second argument, file_stat does not follow links.
You can never get -3 as size if you don't give a second argument.

If there is no such file or directory, zero is returned.

SEE ALSO
get_dir

FUNCTION
file_truncate - truncate a file

SYNTAX
int file_truncate(string file,int length);

DESCRIPTION
Truncates a file to that length. Returns 1 if ok, 0 if failed.

FUNCTION
filter - map a function over elements and filter

SYNTAX
array filter(array arr,function fun,mixed ...extra);
mixed filter(mixed arr,void|mixed fun,void|mixed ...extra);

DESCRIPTION
Calls the given function for all elements in arr, and keeps the elements in arr that resulted in a non-zero value from the function.
arr result
array keep=map(arr,fun,@extra); for (i=0; i<sizeof(arr); i++)    if (keep[i]) res+=({arr[i]});
multiset (multiset)filter((array)arr,fun,@extra);
mapping |
program |
function
 ind=indices(arr),val=values(arr);
keep=map(val,fun,@extra);
for (i=0; i<sizeof(keep); i++)
   if (keep[i]) res[ind[i]]=val[i];
string (string)filter( (array)arr,fun,@extra );
object if arr->cast :
   try filter((array)arr,fun,@extra);
   try filter((mapping)arr,fun,@extra);
   try filter((multiset)arr,fun,@extra);

RETURNS
the same datatype as given, the exception are program and function that gives a mapping back

SEE ALSO
map and foreach

FUNCTION
find_call_out - find a call out in the queue

SYNTAX
int find_call_out(function f);
int find_call_out(mixed id);

DESCRIPTION
This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function. The argument can also be a call out id as returned by call_out, in which case that call_out will be found. (Unless it has already been called.) find_call_out will then return how many seconds remains before that call will be executed. If no call is found, zero_type(find_call_out(f)) will return 1.

SEE ALSO
call_out, remove_call_out and call_out_info

FUNCTION
floatp - is the argument a float?

SYNTAX
int floatp(mixed arg);

DESCRIPTION
Returns 1 if arg is a float, zero otherwise.

SEE ALSO
intp, programp, arrayp, stringp, objectp, mappingp, multisetp and functionp

FUNCTION
floor - truncate a number downward

SYNTAX
float floor(float f);

DESCRIPTION
Return the closest integer value lower or equal to f.

NOTE
floor() does not return an int, merely an integer value stored in a float.

SEE ALSO
ceil and round

FUNCTION
fork - fork the process in two

SYNTAX
int fork();

DESCRIPTION
Fork splits the process in two, and for the parent it returns the pid of the child. Refer to your Unix manual for further details.

NOTE
This function cause endless bugs if used without proper care.

Some operating systems have problems if this function is used together with threads.

SEE ALSO
Process.exec and Stdio.File->pipe

FUNCTION
function_name - return the name of a function, if known

SYNTAX
string function_name(function f);

DESCRIPTION
This function returns the name of the function f. If the function is a pre-defined function in the driver, zero will be returned.

SEE ALSO
function_object and Simulate.get_function

FUNCTION
function_object - return what object a function is in

SYNTAX
object function_object(function f);

DESCRIPTION
Function_object will return the object the function f is in. If the function is a predefined function from the driver, zero will be returned.

SEE ALSO
function_name and Simulate.get_function

FUNCTION
functionp - is the argument a function?

SYNTAX
int functionp(mixed arg);

DESCRIPTION
Returns 1 if arg is a function, zero otherwise.

SEE ALSO
intp, programp, arrayp, stringp, objectp, mappingp, multisetp and floatp

FUNCTION
gc - do garbage collection

SYNTAX
int gc();

DESCRIPTION
This function checks all the memory for cyclic structures such as arrays containing themselves and frees them if appropriate. It also frees up destructed objects. It then returns how many arrays/objects/programs/etc. it managed to free by doing this. Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)

FUNCTION
get_dir - read a directory

SYNTAX
array(string) get_dir(string dirname);

DESCRIPTION
Returns an array of all filenames in the directory dirname, or zero if no such directory exists.

SEE ALSO
mkdir and cd

FUNCTION
get_profiling_info - get profiling information

SYNTAX
array(int|mapping(string:array(int))) get_profiling_info(program prog);

DESCRIPTION
Returns an array with two elements, the first of which is the number of times the program prog has been cloned.
The second element is a mapping(string:array(int)) from function name to an array(int) 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.

NOTE
This function is only available if Pike was compiled with the option '--with-profiling'.

FUNCTION
getcwd - return current working directory

SYNTAX
string getcwd();

DESCRIPTION
getcwd returns the current working directory.

SEE ALSO
cd

FUNCTION
getenv - get an environment variable

SYNTAX
string getenv(string varname);

DESCRIPTION
Returns the value of the environment variable with the name varname, if no such environment variable exists, zero is returned.

NOTE
This function is provided by master.pike.

FUNCTION
getpid - get the process id of this process

SYNTAX
int getpid();

DESCRIPTION
This returns the pid of this process. Useful for sending signals to yourself.

SEE ALSO
kill, fork and signal

FUNCTION
glob - match strings against globs

SYNTAX
int glob(string glob, string str); or
array(string) glob(string glob, array(string) arr);

DESCRIPTION
This function matches "globs". In a glob string a question sign matches any character and an asterisk matches any string. When given two strings as argument a true/false value is returned which reflects if the str matches glob. When given an array as second argument, an array containing all matching strings is returned.

SEE ALSO
sscanf and Regexp

FUNCTION
gmtime - break down time() into intelligible components

SYNTAX
mapping(string:int) gmtime(int time);

DESCRIPTION
This function works like localtime but the result is not adjusted for the local time zone.

SEE ALSO
localtime, time, ctime and mktime

FUNCTION
has_index - does the index exist?

SYNTAX
int has_index(string haystack, int index);
int has_index(array haystack, int index);
int has_index(mapping haystack, mixed index);

DESCRIPTION
Search for index in haystack. Returns 1 if index is in the index domain of haystack, or 0 if not found. The has_index function is equivalent (but sometimes faster) to:
search(indices(haystack), index) != -1

NOTE
A negative index in strings and arrays as recognized by the index operators `[] and `[]= is not considered a proper index by has_index.

SEE ALSO
has_value, indices, search, values and zero_type

FUNCTION
has_value - does the value exist?

SYNTAX
int has_value(string haystack, int value);
int has_value(array haystack, int value);
int has_value(mapping haystack, mixed value);

DESCRIPTION
Search for value in haystack. Returns 1 if value is in the value domain of haystack, or 0 if not found. The has_value function is in all cases except for strings equivalent (but sometimes faster) to:
search(values(haystack), value) != -1
For strings, has_value is equivalent to:
search(haystack, value) != -1

SEE ALSO
has_index, indices, search, values and zero_type

FUNCTION
hash - hash a string

SYNTAX
int hash(string s);
int hash(string s, int max);

DESCRIPTION
This function will return an int derived from the string s. The same string will always hash to the same value. If a second argument is given, the result will be >= 0 and lesser than that argument.

FUNCTION
indices - return an array of all index possible for a value

SYNTAX
array indices(string|array|mapping|multiset|object foo);

DESCRIPTION
indices returns an array of all values you can use as index when indexing foo. For strings and arrays this is simply an array of the ascending numbers. For mappings and multisets, the array may contain any kind of value. For objects, the result is an array of strings.

SEE ALSO
values

FUNCTION
is_absolute_path - Is the given pathname relative or not?

SYNTAX
int is_absolute_path(string path);

DESCRIPTION
Returns 1 if path is an absolute path, 0 otherwise.

FUNCTION
intp - is the argument an int?

SYNTAX
array intp(mixed arg);

DESCRIPTION
Returns 1 if arg is an int, zero otherwise.

SEE ALSO
arrayp, programp, floatp, stringp, objectp, mappingp, multisetp and functionp

FUNCTION
kill - send signal to other process

SYNTAX
int kill(int pid, int signal);

DESCRIPTION
Kill sends a signal to another process. If something goes wrong -1 is returned, 0 otherwise.

Some signals and their supposed purpose:

SIGHUP Hang-up, sent to process when user logs out
SIGINT Interrupt, normally sent by ctrl-c
SIGQUIT Quit, sent by ctrl-\
SIGILL Illegal instruction
SIGTRAP Trap, mostly used by debuggers
SIGABRT Aborts process, can be caught, used by Pike whenever something goes seriously wrong.
SIGBUS Bus error
SIGFPE Floating point error (such as division by zero)
SIGKILL Really kill a process, cannot be caught
SIGUSR1 Signal reserved for whatever you want to use it for.
SIGSEGV Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike.
SIGUSR2 Signal reserved for whatever you want to use it for.
SIGALRM Signal used for timer interrupts.
SIGTERM Termination signal
SIGSTKFLT Stack fault
SIGCHLD Child process died
SIGCONT Continue suspended
SIGSTOP Stop process
SIGSTP Suspend process
SIGTTIN tty input for background process
SIGTTOU tty output for background process
SIGXCPU Out of CPU
SIGXFSZ File size limit exceeded
SIGPROF Profile trap
SIGWINCH Window change signal

Note that you have to use signame to translate the name of a signal to its number.

SEE ALSO
signal, signum, signame and fork

FUNCTION
load_module - load a binary module

SYNTAX
int load_module(string module_name);

DESCRIPTION
This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.

When a module is loaded the functions init_module_efuns and init_module_programs are called to initialize it. When Pike exits exit_module is called in all dynamically loaded modules. These functions _must_ be available in the module.

Please see the source and any examples available at ftp://www.idonex.se/pub/pike for more information on how to write modules for Pike in C.

BUGS
Please use "./name.so" instead of just "foo.so" for the module name. If you use just "foo.se" the module will not be found.

FUNCTION
localtime - break down time() into intelligible components

SYNTAX
mapping(string:int) localtime(int time);

DESCRIPTION
Given a time represented as second since 1970, as returned by the function time(), this function returns a mapping with the following components:
([
   "sec" : int(0..59)   seconds over the minute  
   "min" : int(0..59)   minutes over the hour    
   "hour" : int(0..59)  what hour in the day     
   "mday" : int(1..31)  day of the month         
   "mon" : int(0..11)   what month               
   "year" : int(0..)    years since 1900         
   "wday" : int(0..6)   day of week (0=Sunday)   
   "yday" : int(0..365) day of year              
   "isdst" : int(0..1)  is daylight saving time  
   "timezone" : int     difference between local time and UTC 
])

NOTE
The 'timezone' might not be available on all platforms.

SEE ALSO
Calendar, gmtime, time, ctime and mktime

FUNCTION
log - natural logarithm

SYNTAX
float log(float f);

DESCRIPTION
Return the natural logarithm of f.

SEE ALSO
pow and exp

FUNCTION
lower_case - convert a string to lower case

SYNTAX
string lower_case(string s);

DESCRIPTION
Returns a string with all capital letters converted to lower case.

SEE ALSO
upper_case

FUNCTION
map - map a function over elements

SYNTAX
array map(array arr,function fun,mixed ...extra);
mixed map(mixed arr,void|mixed fun,void|mixed ...extra);

DESCRIPTION
simple use: map() loops over all elements in arr and call the function fun with the element as first argument, with all "extra" arguments following. The result is the same datatype as "arr", but all elements is the result from the function call of the corresponding element.

advanced use is a wide combination of types given as "arr" or "fun".
arr fun result
array function |
program |
object |
array
 array ret; ret[i]=fun(arr[i],@extra);
array multiset |
mapping
 ret = rows(fun,arr)
array string array ret; ret[i]=arr[i][fun](@extra);
array void|int(0) array ret; ret=arr(@extra)
mapping | * mapping ret = mkmapping(indices(arr), map(values(arr),fun,@extra));
multiset * multiset ret = (multiset)(map(indices(arr),fun,@extra));
string * string ret = (string)map((array)arr,fun,@extra);
object * if arr->cast :
   try map((array)arr,fun,@extra);
   try map((mapping)arr,fun,@extra);
   try map((multiset)arr,fun,@extra);
if arr->_sizeof && arr->`[]
   array ret; ret[i]=arr[i];
   ret=map(ret,fun,@extra);

RETURNS
the same datatype as given, but with the subtype set to the return value of the function; the exception are program and function that gives a mapping back

SEE ALSO
filter, enumerate and foreach

NOTE
You may get unexpected errors if you feed the function with illegal values; for instance if fun is an array of non-callables.

FUNCTION
m_delete - remove an index from a mapping

SYNTAX
mixed m_delete(mapping map, mixed index);

DESCRIPTION
Removes the entry with index index from mapping map destructively. If the mapping does not have an entry with index index, nothing is done. Note that m_delete changes map destructively and only returns the mapping for compatibility reasons.

This function returns the value from the key-value pair that was removed from the mapping.

SEE ALSO
mappingp

FUNCTION
mappingp - is the argument a mapping?

SYNTAX
int mappingp(mixed arg);

DESCRIPTION
Returns 1 if arg is a mapping, zero otherwise.

SEE ALSO
intp, programp, arrayp, stringp, objectp, multisetp, floatp and functionp

FUNCTION
master - return the master object

SYNTAX
object master();

DESCRIPTION
Master is added by the master object to make it easier to access it.

FUNCTION
max - return the greatest value

SYNTAX
mixed max(mixed ...arg)

DESCRIPTION
Returns the greatest value of its args.

EXAMPLE
> man( 1,2,3 );
Result: 3

SEE ALSO
min

FUNCTION
min - return the smallest value

SYNTAX
mixed min(mixed ...arg)

DESCRIPTION
Returns the smallest value of its args.

EXAMPLE
> min( 1,2,3 );
Result: 1

SEE ALSO
max

FUNCTION
mkdir - make directory

SYNTAX
int mkdir(string dirname, void|int mode);

DESCRIPTION
Create a directory, return zero if it fails and nonzero if it successful. If a mode is given, it's used for the new directory after being &'ed with the current umask (on OS'es that supports this).

SEE ALSO
rm, cd and Stdio.mkdirhier

FUNCTION
mkmapping - make a mapping from two arrays

SYNTAX
mapping mkmapping(array ind, array val);

DESCRIPTION
Makes a mapping ind[x]:val[x], 0<=x<sizeof(ind). ind and val must have the same size. This is the inverse operation of indices and values.

SEE ALSO
indices and values

FUNCTION
mkmultiset - make a multiset

SYNTAX
multiset mkmultiset(array a);

DESCRIPTION
This function creates a multiset from an array.

EXAMPLE
> mkmultiset( ({1,2,3}) );
Result: (< /* 3 elements */
    1,
    2,
    3
>)

SEE ALSO
aggregate_multiset

FUNCTION
mktime - convert date and time to seconds

SYNTAX
int mktime(mapping tm)
int mktime(int sec, int min, int hour, int mday, int mon, int year, int isdst, int tz)

DESCRIPTION
This function converts information about date and time into an integer which contains the number of seconds since the beginning of 1970. You can either call this function with a mapping containing the following elements:

yearThe number of years since 1900
monThe month
mdayThe day of the month.
hourThe number of hours past midnight
minThe number of minutes after the hour
secThe number of seconds after the minute
isdstIf this is 1, daylight savings time is assumed
tmThe timezone (-12 <= tz <= 12)

Or you can just send them all on one line as the second syntax suggests.

SEE ALSO
time, ctime, localtime and gmtime

FUNCTION
multisetp - is the argument a multiset?

SYNTAX
int multisetp(mixed arg);

DESCRIPTION
Returns 1 if arg is a multiset, zero otherwise.

SEE ALSO
intp, programp, arrayp, stringp, objectp, mappingp, floatp and functionp

FUNCTION
mv - move a file (may handle directories as well)

SYNTAX
int mv(string from,string to);

DESCRIPTION
Rename or move a file between directories. If the destination file already exists, it will be overwritten. Returns 1 on success, 0 otherwise.

SEE ALSO
rm

FUNCTION
new - clone an object from a program

SYNTAX
object new(program p,mixed ... args);

DESCRIPTION
new() creates an object from the program p. Or in C++ terms: It creates an instance of the class p. This clone will first have all global variables initialized, and then create() will be called with args as arguments.

SEE ALSO
clone, destruct, compile_string and compile_file

FUNCTION
next_object - get next object

SYNTAX
object next_object(object o);
object next_object();

DESCRIPTION
All objects are stored in a linked list, next_object() returns the first object in this list, and next_object(o) the next object in the list after o.

EXAMPLE
/* This example calls shutting_down() in all cloned objects */
object o;
for(o=next_object();o;o=next_object(o))
o->shutting_down();

SEE ALSO
clone and destruct

NOTE
This function is not recommended to use.

FUNCTION
object_program - get the program associated with the object

SYNTAX
program object_program(object o);

DESCRIPTION
This function returns the program from which o was cloned. If o is not an object or has been destructed o zero is returned.

SEE ALSO
clone and new

FUNCTION
object_variablep - find out if an object identifier is a variable

SYNTAX
int object_variablep(object o, string var);

DESCRIPTION
This function return 1 if var exists is a non-static variable in o, zero otherwise.

SEE ALSO
indices and values

FUNCTION
objectp - the argument an object?

SYNTAX
int objectp(mixed arg);

DESCRIPTION
Returns 1 if arg is an object, zero otherwise.

SEE ALSO
intp, programp, floatp, stringp, arrayp, mappingp, multisetp and functionp

FUNCTION
pow - raise a number to the power of another

SYNTAX
float pow(float|int n, float|int x);

DESCRIPTION
Return n raised to the power of x.

SEE ALSO
exp and log

FUNCTION
programp - is the argument a program?

SYNTAX
int programp(mixed arg);

DESCRIPTION
Returns 1 if arg is a program, zero otherwise.

SEE ALSO
intp, multisetp, arrayp, stringp, objectp, mappingp, floatp and functionp

FUNCTION
putenv - put environment variable

SYNTAX
void putenv(string varname, string value);

DESCRIPTION
This function sets the environment variable varname to value.

SEE ALSO
getenv and exece

FUNCTION
query_host_name - return the name of the host we are running on

SYNTAX
string query_host_name();

DESCRIPTION
This function returns the name of the machine the interpreter is running on. This is the same thing that the command hostname prints.

FUNCTION
query_num_arg - find out how many arguments were given

SYNTAX
int query_num_arg();

DESCRIPTION
query_num_arg returns the number of arguments given when this function was called. This is only useful for varargs functions.

SEE ALSO
call_function

FUNCTION
random - return a random number

SYNTAX
int random(int max);

DESCRIPTION
This function returns a random number in the range 0 - max-1.

SEE ALSO
random_seed

FUNCTION
random_seed - seed random generator

SYNTAX
void random_seed(int seed);

DESCRIPTION
This function sets the initial value for the random generator.

EXAMPLE
Pike v1.0E-13 Running Hilfe v1.2 (Hubbe's Incremental Pike Front-End)
> random_seed(17);
Result: 0
> random(1000);
Result: 732
> random(1000);
Result: 178
> random(1000);
Result: 94
> random_seed(17);
Result: 0
> random(1000);
Result: 732
> random(1000);
Result: 178
> random(1000);
Result: 94
>

SEE ALSO
random

FUNCTION
remove_call_out - remove a call out from the call out queue

SYNTAX
int remove_call_out(function f);
int remove_call_out(function id);

DESCRIPTION
This function finds the first call to the function f in the call out queue and removes it. The time left to that call out will be returned. If no call out was found, zero_type(remove_call_out(f)) will return 1. You can also give a call out id as argument. (as returned by call_out)

SEE ALSO
call_out_info, call_out and find_call_out

FUNCTION
remove_include_path - remove a directory to search for include files

SYNTAX
void remove_include_path(string path);

DESCRIPTION
This function removes a directory from the list of directories to search for include files. It is the opposite of add_include_path.

SEE ALSO
add_include_path and #include

FUNCTION
remove_module_path - remove a directory to search for modules

SYNTAX
void remove_module_path(string path);

DESCRIPTION
This function removes a directory from the list of directories to search for modules. It is the opposite of add_module_path. For more information about modules, see chapter 8 "Modules".

SEE ALSO
add_module_path

FUNCTION
remove_program_path - remove a directory to search for modules

SYNTAX
void remove_program_path(string path);

DESCRIPTION
This function removes a directory from the list of directories to search for program. It is the opposite of add_program_path. For more information about programs, see section 4.2.4 "program".

SEE ALSO
add_program_path

FUNCTION
replace - generic replace function

SYNTAX
string replace(string s, string from, string to);
string replace(string s, array(string) from, array(string) to);
array replace(array a, mixed from, mixed to);
mapping replace(mapping a, mixed from, mixed to);

DESCRIPTION
This function can do several kinds replacement operations, the different syntaxes do different things as follow:
string replace(string s, string from, string to);
When given strings as second and third argument, a copy of s with every occurrence of 'from' replaced with 'to' is returned.
string replace(string s, array(string) from, array(string) to);
When given arrays of strings as second and third argument, every occurrence of from[0] in s is replaced by to[0], from[1] is replaced by to[1] and so on...
array replace(array a, mixed from, mixed to);
mapping replace(mapping a, mixed from, mixed to);
When the first argument is an array or mapping, the values in a are searched for values equal to from, which are replaced by to destructively.

FUNCTION
replace_master - replace the master object

SYNTAX
void replace_master(object o);

DESCRIPTION
This function replaces the master object with the argument you specify. This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is probably a good idea to have your master inherit the original master and only re-define certain functions.

FUNCTION
reverse - reverse a string, array or int

SYNTAX
string reverse(string s);
array reverse(array a);
int reverse(int i);

DESCRIPTION
This function reverses a string, char by char, an array, value by value or an int, bit by bit and returns the result. Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.

SEE ALSO
sscanf

FUNCTION
rint - round a number

SYNTAX
float rint(float f);

DESCRIPTION
This function is named round in Pike.

NOTE
This function does not exist! Use round!

SEE ALSO
round

FUNCTION
rm - remove file or directory

SYNTAX
int rm(string f);

DESCRIPTION
Remove a file or directory, return 0 if it fails. Nonzero otherwise.

SEE ALSO
mkdir and recursive_rm

FUNCTION
round - round a number

SYNTAX
float round(float f);

DESCRIPTION
Return the closest integer value to f.

NOTE
round() does not return an int, merely an integer value stored in a float.

SEE ALSO
floor and ceil

FUNCTION
rows - select a set of rows from an array

SYNTAX
array rows(mixed data, array index);

DESCRIPTION
This function is exactly equivalent to:

map_array(index,lambda(mixed x,mixed y) { return y[x]; },data)

Except of course it is a lot shorter and faster. That is, it indices data on every index in the array index and returns an array with the results.

SEE ALSO
column

FUNCTION
rusage - return resource usage

SYNTAX
array(int) rusage();

DESCRIPTION
This function returns an array of ints describing how much resources the interpreter process has used so far. This array will have at least 29 elements, of which those values not available on this system will be zero. The elements are as follows:

0: user time 1: system time 2: maxrss 3: idrss 4: isrss 5: minflt 6: minor page faults 7: major page faults 8: swaps 9: block input op. 10: block output op. 11: messages sent 12: messages received 13: signals received 14: voluntary context switches 15: involuntary context switches 16: sysc 17: ioch 18: rtime 19: ttime 20: tftime 21: dftime 22: kftime 23: ltime 24: slptime 25: wtime 26: stoptime 27: brksize 28: stksize

Don't ask me to explain these values, read your system manuals for more information. (Note that all values may not be present though)

SEE ALSO
time

FUNCTION
search - search for a value in a string, array or mapping

SYNTAX
int search(string haystack, string needle, [ int start ]);
int search(array haystack, mixed needle, [ int start ]);
mixed search(mapping haystack, mixed needle, [ mixed start ]);

DESCRIPTION
Search for needle in haystack. Return the position of needle in haystack or -1 if not found. If the optional argument start is present search is started at this position. Note that when haystack is a string needle must be a string, and the first occurrence of this string is returned. However, when haystack is an array, needle is compared only to one value at a time in haystack.

When the haystack is a mapping, search tries to find the index connected to the data needle. That is, it tries to lookup the mapping backwards. If needle isn't present in the mapping, zero is returned, and zero_type() will return 1 for this zero.

SEE ALSO
indices, values and zero_type

FUNCTION
sgn - check the sign of a value

SYNTAX
int sgn(mixed value);
int sgn(mixed value, mixed base);

DESCRIPTION
This function returns -1 if value is less than zero, 1 if value is greater than zero and 0 otherwise. If base is given, -1 is returned if value is lesser than base, 1 if value is greater than base and 0 otherwise.

SEE ALSO
abs

FUNCTION
signal - trap signals

SYNTAX
void signal(int sig, function(int:void) callback);
void signal(int sig);

DESCRIPTION
This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc. I advice you not to. Pike should not receive any such signals and if it does it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.

The callback will receive the signal number as the only argument. See the document for the function 'kill' for a list of signals.

If no second argument is given, the signal handler for that signal is restored to the default handler.

If the second argument is zero, the signal will be completely ignored.

SEE ALSO
kill, signame and signum

FUNCTION
signame - get the name of a signal

SYNTAX
string signame(int sig);

DESCRIPTION
Returns a string describing the signal.

EXAMPLE
> signame(9);
Result: SIGKILL

SEE ALSO
kill, signum and signal

FUNCTION
signum - get a signal number given a descriptive string

SYNTAX
int signum(string sig);

DESCRIPTION
This function is the opposite of signame.

EXAMPLE
> signum("SIGKILL");
Result: 9

SEE ALSO
signame, kill and signal

FUNCTION
sin - trigonometrical sine

SYNTAX
float sin(float f);

DESCRIPTION
Returns the sinus value for f.

SEE ALSO
asin and cos

FUNCTION
sizeof - return the size of an array, string, multiset or mapping

SYNTAX
int sizeof(string|multiset|mapping|array|object a);

DESCRIPTION
This function returns the number of indices available in the argument given to it. It replaces older functions like strlen, m_sizeof and size.

FUNCTION
sleep - let interpreter doze off for a while

SYNTAX
void sleep(float|int s, int|void foo);

DESCRIPTION
This function makes the program stop for s seconds. Only signal handlers can interrupt the sleep. Other callbacks are not called during sleep.

SEE ALSO
signal

FUNCTION
sort - sort an array destructively

SYNTAX
array sort(array(mixed) index, array(mixed) ... data);

DESCRIPTION
This function sorts the array 'index' destructively. That means that the array itself is changed and returned, no copy is created. If extra arguments are given, they are supposed to be arrays of the same size. Each of these arrays will be modified in the same way as 'index'. 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.

Sort can sort strings, integers and floats in ascending order. Arrays will be sorted first on the first element of each array.

Sort returns its first argument.

SEE ALSO
reverse

FUNCTION
sprintf - print the result from sprintf

SYNTAX
string sprintf(string format,mixed arg,....);

DESCRIPTION
The format string is a string containing a description of how to output the data in the rest of the arguments. This string should generally speaking have one %<modifiers><operator> (examples: %s, %0d, %-=20s) for each of the rest arguments.

Modifiers:

0 Zero pad numbers (implies right justification)
! Toggle truncation
' ' (space) pad positive integers with a space
+ pad positive integers with a plus sign
- left adjusted within field size (default is right)
| centered within field size
= column mode if strings are greater than field size
/ Rough line break (break at exactly field size instead of between words)
# table mode, print a list of '\n' separated word (top-to-bottom order)
$ Inverse table mode (left-to-right order)
n (where n is a number or *) a number specifies field size
.n set precision
:n set field size & precision
;n Set column width
* if n is a * then next argument is used for precision/field size
'X' Set a pad string. ' cannot be a part of the pad_string (yet)
~ Get pad string from argument list.
< Use same arg again
^ repeat this on every line produced
@ do this format for each entry in argument array
> Put the string at the bottom end of column instead of top
_ Set width to the length of data

Operators:

%% percent
%b signed binary int
%d signed decimal int
%o signed octal int
%x lowercase signed hexadecimal int
%X uppercase signed hexadecimal int
%c char (or short with %2c, %3c gives 3 bytes etc.)
%f float
%g heuristically chosen representation of float
%G like %g, but uses uppercase E for exponent
%e exponential notation float
%E like %e, but uses uppercase E for exponent
%F binary IEEE representation of float (%4F gives single precision, %8F gives double precision.)
%s string
%O any type (debug style)
%n nop
%t type of argument
%<modifiers>{format%} do a format for every index in an array.

EXAMPLE
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));
fish: A
Result: 8
> write(sprintf("num: %d\n", 10));
num: 10
Result: 8
> write(sprintf("num: %+10d\n", 10));
num:        +10
Result: 16
> write(sprintf("num: %010d\n", 5*2));
num: 0000000010
Result: 16
> write(sprintf("num: %|10d\n", 20/2));
num:     10    
Result: 16
> write(sprintf("%|*s\n",screen_width,"THE NOT END"));
                             THE NOT END                              
Result: 71
> write(sprintf("%|=*s\n",screen_width, "fun with penguins\n"));
                          fun with penguins                           
Result: 71
> write(sprintf("%-=*O\n",screen_width,({ "fish", 9, "gumbies", 2 })));
({ /* 4 elements */                                                   
    "fish",                                                           
    9,                                                                
    "gumbies",                                                        
    2                                                                 
})                                                                    
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"));
This will wordwrap the specified string within the specified field    
size, this is useful say, if you let users specify their screen size, 
then the room descriptions will automagically word-wrap as            
appropriate.                                                          
slosh-n's will of course force a new-line when needed.                
Result: 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.")); 
Two columns next to each other (any The - is to specify justification,
number of columns will of course    this is in adherence to std       
work) independently word-wrapped,   sprintf which defaults to         
can be useful.                      right-justification, this version 
                                    also supports center and right    
                                    justification.                    
Result: 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."));
Given a          list of          slosh-n          
separated        'words',         this option      
creates a        table out        of them          
the number of    columns          be forced        
by specifying a  precision.       The most obvious 
use is for       formatted        ls output.       
Result: 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));
This will apply the format strings between the
procent-braces to all elements in the array:
gurksallad: bing
gurksallad: womble
gurksallad: wuff
gurksallad: gul
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));
Of course all the simple printf options are supported:
 65 as decimal, hex, octal and a char: 65 41 101 A
Result: 106
> write(sprintf("%|*s\n",screen_width, "THE END"));
                               THE END                                
Result: 71
> quit
Exiting.

SEE ALSO
sscanf

FUNCTION
sqrt - square root

SYNTAX
float sqrt(float f);
int sqrt(int i);

DESCRIPTION
Returns the square root of f, or in the second case, the square root truncated to the closest lower integer.

SEE ALSO
pow, log, exp and floor

FUNCTION
strerror - return a string describing an error

SYNTAX
string strerror(int errno);

DESCRIPTION
This function returns a description of an error code. The error code is usually obtained from the file->errno() call.

NOTE
This function may not be available on all platforms.

FUNCTION
stringp - is the argument a string?

SYNTAX
int stringp(mixed arg);

DESCRIPTION
Returns 1 if arg is a string, zero otherwise.

SEE ALSO
intp, multisetp, arrayp, programp, objectp, mappingp, floatp and functionp

FUNCTION
string_to_unicode - convert a string to an UTF16 stream

SYNTAX
string string_to_unicode(string s);

DESCRIPTION
Converts a string into an UTF16 compiant byte-stream.

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.

Characters in range 0x010000 - 0x10ffff are encoded using surrogates.

SEE ALSO
Locale.Charset.decode, string_to_utf8, unicode_to_string and utf8_to_string

FUNCTION
string_to_utf8 - convert a string to an UTF8 stream

SYNTAX
string string_to_utf8(string s); string string_to_utf8(string s, int extended);

DESCRIPTION
Converts a string into an UTF8 compilant byte-stream.

Throws an error if characters not valid in an UTF8 stream are encountered. Valid characters are in the range 0x00000000 - 0x7fffffff.

If extended is 1, characters in the range 0x80000000-0xfffffffff will also be accepted, and encoded using a non-standard UTF8 extension.

SEE ALSO
Locale.Charset.decode, string_to_unicode, unicode_to_string and utf8_to_string

FUNCTION
strlen - return the length of a string

SYNTAX
int strlen(string s);

DESCRIPTION
This function is equal to sizeof.

SEE ALSO
sizeof

FUNCTION
tan - trigonometrical tangent

SYNTAX
float tan(float f);

DESCRIPTION
Returns the tangent value for f.

SEE ALSO
atan, sin and cos

FUNCTION
this_object - return the object we are evaluating in currently

SYNTAX
object this_object();

DESCRIPTION
This function returns the object we are currently evaluating in.

FUNCTION
throw - throw a value to catch or global error handling

SYNTAX
void throw(mixed value);

DESCRIPTION
This function throws a value to a waiting catch. If no catch is waiting global error handling will send the value to handle_error in the master object. If you throw an array with where the first index contains an error message and the second index is a backtrace, (the output from backtrace() that is) then it will be treated exactly like a real error by overlying functions.

SEE ALSO
catch

FUNCTION
time - return the current time

SYNTAX
int time();
int time(1);
float time(int t);

DESCRIPTION
This function returns the number of seconds since 1 Jan 1970. The function ctime() converts this integer to a readable string.

The second syntax does not call the system call time() as often, but is only updated in the backed. (when Pike code isn't running)

The third syntax can be used to measure time more preciely than one second. It return how many seconds has passed since t. The precision of this function varies from system to system.

SEE ALSO
ctime, localtime, mktime and gmtime

FUNCTION
trace - change debug trace level

SYNTAX
int trace(int t);

DESCRIPTION
This function affects the debug trace level. (also set by the -t command line option) The old level is returned. Trace level 1 or higher means that calls to Pike functions are printed to stderr, level 2 or higher means calls to builtin functions are printed, 3 means every opcode interpreted is printed, 4 means arguments to these opcodes are printed as well. See the command lines options for more information

FUNCTION
typeof - check return type of expression

SYNTAX
typeof ( expression );

DESCRIPTION
This is a not really a function even if it looks like it, it returns a human readable (almost) representation of the type that the expression would return without actually evaluating it. The representation is in the form of a string.

EXAMPLE
> typeof(`sizeof);
Result: function(object | mapping | array | multiset | string : int)
> typeof(sizeof(({})));
Result: int
>

FUNCTION
ualarm - set an alarm clock for delivery of a signal

SYNTAX
int ualarm(int useconds);

DESCRIPTION
ualarm arranges for a SIGALRM signal to be delivered to the process in useconds micro seconds.

If useconds is zero, no new alarm is scheduled.

In any event any previously set alarm is canceled.

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.

SEE ALSO
signal

FUNCTION
unicode_to_string - convert an UTF16 stream to a string

SYNTAX
string unicode_to_string(string s);

DESCRIPTION
Converts an UTF16 byte-stream into a string.

NOTE
This function does not decode surrogates.

SEE ALSO
Locale.Charset.decode, string_to_unicode, string_to_utf8 and utf8_to_string

FUNCTION
upper_case - convert a string to upper case

SYNTAX
string upper_case(string s);

DESCRIPTION
Returns a copy of the string s with all lower case character converted to upper case character.

SEE ALSO
lower_case

FUNCTION
utf8_to_string - convert an UTF8 stream to a string

SYNTAX
string utf8_to_string(string s); string utf8_to_string(string s, int extended);

DESCRIPTION
Converts an UTF8 byte-stream into a string.

Throws an error if the stream is not a legal UFT8 byte-stream.

Accepts and decodes the extension used by string_to_utf8(), if extended is 1.

SEE ALSO
Locale.Charset.decode, string_to_unicode, string_to_utf8 and unicode_to_string

FUNCTION
values - return an array of all possible values from indexing

SYNTAX
array values(string|multiset|mapping|array|object foo);

DESCRIPTION
Values return an array of all values you can get when indexing the value foo. For strings, an array of int with the ascii values of the characters in the string is returned. For a multiset, an array filled with ones is return. For mappings, objects and arrays, the returned array may contain any kind of value.

SEE ALSO
indices

FUNCTION
version - return version info

SYNTAX
string version();

DESCRIPTION
This function returns a brief information about the Pike version.

EXAMPLE
> version();
Result: "Pike v0.7 release 1"

FUNCTION
write - write text to stdout

SYNTAX
int write(string text);

DESCRIPTION
Added by the master, it directly calls write in a Stdio.stdout.

SEE ALSO
Stdio.werror

FUNCTION
zero_type - return the type of zero

SYNTAX
int zero_type(mixed a);

DESCRIPTION
There are many types of zeros out there, or at least there are two. One is returned by normal functions, and one returned by mapping lookups and find_call_out() when what you looked for wasn't there. The only way to separate these two kinds of zeros is zero_type. When doing a find_call_out or mapping lookup, zero_type on this value will return 1 if there was no such thing present in the mapping, or no such call_out could be found. If the argument to zero_type is a destructed object or a function in a destructed object, 2 will be returned. Otherwise zero_type will return zero.

If the argument is not an int, zero will be returned.

SEE ALSO
find_call_out

Previous chapter To contents Next chapter