Qore v0.8.0

Programming Language Reference Manual

David Nichols

Helmut Wollmersdorfer

v. 0.8.0

Revision History
Revision 3.018 November 2009dn
Update to 0.8.0
Revision 2.96 November 2009dn
Update to 0.7.7
Revision 2.813 July 2009dn
Update to 0.7.6
Revision 2.722 June 2009dn
Update to 0.7.5
Revision 2.64 April 2009dn
Update to 0.7.4
Revision 2.43 December 2008dn
Update to 0.7.2
Revision 2.26 November 2008dn
Update to 0.7.1
Revision 2.117 July 2008dn
Update to 0.7.0
Revision 2.02 March 2007dn
Update to 0.6.2
Revision 1.98 February 2007dn
Update to 0.6.1
Revision 1.819 January 2007dn
Update to 0.6.0
Revision 1.710 October 2006dn
Update to 0.5.3
Revision 1.615 September 2006dn
Update to 0.5.2
Revision 1.58 June 2006dn
Update to 0.5.1
Revision 1.47 May 2006dn
Update to 0.5.0, extensive updates, new content
Revision 1.330 Nov 2005dn
Update to 0.4.2
Revision 1.226 Oct 2005dn
Update to 0.4.0
Revision 1.114 Oct 2005hw
Converted to docbook.xml
Revision 1.02 Aug 2005hw
First release

Table of Contents

1. Introduction
1.1. Introduction to the Qore Programming Language
1.2. Document Conventions
2. Qore Language Description
2.1. Language Overview
2.2. Environment Variables
2.3. Qore Modules
2.4. Include Files
2.5. Identifiers
2.6. Comments
2.7. Variables
2.8. Basic Data Types
2.9. Container Data Types
2.10. Data Type Declarations
2.11. Time Zone Handling in Qore
2.12. Qore Strings and Character Encoding
2.13. Expressions
2.14. Operators
2.15. Regular Expressions in Qore
2.16. Date/Time Arithmetic
2.17. Statements
2.18. Subroutines
2.19. Namespaces
2.20. Constants
2.21. Classes
2.22. Threading
2.23. Exception Handling
2.24. XML Integration
2.25. Signal Handling
2.26. Event Handling
3. Function Library
3.1. Math Functions
3.2. Output Functions
3.3. Date and Time Functions
3.4. Qore Type Functions
3.5. Environment Functions
3.6. String Functions
3.7. Operating System Functions
3.8. Cryptographic Functions
3.9. Digest Functions
3.10. Filesystem Functions
3.11. Data Compression Functions
3.12. Miscellaneous Functions
3.13. Threading Functions
3.14. XML Functions
3.15. JSON Functions
3.16. Debug Functions
3.17. String Formatting
4. System Namespaces and Class Library
4.1. Qore Constants
4.2. Type Namespace
4.3. File Class
4.4. Dir Class
4.5. TermIOS Class
4.6. GetOpt Class
4.7. FtpClient Class
4.8. Program Class
4.9. Socket Class
4.10. HTTPClient Class
4.11. XmlRpcClient Class
4.12. JsonRpcClient Class
4.13. SSLPrivateKey Class
4.14. SSLCertificate Class
4.15. TimeZone Class
4.16. SQL Constants
4.17. SQL::Datasource Class
4.18. SQL::DatasourcePool Class
4.19. Thread::AbstractSmartLock Class
4.20. Thread::AutoGate Class
4.21. Thread::AutoLock Class
4.22. Thread::AutoReadLock Class
4.23. Thread::AutoWriteLock Class
4.24. Thread::Condition Class
4.25. Thread::Counter Class
4.26. Thread::Queue Class
4.27. Thread::RWLock Class
4.28. Thread::Mutex Class
4.29. Thread::RMutex Class
4.30. Thread::Sequence Class
4.31. Thread::Gate Class
4.32. Xml Namespace
4.33. Xml::XmlDoc Class
4.34. Xml::XmlNode Class
4.35. Xml::XmlReader Class
5. Command-Line Parsing
6. Parse Directives
6.1. disable-all-warnings
6.2. disable-warning
6.3. enable-all-warnings
6.4. enable-warning
6.5. exec-class
6.6. include
6.7. lock-options
6.8. lock-warnings
6.9. no-child-restrictions
6.10. no-class-defs
6.11. no-constant-defs
6.12. no-database
6.13. no-external-info
6.14. no-external-process
6.15. no-filesystem
6.16. no-global-vars
6.17. no-gui
6.18. no-locale-control
6.19. no-namespace-defs
6.20. no-network
6.21. no-new
6.22. no-process-control
6.23. no-subroutine-defs
6.24. no-terminal-io
6.25. no-thread-classes
6.26. no-thread-control
6.27. no-thread-info
6.28. no-threads
6.29. no-top-level
6.30. require-our
6.31. require-prototypes
6.32. require-types
6.33. requires
6.34. strict-args
7. Warnings
8. Appendix A: List of Keywords
9. Appendix B: Known Bugs
10. Appendix D: Future Development

Chapter 1. Introduction

1.1. Introduction to the Qore Programming Language

The Qore programming language is a powerful, thread-capable, embeddable weakly-typed language with optional strong typing and procedural and object-oriented features designed for anything from quick scripting to complex multithreaded, network-aware application development to embedded application scripting. Qore was initially designed to facilitate the rapid implementation of sophisticated interfaces in embedded code in an enterprise environment, and has since grown into a general-purpose language as well.

Qore exports a C++ API to allow programs or libraries to embed Qore code; this manual documents Qore's user-level features, for more information about Qore's C++ API, see the Qore's home page.

Qore features database, XML, and JSON integration into the syntax, functions, data structures, and operators of the language.

Flexible character encoding support is also built-in to Qore strings, and automatic character encoding conversions are supported, enabling correct behavior when working in an environment with mixed character encoding requirements (see Qore Strings and Character Encoding).

Qore includes the following design points:

  • Support for Embedded Logic

    Qore was designed to support embedding logic in applications; this also applies to applications written in Qore as well as applications using the Qore library's public C++ API. By using the Program class, discrete objects can be created and destroyed at will containing embedded code to extend or modify the behavior of your application in user-defined ways. The Program class allows the capabilities of embedded code to be arbitrarily restricted as well.

  • Thread Safety and SMP Scalability

    All elements of Qore are thread-safe, and the language in general has been designed with SMP scalability in mind. The internal design and implementation of Qore favors multithreaded performance over single-threaded performance, so multithreaded Qore programs can count on an efficient and stable execution platform, and do not have to limit themselves to a subset of Qore's functionality (see Threading). Additionally, Qore includes optimizations designed to reduce the number of SMP cache invalidations that provide a substantial performance boost on SMP machines.

    Qore supports deadlock detection in complex locking scenarios and will throw an exception rather than allow an operation to be performed that would cause a deadlock. Furthermore, Qore's threading primitives detect threading errors and throw exceptions in these cases as well.

  • Database Integration and DBI Layer

    Retrieving, comparing, and manipulating data in a consistent manner from heterogenous database types is made possible by Qore's built-in database integration. Qore was designed with a database independent interfacing (DBI) layer, providing a standard interface for Qore programs to access any database supported by a Qore DBI driver (see the Datasource Class).

  • XML and JSON Integration

    Qore uses the libxml2 library to provide fast and efficient XML functionality. Qore's XML integration enables serialization from Qore data structures to XML strings and deserialization from XML strings to Qore data structures, making it trivial to work with data in XML format (see XML Integration). Qore provides JSON and JSON-RPC integration as well. There is also a module providing YAML serialization and deserialization support.

  • Function and Class Library

    Qore's basic functionality covers areas such as: POSIX-compliant command-line parsing (ex: GetOpt Class), XML and JSON serialization/deserialization, strong encryption and digest calculation, thread synchronization (ex: Queue Class, Mutex Class, Condition Class, etc), working with files (File class), socket, HTTP, and higher-level protocol communication (Socket, HTTPClient, XmlRpcClient, JsonRpcClient, FtpClient classes, optionally with TLS/SSL encryption), support for dynamic embedded application logic (Program Class). Additionally, Qore's functionality is extended with modules delivered separately from the Qore library (see Qore's home page for more information.

  • Logical Syntax

    Qore syntax is similar to other programming languages, allowing new programmers to rapidly come up to speed in Qore. Qore borrows features from languages such as: C++ (ex: multiple inheritance, exception handling, static methods), Java (ex: the synchronized keyword, the instanceof operator, object and class implementation), Perl (ex: the foreach statement, splice, push, pop, chomp, splice operators, perl5-compatible regular expressions, and more), the D Programming Language (the on_exit, on_success, and on_error statements provide exception-aware functionality similar to scope(exit), scope(failure), allowing exception-aware cleanup code to be placed next to the code requiring cleanup), and others, also with many features unique to Qore. Furthermore, Qore supports closures (including binding local variables in the closure in a way that is safe to use even in multithreaded contexts) and features for advanced list processing (map, foldl, foldr, and select).

    Qore's operators are designed to produce the expected results for the programmer even when data types are mixed, a feature meant to further flatten the learning curve for new programmers.

Simple or complex interfaces involving data extraction and manipulation from multiple Oracle, MySQL, PostgreSQL and other databases and/or multiple applications connected with a supported messaging bus or through lightweight web service protocols bus can be developed quickly and easily with Qore, particularly in comparison with Java, Perl, or C/C++. Furthermore, solutions based on Qore are transparent and easily maintainable, bringing advantages for the developer and end-user alike.

Additionally, Qore is thoroughly tested with valgrind on Linux and dbx on Solaris for memory leaks and memory errors. While it is possible that there are bugs in some less tested code paths, every effort is made to eliminate all bugs before each new release, particularly memory bugs and race conditions, in order to ensure that Qore releases are of the highest possible quality.

1.2. Document Conventions

Examples of Qore code are given in the following font:

#!/usr/bin/qore
#
# this is an example of Qore code

keywords are given in bold:

# "if" is a key word
if ($a == 1) print("yes\n");

placeholders are given in italics:

if ( expression ) 
    statement

where expressions and statements are defined in this document. The text above indicates that any valid expression and any valid statement may be used in the positions indicated.

Optional text is given in square brackets "[" and "]" as follows:

sub name([$variable1, $variable2, ...])

indicating that an arbitrarily long list of variable names separated by commas (or nothing at all) may appear in subroutine (function) declarations.

Chapter 2. Qore Language Description

2.1. Language Overview

A Qore program is composed of a series of declarations, statements, subroutine definitions, and/or class definitions. Non-block statements are terminated by a semi-colon ";". Block statements are grouped by using curly brackets ("{" and "}"), as in C, C++, Java, and Perl.

Programmers familiar with C, C++, Java, and/or Perl should find the standard Qore syntax intuitive and should be productive fairly quickly with the language. However Qore has unique features that differentiate it from other languages, and these features must be mastered in order to leverage the full power of Qore.

Qore programs/scripts are free form. Formatting does not affect the execution of the program; formatting is at the discretion of the programmer and should be used to enhance readability and clarity of the source code.

Qore was creaetd as a weakly typed language. That means that variables without type restructions can hold values of any type and subroutines with out type restrictions can return any value type (or none at all, see Variables) and take arguments of any type. Furthermore list elements can be of any type (they do not have to be uniform), and multidimensional lists can have a different number of elements in each list. The same type flexibility holds true of hashes, objects, and all combinations of container types.

Qore can be used a a traditional subroutine-based scripting language or as a pure object-oriented language, where the application is defined as a class. Aside from traditional local and global variables, constants, and subroutines, Qore also supports nested namespaces, classes, multiple inheritance, overriding base class constructor arguments, private members and methods, and static class methods.

All elements of Qore are designed to work together seamlessly: database access, XML transformations, socket communication, embedding logic in subprograms, regular expressions, operators, functions, and all other elements are thread-safe and built on an execution engine that was designed for SMP scalability.

Qore automatically converts data types when necessary when evaluating operators. The goal is to provide the expected result for the programmer without requiring the programmer to explicitly convert data types. Please see Operators for more information.

Qore supports signal handling by dispatching Qore-language signal handlers in a safe manner, asynchronously to the actual receipt of the signal.

UNIX operating systems allow an executable script to specify their interpreter. This is done by setting the first line in the program to a special string indicating the location of the Qore binary. For the purposes of this document, the location for the Qore binary is assumed to be /usr/bin/qore. The first line of Qore scripts in this case should look as follows:

#!/usr/bin/qore

If another installation directory is used (such as /usr/local/bin), then the correct path must be reflected in the first line of the Qore script.

Qore convention dictates that Qore script file names end with .q.

2.2. Environment Variables

This section will outline the environment variables that are used by Qore.

Table 2.1. Qore Environment Variables

Environment Variable

Description

QORE_AUTO_MODULE_DIR

This environment variable should contain a colon-separated list of directories which will be searched for Qore modules when Qore starts. If any modules are found, they are loaded automatically before any parsing starts.

QORE_MODULE_DIR

This environment variable should contain a colon-separated list of directories which will be searched when modules are loaded with the %requires parse directive

QORE_INCLUDE_DIR

This variable should be a colon-separated list of directories where the Qore binary should look for include files

QORE_CHARSET

If this variable is set, then the default character encoding name for the process will be the value of this variable. This variable takes precedence over the LANG variable, but can be overridden by the command line using option --charset (see Qore Strings and Character Encoding for more information on this option)

LANG

If this variable is set and includes a character encoding specification, then, if the QORE_CHARSET variable is not set (and no character encoding was specified on the command line), this character encoding will be the default for the process.


2.3. Qore Modules

Qore modules allow the Qore language to be extended at run-time. Qore modules must conform to the Qore Module API and have the file extension *.qmod. Qore modules normally depend on other shared libraries and therefore can only be loaded if the libraries they require are present on the system and can be found in the library path.

Please note that as of version 0.7.0, modules are no longer delivered with the Qore library. Modules must be downloaded separately; see Qore's home page for more information.

To load a module at parse time (normally required for most modules), use the %requires parse directive. If the named feature is not already present in Qore, Qore looks for a module with this name in the directories listed in the QORE_MODULE_DIR environment variable.

Use the load_module() function to load Qore modules at run-time; however, note that any module providing parse support (classes, constants, functions, etc) must be loaded at parse time using the %requires directive.

From Qore 0.7.1, you can specify a comparison operator (one of < <=, =, >=, or >) and version information after the module name as well. Version numbers are compared via integer comparisons of each element, where elements are separated by a '.'. If one of the versions does not have as many elements as another, the missing elements are assumed to be '0' (i.e. version "1.0" compared with version "1.0.1" will be exteneded to "1.0.0").

Also note that DBI drivers are loaded on demand by the Datasource and DatasourcePool classes.

At the time of writing this documentation, the following modules exist for Qore:

Table 2.2. Qore Modules

Module

Description

asn1

Provides ASN.1 functionality to Qore

xmlsec

Provides xmldsig and xmlenc functionality to Qore.

ssh2

Provides SSH2 and SFTP functionality to Qore.

tibrv

Provides TIBCO Rendezvous(R) (TIBCO, Inc) functionality to Qore.

tibae

Provides TIBCO ActiveEnterprise(TM) (TIBCO, Inc) functionality to Qore.

tuxedo

Provides Oracle (ex Bea) Tuxedo functionality to Qore.

mysql

Provides a MySQL DBI driver to Qore.

pgsql

Provides a PostgreSQL DBI driver to Qore.

sqlite3

Provides a SQLite3 DBI driver to Qore.

sybase

Provides a Sybase DBI driver to Qore.

freetds

Provides a FreeTDS-based DBI driver to Qore.

oracle

Provides an Oracle DBI driver to Qore.

db2

Provides an IBM DB2 driver to Qore.

glut

Provides GLUT functionality to Qore.

opengl

Provides an OpenGL API to Qore.

qt-core, qt-gui, qt-svn, qt-opengl

BLACKLISTED: old QT4 modules: please use the much more complete qt4 module. These old modules (never officially released) use a namespace management trick that does not work with qore 0.8.0+, so they will not load with newer versions of qore.

qt4

Provides Nokia (formerly Trolltech) QT4 APIs for GUI development in Qore.

ncurses

Provides curses APIs to Qore.

yaml

Provides YAML functionality to Qore.


2.4. Include Files

A Qore program can include other program code to be used and executed in the current program by using the %include directive. The %include directive must be the first text on the line, and the file name to include must follow. All text on the line after the %include directive will be used for the file name to include. The file name should not be quoted.

Here is an example:

#!/usr/bin/qore
%include /usr/qore/lib/functions.lib

After this, any variable, subroutine, namespace, constant, or object declared in the above file can be used by the Qore program.

The QORE_INCLUDE_DIR environment variable determines the search path for include files.

2.5. Identifiers

Qore identifiers must start with an alphabetic character, and then may contain any number of alphabetic, numeric, or "_" characters. There is no length limit on Qore identifiers.

All Qore identifiers are case-sensitive, therefore the identifier hello_there is not the same as Hello_There or HELLO_THERE.

The following are examples of valid Qore identifiers:

Table 2.3. Examples of Valid Qore Identifiers

Identifier

Description

i

Simple one-character identifier

foo21

Identifier with number

this_is_a_long_identifier

Long identifier with underline characters

Total_318

Identifier with underline and number

AVeryBigNumber

Mixed case identifier name

CAPS

Identifier in all capital letters


The following are invalid identifiers:

Table 2.4. Examples of Invalid Qore Identifiers

Identifier

Description

1a

Does not start with an alphabetic character

this-and-that

Contains "-" characters

Start#10

Contains "#" character


2.6. Comments

Comments are allowed in Qore scripts; line comments are preceded by a hash "#", and block comments are made C-style, ex:

# this is a line comment
/* 
   this is a block comment 
*/

For line comments, all text following a hash until the end-of-line character "\n" is considered a part of the comment.

For block comments, all text between the /* and */ is ignored by the parser.

Here is an example Qore script containing comments:

#!/usr/bin/qore
#
# these are line comments
# another line comment

/*
   --- this text is in block comments
   print("hello"); <- this won't get executed 
   --- because it's in the block comment
*/

2.7. Variables

Variables are Qore identifiers prefixed by a "$" sign, similar to Perl. The data type of variables does not have to be declared in advance, and variable types are assigned and changed automatically as appropriate in the context of the operations being performed on them or the values being assigned. Any Qore variable can hold any Qore data type including container types (lists, hashes, or objects).

A few variables are set by the Qore language during the execution of Qore programs. These are normal variables that can be reassigned to other values by the user if necessary.

Table 2.5. Special Qore Variables

Variable

Type

Data Type

Explanation

$argv

Local

List

automatically assigned local variable containing the list of subroutine or method arguments that were not assigned to parameter variables (see Subroutines and Implicit Arguments for supporting related information)

$ARGV

Global

List

script command-line arguments (use the GetOpt Class to parse command-line arguments)

$QORE_ARGV

Global

List

complete qore command-line arguments

$ENV

Global

Hash

UNIX program environment


Note

As of version 0.5.0, $STDERR and $STDOUT have been removed from Qore. Use the I/O constants stderr, stdout, and stdin constants of the File Class instead.

2.7.1. Variable Declarations and Lexical Scope

Variables not in a parameter list automatically have global scope unless the first reference is prefixed with my. Variable names in a parameter list are always local to their associated subroutine, method, or catch block. Global variables can be explicitly declared with our. The our keyword is required if the parse option PO_REQUIRE_OUR (-O or --require-our command-line option) is set for the parent program. See the section on Parse Options for more information.

Variables may be assigned any value unless restricted with a type declaration. If no type declaration is given, then the variable is assumed to be type any. Note that type declarations are required for all variables (and for function and method parameters and class members) when the PO_REQUIRE_TYPES parse option is set.

Note that variable types can only be declared when the my or our keywords are used; it is a syntax error to declare a variable's type without declaring its scope at the same time with one of these keywords.

Local variables are not shared between threads (local variables have a distinct value in each thread), however global variables are. See Threading (and in particular Threading and Variables) for more information.

For example (in the following script, the our keyword is optional):

#!/usr/bin/qore
#
# variable scoping example

our int $a = 1;                    # this is a global variable
our (string $b, any $c, hash $d);  # list of global variables

if ($a == 1) {
    my int $a = 2; 
    my (string $b, any $c);
    # $a, $b, and $c are local variables, 
    # the use of which will not affect the 
    # global variables of the same name
    print("local a = %d\n", $a); 
}

print("global a = %d\n", $a); 

The first print() statement will output:

local a = 2

The second print() statement will output:

global a = 1

2.8. Basic Data Types

The following are the basic data types in Qore (see Container Data Types for container data types):

Table 2.6. Basic data types

Type

Description

Example

Default Value

Boolean

True or False value

True

False

String

A sequence of characters

"string"

Empty string

Integer

A 64-bit signed integer

1

0

Float

A double-precision floating-point number

1.00023

0.0

Date

A date/time value with an optional time zone component, with resolution to the microsecond.

2010-05-10T18:35:21.001456-07:00

1970-01-01Z

Binary

An opaque binary object

n/a

an empty object of size 0

NULL

Corresponds to a NULL value in a database query (not equivalent to NOTHING)

NULL

NULL

NOTHING

Represents the state of a variable having no value or function returning no value (not equivalent to NULL)

NOTHING

NOTHING


2.8.1. Boolean

The Boolean type can have two values, True and False. When converting other types to a Boolean, any value that converts to a non-zero integer will be evaluated as True. Otherwise the result of the conversion will be False.

2.8.2. String

String values are specified with text between double or single quotes. Text between double quotes is subject to interpretation of escape characters. Please see String Formatting for more information.

Strings are assumed by default to have the encoding given by the QORE_CHARSET or the LANG environment variable. If neither of these variables is set, then all strings will be assumed to have UTF-8 encoding.

For detailed information on Qore character encoding handling, please see Qore Strings and Character Encoding.

It is legal to specify a string literal with newline characters like the following:

$str = "this string
is a multiline string";

Internally, strings are stored as a pointer to the string data, an unsigned integer giving the length of the string, and a pointer to an encoding object, giving the string's character encoding.

2.8.3. Integer

Qore integers are 64-bit signed integers.

2.8.4. Float

Qore floats are double precision floating-point numbers (C/C++ type double), normally a 64-bit value.

2.8.5. Date

Qore dates have a time component supporting a resolution to the microsecond and can be either absolute or relative.

See Date and Time Functions for a list of functions related to date/time processing.

2.8.5.1. Absolute Date/Time Values

Absolute date/time values specify a specific point in time in a certain time zone, such as January 1, 2005 10:35:00 +01:00. They are stored interally as a 64-bit signed offset from the Qore epoch (1970-01-01Z), a positive 4-byte integer for microseconds, and a pointer to a time zone description object that provides the UTC offset and daylight savings time information (see Time Zones for more information). Note that all absolute date/time values in Qore are stored internally in UTC and are converted for display purposes to the representation of wall time in their tagged time zone.

Absolute date/time values can be specified with a syntax based on ISO-8601 date formats as follows:

YYYY-MM-DD[THH:mm:SS[.n*]][Z|[+-]HH[:mm[:SS]]]

Note that if no time zone information is given, the local time zone will be assumed. If a time zone UTC offset is given, it is given in units of time east of UTC (i.e. +05:00 means five hours east of UTC).

Or an alternative format (with a '-' instead ofa 'T' to separate the time component):

YYYY-MM-DD[-HH:mm:SS[.n*]][Z|[+-]HH[:mm[:SS]]]

for example, for just the date in UTC, without a time component:

2010-05-26

or, for just the time, without a date component (note that in this case the date component will be set to Jan 1, 1970, in order for time arithmetic to function properly and will also be tagged with the local time zone):

20:05:10.458342

Some further examples (note that the date/time values without a time zone specification here are tagged with the local time zone):

prompt% qore -X '2005-03-29-18:12:25'
2005-03-29 18:12:25 Tue +02:00 (CEST)
prompt% qore -X '0512-01-01T01:49:59.002213Z'
0512-01-01 01:49:59.002213 Fri Z (UTC)
prompt% qore -X '2005-03-29'
2005-03-29 00:00:00 Tue +02:00 (CEST)
prompt% qore -X '18:35:26+08:00'
1970-01-01 18:35:26 Thu +08:00 (+08)

The year must be a four-digit number, and all other values except microseconds must be two-digit numbers. If microseconds are present, at least one and up to 6 digits may be given after the decimal point. Pad the numbers with leading zeros if the numbers are smaller than the required number of digits. The hour component must be in 24-hour time format. Except for the month and day values, all other values start with 0 (hour = 00 - 23, minute and second: 00 - 59). Any deviation from this format will cause a parse exception.

When a date/time value is converted to an integer or vice-versa, a 64-bit offset in seconds from the start of the "epoch" is used for the conversion. Qore's "zero date" (the start of Qore's "epoch") is January 1, 1970 UTC. When calculating second offsets from this date, a 64-bit integer is used.

Note

The default local time zone for qore is set when the qore library is initialized; see Time Zones for more information.

2.8.5.2. Relative Date/Time Values (Durations)

Relative dates (durations) are normally used for date addition and subtraction. See Date/Time Arithmetic for more information.

Internally, durations are stored as a set of seven discrete signed integer values, one each for years, months, days, hours, minutes, seconds, and microseconds.

There are 3 different formats understood by the Qore parser for describing literal durations in Qore.

Single Relative Time Format

A single relative date/time value (or a duration) may be specified as follows (note that this format is specific to Qore and not based on ISO-8601):

<integer><date component specifier>

Table 2.7. Date Specifiers For Single Values For Relative Dates (non-ISO-8601 syntax)

Component

Meaning

Example

Description

Y

Years

2Y

2 Years

M

Months

3M

3 Months

D

Days

10D

10 Days

h

Hours

15h

15 hours

m

Minutes

25m

25 minutes

s

Seconds

19s

19 seconds

ms

Milliseconds

250ms

250 milliseconds

us

Microseconds

21194us

21194 microseconds


Short Relative Time Format

This and the next duration format for composite relative date/time values are both based on ISO-8601.

This first format has the following syntax:

PnYnMnDTnHnMnSnu

Each element above is optional, but at least one element must be present. Note that "M" means months when before the "T" and minutes when found after the "T". The other elements are years, days, hours, seconds, and, as an extension to ISO-8601, "u" for microseconds. Additionally, the values may be negative.

Here are some examples (using qore's -X command-line option to evaluate and expression and print out the result):

prompt% qore -X 'P1Y3MT4S'
<time: 1 year 3 months 4 seconds>
prompt% qore -X 'PT4M551u'
<time: 4 minutes 551 microseconds>
prompt% qore -X 'P3DT21H'
<time: 3 days 21 hours>
Long Relative Time Format

The second ISO-8601-based format for specifing complex durations with multiple time units has the following syntax:

PYYYY-MM-DDTHH:mm:SS

This format is more limited than the first format, in that all values must be positive, and furthermore, all values must be present (although they may be zero).

Here are some examples of the second format (equivalent to the first examples):

prompt% qore -X 'P0001-03-00T00:00:04'
<time: 1 year 3 months 4 seconds>
prompt% qore -X 'P0000-00-00T00:04:00.000551'
<time: 4 minutes 551 microseconds>
prompt% qore -X 'P0000-00-03T21:00:00'
<time: 3 days 21 hours>

2.8.6. Binary

The binary data type is used to hold binary arbitrary binary data. Internally it is represented by a pointer to a memory location for the data and a size indicator.

Binary data can be concatenated with the + and += operators.

This data can be manipulated by being written and read from File, Socket, and Datasource objects, or converted and parsed to/from base64 encoded strings using the makeBase64String() and parseBase64String() functions, or compressed and decompressed using the compress(), gzip(), bzip2(), etc. functions, and processed by most cryptographic funtions, among others.

Binary objects can be read from a File object using the File::readBinary() method and can be written using the File::write() method. Please see the File Class for more information.

Binary objects can be read from a Socket object using the Socket::recvBinary() method and can be written using the Socket::send() method. Please see the Socket Class for more information.

The Datasource and DatasourcePool classes can also be used to read and write Binary objects as BLOBs.

Note that this is not an exhaustive list; see the function and class library documentation for more examples.

2.8.7. NULL

This data type represents an SQL NULL value. Note that NULL is not equivalent to NOTHING.

2.8.8. NOTHING

This special data type represents no value.

Note

The exists operator will return False when given NOTHING as an argument; for example:

prompt% qore -X 'exists NOTHING'
False

2.8.9. Conversions

Boolean, string, integer, date, and floating point data types can be freely converted from one type to the other, although data loss is possible depending on the conversion (particularly when converting to the boolan type as only two possible values are supported).

The special types NULL and NOTHING are not equivalent and cannot be converted to or from any other type.

When date types are converted from strings, any of the following formats can be used: "YYYYMMDDHHmmSS[.us][Z|+-HH[:MM[:SS]]]", "YYYY-MM-DD HH:mm:SS.us", "YYYY-MM-DDTHH:mm:SS", "YYYY-MM-DDTHH:mm:SS[.us][Z|+-HH[:MM[:SS]]]", and most reasonable combinations thereof. If the time zone component is missing, then the local time zone will be assumed (see Time Zones).

When dates are converted to and from integer values, the a 64-bit second offset from January 1, 1970 in the local time zone is used for the conversion. For example int(2006-01-01) gives 1136073600 (regardless of the local time zone the date is in). To get the second offset of a date from 1970-01-01Z (i.e. the true epoch offset), call get_epoch_seconds() instead.

When an expression requires a certain data type and the source data type cannot be converted to the desired data type, the default value for the desired data type will be used. The default values are given here.

2.9. Container Data Types

Qore supports three types of container types: lists, hashes (associative arrays), and objects (see Objects and Classes for more information). These container types can be combined to make arbitrarily complex data structures.

The data type of any element can be any basic type or another aggregate type. The types do not have to be uniform in one container structure.

2.9.1. Lists

Lists (or arrays) are simply ordered containers of values. A list element can be any Qore type (even another list, hash, or object).

Lists are specified by giving expressions separated by commas as follows:

$list = (expression, expression [, expression ...]);

Here is a concrete example:

my list $list = (1, 2, "three", 4.0, 5, 6, 2001-01-15Z);

Note

Note that trailing commas can be left on the end of a list (or a hash, for that matter). This makes it easier to comment-out the last element of a multi-line list without having to worry about removing the trailing comma.

List elements are dereferenced using square brackets: "[" and "]". The first element in a list has index zero.

$element3 = $list[2];

The following operators perform special processing on lists: elements, shift, unshift, push, pop, splice, [], +, +=, map, foldl, foldr, and select.

2.9.2. Hashes

Hashes are containers that associate values to a string key.

Note

Note that Qore hashes preserve the insertion order in order to be able to guarantee the order of keys when hashes are serialized to XML strings (see XML Integration), therefore the keys operator will always return the hash keys in insertion/creation order.

Hashes are specified using the following syntax:

$hash = ( "key1" : expression,
          "key2" : expression,
	  ... );

Here is a concrete example:

my hash $hash = ( "apple" : 1 + 1,
                  "pear"  : "good" );

Hashes are dereferenced in one of two ways, either using curly brackets: "{" and "}", where any valid Qore expression can be used, or using the dot "." hash member dereferencing operator, where literal strings can be used.

$element3 = $hash{"pe" + "ar"};

Is equivalent to:

$element3 = $hash.pear;

and:

$element3 = $hash."pear";

and:

$element3 = $hash.("pe" + "ar");

Hash members can have the names of keywords, but in this case to dereference them, you cannot use the dot operator with a literal string, otherwise a parse error will be raised. Use quotes around the member name when dereferencing hash members with the same name as a qore keyword as follows:

$element3 = $hash."keys";
$element3 = $hash{"keys"};

A literal string after the dot "." hash member dereferencing operator must be a valid Qore identifier; therefore if you want to use a hash key that's not a valid identifier, enclose the string in quotes.

If you want to use the result of an expression to dereference the hash, then the curly bracket syntax must be used.

Note that hash keys can also be given by constants (as long as the constant resolves to a string) when using curly brackets.

2.9.3. Objects

Qore objects are instantiations of a class. They have members (like a hash - values associated to string keys), and methods. The class definition specifies the methods that run on objects of that class, private members, and static methods associated with the class (however note that static methods do not run in the scope of an object). Qore classes are declared with a special syntax.

The recommend way to instantiate an object is to declare its type and give constructor arguments after the variable name in parentheses as follows:

my class_name_or_path $var_name([argument list])

For example (for a constructor taking no arguments or having only default values for the aguments, the list is empty):

my Mutex $m();

Objects can also be instantiated using the new operator as follows.

new class_identifier([argument list])

For example:

my $m = new Mutex();

Objects have named data members that are referenced like hash elements, although this behavior can be modified for objects using the memberGate() method. Object members are accessed by appending a dot '.' and the member name to the object reference as follows:

object_reference.member_name

For more information, see Object Members.

Object methods are called by appending a dot '.' and a method name to the object reference as follows:

object_reference.method_name([argument_list])

Or, from within the class code itself to call another method from inside the same class hierarchy:

$.method_name([argument_list])

For more information, see Object Method Calls.

The object references above are normally variable references holding an object, but could be any expression that returns an object, such as a new expression or even a subroutine call.

Note

Objects are treated differently than other Qore data types; they are only explicitly copied (see Object References for more informaion). Any object instantiated with the new operator will remain unique until deleted or explicitly copied. An explicit copy is made with the copy method, and does not always guarantee an exact copy of the source object (it depends on the definition of the copy method for the class in question).

Objects exist until they go out of scope, are explicitly deleted, or their last thread exits. For detailed information, see the section Classes on Qore classes.

2.10. Data Type Declarations

Starting in Qore 0.8.0, it is possible to restrict variables, class members, and function and method parameters to certain data types. This allows programmers to write safer code, as many more errors can be caught at parse time that would otherwise be caught at run time. Furthermore, providing type information to the parser allows Qore to implement performance optimizations by performing lookups and resolutions once at parse time rather than every time a variable or class member is accessed at run time.

When types are declared in a parameter list, functions and methods can be overloaded as well.

The types in the following table can be used:

Table 2.8. Data Type Declaration Names

Name

Accepts Qore Type(s)

Returns Qore Type(s)

Description

int

Integer

Integer

Restricts values to Qore's Integer type.

float

Float

Float

Restricts values to Qore's Float type.

bool

Boolean

Boolean

Restricts values to Qore's Boolean type.

string

String

String

Restricts values to Qore's String type.

date

Date

Date

Restricts values to Qore's Date type; values may be either absolute or relative date/time values.

binary

Binary

Binary

Restricts values to Qore's Binary type.

hash

Hash

Hash

Restricts values to Qore's Hash type.

list

List

List

Restricts values to Qore's List type.

object

Object

Object

Restricts values to Qore's Object type.

<classname>

Object

Object

Restricts values to objects of the specific class given; either the class name can be given (ex: Mutex or a qualified path to the class: Qore::Mutex).

null

NULL

NULL

Restricts values to Qore's NULL type; this type has few (if any) practical applications and has been included for completeness' sake.

nothing

NOTHING

NOTHING

Restricts values to Qore's NOTHING type; this type is mostly useful for declaring that a function or method returns no value.

softint

Integer, Float, Boolean, String

Integer

Accepts Integer, Float, Boolean, String and converts non-integer values to an integer and returns the integer.

softfloat

Integer, Float, Boolean, String

Float

Accepts Integer, Float, Boolean, String and converts non-float values to a float and returns the new value.

softbool

Integer, Float, Boolean, String

Boolean

Accepts Integer, Float, Boolean, String and converts non-boolean values to a boolean and returns the new value.

softstring

Integer, Float, Boolean, String

String

Accepts Integer, Float, Boolean, String and converts non-string values to a string and returns the new value.

any

any

same as received

Provides no restrictions on the type of value it receives and returns the same value.

data

String or Binary

same as received

Restricts input to String and Binary and returns the same type.

code

Closure, Call Reference

same as received

Restricts values to closures and call references.

reference

reference to an lvalue

same as received

Restricts values to references to lvalues; currently only usable in function or method parameters.

closure

Closure, Call Reference

same as received

Does not restrict value to just closures, but rather also allows call references. Synonym for code.

callref

Closure, Call Reference

same as received

Does not restrict value to just call references, but rather also allows closures. Synonym for code.


Complex types (hash of lists, reference to string, etc) are currently not possible to declare.

2.10.1. Overloading

Functions and methods can be overloaded if parameter types are declared as in the following example:

sub example(int $i) returns int {
    printf("i=%d\n", $i);
    return $i + 1;
}

sub example(string $str) returns string {
    printf("str=%s\n", $str);
    return $str + "foo";
}

In this case, the first version (example(int)) will be executed if called with an integer argument, and the second (example(string)) if called with a string argument.

Class methods may also be overloaded, but note that destructor(), copy(), methodGate(), memberGate(), and memberNotification() methods may not be overloaded (see Classes for more information).

2.11. Time Zone Handling in Qore

Qore assumes a default time zone for all programs when it starts up. The rules for determining the default time zone are similar to those for the C library in most UNIX or UNIX-like operating systems.

If the TZ environment variable is defined, then the contents of that variable are used to find a zoneinfo file that contains the time zone definition. If this file cannot be found, then the default time zone will default to UTC.

If the TZ environment variable is not defined or is empty, then the Qore library tries to find the default zoneinfo definition file (normally /etc/localtime). If found, this file is read in and provides the information about the local time zone. If not found, the default time zone will default to UTC.

When a zoneinfo file is found, information about local time zone names and daylight savings time is available for times tagged with that time zone.

See the TimeZone class for information about retrieving, setting, and querying time zone information; see Date and Time Functions for a list of functions related to date/time processing.

Here are some examples using Qore's '-X' option for evaluating an expression and displaying the result immediately:

prompt% TZ=America/Chicago qore -X 'now_us()'
2010-05-11 06:14:28.845857 Tue -05:00 (CDT)
prompt% TZ=Europe/Rome qore -X 'now_us()'
2010-05-11 13:14:35.070568 Tue +02:00 (CEST)
prompt% TZ=Australia/Sydney qore -X 'now_us()'
2010-05-11 21:14:45.422222 Tue +10:00 (EST)
prompt% TZ=Asia/Tokyo qore -X 'now_us()'
2010-05-11 20:14:59.609249 Tue +09:00 (CJT)

Note that posix-style time zone rules are not understood if assigned to the TZ environment variable, only file names to a zoneinfo file can be processed at the moment. Furthermore if the zoneinfo file contains leap second information, it is currently ignored.

2.12. Qore Strings and Character Encoding

2.12.1. Overview

The Qore language is character-encoding aware. All strings are assumed to have the default character encoding, unless the program explicitly specified another encoding for certain objects and operations. Every Qore string has a character encoding ID attached to it, so, when another encoding is required, the Qore language will attempt to do an encoding translation.

Qore uses the operating system's iconv library functions to perform any encoding conversions.

Qore supports character encodings that are backwards compatible with 7-bit ASCII. This includes all ISO-8859-* character encodings, UTF-8, KOIR-8, KOIU-8, and KOI7, among others (see the table below: Character Encodings Known to Qore).

However, mutibyte character encodings are currently only properly supported for UTF-8. For UTF-8 strings, the length(), index(), rindex(), substr(), reverse(), the splice operator, print formatting (regarding field lengths) functions and methods taking format strings, and regular expression operators and functions, all work with character offsets, which may be different than byte offsets. For all character encodings other than UTF-8, a 1 byte=1 character relationship is assumed.

Qore will accept any encoding name given to it, even if it is not a known encoding name or alias. In this case, Qore will tag the strings with this encoding, and pass this user-defined encoding name to the iconv library when encodings must be converted. This allows programmers to use encodings known by the system's iconv library, but unknown to qore. In this case, Qore will assume that the strings are backwards compatible with ASCII, meanin that that one character is represented by one byte and that the strings are null-terminated.

Note that when Qore matches an encoding name to a code or alias in the following table, the comparison is not case-sensitive.

Table 2.9. Character Encodings Known to Qore

Code

Aliases

Description

ISO-8859-1

ISO88591, ISO8859-1, ISO-88591, ISO8859P1, ISO81, LATIN1, LATIN-1

latin-1, Western European character set

ISO-8859-2

ISO88592, ISO8859-2, ISO-88592, ISO8859P2, ISO82, LATIN2, LATIN-2

latin-2, Central European character set

ISO-8859-3

ISO88593, ISO8859-3, ISO-88593, ISO8859P3, ISO83, LATIN3, LATIN-3

latin-3, Southern European character set

ISO-8859-4

ISO88594, ISO8859-4, ISO-88594, ISO8859P4, ISO84, LATIN4, LATIN-4

latin-4, Northern European character set

ISO-8859-5

ISO88595, ISO8859-5, ISO-88595, ISO8859P5, ISO85

Cyrillic character set

ISO-8859-6

ISO88596, ISO8859-6, ISO-88596, ISO8859P6, ISO86

Arabic character set

ISO-8859-7

ISO88597, ISO8859-7, ISO-88597, ISO8859P7, ISO87

Greek character set

ISO-8859-8

ISO88598, ISO8859-8, ISO-88598, ISO8859P8, ISO88

Hebrew character set

ISO-8859-9

ISO88599, ISO8859-9, ISO-88599, ISO8859P9, ISO89, LATIN5, LATIN-5

latin-5, Turkish character set

ISO-8859-10

ISO885910, ISO8859-10, ISO-885910, ISO8859P10, ISO810, LATIN6, LATIN-6

latin-6, Nordic character set

ISO-8859-11

ISO885911, ISO8859-11, ISO-885911, ISO8859P11, ISO811

Thai character set

ISO-8859-13

ISO885913, ISO8859-13, ISO-885913, ISO8859P13, ISO813, LATIN7, LATIN-7

latin-7, Baltic rim character set

ISO-8859-14

ISO885914, ISO8859-14, ISO-885914, ISO8859P14, ISO814, LATIN8, LATIN-8

latin-8, Celtic character set

ISO-8859-15

ISO885915, ISO8859-15, ISO-885915, ISO8859P15, ISO815, LATIN9, LATIN-9

latin-9, Western European with euro symbol

ISO-8859-16

ISO885916, ISO8859-16, ISO-885916, ISO8859P16, ISO816, LATIN10, LATIN-10

latin-10, Southeast European character set

KOI7

n/a

Russian: Kod Obmena Informatsiey, 7 bit characters

KOI8-R

KOI8R

Russian: Kod Obmena Informatsiey, 8 bit

KOI8-U

KOI8U

Ukrainian: Kod Obmena Informatsiey, 8 bit

US-ASCII

ASCII, USASCII

7-bit ASCII character set

UTF-8

UTF8

variable-width universal character set


2.12.2. Default Character Encoding

The default character encoding for Qore is determined by environment variables.

First, the QORE_CHARSET environment variable is checked. If it is set, then this character encoding will be the default character encoding for the process. If not, then the LANG environment variable is checked. If a character encoding is specified in the LANG environment variable, then it will be used as the default character encoding. Otherwise, if no character encoding can be derived from the environment, UTF-8 is assumed.

Character encodings are automatically converted by the Qore language when necessary. Encoding conversion errors will cause a Qore exception to be thrown. The character encoding conversions supported by Qore depend on the Operating System's iconv library function.

2.12.3. Character Encoding Usage Examples

The following is a non-exhaustive list of examples in Qore where character encoding processing is performed.

Character encodings can be explicitly performed with the convert_encoding() function, and the encoding attached to a string can be checked with the get_encoding() function. If you have a string with incorrect encoding and want to change the encoding tag of the string (without changing the actual bytes of the string), use the force_encoding() function.

The Datasource and DatasourcePool classes will translate character encodings to the encoding required by the database if necessary as well (this is actually the responsibility of the DBI driver for the database in question).

The File and Socket classes translate character encodings to the encoding specified for the object if necessary, as well as tagging strings received or read with the object's encoding.

The HTTPClient, XmlRpcClient, and JsonRpcClient classes will translate character encodings to the encoding specified for the object if necessary, as well as tag strings received with the object's encoding. Additionally, if an HTTP server response specifies a specific encoding to use, the encoding will be automatically set to this encoding as well.

Additionally you can serialize a Qore hash to an XML string and specify the character encoding to use. If the target encoding is different than the source encoding conversions are automatically performed. See XML Integration for more information about XML handling.

2.13. Expressions

An expression can be any of the following (note that expressions are also recursively defined):

Table 2.10. Expressions

Type

Description

Examples

 

An immediate value

Qore values that can be expressed directly (see Basic Data Types for more information)

True
152
1.2
"a string"
2005-10-27
NULL
NOTHING
("key" : $val)
1, 2.0, "three"
 

A variable reference

Qore variables (see Variables for more information)

$var
 

A variable declaration

Qore variable declarations (see Variables for more information)

my int $var
 

An in-class object member reference

References to members of an object from within the class (see Object Members for more information)

$.member
 

An lvalue assignment

Assigns a value to a lvalue (see Assignment Operator for more information)

$var = 1
($a, $b, $c, $date) = (1, "two", 3.3, 2005-10-28)
 

A subroutine/function call

Qore subroutine calls (see Subroutines for more information)

calculate($var1, $var2, "string", 4)
 

A method call

Qore object method calls (see Object_Method_Calls for more information)

$object.method("argument")
 

An in-class method call

Qore in-class object method calls (see Object_Method_Calls for more information)

$.method("argument")
 

A static method call

Qore static method calls (see Static Methods for more information)

ClassName::static_method("argument")
 

Expressions with operators

Use of Qore operators (see Operators for more information)

1 + 2
$a || $b
background my_function()
 

An expression in parentheses

Use of parentheses for clarity or to specify evaluation precedence.

(1 + 2)
(2 * (3 + 1))
 

A list

a list of values (see Lists for more information)

1, 2, 3, "four", 5.0
 

A hash

a hash (associative/keyed array) value container (see Hashes for more information)

( "key1" : 1, "key2" : "two" )
 

A find expression

Finds a value or values in a hash of lists, such as returned by the Datasource::select() method (see find expressions for more information)

find %name, %id in $data where (%name =~ /Smith/);
 

A context identifier (%column)

A contextual reference to the value of a key of a complex data structure within the current row being iterated by a context, summarize, subcontext statement, or a find expression.

%name
 

A context row identifier (%%)

A contextual reference to the current row of complex data structure being iterated by a context, summarize, subcontext statement, or a find expression. This expression will return a hash of the current row.

%%
 

A call reference

A reference to a function or object method call (similar to a function pointer in C or C++). Function references are resolved in the second phase of parsing (commit phase), and object method references are resolved at run-time.

\function_call()
\$object_expression.method_name()
 

A closure

An anonymous function used a value; technically in computer science a closure must have at least one bound variable, but in qore a closure is any function used as a value, whether or not it encloses local variables from the scope in which it was created or not.

sub (string $a) returns string { return $a + $b; }
 

A call reference call

Calls the code referenced by the call reference expression or closure using any arguments supplied and returns the result.

$result = $call_reference($arg1, $arg2)
 

An implicit argument reference

References an implicit argument.

$1, $2
$$
 

2.13.1. Static Method Calls

Synopsis

Calls to static class methods are made by giving the class name followed by two colons and then the method name. The method name must be implemented and accessible (i.e. not private and accessed outside the class) somewhere within the class hierarchy and must be static or a parse exception will occur.

Syntax

class_name::method_name( [argument_expressions...] )

Description

class_name

The name of the class implementing the static method.

method_name

The name of the static method to call.

[argument_expressions...]

Expressions passing arguments to the static method.

Example
TimeZone::setRegion("Europe/Prague");

2.13.2. Find Expressions

Synopsis

The find expression can be used to quickly find data in a hash of lists (such as a query result set returned by the Datasource::select() method). The find expression will loop through a data structure, and for each element in the structure where the where expression is True, it will evaluate and return a result expression. If the where expression only is true for one element in the list, it will return the result of evaluating the result expression directly, otherwise if the where expression is true more than once, then a list of the results of evaluting the result expression for each element is returned. In each expression in the find expression, column names can be referred to by preceding the name with a '%" character (as with context statements).

Syntax

find result_expression in data_expression where ( where_expression )

Description

result_expression

This expression will be evaluated and returned when the where_expression evaluates to True.

data_expression

This expression must evaluate to a hash of lists, so that the internal context can be set up for the find loop.

where_expression

This expression will be evaluated for each row in the data_expression. Each time it evaluates to True, the result_expression will be evaulated and used for the return value for the find expression.

Example
$rlist = find %name, %id in $data where (%name =~ /Smith/);

2.13.3. Call References

Synopsis

References to functions or object methods are called call references. A call reference can be used like a function pointer; a call reference is a Qore data type that can be returned by functions or methods or assigned to variables.

Note that it is currently not legal to assign a call reference to a constant. This restriction may be lifted in a future version of Qore.

Function Call References

Call references to functions are resolved at parse time; if the function does not exist a parse exception will be thrown.

Object Method Call References

Call references to object methods are executed and resolved at run time; if the object expression does not evaluate to an object at run-time, an OBJECT-METHOD-REFERENCE-ERROR exception will be thrown. If the method does not exist, a METHOD-DOES-NOT-EXIST run-time exception will be thrown.

When called, a call reference to an object method will be executed in the context of the object originally referenced.

Object method call references do not prolong the lifetime of an object; if the object is deleted (for example, by going out of scope), then if called the call reference will cause a OBJECT-ALREADY-DELETED exception to be thrown.

Syntax

\function_name();
\object_expression.method_name();

Description

\function_name()

This form gives a function call references. The function name can be any valid user or builtin function name. Note the backslash at the beginning and the empty pair of parentheses at the end; these are required when specifying a call reference.

\object_expression.method_name()

This form gives an object method call reference. The object expression can be any valid Qore expression that evaluates to an object. The method_name must be an unquoted string (see examples below) and must represent a valid method name of the object's class.

Example
$call_ref = \func_name();
$call_ref = \$object.method_name();

2.13.4. Closures

Synopsis

A closure is an anonymous function used as a value. Closures can be returned from functions or methods, assigned to variables, or passed as arguments to other functions.

Note that it is not legal to assign a closure to a constant.

Syntax

sub ([[type] variable1, ...]) [returns type] { code... }

Description

Closures encapsulate the state and value of local variables of the outer code block referenced from within the closure when the closure is created. Whenever local variables are bound within a closure, these variables are subject to concurrent thread access protection (locking) just as with global variables, in order to allow closures to be used in any context without restriction and to preseve thread-safety regarding bound local variables.

Note that returning a closure from within an object method encapsulates the state of the object as well (it's legal to refer to $self and $.<variable> from within closures created from objects) and additionally prolongs the scope of the object for the lifetime of the closure.

Note that parameter and return types are required when the PO_REQUIRE_TYPES or PO_REQUIRE_PROTOTYPES parse options are set.

Example
# if $b is a local variable in the function where the closure is created
# then $b will be bound to the closure when the closure is created
my code $closure = sub (int $a) returns int { return $a + $b; };

2.13.5. Implicit Argument References

Synopsis

Implicit arguments are arguments not captured by parameter variables as well as automatic arguments in list-processing operator expressions. A special syntax to reference these arguments is documented here.

Syntax

$<integer> # for a single implicit argument
$$         # for the entire implicit argument list

Description

Implicit arguments can be directly referenced using the dollar sign ($) and either a number from 1 onwards (giving the position in the argument list, where 1 is the first element) or a double dollar sign ($$) giving the entire implicit argument list.

For unassigned arguments to functions or methods, this syntax supplements the automatic $argv variable holding all function arguments not assigned to parameter variables.

This syntax is particularly useful when writing expressions for the map, map, foldr, and select operators, where implicit argument references are the only way the operator expressions can reference the current list values that are populated as implicit arguments as the operators traverse the list.

Example
# extract a list of even numbers from a list
my $l = select $list, !($1 % 2);

2.14. Operators

The following table lists all Qore operators in order of precedence, starting with the highest precedence. The lower the precedence number, the higher the precedence, therefore the operators with precedence level 1 ("{}", "[]", ".") have the highest precedence of all Qore operators. The precedence levels in Qore are roughly equal to the precedence levels of C language operators. To explicitly specify the precedence for expression evaluation, use parentheses ().

Table 2.11. Operators

Operator

Prec.

Description

Example

``

1

backquote/backtick operator

`ls -l`

{}

1

hash element or object member expression dereference operator

$hash{"na" + "me"}

.

1

hash element or object member literal dereference operator

$hash.name

$obj.method()

[]

1

list element, string, and binary dereference operator

$list[1]

++

2

pre-increment operator, post-increment operator

++$a, $a++

--

2

pre-decrement operator, post-decrement operator

--$a, $a--

new

3

class instantiation/new object operator

new Socket()

background

3

background/thread creation operator

background mainThread()

delete

3

delete operator

delete $var

remove

3

remove operator

remove $var

cast<>()

3

cast<>() operator

cast<SubClass>($var)

!

4

logical negation operator

if (!($a > 10)) ...

~

5

binary not/bit inversion operator

$var = ~$var

- (unary minus)

6

unary minus operator

$var = -$var

shift

7

shift list element operator

shift $list

pop

7

pop list element operator

pop $list

chomp

7

chomp end-of-line character operator

chomp $string

trim

7

trim characters operator

trim $string

elements

8

number of elements operator (list, hash, string, binary)

elements $list

keys

8

hash key list operator

keys $hash

*

9

arithmetic multiplication operator

$var = $a * 10

/

9

arithmetic division operator

$var = $a / 10

%

10

arithmetic modula operator

$var = $a % 10

+

11

plus operator: string, binary, list, and hash concatenation, integer and float addition

$a + 10

"hello" + "there"

$list + "new value"

$hash + ( "newkey" : 100 )

-

11

minus operator (arithmetic subtraction, hash key removal)

$a - 10

>>

12

bitwise shift right operator

0xff00 >> 8

<<

12

bitwise shift left operator

0xff00 << 8

exists

13

exists value operator

exists $var

instanceof

13

instanceof class operator

instanceof Qore::Mutex

<

14

Logical less than operator

$a < 10

>

14

Logical greater than operator

$a > 10

==

14

Logical equality operator

$a == 10

!=

14

logical inequality operator

$a != 10

<=

14

Logical less then or equals operator

$a <= 10

>=

14

logical greater than or equals operator

$a >= 10

<=>

14

logical comparison operator

$a <=> $b

===

14

absolute logical equality operator

$a === 10

!==

14

absolute logical inequality operator

$a !== 10

=~ //

14

regular expression match operator

$a =~ /text/

!~ //

14

regular expression no match operator

$a !~ /text/

=~ s///

14

regular expression substitution operator

$a =~ s/text/text/

=~ x//

14

regular expression pattern extraction operator

$a =~ x/(\w+):(\w+)/

=~ tr

14

transliteration operator

$a =~ tr/src_chars/targ_chars/

&

15

bitwise AND operator

$a & 0xff

|

15

bitwise OR operator

$a | 0xff

^

15

bitwise XOR operator

$a ^ 0xff

&&

16

logical AND operator

($a = 1) && ($b < 10)

||

16

logical OR operator

($a = 1) || ($b < 10)

? :

17

conditional operator

$a == 2 ? "yes" : "no"

,

18

comma operator

1, 2, 3, 4, 5

unshift

19

unshift list element operator

unshift $list, $val

push

19

push list element operator

push $list, $val

splice

19

splice list or string operator

splice $list, 2, 2, (1, 2, 3)

extract

19

extract list or string operator

my $sublist = extract $list, 2, 2, (1, 2, 3)

map

19

map operator

map $closure($1), $list

foldl

19

fold left to right operator

foldl $closure($1 - $2), $list

foldr

19

fold right to left operator

foldr $closure($1 - $2), $list

select

19

select elements from list operator

select $list, $1 > 1

=

20

assignment operator

$var = 1

+=

21

plus-equals (add-to) operator

$var += 5

-=

21

minus-equals (subtract-from) operator

$var -= 5

&=

21

and-equals operator

$var &= 0x2000

|=

21

or-equals operator

$var |= 0x2000

%=

21

modula-equals operator

$var %= 100

*=

21

multiply-equals operator

$var *= 10

/=

21

divide-equals operator

$var /= 10

^=

21

xor-equals operator

$var ^= 0x2000

<<=

21

shift-left-equals operator

$var <<= 0x2000

>>=

21

shift-right-equals operator

$var >>= 0x2000


Note

All Qore operators perform thread-atomic actions with respect to the immediate arguments of the operator. If the operators are used in a complex expression, the entire expression is not thread-atomic unless explicit user-level locking is used. For example: $a += 5 is a thread-atomic action, but $a += $b-- is not atomic, but rather made up of two atomic actions.

Note

When an operator taking more than one argument is used with arguments of different data types, Qore automatically converts one or both data types to a data type supported by the operator in order to evaluate the result, according to the precedence lists in the following section. That is; when an operator operates on mixed types, the types listed first in the following sections have precedence over types listed farther down in the lists. The result type will always be equal to the final operation type after any conversions due to type precedence per operator. If no type of either argument matches a supported data type for the operator, both types will be converted to the highest precedence data type for the operator and then the operator will evaluate the result. For explicit type conversion, please see the boolean(), string(), date(), int(), float(), etc functions.

2.14.1. Backquote Operator (``)

Synopsis

Executes the shell command in a separate process and returns the stdout as a string. To perform the same action using a Qore expression, see the backquote() function.

Syntax
`shell_command`
Return Type

string

Example
$dirlisting = `ls -l`

Table 2.12. Arguments Processed by ``

Argument

Returns

Processing

string shell_command

string

The shell command will be executed and the stdout is returned as a string.


Table 2.13. Exceptions Thrown by ``

err

desc

BACKQUOTE-ERROR

An error occurred in fork() or creating the output pipe.


2.14.2. Hash Element or Object Member Expression Dereference Operator ({})

Synopsis

Retrieves the value of hash key or object member by evaulating an expression.

Syntax
container_expression{expression}
Return Type

any

Example
printf("%s\n", $hash{getName()});

Table 2.14. Arguments Processed by {}

Argument

Processing

hash | objectcontainer_expression

This expression must evaluate to a hash or an object. If not, then the operator returns no value.

list expression

If the expression evaluates to a list, then a slice of the hash or object is returned as a hash containing keys given in the list that are present in the hash or object. If the key as given in the list (converted to a string if necessary) is not present in the hash or object, then it is also not present in the hash returned.

expression is any type other than list

This expression is evaluated and converted to a string if necessary. The value of the hash key corresponding to this string will be returned. If the key or member does not exist, then no value is returned.


Table 2.15. Exceptions Thrown by {}

err

desc

PRIVATE-MEMBER

Attempt to access a private member outside the class.


2.14.3. Hash Element or Object Member Literal Dereference Operator (.)

Synopsis

Retrieves the value of a hash key or object member using a literal identifier or an expression.

Syntax
container_expression.identifier
container_expression.method_identifier([arguments...])
container_expression.expression
Return Type

any

Example
printf("%s\n", $hash.name);
$obj.method("argument");

Table 2.16. Arguments Processed by .

Argument

Processing

container_expression

This expression must evaluate to a hash or an object. If not, then the operator returns no value.

identifier

The value of the hash key or object member corresponding to this identifier will be returned. If no such key exists, then no value is returned. In order to use hash keys that are not valid Qore identifiers, please use the {} operator. If the member is a private member and access is made outside the class, a run-time exception will be thrown.

method_ídentifier

The container expression must evaluate to an object, or a run-time exception is thrown. If the method does not exist in the class a run-time exception is thrown. Otherwise the method is called with any optional arguments given.

expression = list

If the expression evaluates to a list, then a slice of the hash or object is returned as a hash containing keys given in the list that are present in the hash or object. If the key as given in the list (converted to a string if necessary) is not present in the hash or object, then it is also not present in the hash returned.

expression != list

This expression is evaluated and converted to a string if necessary. The value of the hash key corresponding to this string will be returned. If the key or member does not exist, then no value is returned.


Table 2.17. Exceptions Thrown by .

err

desc

PRIVATE-MEMBER

Attempt to access a private member outside the class.

METHOD-DOES-NOT-EXIST

Attempt to access a method not defined for this class.

METHOD-IS-PRIVATE

Attempt to access a private method from outside the class.

BASE-CLASS-IS-PRIVATE

Attempt to access a method of a privately-inherited base class from outside the class.

OBJECT-METHOD-EVAL-ON-NON-OBJECT

Attempt to execute a method on a non-object.


2.14.4. List, String, and Binary Dereference Operator ([])

Synopsis

Retrieves the value of a list element, the given character of a string, or the integer value of a byte for a binary object. If the index value is not valid for the argument, NOTHING is returned. Note that this operator only works as a list dereferencing operator in lvalue expressions; you cannot assign a character or a byte value to strings or binaries using this operator.

Syntax
list_expression[expression]
string_expression[expression]
binary_expression[expression]
Return Type

any

Example
printf("%s\n", $list[2]);
printf("%s\n", $str[2]);
printf("0x%x\n", $binary[2]);

Table 2.18. Arguments Processed By []

Argument

Processing

list_expression

If the expression evaluates to a list, then the offset_expression will be used to return the given element from the list.

string_expression

If the expression evaluates to a string, then the offset_expression will be used to return the given character from the list; note that multi-byte characters with UTF-8 are properly respected with this operator.

binary_expression

If the expression evaluates to a binary, then the offset_expression will be used to return the integer value of the byte given from the binary object.

expression

The expression is evaluated and converted to an integer if necessary. Then the value of the list element given is returned (elements start at position 0).


This operator does not throw any exceptions; if the first expression does not evaluate to either a list, string, or binary, then no value is returned.

2.14.5. Integer Pre-Increment Operator (++)

Synopsis

increments an lvalue and returns the incremented value.

Syntax
++lvalue
Return Type

int

Example
++$i;

Table 2.19. Arguments Processed By Pre-Increment ++

Argument

Processing

Integer

First converts the value of lvalue to an integer if necessary, then increments the value and returns the result.


This operator does not throw any exceptions.

2.14.6. Integer Post-Increment Operator (++)

Synopsis

increments an lvalue and returns the value before the increment.

Syntax
lvalue++
Return Type

any

Example
$i++;

Table 2.20. Arguments Processed By Post-Increment ++

Argument

Processing

Integer

First converts the value of lvalue to an integer if necessary, then saves this value as the result, then increments the lvalue, then returns the saved original value of lvalue (after conversion to an integer if necessary)


This operator does not throw any exceptions.

2.14.7. Integer Pre-Decrement Operator (--)

Synopsis

decrements an lvalue and returns the decremented value.

Syntax
--lvalue
Return Type

int

Example
--$i;

Table 2.21. Arguments Processed By Pre-Decrement --

Argument

Processing

Integer

First converts the value of lvalue to an integer if necessary, then decrements it and returns the result.


This operator does not throw any exceptions.

2.14.8. Integer Post-Decrement Operator (--)

Synopsis

decrements an lvalue and returns the value before the decrement.

Syntax
lvalue--
Return Type

any

Example
$i--;

Table 2.22. Arguments Processed By Post-Decrement --

Argument

Processing

Integer

First converts the value of lvalue to an integer if necessary, then saves this value as the result, then decrements the lvalue, then returns the saved original value of lvalue (after conversion to an integer if necessary)


This operator does not throw any exceptions.

2.14.9. New Object Operator (new)

Synopsis

Creates an instance of a class by running the class' constructor on the new class (if any exists) and returns the new object.

Note that it is normally better to declare an object with its type and use the abbreviated form to construct the object as follows:

my Mutex $m();

This provides type information to the parser which allows more errors to be caught at parse time (instead of at run time), and furthermore allows Qore improve performance by performing more work once at parse time rather than for every time the object is accessed at run time (for example, method and variant resolution).

Syntax
new class_identifier(constructor_arguments ...)
Return Type

specific class, an object of the class given

Example
$obj = new Qore::Mutex();

Table 2.23. Arguments Processed By new

Argument

Processing

class_identifier

The class_identifier must be an existing class name; if so, the operator instantiates an object of this class, executes the constructor for the class (if any exists, along with any base class constructors, if applicable) on the new object, and returns the object (for constructor execution order in an inherited class, see Class Inheritance). If an exception is thrown in the constructor, the object is deleted immediately.


Table 2.24. Exceptions Thrown by new

err

desc

depends on class/constructor

See class documentation for possible exceptions.


2.14.10. Background Operator (background)

Synopsis

Start a background thread and return the TID (thread ID).

Syntax
background expression
Return Type

int

Example
background startThread();

Table 2.25. Arguments Processed By background

Argument

Processing

string expression

The expression given as an argument will be executed in a new thread. The TID of the new thread will be returned as the return value of the operator.


Note

Please note the following when using the background operator:

  • expressions that have no effect cannot be used with the background operator (a parse exception will be thrown)

  • it is illegal to make changes to a local variable anywhere in a background expression (a parse exception will be thrown)

  • local variables and find expressions are evaluated before the new thread is started and the result of the evaluation is used in the expression in the new thread.

  • it is not possible to pass local variables by reference anywhere in a background expression (a parse exception will be thrown)

Table 2.26. Exceptions Thrown by background

err

desc

THREAD-CREATION-FAILURE

If the thread table is full or if the operating system returns an error while starting the thread, this exception is thrown.


2.14.11. Delete Operator (delete)

Synopsis

The delete operator deletes the contents of an lvalue. If the delete operator is called on an object, the object will be destroyed unconditionally. The delete operator does not return any value. When called on a hash key, the key is removed from the hash entirely; when called on a list, the element is assigned NOTHING.

In the case the delete operator operates on an object, any exception can be thrown that is thrown by the class' destructor.

For a similar operator that returns the value that is removed from the data structure, and does not delete objects, see the remove operator.

Syntax
delete lvalue_expression
Return Type

Does not return any value

Example
delete $value;

This operator does not throw any exceptions, however exceptions could be thrown in an object's destructor method when deleted by this operator.

2.14.12. Remove Operator (remove)

Synopsis

The remove operator removes a value from a data structure, or, in the case the operand of the remove operator is a simple value, the value itself is removed from the variable and returned. The remove operator returns the value removed from the lvalue. When called on a hash key, the key is removed from the hash entirely; when called on a list, the element is assigned NOTHING.

The remove operator does not call destructors when operating on objects, but if removing an object from an lvalue or from a data structure within the lvalue causes the object to go out of scope, it will be destroyed, and then its destructor could throw an exception.

For a similar operator that deletes the value that is removed from the data structure, see the delete operator.

Syntax
remove lvalue_expression
Return Type

any

Example
my $var = remove $hash.value;

This operator does not throw any exceptions, however exception could be thrown in an object's destructor if it goes out of scope due to the action of this operator.

2.14.13. Cast Operator (cast<>())

Synopsis

The cast<>() operator provides a way to tell the parser that the type of object is not actually the declared type but rather a subclass as given between the angle brackets.

Syntax
cast<class_name_or_path>(expression)
Return Type

specific class, the class given

Example
cast<SubClass>($obj).method();

Table 2.27. Arguments Processed By cast<>()

Argument

Processing

object

The object is treated as if it were the class given between the angle brackets; this is mostly useful at parse time to avoid non-existent-method-call warnings.


Table 2.28. Exceptions Thrown by cast<>()

err

desc

RUNTIME-CAST-ERROR

The expression given does not evaluate to an object that can be cast to the given class.


2.14.14. Logical Not Operator (!)

Synopsis

Reverses the logical sense of an expression (True becomes False and False becomes True).

Syntax
!expression
Return Type

bool

Example
if (!exists $error_code)
    do_something();

Table 2.29. Arguments Processed By !

Argument

Processing

expression

The expression is evaluated and converted to Boolean, if necessary. Then the value is logically reversed (True becomes False, False becomes True)


This operator does not throw any exceptions.

2.14.15. Binary Not Operator (~)

Synopsis

The value of each bit in an integer is reversed (0 becomes 1, 1 becomes 0).

Syntax
~expression
Return Type

int

Example
$a = ~$b;

Table 2.30. Arguments Processed By ~

Argument

Processing

expression

The argument is converted to an integer (if necessary), and bitwise negation is performed on the argument (ex: 666 & ~27 = 640)


This operator does not throw any exceptions.

2.14.16. Unary Minus Operator (-)

Synopsis

Changes the sign of numeric values.

Syntax
-expression
Return Type

int or float

Example
$a = -$b;

Table 2.31. Arguments Processed By Unary Minus -

Argument

Processing

float expression

Gives the negative of its argument (ex: -(-1.1) = 1.1, -(1.1) = -1.1

int expression

Gives the negative of its argument (ex: -(-1) = 1, -(1) = -1


This operator does not throw any exceptions.

2.14.17. Shift Operator (shift)

Synopsis

Removes the first element from a list and returns that element.

Syntax
shift lvalue
Return Type

any

Example
$a = shift $ARGV;

Table 2.32. Arguments Processed By shift

Argument

Processing

list lvalue

Returns the first element of the list, and the list is modified by having the first element removed from the list.


This operator does not throw any exceptions.

2.14.18. Pop Operator (pop)

Synopsis

Removes the last element from a list and returns that element.

Syntax
pop lvalue
Return Type

any

Example
$a = pop $list;

Table 2.33. Arguments Processed By pop

Argument

Processing

list lvalue

Returns the last element of the list, and the list is modified, having the last element removed from the list.


This operator does not throw any exceptions.

2.14.19. Chomp Operator (chomp)

Synopsis

Removes the end-of-line marker(s) ('\n' or '\r\n') from a string, or each string element in a list, or each hash key value in a hash (if the value is a string) and returns the number of characters removed.

To perform this operation on a non-lvalue expression, see the chomp() function.

Syntax
chomp lvalue
Return Type

int

Example
chomp $str;

Table 2.34. Arguments Processed By chomp

Argument

Processing

string lvalue

Removes any EOL characters from a string and returns the number of characters removed.

list lvalue

Removes any EOL characters from each string element of the list passed and returns the number of characters removed.

hash lvalue

Removes any EOL characters from each hash key's value (where the value is a string) and returns the number of characters removed.


This operator does not throw any exceptions.

2.14.20. Trim Operator (trim)

Synopsis

Removes whitespace characters from the beginning and end of a string, or each string element in a list, or each hash key value in a hash (if the value is a string) and returns the value processed (string, list, or hash).

To perform this operation on a non-lvalue expression, see the trim() function.

The following whitespace characters are removed from the beginning and end of strings: ' ', '\n', '\r', '\t', '\v' (vertical tab, ASCII 11), and '\0' (null character).

Syntax
trim lvalue
Return Type

string, list, or hash

Example
trim $str;

Table 2.35. Arguments Processed By trim

Argument

Processing

string lvalue

Removes whitespace characters from the beginning and end of a string and returns the value processed.

list lvalue

Removes whitespace characters from the beginning and end of each string element of the list passed and returns the list.

hash lvalue

Removes whitespace characters from the beginning and end of each string value of the hash passed and returns the hash.


This operator does not throw any exceptions.

2.14.21. Map Operator (map)

Synopsis

Executes (or maps) an expression on a list and returns the result. An optional select expression can be given to filter elements out from the result list.

If the second argument is not a list, then map_expression is executed on the single value and the result is returned, and any select expression is ignored.

Return Type

any

Syntax
map map_expression, list, [select_expression]
Example
# returns (2, 4, 6)
map $1 * 2, (1, 2, 3);

Table 2.36. Arguments Processed By map

Argument

Processing

map_expression

The expression to map on the list; the implicit argument $1 represents the current element being processed.

list list

The list to process.

[select_expression]

An optional expression than can be used to filter out elements of the list before the map expression is applied; if this expression evaluates to False on an element, then the element will be skipped and the map expression will not be applied on that element.


This operator does not throw any exceptions (however note that exceptions could be thrown by expressions executed by this operator).

2.14.22. Fold Left Operator (foldl)

Synopsis

Folds an operation on a list from left to right and returns the result. The result of each individual operation is used as the first argument in the foldl expression for the next element in the list. The first operation of the fold is made by executing the fold expression on the first and second elements of the list, from this point onwards, the result of each successive operation is used as the first argument for the next operation, the second argument being the next element in the list.

If the list expression does not evaluate to a list, then the evaluated argument is returned immediately with no processing by the fold expression.

Syntax
foldl expression, list
Return Type

any

Example
# returns 5
foldl $1 - $2, (10, 4, 1);

Table 2.37. Arguments Processed By foldl

Argument

Processing

expression

The expression to fold on the list; the implicit argument $1 represents the result of the last operation (or the first element in the list when beginning the fold), and $2 represents the next element of the list.

list list

The list to process.


This operator does not throw any exceptions (however note that exceptions could be thrown by expressions executed by this operator).

2.14.23. Fold Right Operator (foldr)

Synopsis

Folds an operation on a list from right to left and returns the result. The result of each individual operation is used as the first argument in the foldr expression for the next element in the list in reverse order. The first operation of the right fold is made by executing the fold expression on the last and penultimate elements of the list, from this point onwards, the result of each successive operation is used as the first argument for the next operation, the second argument being the next element in the list in reverse order.

If the list expression does not evaluate to a list, then the evaluated argument is returned immediately with no processing by the fold expression.

Syntax
foldr expression, list
Return Type

any

Example
# returns -13
foldr $1 - $2, (10, 4, 1);

Table 2.38. Arguments Processed By foldr

Argument

Processing

expression

The expression to fold on the list; the implicit argument $1 represents the result of the last operation (or the last element in the list when beginning the fold), and $2 represents the next element of the list in reverse order.

list list

The list to process.


This operator does not throw any exceptions (however note that exceptions could be thrown by expressions executed by this operator).

2.14.24. Select From List Operator (select)

Synopsis

Selects elements from a list that meet the given criteria and returns the new list.

If the list expression does not evaluate to a list, then the select expression is evaluated using the value of the list expression as an argument, if it evalutes to true, then the value is returned, otherwise, no value is returned.

Syntax
select list, expression
Return Type

any

Example
# returns (2, 4, 6)
select (1, 2, 3, 4, 5, 6), !($1 % 2);

Table 2.39. Arguments Processed By select

Argument

Processing

list list

The list to process.

expression

The expression will be evaluated on each element of the list, the implicit argument $1 represents current element of the list; only if the expression evaluates to True will the element appear in the result list.


This operator does not throw any exceptions (however note that exceptions could be thrown by the expression executed by this operator).

2.14.25. Elements Operator (elements)

Synopsis

Returns the number of elements in a list, the number of keys in a hash, the number of characters (not bytes) in a string, or the number of bytes in a binary object.

Syntax
elements expression
Return Type

int

Example
$size = elements $list;

Table 2.40. Arguments Processed By keys

Argument

Processing

list

Returns the number of elements in the list.

hash

Returns the number of keys in the hash.

string

Returns the number of characters in the string.

binary

Returns the number of bytes in the binary object.


This operator does not throw any exceptions.

2.14.26. Keys Operator (keys)

Synopsis

Returns a list representing the keys in a hash.

Syntax
keys hash_expression
Return Type

list or NOTHING

Example
foreach my $key in (keys $hash)
    printf("%s = %s\n", $key, $hash.$key);

Table 2.41. Arguments Processed By keys

Argument

Processing

hash_expression

Returns a list of strings giving the keys in hash_expression, which must evaluate to a hash. If not, then no value is returned.


This operator does not throw any exceptions.

2.14.27. Multiply Operator (*)

Synopsis

Multiplies two arguments.

Syntax
expression1 * expression2
Return Type

int or float

Example
$value = $x * $y

Table 2.42. Argument Processing and Conversion Priorities for *

Argument

Processing

float

Gives the result of multiplying its arguments; if either of the arguments is a float then the result is also a float.

int

Gives the result of multiplying its arguments.

any other type

Converts argument to a float and performs the multiplication.


This operator does not throw any exceptions.

2.14.28. Divide Operator (/)

Synopsis

Divides a number by another.

Syntax
expression1 / expression2
Return Type

int or float

Example
$value = $x / $y;

Table 2.43. Argument Processing and Conversion Priorities for /

Argument

Processing

float

Gives the result of dividing its arguments; if either of the arguments is a float then the result is also a float.

int

Gives the result of dividing its arguments.

any other type

Converts argument to a float and performs the division.


This operator does not throw any exceptions.

2.14.29. Modula Operator (%)

Synopsis

Gives the integer remainder after division of one number by another.

Syntax
expression1 % expression2
Return Type

int

Example
$mod = $x % $y;

Table 2.44. Arguments Processed By %

Argument

Processing

int

Gives expression1 modula expression2 (ex: 12 % 10 = 2). Arguments are converted to integers if necessary.


This operator does not throw any exceptions.

2.14.30. Plus (Addition and Concatentation) Operator (+)

Synopsis

Numeric addition, list, string, binary, and hash concatenation operator.

Syntax
expression1 + expression2
Return Type

int, float, date, list, string, binary, or hash

Example
$a = 1 + 2;
$string = "hello" + "-there";
$list = (1, 2) + ("three", "four", "five");
$hash = ( "key1" : 1, "key2" : 2) + ( "key3" : "three", "key4": "four");
$bin = $bin1 + $bin2;

Table 2.45. Argument Processing and Conversion Priorities for +

Argument

Processing

list

Gives the result of concatenating its arguments, i.e. (1, 2) + (3, 4) = (1, 2, 3, 4)

string

Gives the result of concatenating its arguments.

date

Gives the result of adding date/time values (see Date/Time Arithmetic)

float

Gives the result of adding its arguments.

int

Gives the result of adding its arguments.

hash

Gives the result of concatenating/merging its arguments. Any common keys will be overwritten by the values in the second hash (expression2)


This operator does not throw any exceptions.

2.14.31. Minus Operator (-)

Synopsis

With float or integer arguments, subtracts one number from another.

With date arguments, subtracts one date from another; if both date arguments are absolute dates, the result is a relative date (duration) giving the time between them; if the first date argument is an absolute date and the second is a relative date (duration), then the result is an absolute date. If both date arguments are relative dates, then the result is a relative date. If the first argument is a relative date and the second date is an absolute date, the result is an absolute date as if the operands were reversed.

However, if the left-hand side is a hash, and the right-hand side is a string, then the hash key represented by the string will be removed from the hash. If the left-hand side is a hash and the right-hand side is a list, then each element in the list will be converted to a string and any hash key with that name will be deleted from the hash.

Syntax
expression1 - expression2
Return Type

int, float, date, or hash

Example
$num = $x - $y;
$date = 2010-05-13 - P3MT14H10M;
$hash = $hash - "key";
$hash = $hash - ("key1", "key2", "key3");

Table 2.46. Argument Processing and Conversion Priorities for -

Argument

Processing

date

date subtraction: expression1 - expression2

float

arithmetic subtraction: expression1 - expression2

int

arithmetic subtraction: expression1 - expression2

hash - string

hash key deletion: expression1 - expression2

hash - list

hash key deletion: expression1 - expression2; all elements of the list are converted to strings (if necessary) and any keys with those names are deleted from the hash.


This operator does not throw any exceptions.

2.14.32. Shift Right Operator (>>)

Synopsis

Shifts bits in an integer towards zero (divides an integer by a power of 2)

Syntax
expression1 >> expression2
Return Type

int

Example
$a = $x >> $y;

Table 2.47. Arguments Processed By >>

Argument

Processing

int

Gives the result of shifting expression1 right by expression2 bits. Arguments are converted to integers if necesssary.


This operator does not throw any exceptions.

2.14.33. Shift Left Operator (<<)

Synopsis

Shifts bits in an integer towards infinity (multiplies an integer by a power of 2)

Syntax
expression1 << expression2
Return Type

int

Example
$a = $x << $y;

Table 2.48. Arguments Processed By <<

Argument

Processing

int

Gives the result of shifting expression1 left by expression2 bits. Arguments are converted to integers if necessary.


This operator does not throw any exceptions.

2.14.34. Class Instance Operator (instanceof)

Synopsis

Tests if an expression is an instance of a class or not.

Syntax
expression instanceof class_specification
Return Type

bool

Example
if ($obj instanceof Qore::Mutex)
    print("object is Mutex\n");

Table 2.49. Arguments Processed By instanceof

Argument

Processing

expression

If expression is an instance of the named class, then the operator returns True, otherwise returns False. The operator will return True if the class is a base class, also even if it is privately inherited.


This operator does not throw any exceptions.

2.14.35. Exists Operator (exists)

Synopsis

Tests if an expression represents a value or not.

Syntax
exists expression
Return Type

bool

Example
if (exists $a)
    printf("a = $n\n", $a);

Table 2.50. Arguments Processed By exists

Argument

Processing

expression

If expression evaluates to a value, then the operator returns True, otherwise returns False.


This operator does not throw any exceptions.

2.14.36. Less Than Operator (<)

Synopsis

Tests if a value is less than another; types are converted if necessary (ex: ("1" < 2) is True).

Syntax
expression1 < expression2
Return Type

bool

Example
if ($x < $y)
    printf("%n is less than %n\n", $x, $y);

Table 2.51. Argument Processing and Conversion Priorities for <

Argument

Processing

float

If expression1 is numerically less than expression2, returns True, otherwise returns False

int

If expression1 is numerically less than expression2, returns True, otherwise returns False

string

If expression1 comes before expression2 in string sort order, returns True, otherwise returns False

date

If expression1 is before (or a shorter amount of time than) expression2, returns True, otherwise returns False


This operator does not throw any exceptions.

2.14.37. Greater Than Operator (>)

Synopsis

Tests if a value is greater than another; types are converted if necessary (ex: ("2" > 1) is True).

Syntax
expression1 > expression2
Return Type

bool

Example
if ($x > $y)
    printf("%n is less than %n\n", $x, $y);
expression1 > expression2

Table 2.52. Argument Processing and Conversion Priorities for >

Argument

Processing

float

If expression1 is numerically greater than expression2, returns True, otherwise returns False

int

If expression1 is numerically greater than expression2, returns True, otherwise returns False

string

If expression1 comes after expression2 in string sort order, returns True, otherwise returns False

date

If expression1 is after expression2, returns True, otherwise returns False


This operator does not throw any exceptions.

2.14.38. Equals Operator (==)

Synopsis

Tests if a value is equal to another; types are converted if necessary (ex: ("1" == 1) is True). For absolute equals, where types must also be equal to return true, see the Absolute Equals Operator (===).

Syntax
expression1 == expression2
Return Type

bool

Example
if ($x == $y)
    printf("%n is equal to %n\n", $x, $y);

Table 2.53. Argument Processing and Conversion Priorities for ==

Argument

Processing

string

If expression1 is equal to expression2, returns True, otherwise False

float

If expression1 is equal to expression2, returns True, otherwise False

int

If expression1 is equal to expression2, returns True, otherwise False

date

If expression1 is equal to expression2, returns True, otherwise False

list

If each element in the each list where order is relevant satisfies this operator, the operator returns True, otherwise it returns False

hash

If each hash has the same keys and the value of each equal key in each hash satisfies this operator, the operator returns True, otherwise it returns False

binary

If expression1's memory contents and size are equal to expression2's, then returns True, otherwise False

object

If expression1 is a reference to the same object as expression2, then returns True, otherwise False

null

If both expressions are NULL, returns True, otherwise returns False

nothing

If neither expression has a value, returns True, otherwise returns False


This operator does not throw any exceptions.

2.14.39. Not Equals Operator (!=)

Synopsis

Tests if a value is not equal to another; types are converted if necessary (ex: ("1" != 1) is False).

Syntax
expression1 != expression2
Return Type

bool

Example
if ($x != $y)
    printf("%n is not equal to %n\n", $x, $y);

Table 2.54. Argument Processing and Conversion Priorities for !=

Argument

Processing

string

If expression1 is not equal to expression2, returns True, otherwise returns False

float

If expression1 is not equal to expression2, returns True, otherwise returns False

int

If expression1 is not equal to expression2, returns True, otherwise returns False

date

If expression1 is not equal to expression2, returns True, otherwise returns False

list

If any element in the each list compared where order is relevant satisfies this operator, the operator returns True, otherwise it returns False

hash

If the hashes have different key sets, or the values of any equal key in each hash satisfies this operator, the operator returns True, otherwise it returns False

binary

If either expression1's memory contents and size are not equal to expression2's, returns True, otherwise False.

object

If expression1 is not a reference to the same object as expression2, then returns True, otherwise False.

null

If one expression is NULL and the other not, returns True, otherwise False.

nothing

If one of the expressions has a value, returns True, otherwise False.


This operator does not throw any exceptions.

2.14.40. Less Than Or Equals Operator (<=)

Synopsis

Tests if a value is less than or equals to another value; types are converted if necessary (ex: ("1" <= 2) is True).

Syntax
expression1 <= expression2
Return Type

bool

Example
if ($x <= $y)
    printf("%n is less than or equal to %n\n", $x, $y);

Table 2.55. Argument Processing and Conversion Priorities for <=

Argument

Processing

float

If expression1 is numerically less than or equal to expression2, returns True, otherwise returns False

int

If expression1 is numerically less than or equal to expression2, returns True, otherwise returns False

string

If expression1 comes before in string sort order or is the same as expression2, returns True, otherwise returns False

date

If expression1 is before or is the same exact date and time as expression2, returns True, otherwise returns False


This operator does not throw any exceptions.

2.14.41. Greater Than Or Equals Operator (>=)

Synopsis

Tests if a value is greater than or equals to another value; types are converted if necessary (ex: ("2" >= 1) is True).

Syntax
expression1 >= expression2
Return Type

bool

Example
if ($x >= $y)
    printf("%n is greater than or equal to %n\n", $x, $y);

Table 2.56. Argument Processing and Conversion Priorities for >=

Argument

Processing

float

If expression1 is numerically greater than or equal to expression2, returns True, otherwise returns False

int

If expression1 is numerically greater than or equal to expression2, returns True, otherwise returns False

string

If expression1 comes after in string sort order or is the same as expression2, returns True, otherwise returns False

date

If expression1 is after or is the same exact date and time as expression2, returns True, otherwise returns False


This operator does not throw any exceptions.

2.14.42. Comparison (<=>) Operator

Synopsis

Tests if the left-hand value is less than, equal, or greater than the right-hand value; types are converted if necessary (ex: ("1" <=> 2) returns -1).

Syntax
expression1 <=> expression2
Return Type

int

Example
switch ($x <=> $y) {
    case -1: 
        print("$x is less than $y\n");
        break;

    case 0: 
        print("$x is equal to $y\n");
        break;

    case 1: 
        print("$x is greater than $y\n");
        break;
}

Table 2.57. Argument Processing and Conversion Priorities for <=>

Argument

Processing

string

If expression1 comes after in string sort order as expression2, returns 1, otherwise if they are equal, returns 0, otherwise if expression1 comes before expression2, returns -1

float

If expression1 is numerically greater than expression2, returns 1, otherwise if they are equal returns 0, otherwise returns -1

int

If expression1 is numerically greater than expression2, returns 1, otherwise if they are equal returns 0, otherwise returns -1

date

If expression1 is after expression2, returns 1, otherwise if they are equal returns 0, otherwise returns -1


This operator does not throw any exceptions.

2.14.43. Absolute Equals Operator (===)

Synopsis

Checks two values for equality without doing any data type conversions; if the types do not match, then the result is False.

Syntax
expression1 === expression2
Return Type

bool

Example
if ($x === $y)
    printf("%n is equal to %n and has the same data type as well\n", $x, $y);

Table 2.58. Arguments Processed By ===

Argument

Processing

All

This operator returns True only if the types and values of both sides of the operator are exactly equal, otherwise returns False. No type conversions are done.


This operator does not throw any exceptions.

2.14.44. Absolute Not Equals Operator (!==)

Synopsis

Checks two values for inequality without doing any data type conversions. If the data types do not match, then returns True.

Syntax

expression1 !== expression2

Return Type

bool

Example
if ($x !== $y)
    printf("%n is not equal to %n and may not have the data type as well\n", $x, $y);

Table 2.59. Arguments Processed By !==

Argument

Processing

All

This operator returns True if either the types or the values of the arguments are different, otherwise it retuns False. No type conversions are done.


This operator does not throw any exceptions.

2.14.45. Regular Expression Match Operator (=~)

Synopsis

Checks for a regular expression match; returns True if the expression matches the string, False if not. See Regular Expression Options for the meaning of the i, s, x, and m options after the regular expression.

See Regular Expressions for more information about regular expression support in Qore.

Syntax
expression =~ [m]/regex/[isxm]
Return Type

bool

Example
if ($str =~ /hello/)
    printf("%s contains 'hello'\n", $str);

Table 2.60. Arguments Processed By =~

Argument

Processing

string

This operator returns True if the regular expression in regex matches the string in expression.


This operator does not throw any exceptions.

2.14.46. Regular Expression No Match Operator (!~)

Synopsis

Checks for a regular expression non match; returns True if the expression does not match the string, False if it does. See Regular Expression Options for the meaning of the i, s, x, and m options after the regular expression.

See Regular Expressions for more information about regular expression support in Qore.

Syntax
expression !~ [m]/regex/[isxm]
Return Type

bool

Example
if ($str !~ /hello/)
    printf("%s does not contain 'hello'\n", $str);

Table 2.61. Arguments Processed By !~

Argument

Processing

string

This operator returns True if the regular expression in regex does not match the string in expression.


This operator does not throw any exceptions.

2.14.47. Regular Expression Substitution Operator

Synopsis

Looks for a regular expression match in a string, and, if found, substitutes the matched string with a new string. Subpattern backreferences are supported in the target string, $1=first subpattern, $2=second subpattern, etc... See Regular Expression Options for the meaning of the i, s, x, and m options after the regular expression.

See Regular Expressions for more information about regular expression support in Qore.

Syntax
lvalue =~ s/regex_pattern/target_string/[isxmg]
Return Type

string or NOTHING if the lvalue does not hold a string.

Example
$str =~ s/hello/goodbye/i;
$str =~ s/(\w+) +(\w+)/$2, $1/;

Table 2.62. Arguments Processed By =~ s///

Argument

Processing

string

This operator substitutes text in the lvalue string if the regular expression matches. Subpattern backreferences are supported in the target string, $1=first subpattern, $2=second subpattern, etc..


This operator does not throw any exceptions.

2.14.48. Regular Expression Pattern Extraction Operator

Synopsis

Matches regular expression patterns (enclosed in parentheses) in a string and returns a list giving the text matched for each pattern. If the regular expression does not match, then no value (NOTHING) is returned. See Regular Expression Options for the meaning of the i, s, x, and m options after the regular expression.

See Regular Expressions for more information about regular expression support in Qore.

Syntax
string =~ x/regex_with_patterns/[isxm]
Return Type

list or NOTHING

Example
$list =~ x/(\w+):(\w+)/;
$list =~ x/(.*)\.(.*)/;

Table 2.63. Arguments Processed By =~ x//

Argument

Processing

string

This operator extracts strings from the string based on patterns enclosed in parentheses in the regular expression.


This operator does not throw any exceptions.

2.14.49. Transliteration Operator

Synopsis

Makes character substitutions in an lvalue; character ranges can also be used.

Syntax
lvalue =~ tr/source_chars/target_chars/
Return Type

string or NOTHING if the lvalue does not hold a string.

Example
$str =~ tr/a-z/A-Z/;

Table 2.64. Arguments Processed By =~ tr//

Argument

Processing

string

This operator substitutes characters in the lvalue string. Note that if there are more characters in the source string than in the target string, then the last character in the target string will be used for any source matches where the source character position is greater than the target string.


This operator does not throw any exceptions.

2.14.50. Binary And Operator (&)

Synopsis

Performs a bitwise (binary) AND operation on two integers.

Syntax
expression1 & expression2
Return Type

int

Example
$a = $x & $y;

Table 2.65. Arguments Processed By &

Argument

Processing

int

Gives the result of the binary (bitwise) AND operation between expression1 and expression2 (ex: 0xffb2 & 0xa1 = 0xa1); operands are converted to integers if necessary.


This operator does not throw any exceptions.

2.14.51. Binary Or Operator (|)

Synopsis

Performs a bitwise (binary) OR operation on two integers.

Syntax
expression1 | expression2
Return Type

int

Example
$a = $x | $y;

Table 2.66. Arguments Processed By |

Argument

Processing

int

Gives the result of the binary (bitwise) OR operation between expression1 and expression2 (ex: 0xb001 | 0xfea = 0xbfeb); operands are converted to integers if necessary.


This operator does not throw any exceptions.

2.14.52. Binary Xor Operator (^)

Synopsis

Performs a bitwise (binary) XOR operation on two integers.

Syntax
expression1 ^ expression2
Return Type

int

Example
$a = $x ^ $y;

Table 2.67. Arguments Processed By ^

Argument

Processing

int

Gives the result of the binary (bitwise) EXCLUSIVE OR operation between expression1 and expression2 (ex: 0xaef1 & 0xfb32 = 0x55c3); operands are converted to integers if necessary.


This operator does not throw any exceptions.

2.14.53. Logical And Operator (&&)

Synopsis

Checks to see if two expressions are True with logical short-circuiting.

Syntax
expression1 && expression2
Return Type

bool

Example
if ($x && $y)
    printf("%n and %n are both True\n", $x, $y);

Table 2.68. Arguments Processed By &&

Argument

Processing

bool

Returns True if both expressions are True, False if otherwise. Logical short-circuiting is implemented; if expression1 is False, then expression2 is not evaluated, and the operator returns False.


This operator does not throw any exceptions.

2.14.54. Logical Or Operator (||)

Synopsis

Returns True if either of the arguments are True with logical short-circuiting.

Syntax
expression1 || expression2
Return Type

bool

Example
if ($x || $y)
    printf("either %n or %n or both are True\n", $x, $y);

Table 2.69. Arguments Processed By ||

Argument

Processing

bool

Returns True if either or both expressions evaluate to True, False if otherwise. Logical short-circuiting is implemented; if expression1 is True, then expression2 is not evaluated, and the operator returns True.


This operator does not throw any exceptions.

2.14.55. Conditional Operator (? :)

Synopsis

Evaluates and returns the value of one of two expressions depending on the value of a conditional expression.

Syntax
expression ? if_true_expression : if_false_expression
Return Type

any

Example
$a = ($z > 100 ? "Big" : "Small");

Table 2.70. Arguments Processed By ? :

Argument

Processing

All

If expression is evaluated to be True, then the if_true_expression is evaluated and returned. Otherwise the if_false_expression is evaluated and returned.


This operator does not throw any exceptions.

2.14.56. Comma Operator (,)

Synopsis

Makes a list from more than one element.

Syntax
expression1, expression2
Return Type

list

Example
$a = 1, 2, "three";

Table 2.71. Arguments Processed By ,

Argument

Processing

All

The comma operator builds lists of arguments.


This operator does not throw any exceptions.

2.14.57. Unshift Operator (unshift)

Synopsis

Inserts an element into the first position of a list and moves all other elements up one position.

Syntax
unshift lvalue, expression
Return Type

any

Example
unshift $list, "one";

Table 2.72. Arguments Processed By unshift

Argument

Processing

All

Inserts the value of expression as the first element in the list given by lvalue. All other elements in the list are moved forward.


2.14.58. Push Operator (push)

Synopsis

Adds one element to the end of a list and returns the list processed (or NOTHING if the lvalue is not a list).

Syntax
push lvalue, expression
Return Type

list or NOTHING if the value is not a list

Example
push $list, "last";

Table 2.73. Arguments Processed By push

Argument

Processing

All

Appends the value of the expression as the last element in the list given by lvalue. If expression evaluates to a list, this list will be appended as the last element of lvalue. To concatenate lists, use the Plus Operator.


2.14.59. Splice Operator (splice)

Synopsis

Removes and optionally inserts elements in lists and strings. For a similar operator that returns the values removed, see the extract operator.

Syntax
splice lvalue, offset_expression, [length_expression, [substitution_expression]]
Return Type

list or string

Example
splice $list, 2, 2;
splice $string, 2, 2, "-text-";

Works on either strings or lists in a similar way; removes elements from a list or characters from a string and optionally inserts new ones. If no length_expression is given, splice removes all elements/characters from the list or string starting at offset_expression) (list and string offsets begin at 0). Otherwise, a number of elements/characters equal to length_expression is removed (or up to the end of the list/string if applicable). If substitution_expression is present, then the removed elements/characters are substituted with the elements/string given by this expression.

Note that string splice takes character offsets, which may not be the same as byte offsets for multi-byte character encodings, such as UTF-8

Table 2.74. Arguments Processed By splice

Argument

Processing

list or string lvalue

If the lvalue is a list, list elements are processed, otherwise, if it is a string, characters in the string are processed. For any other data type, no action is taken.

offset_expression

The start element/character position for removing elements/characters from the list or string.

length_expression

The number of elements/characters to remove. If this expression is not present, then all elements/characters from the offset to the end of the list/string are removed. If this expression is present and evaluates to 0, no characters/elements are removed.

substitution_expression

For list splice, an optional element or list to substitute for the removed elements (to insert a list in a single element's position, make sure that the list to be inserted is the first and only element of another list used as the argument in this position; in other words, pass a list within a single-element list). For string splice, an optional string to substitute for the removed characters.


2.14.60. Extract Operator (extract)

Synopsis

Removes and optionally inserts elements in lists and strings. For a similar operator that only removes value and does not return any value, see the splice operator.

Syntax
extract lvalue, offset_expression, [length_expression, [substitution_expression]]
Return Type

list or string

Example
my list $sublist = extract $list, 2, 2;
my string $substring = extract $string, 2, 2, "-text-";

Works on either strings or lists in a similar way; removes elements from a list or characters from a string and optionally inserts new ones. If no length_expression is given, extract removes all elements/characters from the list or string starting at offset_expression) (list and string offsets begin at 0). Otherwise, a number of elements/characters equal to length_expression is removed (or up to the end of the list/string if applicable). If substitution_expression is present, then the removed elements/characters are substituted with the elements/string given by this expression.

When operating on lists, a list is returned of any elements extracted (if no elements are extracted, then an empty list is returned); when operating on strings, a string is extracted of all characters extracted from the string (if no characters are extracted, then an empty string is returned).

Note that string extract takes character offsets, which may not be the same as byte offsets for multi-byte character encodings, such as UTF-8

Table 2.75. Arguments Processed By extract

Argument

Processing

list or string lvalue

If the lvalue is a list, list elements are processed, otherwise, if it is a string, characters in the string are processed. For any other data type, no action is taken.

offset_expression

The start element/character position for removing elements/characters from the list or string.

length_expression

The number of elements/characters to remove. If this expression is not present, then all elements/characters from the offset to the end of the list/string are removed. If this expression is present and evaluates to 0, no characters/elements are removed.

substitution_expression

For list extract, an optional element or list to substitute for the removed elements (to insert a list in a single element's position, make sure that the list to be inserted is the first and only element of another list used as the argument in this position; in other words, pass a list within a single-element list). For string extract, an optional string to substitute for the removed characters.


2.14.61. Assignment Operator (=)

Synopsis

Assigns a value to an lvalue and returns the value assigned.

Syntax
lvalue = expression
Return Type

any

Example
$a = 1;

Table 2.76. Types Processed =

Argument

Processing

All

Assigns the value of expression to lvalue.


2.14.62. Plus Equals Operator (+=)

Synopsis

Increments and concatentates an lvalue with the value of an expression depending on the data type of the lvalue, unless the lvalue is NOTHING, in which case this operator acts like the assignment operator (simply assigns the value of the right hand side to the lvalue).

Syntax
lvalue += expression
Return Type

int, float, date, list, string, binary, hash, or object

Example
$a += 10;
$date += P1M2DT45M;
$list += $new_element;
$string += ".foo";
$binary += <0c67a374>
$hash += ("new-key" : 1, "other" : "two");
$object += $hash;

Table 2.77. Arguments Processed By +=

Argument

Processing

list lvalue

the expression will be evaluated and concatenated to the lvalue. If expression is a list, the lists will be concatenated, to ensure adding a single element to a list, use the push operator (see Push Operator).

hash or object lvalue

the expression will be evaluated, and, if it is a hash or object, then it's members will be added to the lvalue, any duplicate elements in the lvalue will be overridden by elements in the expression.

string lvalue

the expression will be evaluated and converted to a string if necessary and concatenated to the lvalue.

float lvalue

the expression will be evaluated and converted to a float if necessary and added to the lvalue.

binary lvalue

the expression will be evaluated and converted to a binary if necessary and added to the lvalue.

date lvalue

the expression will be evaluated and converted to a date if necessary and added to the lvalue.

nothing lvalue

the lvalue will be assigned to the value of expression.

lvalue: all others

the lvalue's type will be converted to an integer, and the expression will be evaluated and converted to an integer if necessary, and then the result will be added to the lvalue.


2.14.63. Minus Equals Operator (-=)

Synopsis

For a float or integer argument, decrements the value of an lvalue by the value of an expression. However if the lvalue is a hash and the expression is a string, removes the key represented by the string from the hash.

Syntax
lvalue -= expression
Return Type

int, float, date, hash, or object

Example
$a -= 10;
$date -= PT45H213S;
$hash -= "key";
$hash -= ("key1", "key2");
$object -= "key";
$object -= $list_of_keys;

Table 2.78. Arguments Processed By -=

Argument

Processing

float lvalue

the expression will be evaluated and converted to a float if necessary and subtracted from the lvalue

date lvalue

the expression will be evaluated and converted to a date if necessary and subtracted from the lvalue

hash or object lvalue, string expression

the hash key represented by expression will be removed from the lvalue

hash or object lvalue, list expression

each element in the list will be converted to a string (if necessary) and the key represented by each string will be removed from the hash

nothing lvalue, any expression

the lvalue will be assigned to expression

lvalue: all other types

the lvalue's type will be converted to an integer (if necessary), and the expression will be evaluated and converted to an integer (if necessary), and then the result will be subtracted from the lvalue


2.14.64. And Equals Operator (&=)

Synopsis

Performs a bitwise (binary) AND operation on an lvalue using the value of an expression and returns the new value.

Syntax
lvalue &= expression
Return Type

int

Example
$a &= 0xfe;

Table 2.79. Arguments Processed By &=

Argument

Processing

All

the lvalue's type will be converted to an integer if necessary, and the expression will be evaluated and converted to an integer as well if necessary, and then the result will be binary and'ed to the lvalue


2.14.65. Or Equals Operator (|=)

Synopsis

Performs a bitwise (binary) OR operation on an lvalue using the value of an expression and returns the new value.

Syntax
lvalue |= expression
Return Type

int

Example
$a |= 0xba;

Table 2.80. Arguments Processed By |=

Argument

Processing

All

the lvalue's type will be converted to an integer if necessary, and the expression will be evaluated and converted to an integer as well if necessary, and then the result will be binary or'ed to the lvalue


2.14.66. Modula Equals Operator (%=)

Synopsis

Performs a modula calculation on an lvalue using the value of an expression and returns the new value.

Syntax
lvalue %= expression
Return Type

int

Example
$a %= 100;

Table 2.81. Arguments Processed By %=

Argument

Processing

All

the lvalue's type will be converted to an integer if necessary, and the expression will be evaluated and converted to an integer as well if necessary, and then the result will be used to divide the lvalue's value and the remainder will be saved to the lvalue


2.14.67. Multiply Equals Operator (*=)

Synopsis

Performs a multiplication operation on an lvalue using the value of an expression and returns the value assigned.

Syntax
lvalue *= expression
Return Type

int or float

Example
$a *= 10;

Table 2.82. Arguments Processed By *=

Argument

Processing

All

If either side of the operator is a float, the result will be a float as well. Otherwise the result is an integer value. The expression will be evaluated and multiplied by the lvalue, and the result will be saved to the lvalue.


2.14.68. Divide Equals Operator (/=)

Synopsis

Performs a division operation on an lvalue using the value of an expression and returns the value assigned.

Syntax
lvalue /= expression
Return Type

int or float

Example
$a /= 10;

Table 2.83. Arguments Processed By *=

Argument

Processing

All

If either side of the operator is a float, the result will be a float as well. Otherwise the result is an integer value. The expression will be evaluated and used to divide the lvalue, and the result will be saved to the lvalue.


Table 2.84. Exceptions Thrown by /*

err

desc

DIVISION-BY-ZERO

If the divisor expression evaluates to zero, this exception is thrown.


2.14.69. Xor Equals Operator (^=)

Synopsis

Performs an exclusive-or operation on an lvalue using the value of an expression.

Syntax
lvalue ^= expression
Return Type

int

Example
$a ^= 0xf9034ba7;

Table 2.85. Arguments Processed By ^=

Argument

Processing

All

Values are converted to integers if necessary. The expression will be evaluated and exclusive-or'ed with the lvalue, and the result will be saved to the lvalue.


2.14.70. Shift Left Equals Operator (<<=)

Synopsis

Performs a shift-left operation on an lvalue using the value of an expression and returns the value assigned.

Syntax
lvalue <<= expression
Return Type

int

Example
$a <<= 3;

Table 2.86. Arguments Processed By <<=

Argument

Processing

All

Values are converted to integers if necessary. The expression will be evaluated and this value will determine how many bits the lvalue will be shifted left. The result will be saved to the lvalue.


2.14.71. Shift Right Equals Operator (>>=)

Synopsis

Performs a shift-right operation on an lvalue using the value of an expression and returns the value assigned.

Syntax
lvalue >>= expression
Return Type

int

Example
$a >>= 3;

Table 2.87. Arguments Processed By >>=

Argument

Processing

All

Values are converted to integers if necessary. The expression will be evaluated and this value will determine how many bits the lvalue will be shifted right. The result will be saved to the lvalue.


2.15. Regular Expressions in Qore

Regular expression functionality in Qore is provided by PCRE: Perl-Compatible Regular Expression library.

Using this library, Qore implements regular expression pattern matching using the same syntax and semantics as Perl 5.

The following is a list of operators based on regular expressions (or similar to regular expressions in the case of the transliteration operator).

Table 2.88. Regular Expression Operators

Operator

Description

regular expression match operator

Returns True if the regular expression matches a string.

regular expression no match operator

Returns True if the regular expression does not match a string.

regular expression substitution operator

Substitutes text in a string based on matching a regular expression.

regular expression pattern extraction operator

Returns a list of substrings in a string based on matching patterns defined by a regular expression.

transliteration operator

Not a regular expression operator; transliterates one or more characters to other characters in a string.


See the table below for valid regular expression options.

Table 2.89. Regular Expression Options

Option

Description

i

Ignores case when matching

m

makes start-of-line (^) or end-of-line ($) match after or before any newline in the subject string

s

makes a dot (.) match a newline character

x

ignores whitespace characters and enables comments prefixed by #

g

makes global substitutions (only applicable with the substitution operator)


The following is a list of functions providing regular expression functionality where the pattern may be given at run-time:

Table 2.90. Regular Expression Functions

Function

Description

regex()

Returns True if the regular expression matches a string.

regex_subst()

Substitutes a pattern in a string based on regular expressions and returns the new string.

regex_extract()

Returns a list of substrings in a string based on matching patterns defined by a regular expression.


2.16. Date/Time Arithmetic

Date/time arithmetic is relatively straightforward and should normally produce the expected results. However with leap years, months with different lengths, and daylights savings time the situation can be confusing; this section will clarify how Qore does date arithmetic considering these special cases.

2.16.1. Adding and Subtracting Years and Months

Adding or subtracting years and months (ex: $date += 2Y + 3M) will give you the same day on the desired month in the desired year. If the target month has fewer days than the source month, then you will get the last day of the month in that year. For example:

prompt% qore -X '2004-02-29Z - 1Y'
2003-02-28 00:00:00 Fri Z (UTC)

2.16.2. Adding and Subtracting Days

Adding or subtracting days means adding or subtracting 24h periods; i.e. you will get the same time in the result of subtracting days, for example:

prompt% qore -X '2004-02-29T10:15:00Z - 10D'
2004-02-19 10:15:00 Thu Z (UTC)

2.16.3. Finding the Difference Between Two Dates

Subtracting one absolute date from another will result in a relative date, normalized to the hour (that is, microseconds over 999,999 are converted to seconds, seconds over 59 to minutes, and minutes over 59 to hours; days, months, and years will not appear in the result as they do not indicate a fixed period of time but rather can vary in length depending on the absolute date/time starting point. For example:

prompt% qore -X '2007-02-29T10:15:03.255Z - 2004-02-29T10:14:02.100Z'
<time: 26304 hours 1 minute 1 second 155 milliseconds>

To find the difference in seconds between two dates, convert each date value to an integer and subtract as follows:

prompt% qore -X 'int(2004-02-29Z) - int(2004-02-28Z)'
86400

Or use the get_duration_seconds() function as follows:

prompt% qore -X 'get_duration_seconds(2004-02-29Z - 2004-02-28Z)'
86400

2.16.4. Timezones and Daylight Savings Time

Time zones and daylight savings time information is supplied by the system's zoneinfo database (if any exists; see Time Zones for more information).

To find out if the current time zone has daylight savings time, execute the following:

prompt% qore -X 'TimeZone::get().hasDST()'
True

See the TimeZone class for more information on time zone information.

2.16.5. Leap Years and the Gregorian Calendar

Qore is capable of representing and performing calculations on dates before the adoption of the Gregorian calendar (proposed in 1582 and adopted at various times in Europe after this point). However all calculations are made as if the Gregorian calendar were always in effect (Qore implements a proleptic Gregorian calendar).

2.17. Statements

Non-block statements in Qore are always terminated by a semi-colon ";" as in Perl, C, or Java. Statements can be grouped into blocks, which are delimited by curly brackets "{" and "}" containing zero or more semi-colon delimited statements, as in C or Java. Like C, C++, and Java, but unlike perl, any Qore statement taking a statement modifier will accept a single statement or a statement block.

A statement can be any of the following (note that statements are also recursively defined):

Table 2.91. Qore Statements

Type

Examples

Reference

An expression that changes an lvalue

$var = 1;
$var += 5;
$var[1].count++;
shift $var.key[$i];

Expressions

An expression with the new operator

new ObjectClass(1, 2, 3);

class instantiation/new object operator

An expression with the background operator

background function();

background/thread creation operator

A call reference or closure call

$call_reference($arg1, $arg2);

call references, closures

A method call

$object.method(1, 2, 3);

Classes

An if statement

if ($var == 3) statement

if and else statements

An "if ... else" statement

if ($var == 3)
    statement
else
    statement

if and else statements

A while statement

while ($var < 10) 
    statement

while statements

A do while statement

do statement while 
    (expression);

do while statements

A for statement

for (expression1; expression2; 
    expression3) statement

for statements

A foreach statement

foreach $variable in 
    (expression) statement

foreach statements

A switch statement

switch (expression) {
    case case_expression: 
        statement(s) 
    [ default : 
        statement(s) ]
}

switch statements

A return statement

return expression;

return statements

A local variable declaration

my $var;
my ($a, $b, $c);

Variables

A global variable declaration

our $var;
our ($a, $b, $c);

Variables

A function call

calculate($this, $that, $the_other);

Function Library

A continue statement

continue;

continue statements

A break statement

break;

break statements

A statement block

{ statement }

one or more statements enclosed in curly brackets.

A throw statement

throw expression;

throw statements

try and catch statements

try
    statement
catch ($var)
    statement

try and catch statements

A rethrow statement

rethrow;

rethrow statements

A thread_exit statement

thread_exit;

thread_exit statements

A context statement

context [name] (expression) 
    statement

context statements

A summarize statement

summarize expression by ( expression )
    statement

summarize statements

A subcontext statement

subcontext
    statement

subcontext statements

An on_exit statement

on_exit
    statement

on_exit statements

An on_success statement

on_success
    statement

on_success statements

An on_error statement

on_error
    statement

on_error statements


2.17.1. if and else Statements

Synopsis

The if statement allows for conditional logic in a Qore program's flow; the syntax is similar to that of C, C++, or Java.

Syntax
if ( expression ) 
    statement
[else
    statement]
Description

Qore if statements work like if statements in C or Java. If the result of evaluating the expression converted to a Boolean value is True, then the first statement (which can also be a block) is executed. If the result is False, and there is an else keyword after the first statement, the following statement is executed.

Note

Any expression that evaluates to a non-zero integer value will be converted to a Boolean True. Any expression that evaluates to zero value is interpreted as False. This is more like C and Java's behavior and not like Perl's (where any non-null string except "0" is True).

2.17.2. for Statements

Synopsis

The Qore for statement is most similar to the for statement in C and Java, or the non array iterator for statement in Perl. This statement is ideal for loops that should execute a given number of times, then complete. Each of the three expressions in the for statement is optional and may be omitted. To iterate through a list without directly referencing list index values, see the foreach statement.

Syntax
for ( [initial_expression] ; [test_expression] ; [iterator_expression] )
      statement
Description

[initial_expression]

The initial_expression is executed only once at the start of each for loop. It is typically used to initialize a loop variable.

[test_expression]

The test_expression is executed at the start of each for loop iteration. If this expression evaluates to Boolean False, the loop will terminate.

[iterator_expression]

The iterator_expression is executed at the end of each for loop iteration. It is typically used to increment or decrement a loop variable that will be used in the test_expression.

Example

Here is an example of a for loop using a local variable:

for (my $i = 0; $i < 10; $i++)
    print("%d\n", $i);

2.17.3. foreach Statements

Synopsis

The Qore foreach statement is most similar to the for or foreach array iterator statement in Perl. To iterate an action until a condition is true, use the for statement instead.

Syntax
foreach [my] $variable in (expression)
    statement
Description

If the expression does not evaluate to a list, then the variable will be assigned the value of the expression evaluation and the statement will only execute one time. Otherwise the variable will be assigned to each value of the list and the statement will be called once for each value.

Example

Here is an example of a foreach loop using a local variable:

# if $str_list is a list of strings, this will remove all whitespace from the
# strings; the reference in the list expression ensures that changes
# to the iterator variable are written back to the list
foreach my $string in (\$str_list)
    trim $string;

Note

Note that if a reference (\$lvalue_expression) is used as the list expression, any changes made to the foreach iterator variable will be written back to the list.

2.17.4. switch Statements

Synopsis

The Qore switch statement is similar to the switch statement in C and C++, except that the case values can be any expression that does not need run-time evaluation and can also be expressions with simple relational operators or regular expressions using the switch value as an implied operand.

Syntax
switch (expression) { 
    case case_expression: 
        statement(s) 
    ...
    [ default : 
        statement(s) ]
}
Example
switch ($val) {
    case < -1: 
        printf("less than -1\n");
	break;
    case "string":
        printf("string\n");
	break;
    case > 2007-01-22T15:00:00: 
        printf("greater than 2007-01-22 15:00:00\n");
	break;
    case /abc/:
        printf("string with 'abc' somewhere inside\n");
	break;
    default:
        printf("default\n");
	break;
}
Description

The first expression is evaluated and then compared to the value of each case expression in declaration order until one of the case expressions matches or is evaluated to True. In this case all code up to a break statement is executed, at which time execution flow exits the switch statement. Unless relational operators are used, the comparisons are "hard" comparisons; no type conversions are done, so in order for a match to be made, both the value and types of the expressions must match exactly. When relational operators are used, the operators are executed exactly as they are in the rest of qore, so type conversions may be performed if nesessary.

To use soft comparisons, you must explicitly specify the soft equals operator as follows:

switch (1) {
    case == "1": print("true\n"); break;
}

If no match is found and a default label has been given, then any statements after the default label will be executed. If a match is made, then the statements following that case label are executed.

To break out of the switch statement, use the break statement.


2.17.5. while Statements

Synopsis

while statements in Qore are similar to while statements in Perl, C and Java. They are used to loop while a given condition is True.

Syntax
while ( expression )
    statement
Description

First the expression will be evaluated; if it evaluates to True, then statement will be executed. If it evaluates to False, the loop terminates.

Example
$a = 1;
while ($a < 10)
    $a++;

2.17.6. do while Statements

Synopsis

do while statements in Qore are similar to do while statements in C. They are used to guarantee at least one iteration and loop until a given expression evaluates to False.

Syntax
do
    statement
while ( expression );
Description

First, statement will be executed, then expression will be evaluated; if it evaluates to True, then the loop iterates again. If it evaluates to False, the loop terminates. The difference between do while statements and while statements is that the do while statement evaluates its loop expression at the end of the loop, and therefore guarantees at least one iteration of the loop.

Example
$a = 1;
do 
    $a++;
while ($a < 10);

2.17.7. continue Statements

Synopsis

Skips the rest of a loop and jumps right to the evaluation of the iteration expression.

Syntax
continue;
Description

The continue statement affects loop processing; that is; it has an affect on for, foreach, while, do while, context, summarize, and subcontext loop processing. When this statement is encountered while executing a loop, execution control jumps immediately to the evaluation of the iteration expression, skipping any other statements that might otherwise be executed.

2.17.8. break Statements

Synopsis

Exits immediately from a loop statement or switch block.

Syntax
break;
Description

The break statement affects loop processing; that is; it has an affect on for, while, do while, context, summarize, and subcontext loop processing. When this statement is encountered while executing a loop, the loop is immediately exited, and execution control passes to the next statement outside the loop.

2.17.9. throw Statements

Synopsis

In order to throw an exception explicitly, the throw statement must be used.

Syntax
throw expression;
Description

The expression will be passed to the catch block of a try/catch statement, if the throw is executed in a try block. Otherwise the default system exception handler will be run and the currently running thread will terminate.

Qore convention dictates that a direct list is thrown with at least two string elements, the error code and a description. All system exceptions have this format. See try and catch statements for information on how to handle exceptions, and see Exception Handling for information about how throw arguments are mapped to the exception hash.

2.17.10. try and catch Statements

Synopsis

Some error conditions can only be detected and handled using exception handlers. To catch exceptions, try and catch statements can to be used. When an exception occurs while executing the try block, execution control will immediately be passed to the catch block, which can capture information about the exception.

Syntax

try
    statement
catch ([$exception_hash_variable])
    statement

Description

A single variable can be specified in the catch block to be instantiated with the exception hash, giving information about the exception that has occurred. For detailed information about the exception hash, see Exception Handling.

If no variable is given in the catch declaration, it will not be possible to access any information about the exception in the catch block. However, the rethrow statement can be used to rethrow exceptions at any time in a catch block.

2.17.11. rethrow Statements

Synopsis

A rethrow statement can be used to rethrow an exception in a catch block. In this case a entry tagged as a rethrow entry will be placed on the exception call stack. This statement can be used to maintain coherent call stacks even when exceptions are handled by more than one catch block (for detailed information about the exception hash and the format of call stacks, see Exception Handling).

Syntax
rethrow;
Description

The rethrown exception will be either passed to the next higher-level catch block, or to the system default exception handler, as with a throw statement. Note that it is an error to call rethrow outside of a catch block.

2.17.12. thread_exit Statements

Synopsis

thread_exit statements cause the current thread to exit immediately. Use this statement instead of the exit() function when only the current thread should exit.

Syntax
thread_exit;
Description

This statement will cause the current thread to stop executing immediately.

2.17.13. context Statements

Synopsis

To easily iterate through multiple rows in a hash of arrays (such as a query result set returned by the Datasource::select() method), the context statement can be used. Column names can be referred to directly in expressions in the scope of the context statement by preceding the name with a '%" character.

Syntax

context [name] ( data_expression ) 
        [ where ( expression ) ] 
        [ sortBy ( expression ) ] 
        [ sortDescendingBy ( expression ) ]
   statement

Description

data_expression

This must evaluate to a hash of arrays in order for the context statement to execute.

[ where ( expression ) ]

An optional where expression may be given, in which case for each row in the hash, the expression will be executed, and if the where expression evaluates to True, the row will be iterated in the context loop. If this expression evaluates to False, then the row will not be iterated. This option is given so the programmer can create multiple views of a single data structure (such as a query result set) in memory rather than build different data structures by hand.

[ sortBy ( expression ) ]

An optional sort_by expression may also be given. In this case, the expression will be evaluated for each row of the query given, and then the result set will be sorted in ascending order by the results of the expressions according to the resulting type of the evaluated expression (i.e. if the result of the evaluation of the expression gives a string, then string order is used to sort, if the result of the evaluation is an integer, then integer order is used, etc).

[ sortDescendingBy ( expression ) ]

Another optional modifier to the context statement that behaves the same as above except that the results are sorted in descending order.

Example
# note that "%service_type" and "%effective_start_date" represent values
# in the $service_history hash of arrays.

context ($service_history) where (%service_type == "voice")
sortBy (%effective_start_date) {
   printf("%s: start date: %s\n", %msisdn, format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
}

2.17.14. summarize Statements

Synopsis

summarize statements are like context statements with one important difference: results sets are grouped by a by expression, and the statement is executed only once per discrete by expression result. This statement is designed to be used with the subcontext statement.

Syntax
summarize ( expression ) by ( expression )
          [ where ( expression ) ] 
          [ sortBy ( expression ) ] 
          [ sortDescendingBy ( expression ) ]
   statement
Description

summarize statements modifiers have the same effect as those for the context statement, except for the following:

by ( expression )

The by expression is executed for each row in the data structure indicated. The set of unique results defines groups of result rows. For each group of result rows, each row having an identical result of the evaluation of the by expression, the statement is executed only once.

Example
# note that "%service_type" and "%effective_start_date" represent values 
# in the $services hash of arrays.

summarize ($services) 
    by (%effective_start_date) 
    where (%service_type == "voice") 
    sortBy (%effective_start_date) {
    printf("account has %d service(s) starting on %s\n", 
           context_rows(),
           format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
}

2.17.15. subcontext Statements

Synopsis

Statement used to loop through values within a summarize statement.

Syntax
subcontext [ where ( expression ) ] 
           [ sortBy ( expression ) ] 
           [ sortDescendingBy ( expression ) ]
    statement
Description

The subcontext statement is used in conjunction with summarize statements. When result rows of a query should be grouped, and then each row in the result set should be individually processed, the Qore programmer should first use a summarize statement, and then a subcontext statement. The summarize statement will group rows, and then the nested subcontext statement will iterate through each row in the current summary group.

Example
summarize ($services) 
    by (%effective_start_date) 
    where (%service_type == "voice") 
    sortBy (%effective_start_date) {
    printf("account has %d service(s) starting on %s\n", 
           context_rows(),
           format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
    subcontext sortDescendingBy (%effective_end_date) {
        printf("\tservice %s: ends: %s\n", %msisdn, format_date("YYYY-MM-DD HH:mm:SS", %effective_end_date));
    }
}

2.17.16. return Statements

Synopsis

return statements causes the flow of execution of the subroutine, method or program to stop immediately and return to the caller. This statement can take an optional expression to return a value to the caller as well.

Syntax
return [expression];
Description

This statement causes execution of the current subroutine, method, or program to cease and optionalls returns a value to the caller.

Example
sub getName() returns string {
   return "Barney";
}

my string $name = getName();

2.17.17. on_exit Statements

Synopsis

Queues a statement or statement block for unconditional execution when the block is exited, even in the case of exceptions or return statements. For similar statement that queue code for execution depending on the exception status when the block exits, see on_success statements and on_error statements.

Syntax
on_exit
    statement
Description

The on_exit statement provides a clean way to do exception-safe cleanup within Qore code. Any single statment (or statement block) after the on_exit keyword will be executed when the current block exits (as long as the statement itself is reached when executing - on_exit statements that are never reached when executing will have no effect). The the position of the on_exit statement in the block is important, as the immediate effect of this statement is to queue its code for execution when the block is exited. Even if an exception is raised or a return statement is executed, any on_exit code that is queued will be executed. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup.

Note that if this statement is reached when executing in a loop, the on_exit code will be executed for each iteration of the loop.

By using this statement, programmers ensure that necessary cleanup will be performed regardless of the exit status of the block (exception, return, etc).

Example
{
    $mutex.lock();
    # here we queue the unlock of the mutex when the block exits, even if an exception is thrown below
    on_exit $mutex.unlock();
    if ($error)
        throw "ERROR", "Scary error happened";
    print("everything's OK!\n");
    return "OK";
}
# when the block exits for any reason, the mutex will be unlocked

2.17.18. on_success Statements

Synopsis

Queues a statement or statement block for execution when the block is exited in the case that no exception is active. Used often in conjunction with the on_error statement and related to the on_exit statement.

Syntax
on_success
    statement
Description

The on_success statement provides a clean way to do block-level cleanup within Qore code in the case that no exception is thrown in the block. Any single statment (or statement block) after the on_success keyword will be executed when the current block exits as long as no unhandled exception has been thrown (and as long as the statement itself is reached when executing - on_success statements that are never reached when executing will have no effect). The the position of the on_success statement in the block is important, as the immediate effect of this statement is to queue its code for conditional execution when the block is exited. Even if a return statement is executed later in the block, any on_success code that is queued will be executed as long as there is no active (unhandled) exception. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup, along with on_error statements, which are executed in a manner similar to on_success statements, except on_error statements are only executed when there is an active exception when the block is exited.

Note that if this statement is reached when executing in a loop, the on_success code will be executed for each iteration of the loop (as long as there is no active exception).

Example
{
    $db.beginTransaction();
    # here we queue the commit in the case there are no errors
    on_success $db.commit();
    # here we queue a rollback in the case of an exception
    on_error $db.rollback();
    $db.select("select * from table where id = %v for update", $id);
    # .. more code

    return "OK";
}
# when the block exits. the transaction will be either committed or rolled back, 
# depending on if an exception was raised or not

2.17.19. on_error Statements

Synopsis

Queues a statement or statement block for execution when the block is exited in the case that no exception is active. Used often in conjunction with the on_success statement and related to the on_exit statement.

Syntax
on_error
    statement
Description

The on_error statement provides a clean way to do block-level cleanup within Qore code in the case that an exception is thrown in the block. Any single statment (or statement block) after the on_error keyword will be executed when the current block exits as long as an unhandled exception has been thrown (and as long as the statement itself is reached when executing - on_error statements that are never reached when executing will have no effect). The the position of the on_error statement in the block is important, as the immediate effect of this statement is to queue its code for conditional execution when the block is exited. Even if a return statement is executed later in the block, any on_error code that is queued will be executed as long as there is an active (unhandled) exception. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup, along with on_success statements, which are executed in a manner similar to on_error statements, except on_success statements are only executed when there is no active exception when the block is exited.

Note that the code in this statement can only be executed once in any block, as a block (even a block within a loop) can only exit the loop once with an active exception (in contrast to on_success and on_exit statements, which are executed for every iteration of a loop).

Example
{
    $db.beginTransaction();
    # here we queue the commit in the case there are no errors
    on_success $db.commit();
    # here we queue a rollback in the case of an exception
    on_error $db.rollback();
    $db.select("select * from table where id = %v for update", $id);
    # .. more code

    return "OK";
}
# when the block exits. the transaction will be either committed or rolled back, 
# depending on if an exception was raised or not

2.18. Subroutines

A subroutine is declared in Qore by using the key word sub as follows:

sub subroutine_name([[type] variable1, ...]) [returns type] {
    statements;
}

Variables listed in parentheses after the subroutine name are the parameters to the subrouting and automatically get local lexical scoping. In order to process a variable number of arguments to a function, the $argv variable (local variable) is instantiated as a list with the remaining arguments passed to the subroutine. Type declarations optionally precede the parameter variable and will restrict any arguments passed to the type declared. The same subrouting can be declared multiple times if each declaration has different parameter types; this is called overloading the subroutine.

Subroutines can use the return statement to provide a return value. Subroutine names must be valid Qore identifiers.

The return type of the subroutine can be given by listing a type declaration after the returns keyword after the parentheses after the subroutine name.

Note that parameter and return types are required when the PO_REQUIRE_TYPES or PO_REQUIRE_PROTOTYPES parse options are set.

Note

Variables passed as function arguments are passed by value by default, unless the caller places a "\" character before an lvalue in the argument list. In this case the subroutine must have a parameter defined to accept the variable passed by reference. Any changes to the local variable will be reflected in the original variable for variables passed by reference. Also note that it is illegal to pass an argument by reference in a background expression.

Subroutines can return values to the calling expression by using the return statement, with the following syntax:

return expression;

Here is an example subroutine declaration for a function returning a value:

#!/usr/bin/qore
#
# subroutine declaration example

sub print_string(string $string) returns int {
    print("%s\n", $string);
    return 1;
}

Subroutines may also be recursive. Here is an example of a recursive Qore subroutine definition implementing the Fibonacci function:

#!/usr/bin/qore
#
# recursive subroutine example

sub fibonacci(int $num) returns int {
    if ($num == 1)
        return 1;
    return $num * fibonacci($num - 1);
}

Note

Function names are resolved during the second parse pass; therefore functions do not need to be declared before being referenced. This allows an easy definition of 2 or more self-referencing functions.

2.19. Namespaces

Namespaces allow constants, classes, and even other namespaces with the same name to co-exist in the same program by defining them in separate namespaces. Constants, classes, and sub-namespaces can be declared to belong to a particular namespace either by defining them in-line within a namespace declaration, or by including the namespace name/path prepended to the constant, class, or namespace declaration separated by two colons "::".

If the user does not specify the parent namespace with a namespace path in constant, class, or namespace declarations, the declaration will be by default in the unnamed default root namespace.

2.19.1. Namespace Declarations

In-line namespace declaration:

namespace [namespace_path::]namespace_identifier {
    [constant_declarations]
    [class_declarations]
    [sub-namespace-declarations]
}

Out of line namespace declaration:

namespace [namespace_path::]namespace_identifier;

2.19.2. Namespace Resolution

Namespaces can either be resolved by giving a path to the constant, class, or namespace desired, or by leaving out the namespace path and allowing the system to search for the constant, class, or namespace. In either case, a depth-first search of the namespace tree is made for a match. If a namespace path is included, then the tree is searched for the first namespace match. and, if the rest of the declaration cannot be matched, the search continues in the entire namespace tree until a complete match is found.

Namespace paths look like the following:

starting_namespace::[sub-namespaces::]constant|class|namespace

2.19.3. System Namespaces

All Qore-language constants and classes are defined in the Qore namespace or in a subnamespace of the Qore namespace. The Qore namespace is a direct child of the unnamed default root namespace (::).

For detailed information on all constants and classes defined in system namespaces, see System Namespaces and Class Library.

2.20. Constants

Constant definitions allow programmers to refer to values with Qore identifiers rather than using the value or the expression that generates the value. Constants are defined with the following syntax:

const [namespace_path::]constant_identifier = expr;

Note

The expression cannot be an expression that has side effects or a parse exception will be raised. Only functions tagged with the CONST can be used to initialize a constant.

2.21. Classes

Objects are instantiations of a Qore class. Classes can define private members and methods, which are functions that operate only on the objects of that class.

Classes are declared with the following syntax:

class [namespace_path::...]class_identifier [inherits [private|public] [namespace_path::...]class_identifier[, ...]] {
    [private $.var1[, ...];]

    [private {
        [type] $.member_name [ = expr];
	...
    }]

    [public {
        [type] $.member_name [ = expr];
	...
    }]

    [static] [synchronized] [private] [namespace_path::]method_name_identifier([[type] $var1, ...]) {
         statements;
    }
    ...
}

Alternatively objects can be defined out of line as follows:

class [namespace_path::]class_identifier [inherits [private|public] [namespace_path::...]class_identifier[, ...]];

[static] [synchronized] [private] [namespace_path::]class_identifier::method_identifier([[type] $var1, ...]) {
    statements;
}

Public and private members can only be declared in an in-line class definition (the first example above). If a class has at least one public member declared (or inherits a class with at least one public member declared), then only those members declared as public can be accessed from outside the class, and from within the class only members explicitly declared can be accessed as well (unless the class also defines a memberGate() method). In this way typographical errors in member names can be caught (at parse time if types are declared).

In a class hierarchy, base class constructor methods can be explicitly specified using a special syntax unique to subclass constructor methods. Please see Class Inheritance for more information.

Note

It's possible to write purely object-oriented scripts/programs in Qore by defining an application class and using the -x or --exec-class command-line arguments to tell Qore to instantiate the class instead of doing normal top-level execution (in fact, the --exec-class arguments disallow the use of top-level statements entirely). For more information, please see Command-Line Parsing and Parse Directives.

2.21.1. Private and Synchronized Methods

Methods declared with the private keyword can only be called by other member functions of the same class. Any attempt to call these methods from outside the class will result in a run-time exception.

Methods declared with the synchronized keyword will only run in one thread at a time.

2.21.2. Static Methods

Methods declared with the static keyword are like regular subroutines that are attached to the class. These methods are not associated with a particular object's state and therefore are not allowed to refer to object members or call non-static methods. Also, no reference to the special $self variable is allowed within static methods.

Static method calls take a special syntax as documented here.

2.21.3. Constructors, Destructors, and Other Special Methods

All class methods are optional, but some methods have a special meaning.

Table 2.93. Special Methods

Name

Description

constructor()

Called when objects are created when instantiated by a variable declaration with a class type and constructor arguments or explicitly with the new operator. User code may not explicitly call constructor() methods directly. In a class tree, constructor() methods are called for base classes first in left-to-right, depth-first declaration order.

constructor() methods may be overloaded and also private constructors may be defined. Private constructor can only be called from within the class.

copy()

When a user explicitly calls a copy method, Qore will generate a new object with references to the same members as the source object. Then, if there are any base classes, base class copy() methods are called in the same order as the constructor() methods. If a copy() method is defined, it will be run in the new object with a reference to the old object passed as the first argument. Any other arguments passed to the copy() method are ignored.

copy() methods cannot be overloaded and cannot be private.

destructor()

Called when objects go out of scope or are explicitly deleted. User code may not explicitly call destructor() methods. In a class tree, destructor() methods are called for base classes in the opposite order in which the constructors are called.

destructor() methods cannot be overloaded and cannot be private.

memberGate(string $name) returns any

If this method is implemented in the class, it is called when read access is attempted to private member or members that do not exist in the current object; the return value of this method is returned as the value of the member.

memberGate() methods cannot be overloaded and are not inherited by subclasses.

methodGate(string $name) returns any

If this method is implemented in the class, it is called when methods are called on the object that do not exist in the current object and the return value of this method is returned as the value of the method call.

methodGate() methods cannot be overloaded and are not inherited by subclasses.

memberNotification(string $name)

If this method is implemented in the class, it is called when an object member is updated outside the class with the member name as the argument. Note that this method is called after the member has been updated and without locking; the call is not atomic respective to other threads that also may update the same member simultaneously.

memberNotification() methods cannot be overloaded and are not inherited by subclasses.


2.21.4. Object Members

When defining a class, members of the current object can be referred to with a special syntax as follows:

$.member_name_identifier

Furthermore, the automatic variable $self is instantiated which represents the current object (similar to the this in C++ or Java). Therefore if you need to access hash members which are not valid Qore identifiers, then enclose the member name in double quotes after the dot operator as follows:

$self."&member-name"

The automatic $argv local variable is instantiated as usual in all class methods where there are more arguments than variables declared in the method declaration.

If the class implements a memberGate() method, then whenever a non-existant member of the class is accessed (read), this method will be called with the name of the member as the sole argument, so that the class can create the member (or react in some other way) on demand. This method is also called when methods of the same class try to access (read) non-existant methods, but is not called from within the memberGate() method itself.

To monitor writes to the object, the class can implement a memberNotification() method, which is called whenever an object member is modified from outside class member code. In this case, the memberNotification() method is called with the name of the member that was updated so that an object can automatically react to changes to its members (writes to members) from outside the class. This method is not called when members are updated from within class member code.

If a class has at least one public member declared (or inherits a class with at least one public member declared), then only those members declared as public can be accessed from outside the class, and from within the class only members explicitly declared can be accessed as well (unless the class also defines a memberGate() method). In this way typographical errors in member names can be caught (at parse time if types are declared).

2.21.5. Object Method Calls

Within a class method definition, calls to methods in the same class hierarchy (of the current class or a base class) can be defined as follows:

[namespace_path::]$.method_name([arg, ...])

For example:

# to call base class Mutex::lock()
Thread::Mutex::$.lock();
# to call lock() in the current (or lower base) class
$.lock();

This syntax can only be used to call methods in the current class or in base classes. This is because these calls are resolved at parse time, and only these classes are known and accessible at parse time. To call a derived class method from a base class, you must use the $self variable to call the method, so that the call will be resolved at run-time, for example:

# this way, "member" can be resolved to a derived class method
$self.member();

Calls to object methods can be made outside the class by using the above syntax as well. All such calls are resolved at run-time, therefore if the call is made to a private function outside the defining class, then a run-time METHOD-IS-PRIVATE (if the method is private) or BASE-CLASS-IS-PRIVATE (if the method resolves to a privately-inherited base class) exception will be raised.

2.21.6. Class Inheritance

Class inheritance is a powerful concept for easily extending and resuing object-oriented code, but is also subject to some limitations. This section will explain how class inheritance works in Qore.

Classes inherit the methods of a parent class by using the inherits as specified above. Multiple inheritance is supported; a single Qore class can inherit one or more classes. When a class is inherited by another class, it is called a base class. Private inheritance is speficied by including the keyword private before the inherited class name. When a class is privately inherited, it means that the inherited class' public members are treated as private members in the context of accesses outside the class.

Inheritance is public by default, to inherit a class privately, use the private keyword before the class name or class path to inherit.

It is not legal to directly inherit the same class more than once; that is; it is not legal to list the same class more than once after the inherits keyword. However, it is possible that a base class could appear more than once in the inheritance tree if that class is inherited separately by two or more classes in the tree. In this case, the base class will actually only be inherited once in the subclass, even though it appears in the inheritance tree more than once. This must be taken into consideration when designing class hierarchies, particularly if base class constructor parameters for that class are explicitly provided in a different way by the inheriting classes.

Note

Class members only exist once for each object; therefore if classes in an inheritance tree have different uses for members with the same name, then a class hierarchy built of such classes will probably not function properly.

Subclasses can give explicit arguments to their base class constructors using a special syntax (only available to subclass constructors) similar to the C++ syntax for the same purpose as follows:

class_name::constructor([[type] $var1, ...) : base_class_identifier(expression(s))[, ...] {
    statements;
}

Here is a concrete example of giving arguments to an inherited base class:

class XmlRpcClient inherits Qore::HTTPClient {
    # calls the base class HTTPClient constructor, overrides the "protocols" key to "xmlrpc"
    constructor(hash $opts = hash()) : Qore::HTTPClient($opts + ( "protocols" : "xmlrpc" ))
    ...
}

Because base class constructors are executed before subclass constructors, the only local variables in the constructor that can be referenced are those declared in the subclass constructor declaration (if any). What this means is that if you declare local variables in the expressions giving base class arguments, these local variables are not accessible from the constructor body.

Note

Base classes that give explicit arguments to their base class constructors can be overridden by subclasses by simply listing the base class in the base class constructor list and providing new arguments.

2.21.7. Object References

Like Java, in Qore, objects are treated differently from all other data types in that they are by default passed as arguments to functions and methods by passing a copy of a reference to the object. That means that passing an object to a function that modifies the object will by default modify the original object and not a copy, however reassigning a local parameter variable assigned an object passed as an argument (that is only assigned to a local variable in the calling function) will not result in deleting the object, but rather decrement its scope reference count (note that if the object were created as a part of the call and reassigning the variable would cause the object's scope reference count to reach zero, then the object would be deleted in this case).

Assigning an object to a variable has the same effect; a copy of a reference to the object is assigned to the variable. This results in prolonging the object's scope (by owning a new copy of a reference to the object).

An example:

sub test2(any $x) {
   # we can modify the original object like so:
   $x.member = "tree";

   # here we re-assign $x, but since the object is also assigned
   # to $o in the calling function, the object's scope is still
   # valid, and therefore nothing happens so the object
   $x = 1;
}

sub test() {
   my TestObject $o();

   # here we pass a copy of a reference to the object in $o
   test2($o);

   # this will print out "ok\n", because the object is still
   # valid and the member has been set by test2()
   if ($o.member == "tree")
      print("ok\n");
}
# when test() exits, the object in $o will go out of scope
# and be deleted

If, however, an object is passed by reference, then the local variable of the called function that accepts the object owns the scope reference of the calling functions's variable.

An example:

sub test2(any $x) {
   # we can modify the original object like so:
   $x.member = "tree";

   # here we re-assign $x, and since we own the only scope 
   # reference to the object, the object will go out of 
   # scope here and be deleted
   $x = 1;
}

sub test() {
   my TestObject $o();

   # here we pass a reference to the object in $o
   test2(\$o);

   # the object has already been deleted in test2() and
   # therefore nothing will be printed out
   if ($o.member == "tree")
      print("ok\n");
}

2.21.8. Object Scope

Objects are automatically deleted when their scope-relevant reference count reaches zero (note that objects can be deleted manually at any time by using the delete operator). Whenever an object is deleted, the object's class' destructor method is run on the object.

The following affect objects' scope:

  • Variable Assignments

    An object's automatic scope is prolonged as long as the object is assigned to a local variable.

  • Existence of a Closure Created Within the Object

    Any closures created from within the object encapsulate the object's state (along with any local variables referenced within the closure) and also prolong the object's automatic scope as long as the closure exists.

  • Object Method Thread Launched Within the Object

    If a member function thread was launched from within the object using the background operator, the object's automatic scope is prolonged to the life of the new thread. Object threads started externally to the object (i.e. not directly from an expression with the background operator within a method) will not prolong the scope of the object.

    If an object with running threads is explicitly deleted, and this case is not handled in the object's destructor() method (by ensuring that all other running threads terminate gracefully), exceptions will be thrown in other threads at any attempt to access the already-deleted object.

    For more information about threading, please see the following section Threading

Note

The fact that object threads and closures can prolong object scope means, for example, that objects assigned to local variables can exist for longer than the scope of their host variable if they have one or more methods running in other threads or if closures created from within the object still exist at the time the local variable goes out of scope.

2.21.9. Copying Objects

To explicitly generate a copy of an object, the copy() constructor must be called. This is a special method that exists implicitly for every class even if it is not explicitly defined (like constructor() and destructor() methods). The implicit behavior of the copy() constructor is to create a new object with new members that are copies of the original members (except objects are once again referenced). Then, if any copy() method exists, it will be executed in the new object, passing a reference to the old object as the first paramter.

Note

In a class hierarchy copy() methods are called in the same order as constructor() methods.

Note

Not all built-in classes can be copied. Classes not supporting copying will throw an exception when the copy() methods are called. See the documentation for each class for more information.

2.22. Threading

A thread is an independent sequence of execution of Qore code within a Qore program or script. Each thread has a thread ID or TID.

The first thread of execution in a Qore program has TID 1. TID 0 is always reserved for the special signal handler thread.

The Qore language is designed to be thread-safe and Qore programs should not crash the Qore executable due to threading errors. Threading errors should only cause exceptions to be thrown or application errors to occur.

Threading functionality in Qore is provided by the operating system's POSIX threads library.

2.22.1. Creating and Terminating Threads

New threads are created with the background operator. This operator executes the expression given as an argument in a new thread and returns the TID of the new thread to the calling thread. This is most useful for calling user subroutines or object methods designed to run in a separate thread.

To terminate a thread, the thread_exit statement should be called, as calling the exit() function will terminate the entire UNIX process (and therefore all threads) immediately.

2.22.2. Threading and Variables

All global variables are shared in Qore programs, while local variables (declared with my) are generally local to each thread (and thus accessed without any mutual-exclusion locking), regardless of location. This means that if a variable is declared with my at the top level, it will actually have global scope, but also each thread will have its own copy of the variable. In effect, declaring a top-level local variable with my actually creates a global thread-local variable.

The following code gives an example of declaring a global thread-local variable by using my at the top-level:

%require-our
sub t() {
    printf("x=%n\n", $x);
}
my $x = 2;
t();
background t();

This will print out:

x=2
x=<NOTHING>

Note that the second time the local variable is accessed in the background thread, it has no value.

Due to the way Qore's local variables work, it is illegal to declare a top-level local variable after first block is parsed in the program; that is; if any call to parse() or Program::parse() is made in an existing program (where a top-level block already exists), and an attempt to declare a new top-level local variable is made, then a ILLEGAL-TOP-LEVEL-LOCAL-VARIABLE parse exception will be raised.

Access to global variables in qore is wrapped in mutual-exclusion locks to guarantee safe access to global variable data in a multithreaded context. Local variables are thread-local and therefore not locked, except when referenced in a closure expression, in which case the local variable's scope is extended to that of the closure's, and all accesses to the bound local variable are made within mutual-exclusion locks as these variables may be used in multithreaded contexts.

An alternative to global thread-local variables is offered by the save_thread_data() and get_thread_data() functions (documented in Threading Functions).

2.22.3. Thread Synchronization and Inter-Thread Communication

The synchronized keyword can be used before subroutine or class method definitions in order to guarantee that the function or method call will only be executed in one thread at a time. As in Java, this keyword can also be used safely with recursive functions and methods (internally a Gate-like object is used to guarantee thread-exclusivity and allow recursion).

The following classes are useful when developing multi-threaded Qore programs:

Table 2.94. Classes Useful With Threading

Class

Description

Mutex

A mutual-exclusion thread lock.

Gate

A recursive thread lock.

RWLock

A read-write thread lock.

Condition

Allows Qore programs to block until a certain condition becomes true.

Counter

A blocking counter class.

Queue

A thread-safe, blocking queue class (useful for message passing).

RMutex

DEPRECATED in favor of the Gate class: A recursive mutual-exclusion thread lock.

Sequence

A simple, thread-atomic sequence object (increment-only).

AutoLock

A helper class to automatically release Mutex locks when the AutoLock object is deleted.

AutoGate

A helper class to automatically exit Gate locks when the AutoGate object is deleted.

AutoReadLock

A helper class to automatically release read locks when the AutoReadLock object is deleted.

AutoWriteLock

A helper class to automatically release read locks when the AutoWriteLock object is deleted.


The following functions assist writing safe and efficient multi-threaded Qore programs:

Table 2.95. Thread Functions

Function

Description

save_thread_data()

Saves a thread-local value against a key.

get_all_thread_data()

Retrieves the entire thread-local hash.

get_thread_data()

Retrieves a thread-local value based on a key.

delete_all_thread_data()

Deletes the entire thread-local data hash.

delete_thread_data()

Delete the value of a key in the thread-local data hash.

gettid()

Gets the thread's TID (thread identifier)

thread_list()

Returns a list of TIDs of running threads

num_threads()

Returns the number of running threads


2.22.4. Deadlocks

Qore supports deadlock detection in complex locking scenarios and will throw a THREAD-DEADLOCK exception rather than allow an operation to be performed that would cause a deadlock. Deadlock detection is implemented for internal locking (global variable and object access), synchronized methods and subroutinges, etc, as well as for all Qore threading classes.

Qore can only detect deadlocks when a lock resource acquired by one thread is required by another who holds a lock that the first thread also needs. Other errors such as forgetting to unlock a global lock and trying to acquire that lock in another thread cannot be differentiated from valid use of threading primitives and will result in a process that never terminates. However, common threading errors such as trying to lock the same Mutex twice in the same thread without unlocking it between the two Mutex::lock() calls are caught in Qore and exceptions are thrown. Additionally, locks are tracked as thread resources, so if a thread terminates while holding a lock, an exception will be thrown and the lock will be automatically released.

2.23. Exception Handling

Exceptions are errors that can only be handled using a try catch block. Any exception that is thrown in a try block will immediately cause execution of that thread to begin with the first statement of the catch block, regardless of the position of the program pointer of the running thread, even if nested subroutines or object method calls have been made.

Exceptions can be thrown by the Qore system for a number of reasons, see the documentation for each function and object method for details.

Programmers can also throw exceptions explicitly by using the throw and rethrow statements.

Information about the exception, including the context in which the exception occurred, is saved in the exception hash, which can be retrieved by using a parameter variable in the catch block (for more information about try catch blocks, see try and catch statements).

The exception hash contains the following members:

Table 2.96. Exception Hash Keys

Name

Type

Description

type

string

"System" or "User" depending on exception type

file

string

File name of file where exception occurred

line

integer

Line number where exception occurred

callStack

list of hashes

Backtrace information

err

any

This key is populated with the value of the first expression of the throw statement. For system exceptions, this is a string giving the exception code.

desc

any

This key is populated with the value of the second expression of the throw statement (if a list was thrown). For system exceptions, this is a string giving a text description of the error.

arg

any

This key is populated with the value of the third expression of the throw statement (if a list was thrown). For system exceptions, this is populated for some exceptions where additional information is provided.


Table 2.97. Call Stack Description

Name

Type

Description

function

string

function name

line

integer

line number

file

string

file name

type

string

Exception Type (ET_*) constants; see Exception Constants for values.

typecode

integer

Call Type (CT_*) constants; see Exception Constants for values.


System exceptions always throw 2 values, populating the "err" and "desc" keys of the exception hash, giving the exception string code and the exception description string, respectively, and occassionally, depending on the function, the "arg" key may be populated with supporting information. User exceptions have no restrictions, any values given in the throw statement will be mapped to exception keys as per the table above.

See the on_exit, on_success statement, and on_error statement for statements that allow for exception-safe and exception-dependent cleanup in Qore code.

Classes that assist in exception-safe lock handling are the AutoLock class, the AutoGate class, the AutoReadLock class, and the AutoWriteLock class.

2.24. XML Integration

XML functionality in Qore is provided by the libxml2 library, which provides a powerful, stable, clean, and thread-safe basis for XML integration in Qore.

XML provides an excellent way to describe hierarchical data, and thanks to libxml2, Qore can allow for easy serialization and deserialization between XML strings and Qore data structures.

XML serialization (conversion from Qore data structures to XML strings) in Qore relies on the fact that Qore hashes retain insertion order, which means that conversion to and from Qore data structures and XML strings can be done without data loss and without reordering the XML elements. In general, XML serialization is relatively straighforward, but there are a few issues to be aware of, particularly regarding element attributes and lists. These issues are described in the following paragraphs.

First, a straightforward example:

$h = ( "record" : ( "name" : ( "first" : "Fred", "last" : "Smith" ) ) );
printf("%s\n", makeFormattedXMLString($h));

This produces the following result

<?xml version="1.0" encoding="UTF-8"?>
<record>
  <name>
    <first>Fred</first>
    <last>Smith</last>
  </name>
</record>

To set XML attributes, the Qore value must be a hash and the attributes are stored in another hash in the key ^attributes^. That is; the value of the ^attributes^ key must be a hash, and each member of this hash will represent an attribute-value pair.

For example:

$h = ( "record" : ( "^attributes^" : ( "type" : "customer" ) , 
	            "name" : ( "first" : "Fred", "last" : "Smith" ) ) );
printf("%s\n", makeFormattedXMLString($h));

This produces the following results:

<?xml version="1.0" encoding="UTF-8"?>
<record type="customer">
  <name>
    <first>Fred</first>
    <last>Smith</last>
  </name>
</record>

If instead we wanted to have text instead of child data under the "record" node, we must set the ^value^ key of the hash along with the ^attributes^ key as follows:

$h = ( "record" : ( "^attributes^" : ( "type" : "customer" ) , 
	            "^value^" : "NO-RECORD" ) );
printf("%s\n", makeFormattedXMLString($h));

Giving the following results:

<?xml version="1.0" encoding="UTF-8"?>
<record type="customer">NO-RECORD</record>

Arrays are serialized with repeating node names as follows:

$h = ( "record" : ( "part" : ( "part-02-05", "part-99-23", "part-34-28" ) ) );
printf("%s\n", makeFormattedXMLString($h));

Producing the following results:

<?xml version="1.0" encoding="UTF-8"?>
<record type="customer">
  <part>part-02-05</part>
  <part>part-99-23</part>
  <part>part-34-28</part>
</record>

It gets a little trickier when a key should repeated at the same level in an XML string, but other keys come between, for example, take the following XML string:

<?xml version="1.0" encoding="UTF-8"?>
<para>Keywords: <code>this</code>, <code>that</code>, and <code>the_other</code>.</para>

It's not possible to use a list, because text is required in between. As described earlier, the ^value^ hash key can be used to serialize text in an XML string. In this case, we need to have several text nodes and several code nodes in a mixed-up order to give us the XML string we want. Because qore hases have unique keys (we can't use the same key twice in the same hash), we resort to a key naming trick that allows us to virtually duplicate our key names and therefore arrive at the XML string we want. We do this by appending a '^' character to the end of the key name and then some unique text. When serializing hash keys, any text after (and including) the '^' character is ignored. For the special key name ^value^, we do not need to duplicate the final '^' character. Instead we just add unique text to ensure that our hash can contain all the data we want and that it will be serialized in the right order to the XML string as follows:

$h = ( "para" : ( "^value^" : "Keywords: ", 
                  "code" : "this", 
                  "^value^1" : ", ", 
                  "code^1" : "that", 
                  "^value^2" : ", and ", 
                  "code^2" : "the_other", 
                  "^value^3" : "." ) );
printf("%s\n", makeFormattedXMLString($h));

By ignoring the text after the '^' character, the above code will serialize to the XML string we want. In general, by using this convention, we can properly serialize multiple out-of-order keys without losing data and still have unique names for our hash keys.

Note than when deserializing XML strings to Qore data structures, the above rules are applied in reverse. If any out-of-order duplicate keys are detected, Qore will automatically generate unique hash key names based on the above rules.

Also note that CDATA text will be generated if a hash key starts with '^cdata'; such text will not be processed for escape code substitution. When deserializing XML strings to qore data structures, CDATA text will be placed unmodified under such a hash key as well.

Table 2.98. Functions For XML Serialization and Deserialization

Function Name

Description

makeFormattedXMLFragment()

Serializes a hash into an XML string with formatting without an XML header.

makeFormattedXMLString()

Serializes a hash into an XML string with formatting and an XML header.

makeXMLFragment()

Serializes a hash into an XML string without an XML header or formatting.

makeXMLString()

Serializes a hash into a complete XML string with an XML header and without formatting.

parseXMLAsData()

parses an XML string as data (duplicate, out-of-order XML elements are collapsed into lists) and returns a Qore hash structure.

parseXMLAsDataWithSchema()

parses an XML string as data (duplicate, out-of-order XML elements are collapsed into lists) and validates against an XSD schema string and returns a Qore hash structure.

parseXML()

parses an XML string (XML element order is preserved by appending numeric suffixes to Qore hash key names when necessary) and returns a Qore hash structure.

parseXMLWithSchema()

parses an XML string (XML element order is preserved by appending numeric suffixes to Qore hash key names when necessary) and validates against an XSD schema string and returns a Qore hash structure.


Table 2.99. Classes Providing XML Functionality

Class

Description

XmlDoc

For analyzing and manipulating XML documents.

XmlNode

Gives information about XML data in an XML document.

XmlReader

For parsing or iterating through the elements of an XML document.


XML-RPC is a lightweight but powerful XML over HTTP web service protocol. Qore includes builtin support for this protocol. You can find more information about XML-RPC, including specifications and examples at http://xmlrpc.org.

Information about Qore's XML-RPC serialization can be found below.

Table 2.100. XML-RPC Serialization in Qore

Qore Type

XML-RPC Type

Description

 

string

string

direct conversion to UTF-8 string

 

integer

i4 or string

If the integer requires more than 32 bits to represent, then it is sent as a string

 

float

double

direct conversion

 

boolean

boolean

direct conversion

 

date

iso8601

Absolute date/time values will convert to the default time zone for the calling context for the output string if necessary. Note that relative date/time values (durations) will be serialized with the same format as absolute date/time values.

 

binary

base64

direct conversion

 

list

array

direct conversion

 

hash

struct

direct conversion

 

all others

n/a

All other types will cause an XML-RPC-SERIALIZATION-ERROR to be raised.

 

Table 2.101. Functions Providing XML-RPC Functionality

Function Name

Description

makeFormattedXMLRPCCallString()

Serializes a hash into an XML string formatted for an XML-RPC call with formatting.

makeFormattedXMLRPCCallStringArgs()

Serializes a hash into an XML string formatted for an XML-RPC call with formatting, taking a single list argument for the argument list.

makeFormattedXMLRPCFaultResponseString()

Serializes a hash into an XML string formatted for an XML-RPC fault response with formatting.

makeFormattedXMLRPCResponseString()

Serializes a hash into an XML string formatted for an XML-RPC response with formatting.

makeFormattedXMLRPCValueString()

Serializes a hash into an XML string in XML-RPC value format with formatting.

makeXMLRPCCallString()

Serializes a hash into an XML string formatted for an XML-RPC call without formatting.

makeXMLRPCCallStringArgs()

Serializes a hash into an XML string formatted for an XML-RPC call without formatting, taking a single list argument for the argument list.

makeXMLRPCFaultResponseString()

Serializes a hash into an XML string formatted for an XML-RPC fault response without formatting.

makeXMLRPCResponseString()

Serializes a hash into an XML string formatted for an XML-RPC response without formatting.

makeXMLRPCValueString()

Serializes a hash into an XML string in XML-RPC value format without formatting.

parseXMLRPCCall()

deserializies an XML-RPC call string, returning a Qore hash respresenting the call information.

parseXMLRPCResponse()

deserializies an XML-RPC response string, returning a Qore hash respresenting the response information.

parseXMLRPCValue()

deserializies an XML-RPC value tree, returning a Qore hash respresenting the information.


2.25. Signal Handling

Qore implements safe signal handling. Signals do not interrupt Qore threads, rather Qore uses a special signal handling thread with TID 0, dedicated to handling signals. The signal handling thread uses very few resources; it stays blocked (using no processor time and very little memory) until a signal with a Qore signal handler is raised; it then executes the handler and resumes waiting for signals.

Because the signal Qore's signal handling thread is not a normal thread, it does not affect num_threads() and does not appear in the list returned by thread_list().

Internally, Qore masks (blocks) all signals in every thread except the signal handling thread. In the signal handling thread, all signals are unmasked, except those with Qore-language handlers, then an internal call to sigwait() is made to receive and process signals raised one at a time.

Qore-language signal handlers are installed by passing a signal constant and a closure or call reference to the code to execute when the signal is raised to the set_signal_handler() function. Signal handlers are removed by passing a signal constant to the remove_signal_handler() function.

When a signal has been raised and the signal handler is called, the signal number is passed as the sole argument to the signal handler code.

Table 2.102. Signal Handling Functions

Function Name

Description

set_signal_handler()

Sets up a Qore signal handler using a signal number and a call reference.

remove_signal_handler()

Removes a Qore signal handler using a signal number.


See Signal Constants for a list of signal constants and Signal Mapping Hash Constants for two hash constants that can be used to map signal names to numbers and vice-versa. Note that signal constants are system-dependent; not all signals will be available in all systems; in case of doubt, see your system documentation for information on which signals are available.

The above functions are atomic, meaning that when they return to the caller, the signal handling thread has already acknowledged the changes.

It is not possible to set signal masks per thread; all signals are delivered to the signal handling thread. Signals not handled with a Qore signal handler are handled with their default action. It is not possible to catch SIGPIPE. SIGPIPE is always ignored in Qore.

Some issues to be aware of in signal handlers:

  • Thread-local storage is not persistent in signal handlers; it is deleted after every signal handler is run.

  • A signal handler that does not terminate will block the execution of further signal handlers and will block signal handling changes (such as updating the signal mask), resulting in a Qore process that must be killed manually. Because all Qore signal handling code is executed serially in a single thread, Qore signal handlers should execute and return quickly to give time to execute other handlers.

  • Signal handlers may install or remove signal handlers using set_signal_handler() or remove_signal_handler(), however in this case, changes to signal handling are made after the signal handler returns.

  • Signal handlers cannot call fork(); any attempt to call fork() in a signal handler will result in an an exception.

  • fork() (called externally to a signal handler) is handled as follows: the signal handling thread is terminated, fork() is executed, all signals are masked in the primary thread in the new process, then the signal handling thread is resumed in both processes. No signals can be received or handled while the signal handling thread is terminated. After the fork(), the new process will have exactly the same signal handlers and signal masks as the parent process.

  • Unhandled exceptions in signal handlers will simply be displayed on stderr as an unhandled exception and will have no other effect on Qore or Qore code (in particular, unhandled exceptions will not cause the signal handling thread to terminate).

  • If a signal handler executes the thread_exit statement, execution of the signal handler will terminate immediately, but the signal handling thread will not be stopped. Execution of further signal handlers (including that for the same signal being handled when thread_exit is executed) will not be affected.

2.26. Event Handling

Qore supports a simple event-handling mechanism to provide notification and details of socket and network events in higher-level classes. Classes currently supporting events are the Socket, HTTPClient, and FtpClient classes.

See Event Constants for a list of all event constants; details about each event are documented in the following sections.

Event information is placed on the event queue (which must be a Queue object) in the form of a hash. Each event has at least the following keys:

Table 2.103. Event Hash Common Keys

Key

Value

event

This key holds the event code; see information for individual events in the following sections

source

This key holds the event source code

id

The value of this key is a unique integer that can be used to uniquely identify the object generating the event.


2.26.1. EVENT_PACKET_READ

Event

EVENT_PACKET_READ

Source

SOURCE_SOCKET

Description

This event is raised immediately after a network packet is received. The event hash contains the following keys:

Table 2.104. EVENT_PACKET_READ Event Hash

Key

Value

event

EVENT_PACKET_READ

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

read

The number of bytes read in the packet.

total_read

The total number of bytes read in the read loop.

[total_to_read]

The total number of bytes to read in the read loop (this key is only present if the total number of bytes to read is known).


2.26.2. EVENT_PACKET_SENT

Event

EVENT_PACKET_SENT

Source

SOURCE_SOCKET

Description

This event is raised immediately after a network packet is sent. The event hash contains the following keys:

Table 2.105. EVENT_PACKET_SENT Event Hash

Key

Value

event

EVENT_PACKET_SENT

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

socket

The file descriptor number of the socket.

sent

The number of bytes sent in the packet.

total_sent

The total number of bytes sent in the send loop.

total_to_send

The total number of bytes to send in the send loop.


2.26.3. EVENT_HTTP_CONTENT_LENGTH

Event

EVENT_HTTP_CONTENT_LENGTH

Source

SOURCE_HTTPCLIENT

Description

This event is raised immediately after an HTTP header is received containing a content length header line, but before the message body is received. The event hash contains the following keys:

Table 2.106. EVENT_HTTP_CONTENT_LENGTH Event Hash

Key

Value

event

EVENT_HTTP_CONTENT_LENGTH

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

id

A unique integer ID for the socket object.

len

The number of bytes given for the content length.


2.26.4. EVENT_HTTP_CHUNKED_START

Event

EVENT_HTTP_CHUNKED_START

Source

SOURCE_HTTPCLIENT

Description

This event is raised after receiving an HTTP header with Transfer-Encoding set to chunked and before the chunked data is read. The event hash contains the following keys:

Table 2.107. EVENT_HTTP_CHUNKED_START Event Hash

Key

Value

event

EVENT_HTTP_CHUNKED_START

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

id

A unique integer ID for the socket object.


2.26.5. EVENT_HTTP_CHUNKED_END

Event

EVENT_HTTP_CHUNKED_END

Source

SOURCE_HTTPCLIENT

Description

This event is raised after all chunked data is read from the socket. The event hash contains the following keys:

Table 2.108. EVENT_HTTP_CHUNKED_END Event Hash

Key

Value

event

EVENT_HTTP_CHUNKED_END

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

id

A unique integer ID for the socket object.


2.26.6. EVENT_HTTP_REDIRECT

Event

EVENT_HTTP_REDIRECT

Source

SOURCE_HTTPCLIENT

Description

This event is raised after a redirect response is received from an HTTP server. The event hash contains the following keys:

Table 2.109. EVENT_HTTP_REDIRECT Event Hash

Key

Value

event

EVENT_HTTP_REDIRECT

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

id

A unique integer ID for the socket object.

location

The redirect location given by the HTTP server

[status_message]

Any status message sent by the HTTP server; if no message was sent, then this key will not be present in the event hash.


2.26.7. EVENT_CHANNEL_CLOSED

Event

EVENT_CHANNEL_CLOSED

Source

SOURCE_SOCKET

Description

This event is raised immediately after the socket is closed. The event hash contains the following keys:

Table 2.110. EVENT_CHANNEL_CLOSED Event Hash

Key

Value

event

EVENT_CHANNEL_CLOSED

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.


2.26.8. EVENT_DELETED

Event

EVENT_DELETED

Source

SOURCE_SOCKET

Description

This event is raised when the socket object is deleted. The event hash contains the following keys:

Table 2.111. EVENT_DELETED Event Hash

Key

Value

event

EVENT_DELETED

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.


2.26.9. EVENT_FTP_SEND_MESSAGE

Event

EVENT_FTP_SEND_MESSAGE

Source

SOURCE_FTPCLIENT

Description

This event is raised immediately before a message is sent on the FTP control channel. The event hash contains the following keys:

Table 2.112. EVENT_FTP_SEND_MESSAGE Event Hash

Key

Value

event

EVENT_FTP_SEND_MESSAGE

source

SOURCE_FTPCLIENT, indicating the FtpClient class

id

A unique integer ID for the socket object.

command

A string giving the FTP command sent (ex: RETR).

[arg]

The argument to the command; if no argument is sent, then this key will not be present.


2.26.10. EVENT_FTP_MESSAGE_RECEIVED

Event

EVENT_FTP_MESSAGE_RECEIVED

Source

SOURCE_FTPCLIENT

Description

This event is raised immediately after a message is received on the FTP control channel. The event hash contains the following keys:

Table 2.113. EVENT_FTP_MESSAGE_RECEIVED Event Hash

Key

Value

event

EVENT_FTP_MESSAGE_RECEIVED

source

SOURCE_FTPCLIENT, indicating the FtpClient class

id

A unique integer ID for the socket object.

command

A string giving the FTP command sent (ex: RETR).

[arg]

The argument to the command; if no argument is sent, then this key will not be present.


2.26.11. EVENT_HOSTNAME_LOOKUP

Event

EVENT_HOSTNAME_LOOKUP

Source

SOURCE_SOCKET

Description

This event is raised immediately before a hostname lookup is made. The event hash contains the following keys:

Table 2.114. EVENT_HOSTNAME_LOOKUP Event Hash

Key

Value

event

EVENT_HOSTNAME_LOOKUP

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

name

A string giving the name to be looked up.


2.26.12. EVENT_HOSTNAME_RESOLVED

Event

EVENT_HOSTNAME_RESOLVED

Source

SOURCE_SOCKET

Description

This event is raised immediately after a successful hostname resolution. The event hash contains the following keys:

Table 2.115. EVENT_HOSTNAME_RESOLVED Event Hash

Key

Value

event

EVENT_HOSTNAME_RESOLVED

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

address

A string giving the network address the name was resolved to.


2.26.13. EVENT_HTTP_SEND_MESSAGE

Event

EVENT_HTTP_SEND_MESSAGE

Source

SOURCE_HTTPCLIENT or SOURCE_SOCKET

Description

This event is raised immediately before an HTTP message is sent. The event hash contains the following keys:

Table 2.116. EVENT_HTTP_SEND_MESSAGE Event Hash

Key

Value

event

EVENT_HTTP_SEND_MESSAGE

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class, or SOURCE_SOCKET, indicating the Socket class

message

The first string in the HTTP message (ex: GET / HTTP/1.1).

headers

A hash of all headers to send in the message.


2.26.14. EVENT_HTTP_MESSAGE_RECEIVED

Event

EVENT_HTTP_MESSAGE_RECEIVED

Source

SOURCE_HTTPCLIENT or SOURCE_SOCKET

Description

This event is raised immediately after an HTTP message is received. The event hash contains the following keys:

Table 2.117. EVENT_HTTP_MESSAGE_RECEIVED Event Hash

Key

Value

event

EVENT_HTTP_MESSAGE_RECEIVED

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class, or SOURCE_SOCKET, indicating the Socket class

headers

A hash of all headers received in the message, plus the following headers giving additional information about the message: http_version giving the HTTP protocol version in the message, status_code giving the HTTP status code if the message is a response, status_message giving any HTTP status message if the message is a response, method giving the HTTP method if the message is a request, path providing the path in request messages.


2.26.15. EVENT_HTTP_FOOTERS_RECEIVED

Event

EVENT_HTTP_FOOTERS_RECEIVED

Source

SOURCE_HTTPCLIENT

Description

This event is raised immediately after HTTP footers are received after receiving chunked data. The event hash contains the following keys:

Table 2.118. EVENT_HTTP_FOOTERS_RECEIVED Event Hash

Key

Value

event

EVENT_HTTP_FOOTERS_RECEIVED

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

headers

A hash of all footers received in the message.


2.26.16. EVENT_HTTP_CHUNKED_DATA_RECEIVED

Event

EVENT_HTTP_CHUNKED_DATA_RECEIVED

Source

SOURCE_HTTPCLIENT

Description

This event is raised immediately after chunked data is received. The event hash contains the following keys:

Table 2.119. EVENT_HTTP_CHUNKED_DATA_RECEIVED Event Hash

Key

Value

event

EVENT_HTTP_CHUNKED_DATA_RECEIVED

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

read

An integer giving the number of bytes read in the chunk.

total_read

An integer giving the total number of bytes of chunked data read in the current message.


2.26.17. EVENT_HTTP_CHUNK_SIZE

Event

EVENT_HTTP_CHUNK_SIZE

Source

SOURCE_HTTPCLIENT

Description

This event is raised immediately after chunk information is received providing the size of the next chunk. The event hash contains the following keys:

Table 2.120. EVENT_HTTP_CHUNK_SIZE_RECEIVED Event Hash

Key

Value

event

EVENT_HTTP_CHUNK_SIZE_RECEIVED

source

SOURCE_HTTPCLIENT, indicating the HTTPClient class

size

An integer giving the number of bytes in the next chunk.

total_read

An integer giving the total number of bytes of chunked data read in the current message.


2.26.18. EVENT_CONNECTING

Event

EVENT_CONNECTING

Source

SOURCE_SOCKET

Description

This event is raised immediately before a socket connection is attempted. The event hash contains the following keys:

Table 2.121. EVENT_CONNECTING Event Hash

Key

Value

event

EVENT_CONNECTING

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

type

The type of address for the socket; one of the Network Address Constants.

target

The target address for the connection.

[port]

The target port for the connection; if not applicable for the address family then this hash key is not included.


2.26.19. EVENT_CONNECTED

Event

EVENT_CONNECTED

Source

SOURCE_SOCKET

Description

This event is raised immediately after a socket connection is established. The event hash contains the following keys:

Table 2.122. EVENT_CONNECTED Event Hash

Key

Value

event

EVENT_CONNECTED

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.


2.26.20. EVENT_START_SSL

Event

EVENT_START_SSL

Source

SOURCE_SOCKET

Description

This event is raised immediately before SSL negotiation is attempted. The event hash contains the following keys:

Table 2.123. EVENT_START_SSL Event Hash

Key

Value

event

EVENT_START_SSL

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.


2.26.21. EVENT_SSL_ESTABLISHED

Event

EVENT_SSL_ESTABLISHED

Source

SOURCE_SOCKET

Description

This event is raised immediately after SSL negotiation has been successfully established. The event hash contains the following keys:

Table 2.124. EVENT_SSL_ESTABLISHED Event Hash

Key

Value

event

EVENT_SSL_ESTABLISHED

source

SOURCE_SOCKET, indicating the Socket class

id

A unique integer ID for the socket object.

cipher

A string giving the name of the cipher algorithm used for the connection.

cipher_version

A string giving the version of the cipher algorithm used for the connection.


2.26.22. EVENT_OPEN_FILE

Event

EVENT_OPEN_FILE

Source

SOURCE_FILE

Description

This event is raised immediately before a file is opened. The event hash contains the following keys:

Table 2.125. EVENT_OPEN_FILE Event Hash

Key

Value

event

EVENT_OPEN_FILE

source

SOURCE_FILE, indicating the File class

id

A unique integer ID for the file object.

filename

The file's name.

flags

The flags used to open the file.

mode

The mode to open the file with.

encoding

The character encoding given used for reading from or writing to the file.


2.26.23. EVENT_FILE_OPENED

Event

EVENT_FILE_OPENED

Source

SOURCE_FILE

Description

This event is raised immediately after a file has been successfully opened. The event hash contains the following keys:

Table 2.126. EVENT_FILE_OPENED Event Hash

Key

Value

event

EVENT_FILE_OPENED

source

SOURCE_FILE, indicating the File class

id

A unique integer ID for the file object.

filename

The file's name.

flags

The flags used to open the file.

mode

The mode to open the file with.

encoding

The character encoding given used for reading from or writing to the file.


2.26.24. EVENT_DATA_READ

Event

EVENT_DATA_READ

Source

SOURCE_FILE

Description

This event is raised immediately after data is read from a file. The event hash contains the following keys:

Table 2.127. EVENT_DATA_READ Event Hash

Key

Value

event

EVENT_DATA_READ

source

SOURCE_FILE, indicating the File class

id

A unique integer ID for the file object.

read

The number of bytes read from the file.

total_read

The total number of bytes read in the read loop.

total_to_read

The total number of bytes to read in the read loop.


2.26.25. EVENT_DATA_WRITTEN

Event

EVENT_DATA_WRITTEN

Source

SOURCE_FILE

Description

This event is raised immediately after data is written from a file. The event hash contains the following keys:

Table 2.128. EVENT_DATA_WRITTEN Event Hash

Key

Value

event

EVENT_DATA_WRITTEN

source

SOURCE_FILE, indicating the File class

id

A unique integer ID for the file object.

written

The number of bytes written to the file.

total_written

The total number of bytes written in the write loop.

total_to_write

The total number of bytes to write in the write loop.


Chapter 3. Function Library

This section describes the built-in subroutines in the Qore language making up the system function library. Following is a list of function categories, and below there is an alphabetically-ordered list of all Qore built-in functions.


Each builtin function or method has flags that describe its properties. The following table provides the key to the flags as given in the function and method lists.

Table 3.2. Code Flags

Abbr

Description

NOOP

Code with this flag makes no calculations, but rather returns a constant value. This flag is given to function and method variants that return a default value depending on the type of argument(s). When variants with this flag are resolved at parse time, a call-with-type-errors warning is raised (assuming this warning is enabled).

RT_NOOP

Code with this flag makes no calculations, but rather returns a constant value. This flag is given to function and method variants that return a default value depending on the type of argument(s). When variants with this flag are resolved at parse time, a call-with-type-errors warning is raised (assuming this warning is enabled), unless PO_REQUIRE_TYPES or PO_STRICT_ARGS is set. If PO_REQUIRE_TYPES or PO_STRICT_ARGS is set, then these variants are inaccessible; resolving to a variant with this flag set at parse time or run time causes an exception to be thrown. These variants are included for backwards-compatibility with qore prior to version 0.8.0 for functions that would ignore type errors in arguments.

CONST

Code with this flag is safe to be used when assigning a constant, because it has no side effects and normally does not throw an exception (at least in the context of assigning a constant).

DEPRECATED

Code with this flag is deprecated and will be removed in a future version of Qore; if a variant with this flag is resolved at parse time, a deprecated warning is raised (assuming this warning is enabled).


Table 3.3. System Function Library

Function Name

Ex?

Brief Description

abort() returns nothing

N

aborts the process

abs(softfloat) returns float

abs(int) returns int

abs() returns float (RT_NOOP)

N

Returns the absolute value of the argument passed

acos(any) returns float

N

Returns the arc cosine of the number passed in radians

asin(softfloat) returns float

asin() returns float (RT_NOOP)

N

Returns the arc sine of the number passed in radians.

atan(softfloat) returns float

atan() returns float (RT_NOOP)

N

Returns the arc tangent of the number passed in radians.

backquote(string) returns string

backquote() returns nothing (RT_NOOP)

Y

Executes a process and returns a string of the output (stdout only)

basename(string) returns string

basename() returns nothing (RT_NOOP)

N

Returns a string giving the last element of a file path.

binary(softstring) returns binary (CONST)

binary(binary) returns binary (CONST)

binary(null) returns binary (CONST)

binary() returns binary (CONST)

N

Returns a binary data type of the data passed.

binary_to_string(binary) returns string

binary_to_string(binary, string) returns string

Y

Returns a string created from the binary data passed.

bindex(softstring, softstring, softint = 0) returns int

bindex() returns int (RT_NOOP)

N

Returns the byte position of a substring within a string and takes an optional starting offset

blowfish_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for the blowfish algorithm.

blowfish_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for the blowfish algorithm.

blowfish_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for the blowfish algorithm.

boolean(softbool) returns bool (CONST)

boolean(null) returns bool (CONST)

boolean() returns bool (CONST)

N

Converts the argument to a boolean value.

brindex(softstring, softstring, softint = -1) returns int

brindex() returns int (RT_NOOP)

N

Returns the byte position of a substring within a string as searched from the end of the string and takes an optional starting offset

bunzip2_to_binary(binary) returns binary

bunzip2_to_binary() returns nothing (RT_NOOP)

Y

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary.

bunzip2_to_string(binary, string = defaultEncoding) returns string

bunzip2_to_string() returns nothing (RT_NOOP)

Y

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a string.

bzip2(data, softint = 9) returns binary

bzip2() returns nothing> (RT_NOOP)

Y

Compresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary.

call_builtin_function(string, ...) returns any

Y

Calls a builtin function identified by the first string argument and returns the return value, passing the remaining arguments after the function name to the function

call_builtin_function_args(string, list) returns any

call_builtin_function_args(string, any) returns any

Y

Calls a builtin function identified by the first string argument and returns the return value, using the argument after the function name as a list of arguments to pass to the function.

call_function(string, ...) returns any

call_function(code, ...) returns any

Y

Calls a function, closure, or call reference and returns the return value, passing the remaining arguments after the function name to the function (or call reference).

call_function_args(string, list) returns any

call_function_args(string, any) returns any

call_function_args(code, list) returns any

call_function_args(code, any) returns any

Y

Calls a function, closure, or call reference and returns the return value, using the argument after the function name as a list of arguments to pass to the function, closure, or call reference.

callObjectMethod(object, string) returns any

callObjectMethod() returns nothing (RT_NOOP)

Y

calls a method given by a string of the object passed, passing the remaining arguments to the method as arguments

callObjectMethodArgs(object, string, list) returns any

callObjectMethodArgs(object, string, any) returns any

callObjectMethodArgs() returns nothing (RT_NOOP)

Y

calls a method given by a string of the object passed, using the argument after the method name as the list of arguments to pass to the method

cast5_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for the CAST5 algorithm.

cast5_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for the CAST5 algorithm.

cast5_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for the CAST5 algorithm.

cbrt(softfloat) returns float

cbrt() returns float (RT_NOOP)

N

Returns the cube root of the number passed.

ceil(softfloat) returns float

ceil() returns float (RT_NOOP)

N

Returns a value rounded up to the next highest integer

chdir(string) returns int

Y

Changes the current working directory.

chmod(string, int) returns int

Y

Changes the mode of a file.

chomp(string) returns string

chomp(reference) returns any

N

Removes the trailing end-of-line indicator from a string and returns the new string (also see the chomp operator); also accepts variable references to do modifications in-place.

chown(string, softint = -1, softint = -1) returns int

N

Changes the user and group owners of a file (if the current user has permission to do so), follows symbolic links.

chr(softint) returns string

chr(any) returns string (NOOP)

chr() returns nothing (RT_NOOP)

N

Returns a string containing a single ASCII character represented by the numeric value passed.

clock_getmicros() returns int (CONST)

N

Returns the system time in microseconds (1/1000000 second intervals) since Jan 1, 1970 00:00:00Z.

clock_getmillis() returns int (CONST)

N

Returns the system time in milliseconds (1/1000 second intervals) since Jan 1, 1970 00:00:00Z.

clock_getnanos() returns int (CONST)

N

Returns the system time in nanoseconds (1/1000000000 second intervals) since Jan 1, 1970 00:00:00.

compress(data, softint = -1) returns binary

compress() returns nothing (RT_NOOP)

Y

Performs zlib-based "deflate" data compression (RFC 1951) and returns a binary object of the compressed data.

convert_encoding(string, string) returns string (CONST)

convert_encoding() returns nothing (RT_NOOP)

Y

Performs explicit string character encoding conversions.

cos(softfloat) returns float (CONST)

cos() returns float (RT_NOOP)

N

Returns the cosine of the number in radians passed.

cosh(softfloat) returns float (CONST)

cosh() returns float (RT_NOOP)

N

Returns the hyperbolic cosine of the number passed.

date(string) returns date (CONST)

date(softint) returns date (CONST)

date(null) returns date (CONST)

date() returns date (CONST)

N

Converts the argument passed to a date.

date_ms(softint) returns date (CONST)

date_ms() returns date (RT_NOOP)

N

Converts an integer argument as a millisecond offset from January 1, 1970Z to a date.

date_us(softint) returns date (CONST)

date_us() returns date (RT_NOOP)

N

Converts an integer argument as a microsecond offset from January 1, 1970Z to a date.

days(softint) returns date (CONST)

days() returns date (RT_NOOP)

N

Returns a relative date in days for date arithmetic.

decode_url(string) returns string (CONST)

decode_url() returns nothing (RT_NOOP)

N

Decodes percent numeric codes in a URL string and returns the decoded string.

delete_all_thread_data()

N

Deletes all keys in the thread-local data hash.

delete_thread_data(list) returns nothing

delete_thread_data(...) returns nothing

N

Deletes the data associated to one or more keys in the thread-local data hash (destroys any objects as well).

des_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for the DES algorithm.

des_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for the DES algorithm.

des_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data using the Cipher Block Chaining function for the DES algorithm.

des_ede_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm.

des_ede_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm.

des_ede_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for the two-key triple DES algorithm.

des_ede3_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm.

des_ede3_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm.

des_ede3_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for the three-key triple DES algorithm.

desx_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm.

desx_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm.

desx_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Encrypts data to a string using the Cipher Block Chaining function for RSA's DESX algorithm.

DSS(data) returns string

Y

Returns the DSS message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

DSS_bin(data) returns binary

Y

Returns the DSS message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

DSS1(data) returns string

Y

Returns the DSS1 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

DSS1_bin(data) returns binary

Y

Returns the DSS1 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

errno() returns int

N

Returns the value of the system "errno" variable, holding the last error code generated by a system call

exec(string) returns nothing

exec() returns nothing (RT_NOOP)

N

Replaces the current process image with another.

existsFunction(string) returns bool (CONST)

existsFunction(code) returns bool (NOOP)

existsFunction() returns nothing (RT_NOOP)

N

Returns True if the function exists in the current program's function name space.

exit(any = 0) returns nothing

N

Exits the program

exp(softfloat) returns float (CONST)

exp() returns float (RT_NOOP)

N

Returns the value of e raised to the power of the argument passed

exp2(softfloat) returns float (CONST)

exp2() returns float (RT_NOOP)

N

Returns the value of 2 raised to the power of the argument passed

expm1(softfloat) returns float (CONST)

expm1() returns float (RT_NOOP)

N

Returns an equivalent of exp(x) - 1

f_printf(string, ...) returns string

f_printf() returns string (RT_NOOP)

Y

"field" printf, field width specifiers are respected. Returns string printed.

f_sprintf(string, ...) returns string (CONST)

f_sprintf() returns string (RT_NOOP)

Y

"field" sprintf(), field width specifiers are respected

float(softfloat) returns float (CONST)

float(null) returns float (CONST)

float() returns float (CONST)

N

Returns the argument converted to a floating-point number

floor(softfloat) returns float (CONST)

floor() returns float (RT_NOOP)

N

Returns a value rounded down to the nearest integer

flush() returns nothing

N

Flushes output to the console output with print(), printf(), etc

force_encoding(string, string) returns string (CONST)

force_encoding() returns nothing (RT_NOOP)

N

Returns a string tagged with the given character encoding; does not actually change the string data; use only in the case that a string is tagged with the wrong encoding.

fork() returns int

N

Creates a duplicate of the current process

format_date(string, date) returns string (CONST)

format_date() returns nothing (RT_NOOP)

N

Allows dates to be formatted

format_number(string, any) returns string (CONST)

format_number() returns nothing (RT_NOOP)

N

Allows numbers to be formatted with more options than sprintf()

functionType(string) returns any (CONST)

functionType() returns nothing (RT_NOOP)

N

Returns "builtin", "user", or NOTHING according to the function name passed

get_all_thread_data() returns hash (CONST)

N

Returns the entire thread data hash.

get_byte(string, int = 0) returns any (CONST)

N

Returns the byte value at the given byte offset or NOTHING if the offset is not legal for the given data.

get_days(date) returns int (CONST)

get_days() returns nothing (RT_NOOP)

N

Returns an integer value representing the days value of the date passed (can be either a relative or absolute date).

get_default_encoding() returns string (CONST)

N

Returns the name of the default character encoding for the Qore library.

get_duration_microseconds(date) returns int (CONST)

N

Returns an integer giving the duration in microseconds as described by the argument; if the argument is a relative date, then it is converted to microseconds, if it is absolute, then a number of microseconds between the current time and the time given is returned.

get_duration_milliseconds(date) returns int (CONST)

N

Returns an integer giving the duration in milliseconds as described by the argument; if the argument is a relative date, then it is converted to milliseconds, if it is absolute, then a number of milliseconds between the current time and the time given is returned.

get_duration_seconds(date) returns int (CONST)

N

Returns an integer giving the duration in seconds as described by the argument; if the argument is a relative date, then it is converted to seconds, if it is absolute, then a number of seconds between the current time and the time given is returned.

get_encoding(string) returns string (CONST)

get_encoding() returns nothing (RT_NOOP)

N

Returns a string describing the character encoding of the string passed.

get_epoch_seconds(date) returns int (CONST)

get_epoch_seconds() returns nothing (RT_NOOP)

N

Returns the number of seconds after Jan 1, 1970, 00:00:00Z for the date/time value passed.

get_hours(date) returns int (CONST)

get_hours() returns nothing (RT_NOOP)

N

Returns an integer value representing the hours value of the date passed (can be either a relative or absolute date).

get_microseconds(date) returns int (CONST)

N

Returns an integer value representing the microseconds value of the date passed (can be either a relative or absolute date).

get_midnight(date) returns date (CONST)

get_midnight() returns nothing (RT_NOOP)

N

Returns a date/time value representing midnight on the date passed (strips the time from the date passed and returns the new value)

get_milliseconds(date) returns int (CONST)

get_milliseconds() returns nothing (RT_NOOP)

N

Returns an integer value representing the milliseconds value of the date passed (can be either a relative or absolute date).

get_minutes(date) returns int (CONST)

get_minutes() returns nothing (RT_NOOP)

N

Returns an integer value representing the minutes value of the date passed (can be either a relative or absolute date).

get_months(date) returns int (CONST)

get_months() returns nothing (RT_NOOP)

N

Returns an integer value representing the months value of the date passed (can be either a relative or absolute date).

get_qore_library_info() returns hash (CONST)

N

Returns a hash of build and version information for the qore library.

get_qore_option_list() returns list (CONST)

N

Returns a list of hashes giving information about qore library options.

get_seconds(date) returns int (CONST)

get_seconds() returns nothing (RT_NOOP)

N

Returns an integer value representing the seconds value of the date passed (can be either a relative or absolute date).

get_script_path() returns any (CONST)

N

Returns a string giving the path (directory and filename) from which the current script was executed (if known).

get_script_dir() returns any (CONST)

N

Returns a string giving the directory from which the current script was executed (if known).

get_script_name() returns any (CONST)

N

Returns a string giving the filename of the current script (if known).

get_thread_data(string) returns any (CONST)

get_thread_data() returns nothing (RT_NOOP)

N

Returns the value of the thread-local data attached to the key passed

get_word_16(data, softint = 0) returns any (CONST)

N

Returns the 16-bit value at the given 2-byte offset or NOTHING if the offset is not legal for the given data; assumes MSB byte order.

get_word_16_lsb(data, softint = 0) returns any (CONST)

N

Returns the 16-bit value at the given 2-byte offset or NOTHING if the offset is not legal for the given data; assumes LSB byte order.

get_word_32_lsb(data, softint = 0) returns any (CONST)

N

Returns the 32-bit value at the given 4-byte offset or NOTHING if the offset is not legal for the given data; assumes LSB byte order..

get_word_64_lsb(data, softint = 0) returns any (CONST)

N

Returns the 64-bit value at the given 8-byte offset or NOTHING if the offset is not legal for the given data; assumes LSB byte order..

get_years(date) returns int (CONST)

get_years() returns nothing (RT_NOOP)

N

Returns an integer value representing the years value of the date passed (can be either a relative or absolute date).

getAllThreadCallStacks() returns hash

N

Returns a hash of call stacks keyed by each TID (thread ID).

getByte(data, softint = 0) returns any (CONST)

getByte() returns nothing (RT_NOOP)

N

Returns the byte value withing the string or binary object passed, or if the offset is out of range, returns NOTHING.

getClassName(object) returns string (CONST)

getClassName() returns nothing (RT_NOOP)

N

Returns the class name of the object passed.

getcwd() returns any

N

Returns the name of the current working directory or NOTHING if an error occurs.

getcwd2() returns string

Y

Returns the name of the current working directory and throws an exception if an error occurs.

getDateFromISOWeek(softint, softint, softint = 1) returns date

Y

Retuns an absolute date value in the local time zone for the ISO-8601 calendar week information passed (year, week number, optional: day); throws an exception if the arguments are invalid.

getDayOfWeek(date) returns int (CONST)

getDayOfWeek() returns nothing (RT_NOOP)

N

Returns an integer representing the day of the week for the absolute date passed (0=Sunday, 6=Saturday)

getDayNumber(date) returns int (CONST)

getDayNumber() returns nothing (RT_NOOP)

N

Returns an integer representing the ordinal day number in the year for the absolute date passed

getDBIDriverCapabilities(string) returns any

getDBIDriverCapabilities() returns nothing (RT_NOOP)

N

Returns an integer representing the capabilities of a DBI driver or NOTHING if the driver cannot be loaded.

getDBIDriverCapabilityList(string) returns any

getDBIDriverCapabilityList() returns nothing (RT_NOOP)

N

Returns a list of codes representing the capabilities of a DBI driver of NOTHING if the driver cannot be loaded.

getDBIDriverList() returns any

N

Returns a list of strings of DBI drivers currently loaded or NOTHING if no drivers have been loaded.

getegid() returns int (CONST)

N

Returns the effective group ID of the current process.

geteuid() returns int (CONST)

N

Returns the effective user ID of the current process.

getFeatureList() returns list (CONST)

N

Returns a list of strings of the builtin and module-supplied features of Qore.

getenv(string) returns any (CONST)

getenv() returns nothing (RT_NOOP)

N

Retrieves the value of an environment variable or NOTHING if the variable is not set

getgid returns int (CONST)

N

Returns the real group ID of the current process.

getgrnam(string) returns any (CONST)

N

Returns a hash representing the group information of the group name passed or NOTHING if the group name is not found.

getgrnam2(string) returns hash

N

Returns a hash representing the group information of the group name passed; throws an exception if the group name is not found.

getgrgid(softint) returns any (CONST)

N

Returns a hash representing the group information of the group ID passed or NOTHING if the group ID is not found.

getgrgid2(softint) returns hash

N

Returns a hash representing the group information of the group ID passed; throws an exception if the group ID is not found.

gethostbyaddr(string, softint = AF_INET) returns any (CONST)

gethostbyaddr() returns nothing (RT_NOOP)

N

Returns the official hostname corresponding to the network addressed passed or NOTHING if the address cannot be resolved.

gethostbyaddr_long(string, softint = AF_INET) returns any (CONST)

gethostbyaddr_long() returns nothing (RT_NOOP)

N

Returns all host information corresponding to the network address as a hash or NOTHING if the address cannot be resolved.

gethostbyname(string) returns any (CONST)

gethostbyname() returns nothing (RT_NOOP)

N

Returns the first network address corresponding to the hostname as a string or NOTHING if the name cannot be resolved.

gethostbyname_long(string) returns any (CONST)

N

Returns all host information corresponding to the hostname as a hash or NOTHING if the name cannot be resolved.

gethostname() returns string

Y

Returns the hostname of the system; throws an exception if an error occurs.

getISODayOfWeek(date) returns int (CONST)

getISODayOfWeek() returns nothing (RT_NOOP)

N

Returns an integer representing the ISO-8601 day of the week for the absolute date passed (1=Monday, 7=Sunday)

getISOWeekHash(date) returns hash (CONST)

getISOWeekHash() returns nothing (RT_NOOP)

N

Returns a hash representing the ISO-8601 calendar week information for the absolute date passed (hash keys: year, week, day)

getISOWeekString(date) returns string (CONST)

getISOWeekString() returns nothing (RT_NOOP)

N

Returns a string representing the ISO-8601 calendar week information for the absolute date passed (ex: 2006-01-01 = "2005-W52-7")

getMethodList(object) returns list (CONST)

getMethodList() returns nothing (RT_NOOP)

N

Returns a list of strings of the names of the public and private methods of the class of the object passed as a parameter (does not return base class method names).

getModuleList() returns list (CONST)

N

Returns a list of hashes describing the currently-loaded Qore modules.

getpid() returns int (CONST)

N

Returns the PID (process ID) of the current process.

getppid() returns int (CONST)

N

Returns the parent PID of the current process.

getpwnam(string) returns any (CONST)

N

Returns a hash representing the user information of the username passed or NOTHING if the username is not found.

getpwnam2(string) returns hash

N

Returns a hash representing the user information of the username passed; throws an exception if the username is not found.

getpwuid(softint) returns any (CONST)

N

Returns a hash representing the user information of the user ID passed or NOTHING if the user ID is not found.

getpwuid2(softint) returns hash

N

Returns a hash representing the user information of the user ID passed; throws an exception if the user ID is not found.

gettid() returns int (CONST)

N

Returns the Qore thread ID (TID) of the current thread.

getuid() returns int (CONST)

N

Returns the real user ID of the current process.

getWord32(string, int = 0) returns any (CONST)

getWord32(binary, int = 0) returns any (CONST)

getWord32() returns nothing (RT_NOOP)

N

Returns the 32-bit value at the given 4-byte offset or NOTHING if the offset is not legal for the given data.

glob(string) returns any

glob() returns nothing (RT_NOOP)

N

Returns a list of files matching the string argument or NOTHING if the call to glob() fails.

gmtime(date) returns date (CONST)

gmtime(softint, softint = 0) returns date (CONST)

gmtime() returns date (CONST)

N

Returns a date/time value in UTC (GMT).

gunzip_to_binary(binary) returns binary

gunzip_to_binary() returns nothing (RT_NOOP)

Y

Uncompresses data compressed with the "gzip" algorithm (RFC 1952) using zlib functions and returns a binary object.

gunzip_to_string(binary) returns string

gunzip_to_string(binary, string) returns string

gunzip_to_string() returns nothing (RT_NOOP)

Y

Uncompresses data compressed with the "gzip" algorithm (RFC 1952) using zlib functions and returns a string.

gzip(string, softint = -1) returns binary

gzip(binary, softint = -1) returns binary

gzip() returns nothing (RT_NOOP)

Y

Performs zlib-based "gzip" data compression (RFC 1952) and returns a binary object of the compressed data.

hash(list $list) returns hash

hash(list $keys, list $values) returns hash

hash(hash $hash) returns hash (CONST)

hash(object $obj) returns hash

hash() returns hash (CONST)

N

Converts an object or a list to a hash; otherwise returns an empty hash.

hash_values(hash) returns list (CONST)

hash_values() returns nothing (RT_NOOP)

N

Returns a list of all the values in the hash argument passed.

hextoint(string) returns bigint

Y

Returns an integer for a hexadecimal string value; throws an exception if non-hex digits are found.

hlstat(string) returns any

hlstat() returns nothing (RT_NOOP)

N

Returns a hash of information about the file corresponding to the pathname argument; does not follow symbolic links (returns information about symbolic links). Returns NOTHING if the stat() call fails.

hours(softint) returns date (CONST)

hours() returns date (RT_NOOP)

N

Returns a relative date in hours to be used in date arithmetic.

hstat(string) returns any

hstat() returns nothing (RT_NOOP)

N

Returns a hash of information about the file corresponding to the pathname argument; follows symbolic links. Returns NOTHING if the stat() call fails.

html_decode(string) returns string (CONST)

html_decode() returns nothing (RT_NOOP)

N

Returns a string with any HTML escape codes translated to the original characters

html_encode(string) returns string (CONST)

html_encode() returns nothing (RT_NOOP)

N

Returns a string with any characters that can be escaped translated to HTML escape codes.

hypot(any, softfloat) returns float (CONST)

hypot(softfloat, any) returns float (CONST)

hypot() returns float (RT_NOOP)

N

Returns the length of the hypotenuse of a right-angle triangle with sides given as the two arguments.

index(softstring, softstring, softint = 0) returns int (CONST)

index() returns int (RT_NOOP)

N

Returns the character position of a substring within a string and takes an optional starting offset

inlist(any, list) returns bool

inlist(any, any) returns bool

inlist() returns bool (RT_NOOP)

N

Returns True if the first argument is a member of the second argument list using comparisons with type conversions.

inlist_hard(any, list) returns bool

inlist_hard(any, any) returns bool

N

Returns True if the first argument is a member of the second argument list using comparisons without type conversions.

int(softint) returns int (CONST)

int(null) returns int (CONST)

int() returns int (CONST)

N

Returns the argument converted to an integer

is_bdev(string) returns bool (CONST)

N

Returns True if the string passed identifies a block device file on the filesystem.

is_cdev(string) returns bool (CONST)

N

Returns True if the string passed identifies a character device file on the filesystem.

is_date_absolute(date) returns bool (CONST)

is_date_absolute(any) returns bool (RT_NOOP)

N

Returns True if an absolute date is passed as an argument, False if not.

is_date_relative(date) returns bool (CONST)

is_date_relative(any) returns bool (RT_NOOP)

N

Returns True if a relative date is passed as an argument, False if not.

is_dev(string) returns bool (CONST)

N

Returns True if the string passed identifies a device file (either block or character) on the filesystem.

is_dir(string) returns bool (CONST)

N

Returns True if the string passed identifies a directory on the filesystem.

is_executable(string) returns bool (CONST)

N

Returns True if the string passed identifies an executable file.

is_file(string) returns bool (CONST)

N

Returns True if the string passed identifies a regular file on the filesystem.

is_link(string) returns bool (CONST)

N

Returns True if the string passed identifies a symbolic link on the filesystem.

is_pipe(string) returns bool (CONST)

N

Returns True if the string passed identifies a pipe (FIFO) on the filesystem.

is_readable(string) returns bool (CONST)

N

Returns True if the string passed identifies a file readable by the current user.

is_socket(string) returns bool (CONST)

N

Returns True if the string passed identifies a socket on the filesystem.

is_writeable(string) returns bool (CONST)

N

Returns True if the string passed identifies a file writable by the current user.

join(string, list) returns string (CONST)

join(string, ...) returns string (CONST)

join() returns nothing (RT_NOOP)

N

Creates a string from a list and separator character

kill(softint, softint = SIGHUP) returns int

kill() returns nothing (RT_NOOP)

N

Sends a signal to a process (default: SIGHUP)

lchown(string, softint = -1, softint = -1) returns int

N

Changes the user and group owners of a file (if the current user has permission to do so), does not follow symbolic links.

length(softstring) returns int (CONST)

length(binary) returns int (CONST)

length(any) returns int (NOOP)

length() returns nothing (RT_NOOP)

N

Returns the length in characters for the string passed.

list(...) returns list (CONST)

N

Returns a list with the argument passed as the first element (or an empty list if no argument is passed)

load_module(string) returns nothing

load_module() returns nothing (RT_NOOP)

Y

Loads a Qore module at run-time if the feature name is not already present in the current Program object.

localtime(date) returns date (CONST)

localtime(softint, softint = 0) returns date (CONST)

localtime() returns date (CONST)

N

Returns a date value in localtime; if an argument is passed, then the date is created based on the value of the argument passed, for an integer, it is the number of seconds after Jan 1, 1970, 00:00:00Z (UTC).

log10(softfloat) returns float (CONST)

log10() returns float (RT_NOOP)

N

Returns the base 10 logarithm of the value passed

log1p(softfloat) returns float (CONST)

log1p() returns float (RT_NOOP)

N

Returns the natural logarithm of the value passed plus 1

logb(softfloat) returns float (CONST)

logb() returns float (RT_NOOP)

N

Returns the exponent of a number.

lstat(string) returns any

lstat() returns nothing (RT_NOOP)

N

Returns a list of filesystem values for the file or symbolic link passed or NOTHING if the call to stat() fails.

makeBase64String(data) returns string (CONST)

makeBase64String() returns nothing (RT_NOOP)

N

Returns a base64-encoded representation of a binary object or a string.

makeFormattedJSONRPC11ErrorString(softint, string, any, any) returns string

Y

Creates a JSON-RPC 1.1 error response string from the parameters passed, formatted with line breaks for easier readability.

makeFormattedJSONRPCErrorString(any, any, any) returns string

Y

Creates a generic JSON-RPC error response string from the parameters passed, formatted with line breaks for easier readability.

makeFormattedJSONRPCRequestString(string, any, any, any) returns string

Y

Creates a JSON-RPC request string from the parameters passed, formatted with line breaks for easier readability.

makeFormattedJSONRPCResponseString(any, any, any) returns string

Y

Creates a JSON-RPC response string from the parameters passed, formatted with line breaks for easier readability.

makeFormattedJSONString(any, string) returns string

makeFormattedJSONString(any) returns string

Y

Serializes qore data into a JSON string, formatted with line breaks for easier readability.

makeFormattedXMLFragment(hash, string) returns string

makeFormattedXMLFragment(hash) returns string

makeFormattedXMLFragment() returns nothing (RT_NOOP)

Y

Serializes a hash into an XML string with formatting and without an XML header.

makeFormattedXMLRPCCallString(string, ...) returns string

Y

Serializes the arguments into an XML string for an XML-RPC call with formatting.

makeFormattedXMLRPCCallStringWithEncoding(string, string, ...) returns string

Y

Serializes the arguments into an XML string for an XML-RPC call with formatting, taking an initial string argument to give the encoding for the created XML.

makeFormattedXMLRPCCallStringArgs(string, any) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call with formatting, taking a single list argument for the argument list.

makeFormattedXMLRPCCallStringArgsWithEncoding(string, string, any) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call with formatting, taking an initial string argument to give the encoding for the created XML, followed by the method name and a single list argument for the argument list.

makeFormattedXMLRPCFaultResponseString(any, string) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting.

makeFormattedXMLRPCFaultResponseStringWithEncoding(string, any, string) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting, taking an initial string argument to give the encoding for the created XML.

makeFormattedXMLRPCResponseString(...) returns any

Y

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting; if no arguments are passed, then NOTHING is returned.

makeFormattedXMLRPCResponseStringWithEncoding(string, ...) returns any

Y

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting, taking an initial string argument to give the encoding for the created XML. If no arguments after the encoding string are passed, then NOTHING is returned.

makeFormattedXMLRPCValueString(any, string) returns string

makeFormattedXMLRPCValueString(any) returns string

Y

Serializes the arguments into an XML string in XML-RPC Value format with whitespace formatting.

makeFormattedXMLString(hash) returns string

makeFormattedXMLString(hash, string) returns string

makeFormattedXMLString(string, hash) returns string

makeFormattedXMLString(string, hash, string) returns string

Y

Serializes a hash into an XML string with formatting and an XML header.

makeHexString(data) returns string (CONST)

makeHexString() returns nothing (RT_NOOP)

N

Returns a hex-encoded representation of a binary object or a string.

makeJSONRPC11ErrorString(softint, string, any, any) returns string

Y

Creates a JSON-RPC 1.1 error response string from the parameters passed, without any line breaks.

makeJSONRPCErrorString(any, any, any) returns string

Y

Creates a generic JSON-RPC error response string from the parameters passed, without any line breaks.

makeJSONRPCRequestString(string, any, any, any) returns string

Y

Creates a JSON-RPC request string from the parameters passed, without any line breaks.

makeJSONRPCResponseString(any, any, any) returns string

Y

Creates a JSON-RPC response string from the parameters passed, without any line breaks.

makeJSONString(any, string) returns string

makeJSONString(any) returns string

Y

Serializes qore data into a JSON string, without any line breaks.

makeXMLFragment(hash, string) returns string

makeXMLFragment(hash) returns string

makeXMLFragment() returns nothing (RT_NOOP)

Y

Serializes a hash into an XML string without an XML header or formatting.

makeXMLRPCCallString(string, ...) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call without formatting.

makeXMLRPCCallStringWithEncoding(string, string, ...) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call without formatting, taking an initial string argument to give the target character encoding for the XML string.

makeXMLRPCCallStringArgs(string, any) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call without formatting, taking a single list argument for the argument list.

makeXMLRPCCallStringArgsWithEncoding(string, string, any) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC call without formatting, taking an initial string argument to give the target character encoding for the XML string followed by a list argument for the argument list.

makeXMLRPCFaultResponseString(any, string) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC fault response without formatting.

makeXMLRPCFaultResponseStringWithEncoding(string, any, string) returns string

Y

Serializes the arguments into an XML string formatted for an XML-RPC fault response without formatting, taking an initial string argument to give the target character encoding for the XML string.

makeXMLRPCResponseString(...) returns any

Y

Serializes the arguments into an XML string formatted for an XML-RPC response without formatting; if no arguments are passed then NOTHING is returned.

makeXMLRPCResponseStringWithEncoding(string, ...) returns any

Y

Serializes the arguments into an XML string formatted for an XML-RPC response without formatting, taking an initial string argument to give the target character encoding for the XML string. If no arguments after the encoding string are passed, then NOTHING is returned.

makeXMLRPCValueString(any, string) returns string

makeXMLRPCValueString(any) returns string

Y

Serializes the arguments into an XML string in XML-RPC Value format without formatting.

makeXMLString(hash) returns string

makeXMLString(hash, string) returns string

makeXMLString(string, hash) returns string

makeXMLString(string, hash, string) returns string

Y

Serializes a hash into a complete XML string with an XML header and without formatting.

max(...) returns any (CONST)

max(list) returns any (CONST)

max(list, string) returns any

max(list, code) returns any

N

Returns the maximum value in a list (see also min()); one variant takes an optional callback reference to process lists of complex data types.

MD2(data) returns string

Y

Returns the MD2 message digest of the supplied argument as a hex string (for string arguments, the trailing null character is not included in the digest)

MD2_bin(data) returns binary

Y

Returns the MD2 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

MD4(data) returns string

Y

Returns the MD4 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

MD4_bin(data) returns binary

Y

Returns the MD4 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

MD5(data) returns string

Y

Returns the MD5 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

MD5_bin(data) returns binary

Y

Returns the MD5 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

MDC2(data) returns string

Y

Returns the MDC2 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

MDC2_bin(data) returns binary

Y

Returns the MDC2 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

microseconds(softint) returns date (CONST)

microseconds() returns date (RT_NOOP)

N

Returns a relative date in microseconds to be used in date arithmetic.

milliseconds(softint) returns date (CONST)

milliseconds() returns date (RT_NOOP)

N

Returns a relative date in milliseconds to be used in date arithmetic.

min(...) returns any (CONST)

min(list) returns any (CONST)

min(list, string) returns any

min(list, code) returns any

N

Returns the minumum value in a list (see also max()); one variant takes an optional closure or call reference to process lists of complex data types.

minutes(softint) returns date (CONST)

minutes() returns date (RT_NOOP)

N

Returns a relative date in minutes to be used in date arithmetic.

mkdir(string, softint = 0777) returns int

Y

Creates a directory with the given mode/permissions.

mkfifo(string, softint = 0600) returns int

N

Creates a named pipe with the given mode/permissions.

mktime(date) returns int (CONST)

mktime() returns nothing (RT_NOOP)

N

Returns the number of seconds after Jan 1, 1970, 00:00:00Z for the date/time value passed.

months(softint) returns date (CONST)

months() returns date (RT_NOOP)

N

Returns a relative date in months to be used in date arithmetic.

nlog(softfloat) returns float (CONST)

nlog() returns float (RT_NOOP)

N

Returns the natural logarithm of the value passed

now() returns date (CONST)

N

Returns current date and time with resolution to the second

now_ms() returns date (CONST)

N

Returns current date and time with resolution to the millisecond

now_us() returns date (CONST)

N

Returns current date and time with resolution to the microsecond

now_utc() returns date (CONST)

N

Returns current UTC date and time with resolution to the microsecond.

num_threads() returns int (CONST)

N

Returns the current number of threads in the process

ord(softstring, softint = 0) returns int (CONST)

ord() returns nothing (RT_NOOP)

N

Gives the numeric value of the character passed

parse(string, string) returns nothing

parse() returns nothing (RT_NOOP)

Y

Adds the text passed to the current program's code

parse_url(string) returns hash

Y

Parses a URL string and returns a hash of the components; throws an exception if the string cannot be parsed as URL.

parseBase64String(string) returns binary

parseBase64String() returns nothing (RT_NOOP)

Y

Parses a base64 encoded string and returns the binary object

parseDatasource(string) returns hash

parseDatasource() returns nothing (RT_NOOP)

N

Returns a hash of the components of a datasource string (ex: "user/pass@db(encoding)%host:port{min=2,max=4}").

parseHexString(string) returns binary

parseHexString() returns nothing (RT_NOOP)

Y

Parses a hex-encoded string and returns the binary object; if invalid hex digits are found an exception is thrown.

parseJSON(string) returns any

parseJSON() returns nothing (RT_NOOP)

Y

Parses a JSON string and returns the corresponding qore data structure.

parseURL(string) returns any

parseURL() returns nothing (RT_NOOP)

N

Parses a URL string and returns a hash of the components, unless the string cannot be parsed as URL in which case NOTHING is returned.

parseXML(string) returns hash

parseXML(string, string) returns hash

parseXML() returns nothing (RT_NOOP)

Y

parses an XML string and returns a Qore hash structure.

parseXMLAsData(string) returns hash

parseXMLAsData(string, string) returns hash

parseXMLAsData() returns nothing (RT_NOOP)

Y

parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list) and returns a Qore hash structure.

parseXMLAsDataWithRelaxNG(string, string) returns hash

parseXMLAsDataWithRelaxNG(string, string, string) returns hash

Y

parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list), validates the generated XML against a RelaxNG schema string, and returns a Qore hash structure.

parseXMLAsDataWithSchema(string, string) returns hash

parseXMLAsDataWithSchema(string, string, string) returns hash

Y

parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list), validates the generated XML against an XSD schema string, and returns a Qore hash structure.

parseXMLAsData(string) returns hash

parseXMLAsData(string, string) returns hash

parseXMLAsData() returns nothing (RT_NOOP)

Y

deserializies an XML-RPC call string, returning a Qore data structure representing the call information.

parseXMLRPCResponse(string) returns hash

parseXMLRPCResponse(string, string) returns hash

parseXMLRPCResponse() returns nothing (RT_NOOP)

Y

deserializies an XML-RPC response string, returning a Qore data structure representing the response information.

parseXMLRPCValue(string) returns hash

parseXMLRPCValue(string, string) returns hash

parseXMLRPCValue() returns nothing (RT_NOOP)

Y

deserializies an XML-RPC value tree, returning Qore data representing the information.

parseXMLWithRelaxNG(string, string) returns hash

parseXMLWithRelaxNG(string, string, string) returns hash

Y

parses an XML string, validates the generated XML against a RelaxNG schema string, and returns a Qore hash structure.

parseXMLWithSchema(string, string) returns hash

parseXMLWithSchema(string, string, string) returns hash

Y

parses an XML string, validates the generated XML against an XSD schema string, and returns a Qore hash structure.

pow(softfloat = 0.0, softfloat = 0.0) returns float

Y

Returns the value of the first argument raised to the power of the second

print(...) returns nothing

N

Prints the string passed without any formatting.

printf(string, ...) returns string

printf() returns string (RT_NOOP)

Y

Prints a formatted string and returns string printed.

rand() returns int

N

Returns a random integer number.

rc2_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

rc2_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

rc2_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

rc4_encrypt(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

rc4_decrypt(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

rc4_decrypt_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

rc5_encrypt_cbc(data, data, data = defaultIV) returns binary

Y

Encrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

rc5_decrypt_cbc(binary, data, data = defaultIV) returns binary

Y

Decrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

rc5_decrypt_cbc_to_string(binary, data, data = defaultIV) returns string

Y

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

readlink(string) returns string

N

Returns the target of a symbolic link; throws an exception if an error occurs.

regex(string, string, int = 0) returns bool

regex() returns nothing (RT_NOOP)

Y

Returns true if the regular expression matches the string passed

regex_extract(string, string, int = 0) returns any

regex_extract() returns nothing (RT_NOOP)

Y

Returns a list of substrings in a string based on matching patterns defined by a regular expression.

regex_subst(string, string, string, int = 0) returns string

regex_subst() returns nothing (RT_NOOP)

Y

Returns a string with patterns substituted according to the arguments passed.

remove_signal_handler(softint) returns nothing

N

Removes an installed signal handler and returns the signal handling state to the default.

remove_thread_data(list) returns nothing

remove_thread_data(...) returns nothing

N

Removes the listed keys from the thread-local data hash.

rename(string, string) returns nothing

Y

Renames (or moves) a file or directory.

replace(string, string, string) returns string

replace() returns nothing (RT_NOOP)

N

Replaces all occurrances of a substring in a string with another string and returns the new string.

reverse(string) returns string (CONST)

reverse(list) returns list (CONST)

reverse() returns nothing (RT_NOOP)

N

Reverses the order of a string or a list and returns the new string or list.

RIPEMD160(data) returns string

Y

Returns the RIPEMD160 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

RIPEMD160_bin(data) returns binary

Y

Returns the RIPEMD160 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

rindex(softstring, softstring, softint = -1) returns int (CONST)

rindex() returns int (RT_NOOP)

N

Returns the starting character position of a string in another string as searched from the end of the string.

rmdir(string) returns int

N

Removes a directory.

round(softfloat) returns float (CONST)

round() returns float (RT_NOOP)

N

Returns a value rounded up to the nearest integer.

save_thread_data(hash) returns nothing

save_thread_data(string, any) returns nothing

save_thread_data() returns nothing (RT_NOOP)

Y

Saves the data passed against the key passed in thread-local storage.

seconds(softint) returns date (CONST)

seconds() returns date (RT_NOOP)

N

Returns a relative date/time value in seconds to be used in date arithmetic.

set_signal_handler(softint, code) returns nothing

N

Installs or replaces a signal handler.

setegid(softint) returns int

N

Changes the process effective group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

seteuid(softint) returns int

N

Changes the process effective user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

setenv(string, softstring) returns int

setenv() returns nothing (RT_NOOP)

N

Sets the value of an environment variable

setgid(softint) returns int

N

Changes the process group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

setsid() returns int

N

Creates a new session lead by the current process.

setuid(softint) returns int

N

Changes the process user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

SHA(data) returns string

Y

Returns the SHA message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA_bin(data) returns binary

Y

Returns the SHA message digest of the supplied argument as a binary object(for strings, the trailing null character is not included in the digest)

SHA1(data) returns string

Y

Returns the SHA1 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA1_bin(data) returns binary

Y

Returns the SHA1 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

SHA224(data) returns string

Y

Returns the SHA224 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA224_bin(data) returns binary

Y

Returns the SHA224 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

SHA256(data) returns string

Y

Returns the SHA256 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA256_bin(data) returns binary

Y

Returns the SHA256 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

SHA384(data) returns string

Y

Returns the SHA384 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA384_bin(data) returns binary

Y

Returns the SHA384 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

SHA512(data) returns string

Y

Returns the SHA512 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)

SHA512_bin(data) returns binary

Y

Returns the SHA512 message digest of the supplied argument as a binary object (for strings, the trailing null character is not included in the digest)

sleep(softint) returns int

sleep(date) returns int

sleep() returns nothing (RT_NOOP)

N

Causes the current thread to sleep for a certain number of seconds.

sort(list) returns list (CONST)

sort(list, code) returns list

sort(list, string) returns list

sort() returns nothing (RT_NOOP)

Y

Sorts a list in ascending order (unstable); optionally takes a closure or a call reference (function or object method reference) to sort non-trivial data types.

sortDescending(list) returns list (CONST)

sortDescending(list, code) returns list

sortDescending(list, string) returns list

sortDescending() returns nothing (RT_NOOP)

Y

Sorts a list in descending order (unstable); optionally takes a closure or call reference (function or object method reference) to sort non-trivial data types.

sortDescendingStable(list) returns list (CONST)

sortDescendingStable(list, code) returns list

sortDescendingStable(list, string) returns list

sortDescendingStable() returns nothing (RT_NOOP)

Y

Performs a descending stable sort on a list and returns the new list; optionally takes a closure or call reference (function or object method reference) to sort non-trivial data types.

sortStable(list) returns list (CONST)

sortStable(list, code) returns list

sortStable(list, string) returns list

sortStable() returns nothing (RT_NOOP)

Y

Performs an ascending stable sort on a list and returns the new list; optionally takes a closure or call reference (function or object method reference) to sort non-trivial data types.

split(string, string) returns list (CONST)

split(binary, binary) returns list (CONST)

split() returns list (RT_NOOP)

N

Splits a string into a list of components based on a separator string

sprintf(string, ...) returns string (CONST)

sprintf() returns string (RT_NOOP)

Y

Creates a string from the format argument passed and the other arguments.

sin(softfloat) returns float (CONST)

sin() returns float (RT_NOOP)

N

Returns the sine of the number in radians passed.

sinh(softfloat) returns float (CONST)

sinh() returns float (RT_NOOP)

N

Returns the hyperbolic sine of the number passed.

sqrt(softfloat) returns float (CONST)

sqrt() returns float (RT_NOOP)

N

Returns the square root of the number passed.

srand(softint) returns nothing

srand() returns nothing (RT_NOOP)

N

Seeds the random number generator with the integer passed.

stat(string) returns any

stat() returns nothing (RT_NOOP)

N

Returns a list of filesystem information for the filename passed or NOTHING if the stat call fails.

strerror(softint) returns string (CONST)

strerror() returns nothing (RT_NOOP)

N

Returns the description of the error number passed

string(softstring) returns string (CONST)

string(null) returns string (CONST)

string() returns string (CONST)

N

Returns the argument converted to a string

strlen(softstring) returns int (CONST)

strlen(any) returns int (NOOP)

strlen() returns nothing (RT_NOOP)

N

Returns the number of characters in a string.

strtoint(softstring, int = 10) returns int (CONST)

strtoint() returns nothing (RT_NOOP)

N

Returns an integer corresponding to the string passed with the possibility to specify the base (default base 10).

substr(softstring, softint, softint) returns string (CONST)

substr(softstring, softint) returns string (CONST)

substr() returns nothing (RT_NOOP)

N

Returns a substring of a string

system(string) returns int

system() returns nothing (RT_NOOP)

Y

Executes a process and returns the return code

tan(softfloat) returns float (CONST)

tan() returns float (RT_NOOP)

N

Returns the tangent of the number in radians passed.

tanh(softfloat) returns float (CONST)

tanh() returns float (RT_NOOP)

N

Returns the hyperbolic tangent of the number passed.

thread_list() returns list (CONST)

N

Returns a list of all current thread IDs

throwThreadResourceExceptions() returns nothing

Y

Immediately runs all thread resource cleanup routines for the current thread and throws all associated exceptions.

timegm(date) returns int (CONST)

timegm() returns nothing (RT_NOOP)

N

Returns the number of seconds since January 1, 1970 00:00:00 in the local time zone for a given date.

tolower(string) returns string (CONST)

tolower() returns nothing (RT_NOOP)

N

Converts a string to all lowercase

toupper(string) returns string (CONST)

toupper() returns nothing (RT_NOOP)

N

Converts a string to all uppercase

trim(string, string = "") returns string (CONST)

trim(reference, string = "") returns any

trim() returns nothing (RT_NOOP)

N

Removes the characters from a string (whiltespace by default, can be overridden) and returns the new string (also see the trim operator); also accepts an lvalue reference to do modifications in-place.

type(any) returns string (CONST)

N

Returns the data type of the argument passed (see Type_Constants)

typename(any) returns string (CONST, DEPRECATED)

N

deprecated: use type() instead

umask(softint) returns int

umask() returns nothing (RT_NOOP)

N

Sets the file creation mask for the process

uncompress_to_binary(binary) returns binary

uncompress_to_binary() returns nothing (RT_NOOP)

Y

Uncompresses (inflates) data compressed with the "deflate" algorithm (RFC 1951) using zlib functions and returns a binary object.

uncompress_to_string(binary) returns string

uncompress_to_string(binary, string) returns string

uncompress_to_string() returns nothing (RT_NOOP)

Y

Uncompresses (inflates) data compressed with the "deflate" algorithm (RFC 1951) using zlib functions and returns a string.

unlink(string) returns int

unlink() returns nothing (RT_NOOP)

N

Deletes a file and returns 0 for success.

unsetenv(string) returns int

unsetenv() returns nothing (RT_NOOP)

N

Unsets an environment variable

usleep(date) returns int

usleep(softint) returns int

usleep() returns nothing (RT_NOOP)

N

Causes the current thread to sleep for a certain number of microseconds

vprintf(string, any) returns string

vprintf() returns string (RT_NOOP)

Y

Outputs a formatted string based on a variable number of arguments given in a list after the format string. Returns the string printed.

vsprintf(string, any) returns string

vsprintf() returns string (RT_NOOP)

Y

Formats a string based on a variable number of arguments given in a list after the format string and returns this formatted string.

years(softint) returns date

years() returns date (RT_NOOP)

N

Returns a relative date/time value in years to be used in date arithmetic.


3.1. Math Functions

3.1.1. abs()

Synopsis

Returns the absolute value of the argument passed.

Prototype

abs(softfloat) returns float

abs(int) returns int

abs() returns float (RT_NOOP)

Example
$x = abs($y);

Table 3.4. Arguments and Return Values for abs()

Argument Type

Return Type

Description

int

int

Absolute value of the integer passed.

softfloat

float

Absolute value of the floating-point value passed.


This function does not throw any exceptions.

3.1.2. acos()

Synopsis

Returns the arc cosine of the number passed in radians

Prototype

acos(any) returns float

Example
$x = acos($y);

Table 3.5. Arguments and Return Values for acos()

Argument Type

Return Type

Description

any

float

Returns the arc cosine of the value passed convert to a float in radians.


This function does not throw any exceptions.

3.1.3. asin()

Synopsis

Returns the arc sine of the number passed in radians

Prototype

asin(softfloat) returns float

asin() returns float (RT_NOOP)

Example
$x = asin($y);

Table 3.6. Arguments and Return Values for asin()

Argument Type

Return Type

Description

softfloat

float

Returns the arc sine of the number passed in radians.


This function does not throw any exceptions.

3.1.4. atan()

Synopsis

Returns the arc tangent of the number passed in radians

Prototype

atan(softfloat) returns float

atan() returns float (RT_NOOP)

Example
$x = atan($y);

Table 3.7. Arguments and Return Values for atan()

Argument Type

Return Type

Description

softfloat

float

Returns the arc tangent of the number passed in radians.


This function does not throw any exceptions.

3.1.5. cbrt()

Synopsis

Returns the cube root of the number passed.

Prototype

cbrt(softfloat) returns float

cbrt() returns float (RT_NOOP)

Example
$x = cbrt($y);

Table 3.8. Arguments and Return Values for cbrt()

Argument Type

Return Type

Description

softfloat

float

Returns the cube root of the number passed.


This function does not throw any exceptions.

3.1.6. ceil()

Synopsis

Returns a floating-point number equal to the smallest integral value greater than or equal to the argument passed.

Prototype

ceil(softfloat) returns float

ceil() returns float (RT_NOOP)

Example
$x = ceil(3.2); # will return 4.0 

Table 3.9. Arguments and Return Values for ceil()

Argument Type

Return Type

Description

softfloat

float

Returns a value rounded up to the nearest integral floating-point value.


This function does not throw any exceptions.

3.1.7. cos()

Synopsis

Returns the cosine of the number in radians passed.

Prototype

cos(softfloat) returns float (CONST)

cos() returns float (RT_NOOP)

Example
$x = cos($y);

Table 3.10. Arguments and Return Values for cos()

Argument Type

Return Type

Description

softfloat

float

Returns the cosine of the number in radians passed.


This function does not throw any exceptions.

3.1.8. cosh()

Synopsis

Returns the hyperbolic cosine of the number in radians passed.

Prototype

cosh(softfloat) returns float (CONST)

cosh() returns float (RT_NOOP)

Example
$x = cosh($y);

Table 3.11. Arguments and Return Values for cosh()

Argument Type

Return Type

Description

softfloat

float

Returns the hyperbolic cosine of the number in radians passed.


This function does not throw any exceptions.

3.1.9. exp()

Synopsis

Returns the value of e raised to the power of the argument passed.

Prototype

exp(softfloat) returns float (CONST)

exp() returns float (RT_NOOP)

Example
$x = exp($y);

Table 3.12. Arguments and Return Values for exp()

Argument Type

Return Type

Description

softfloat

float

Returns the value of e raised to the power of the argument passed.


This function does not throw any exceptions.

3.1.10. exp2()

Synopsis

Returns the value of 2 raised to the power of the argument passed.

Prototype

exp2(softfloat) returns float (CONST)

exp2() returns float (RT_NOOP)

Example
$x = exp2($y);

Table 3.13. Arguments and Return Values for exp2()

Argument Type

Return Type

Description

softfloat

float

Returns the value of 2 raised to the power of the argument passed.


This function does not throw any exceptions.

3.1.11. expm1()

Synopsis

Returns an equivalent of exp(x) - 1.

Prototype

expm1(softfloat) returns float (CONST)

expm1() returns float (RT_NOOP)

Example
$x = expm1($y);

Table 3.14. Arguments and Return Values for expm1()

Argument Type

Return Type

Description

softfloat

float

Returns an equivalent of exp(x) - 1.


This function does not throw any exceptions.

3.1.12. floor()

Synopsis

Returns a floating-point value rounded down to the integral value.

Prototype

floor(softfloat) returns float (CONST)

floor() returns float (RT_NOOP)

Example
$x = floor(3.7); # will return 3.0

Table 3.15. Arguments and Return Values for floor()

Argument Type

Return Type

Description

softfloat

float

Returns a float-point value rounded down to the integral value.


This function does not throw any exceptions.

3.1.13. format_number()

Synopsis

Returns a string of a formatted number according to the arguments passed.

Prototype

format_number(string, any) returns string (CONST)

format_number() returns nothing (RT_NOOP)

Description

The format_string has the following format: <thousands_separator>[<decimal_separator><decimals>], where thousands_separator and decimal_separator are single ASCII characters defining the thousands and decimal separator characters respectively, and decimals is a single digit defining how may decimals should appear after the decimal point.

Example
format_number(".,3", -48392093894.2349); # returns "-48.392.093.894,235"

Table 3.16. Arguments and Return Values for format_number()

Argument Types

Return Type

Description

string, any

string

Returns a string corresponding to a number according to the formatting string passed.


This function does not throw any exceptions.

3.1.14. hypot()

Synopsis

Returns the length of the hypotenuse of a right-angle triangle with sides given as the two arguments.

Prototype

hypot(any $x, softfloat $y) returns float (CONST)

hypot(softfloat $x, any $y) returns float (CONST)

hypot() returns float (RT_NOOP)

Example
$z = hypot($x, $y);

Table 3.17. Arguments and Return Values for hypot()

Argument Type

Return Type

Description

softfloat

float

Returns the length of the hypotenuse of a right-angle triangle with sides given as the two arguments.


This function does not throw any exceptions.

3.1.15. log10()

Synopsis

Returns the base 10 logarithm of the value passed.

Prototype

log10(softfloat) returns float (CONST)

log10() returns float (RT_NOOP)

Example
$x = log10($y);

Table 3.18. Arguments and Return Values for log10()

Argument Type

Return Type

Description

softfloat

float

Returns the base 10 logarithm of the value passed.


This function does not throw any exceptions.

3.1.16. log1p()

Synopsis

Returns the natural logarithm of the value passed plus 1.

Prototype

log1p(softfloat) returns float (CONST)

log1p() returns float (RT_NOOP)

Example
$x = log1p($y);

Table 3.19. Arguments and Return Values for log1p()

Argument Type

Return Type

Description

softfloat

float

Returns the natural logarithm of the value passed plus 1.


This function does not throw any exceptions.

3.1.17. logb()

Synopsis

Returns the exponent of a number.

Prototype

logb(softfloat) returns float (CONST)

logb() returns float (RT_NOOP)

Example
$x = logb($y);

Table 3.20. Arguments and Return Values for logb()

Argument Type

Return Type

Description

softfloat

float

Returns the exponent of a number.


This function does not throw any exceptions.

3.1.18. nlog()

Synopsis

Returns the natural logarithm of the value passed.

Prototype

nlog(softfloat) returns float (CONST)

nlog() returns float (RT_NOOP)

Example
$x = nlog();

Table 3.21. Arguments and Return Values for nlog()

Argument Type

Return Type

Description

softfloat

float

Returns the natural logarithm of the value passed.


This function does not throw any exceptions.

3.1.19. pow()

Synopsis

Returns a number raised to the power of another number.

Prototype

pow(softfloat $x = 0.0, softfloat $y = 0.0) returns float

Example
$z = pow($x, $y);

Table 3.22. Arguments and Return Values for pow()

Argument Types

Return Type

Description

softfloat $x

softfloat $y

Returns x raised to the power of y.


Table 3.23. Exceptions Thrown by pow()

err

desc

DIVISION-BY-ZERO

pow(x, y): y must be a non-negative value.

INVALID-POW-ARGUMENTS

pow(x, y): x cannot be negative when y is not an integer value.


3.1.20. round()

Synopsis

Returns a floating-point number equal to the closest integer to the argument passed. Numers halfway between two integers are arounded away from zero. The availability of this function depends on the presence of the C-library's round() function; for maximum portability check the constant HAVE_ROUND before running this function. See Library Option Constants for a list of all option constants.

Prototype

round(softfloat) returns float (CONST)

round() returns float (RT_NOOP)

Example
$x = round(3.2); # returns 3.0 

Table 3.24. Arguments and Return Values for round()

Argument Type

Return Type

Description

softfloat

float

Returns a value rounded to the nearest integral floating-point value, half-way cases are rounded away from zero.


Table 3.25. Exceptions Thrown by round()

err

desc

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_ROUND before calling this function.


3.1.21. sin()

Synopsis

Returns the sine of the number in radians passed.

Prototype

sin(softfloat) returns float (CONST)

sin() returns float (RT_NOOP)

Example
$x = sin($y);

Table 3.26. Arguments and Return Values for sin()

Argument Type

Return Type

Description

softfloat

float

Returns the sine of the number in radians passed.


This function does not throw any exceptions.

3.1.22. sinh()

Synopsis

Returns the hyperbolic sine of the number in radians passed.

Prototype

sinh(softfloat) returns float (CONST)

sinh() returns float (RT_NOOP)

Example
$x = sinh($y);

Table 3.27. Arguments and Return Values for sinh()

Argument Type

Return Type

Description

softfloat

float

Returns the hyperbolic sine of the number in radians passed.


This function does not throw any exceptions.

3.1.23. sqrt()

Synopsis

Returns the square root of the number passed.

Prototype

sqrt(softfloat) returns float (CONST)

sqrt() returns float (RT_NOOP)

Example
$x = sqrt($y);

Table 3.28. Arguments and Return Values for sqrt()

Argument Type

Return Type

Description

softfloat

float

Returns the square root of the number passed.


This function does not throw any exceptions.

3.1.24. tan()

Synopsis

Returns the tangent of the number in radians passed.

Prototype

tan(softfloat) returns float (CONST)

tan() returns float (RT_NOOP)

Example
$x = tan($y);

Table 3.29. Arguments and Return Values for tan()

Argument Type

Return Type

Description

softfloat

float

Returns the tangent of the number in radians passed.


This function does not throw any exceptions.

3.1.25. tanh()

Synopsis

Returns the hyperbolic tangent of the number in radians passed.

Prototype

tanh(softfloat) returns float (CONST)

tanh() returns float (RT_NOOP)

Example
$x = tanh($y);

Table 3.30. Arguments and Return Values for tanh()

Argument Type

Return Type

Description

softfloat

float

Returns the hyperbolic tangent of the number in radians passed.


This function does not throw any exceptions.

3.2. Output Functions

The functions in this section operate only on stdout. For generic file I/O please see the File class.

3.2.1. f_printf()

Synopsis

Outputs a formatted string to standard output, respecting field widths in the formatting string. See String Formatting for information on the formatting string, and see printf() for a similar function that does not enforce field widths.

Prototype

f_printf(string $fmt, ...) returns string

f_printf() returns string (RT_NOOP)

Example
f_printf("%5s\n", "long string"); # will print "long \n", respecting the 5-character field width
Restrictions

Not available with PO_NO_TERMINAL_IO

Table 3.31. Arguments and Return Values for f_printf()

Arguments

Return Type

Description

string $fmt, [...]

string

Returns the string output (see String Formatting for information on the format string)


This function does not throw any exceptions.

3.2.2. f_sprintf()

Synopsis

Returns a formatted string without doing any output, respecting field widths. See String Formatting for information on the formatting string, and see sprintf() for a similar function that does not enforce field widths.

Prototype

f_sprintf(string $fmt, ...) returns string (CONST)

f_sprintf() returns string (RT_NOOP)

Example
$str = f_sprintf("%5s", "a long string"); # will return "a lon"

Table 3.32. Arguments and Return Values for f_sprintf()

Argument Type

Return Type

Description

string $fmt, [...]

string

Returns a formatted string without doing any output, enforcing any field widths. See String Formatting for information on the format string.


This function does not throw any exceptions.

3.2.3. flush()

Synopsis

Flushes output to the console output with print(), printf(), etc.

Prototype

flush() returns nothing

Example
flush();
Restrictions

Not available with PO_NO_TERMINAL_IO

Table 3.33. Arguments and Return Values for flush()

Arguments

Return Type

Description

n/a

n/a

Thie function takes no arguments.


This function does not throw any exceptions.

3.2.4. print()

Synopsis

Outputs a string to standard output with no formatting. See printf() for a function that allows for formatted output.

Prototype

print(...) returns nothing

Example
print("hello\n"); # do not use formatting with this function
Restrictions

Not available with PO_NO_TERMINAL_IO

Table 3.34. Arguments and Return Values for print()

Argument Type

Return Type

Description

string

n/a

Outputs the string to stdout with no formatting.


This function does not throw any exceptions.

3.2.5. printf()

Synopsis

Outputs the string passed to standard output, using the first argument as a formatting string. See f_printf() for a similar function that enforces field widths, and print for an simple output function that does not accept a formatting string. See String Formatting for information on the formatting string.

Prototype

printf(string $fmt, ...) returns string

printf() returns string (RT_NOOP)

Example
printf("%5s\n", "a long string"); # will output "a long string", exceeding the field width
Restrictions

Not available with PO_NO_TERMINAL_IO

Table 3.35. Arguments and Return Values for printf()

Arguments

Return Type

Description

string $fmt, [...]

string

See String Formatting for information on the format string. This is the "normal" (non-field) printf() version, so any field widths are considered as soft limits, and arguments are allowed to exceed their field widths. Only when an argument is less than the field width will it be padded to the field width specified. Returns the string output.


This function does not throw any exceptions.

3.2.6. sprintf()

Synopsis

Returns a formatted string without enforcing hard field limits. See f_sprintf() for a similar function that enforces field widths, and see String Formatting for information on the formatting string.

Prototype

sprintf(string $fmt, ...) returns string (CONST)

sprintf() returns string (RT_NOOP)

Example
$str = sprintf("%5s", "a long string"); # returns "a long string", exceeding the field width

Table 3.36. Arguments and Return Values for sprintf()

Argument Type

Return Type

Description

string $fmt, [...]

string

See String Formatting for information on the format string. Field widths are considered soft limits (arguments are allowed to exceed their field widths). Only when an argument is less than the field width will it be padded to the field width specified.


This function does not throw any exceptions.

3.2.7. vprintf()

Synopsis

Outputs a formatted string based on a variable number of arguments given in a list after the format string and returns the string printed. See String Formatting for information on the formatting string.

Prototype

vprintf(string $fmt, any $arg_or_list) returns string

vprintf() returns string (RT_NOOP)

Example
vprintf("%5s %3d\n", ("a long string", 5000)); # outputs "a long string 5000", exceeding field width of 5
Restrictions

Not available with PO_NO_TERMINAL_IO

Table 3.37. Arguments and Return Values for vprintf()

Argument Type

Return Type

Description

string $fmt, any $arg_or_list

string

See String Formatting for information on the format string. Arguments to the formatting string are supplied in the optional second argument as a list. Field widths are considered as soft limits; arguments are allowed to exceed their field widths. Only when an argument is less than the field width will it be padded to the field width specified. Returns the string output.


This function does not throw any exceptions.

3.2.8. vsprintf()

Synopsis

Formats a string based on two arguments: a format string and a list. Does not enforce hard field widths. Returns this formatted string. See String Formatting for information on the formatting string.

Prototype

vsprintf(string $fmt, any $arg_or_list) returns string

vsprintf() returns string (RT_NOOP)

Example
$str = vsprintf("%5s %3d\n", ("a long string", 5000)); # returns "a long string 5000", exceeding field width of 5

Table 3.38. Arguments and Return Values for vsprintf()

Argument Type

Return Type

Description

string $fmt, any $arg_or_list

string

See String Formatting for information on the format string. Arguments to the formatting string are supplied in the optional second argument as a list. Field widths are considered soft limits (arguments are allowed to exceed their field widths). Only when an argument is less than the field width will it be padded to the field width specified. Returns the formatted string.


This function does not throw any exceptions.

3.3. Date and Time Functions

3.3.1. clock_getmicros()

Synopsis

Returns an integer representing the system time in microseconds (1/1000000 second intervals) since Jan 1, 1970 00:00:00Z.

Prototype

clock_getmicros() returns int (CONST)

Example
$time = clock_getmicros();

Table 3.39. Arguments and Return Values for clock_getmicros()

Argument Type

Return Type

Description

n/a

int

Returns the number of microseconds (1/1000000 second) since Jan 1, 1970 00:00.


This function does not throw any exceptions.

3.3.2. clock_getmillis()

Synopsis

Returns an integer representing the system time in milliseconds (1/1000 second intervals since Jan 1, 1970 00:00).

Prototype

clock_getmillis() returns int (CONST)

Example
$time = clock_getmillis();

Table 3.40. Arguments and Return Values for clock_getmillis()

Argument Type

Return Type

Description

n/a

int

Returns the number of milliseconds (1/1000 second) since Jan 1, 1970 00:00.


This function does not throw any exceptions.

3.3.3. clock_getnanos()

Synopsis

Returns the system time in nanoseconds (1/1000000000 second intervals) since Jan 1, 1970 00:00:00Z.

Prototype

clock_getnanos() returns int (CONST)

Example
$time = clock_getnanos();

Table 3.41. Arguments and Return Values for clock_getnanos()

Argument Type

Return Type

Description

n/a

int

Returns the number of nanoseconds (1/1000000000 second) since Jan 1, 1970 00:00:00Z.


This function does not throw any exceptions.

3.3.4. date_ms()

Synopsis

Converts an integer argument representing the offset in milliseconds from January 1, 1970 in the local time zone to a date in the local time zone.

See also date(), date_us(), and localtime().

Prototype

date_ms(softint) returns date (CONST)

date_ms() returns date (RT_NOOP)

Example
my date $date = date_ms(1); # returns 1970-01-01T00:00:00.001

Table 3.42. Arguments and Return Values for date_ms()

Argument Type

Return Type

Description

int

date

Returns the date corresponding to the offset in ms given from January 1, 1970 in the local time zone.


This function does not throw any exceptions.

3.3.5. date_us()

Synopsis

Converts an integer argument representing the offset in microseconds from January 1, 1970 in the local time zone to a date in the local time zone.

See also date(), date_ms(), and localtime().

Prototype

date_us(softint) returns date (CONST)

date_us() returns date (RT_NOOP)

Example
my date $date = date_us(1); # returns 1970-01-01T00:00:00.000001

Table 3.43. Arguments and Return Values for date_us()

Argument Type

Return Type

Description

int

date

Returns the date corresponding to the offset in microseconds given from January 1, 1970 in the local time zone.


This function does not throw any exceptions.

3.3.6. days

Synopsis

Returns a relative date/time value in days for date arithmetic.

Prototype

days(softint) returns date (CONST)

days() returns date (RT_NOOP)

Example
$days = days(5 * 5); # returns 25D

Table 3.44. Arguments and Return Values for days()

Argument Type

Return Type

Description

int

date

Returns a relative date/time value corresponding to the number of days passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.7. format_date()

Synopsis

Returns a formatting string for a date argument passed. See Date Formatting for information about the formatting string.

Prototype

format_date(string, date) returns string (CONST)

format_date() returns nothing (RT_NOOP)

Example
my string $str = format_date("Day, Mon D, YYYY-MM-DD HH:mm:SS", 2004-02-01T12:30:00);
# returns "Sunday, Feb 1, 2004-02-01 12:30:00"

Table 3.45. Arguments and Return Values for format_date()

Argument Type

Return Type

Description

string, Date

string

Formats the date value using the string as a formatting specification.


This function does not throw any exceptions.

Table 3.46. Date Format Arguments

Format Code

Description

YY

last two digits of year

YYYY

four-digit year

M

non zero-padded month number (1-12)

MM

zero-padded two-digit month number (01-12)

Month

long month string (ex: January)

MONTH

long month string capitalized (ex: JANUARY)

Mon

abbreviated month (ex: Jan)

MON

abbreviated month, capitalized (ex: JAN)

D

non zero-padded day number (1 - 31)

DD

zero-padded day number (01 - 31)

Day

long day of week string (ex: Monday)

DAY

long day of week string, capitalized (ex: MONDAY)

Dy

abbreviated day of week string (ex: Mon)

DY

abbreviated day of week string capitalised (ex: MON)

H

non zero-padded hour number (0 - 23)

HH

zero-padded hour number (00 - 23)

h

non zero-padded hour number, 12-hour clock (1 - 12)

hh

zero-padded hour number, 12-hour clock (01 - 12)

m

non zero-padded minute number (0 - 59)

mm

zero-padded minute number (00 - 59)

S

non zero-padded second number (0 - 59)

SS

zero-padded second number (00 - 59)

P

AM or PM (upper-case)

p

am or pm (lower-case)

u

non zero-padded millisecond number (0 - 999)

uu or ms

zero-padded millisecond number (000 - 999)

x

non zero-padded microsecond number (0 - 999999)

xx or ms

zero-padded microsecond number (000000 - 999999)

y

microseconds, with trailing zeros removed (suitable for use after the '.')

z

local time zone name (ex: 'EST') if available, otherwise the UTC offset (see 'Z')

Z

time zone UTC offset like +HH:mm[:SS], seconds are included if non-zero


All other text is output directly in the output text unchanged.

3.3.8. get_days()

Synopsis

Returns an integer value representing the days value of the date passed (can be either a relative or absolute date).

Prototype

get_days(date) returns int (CONST)

get_days() returns nothing (RT_NOOP)

Example
$days = get_days(2007-01-23); # returns 23

Table 3.47. Arguments and Return Values for get_days()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the days value of the date passed (can be either a relative or absolute date).


3.3.9. get_duration_microseconds()

Synopsis

Returns an integer value representing the the number of microseconds in the value of the date passed (can be either a relative or absolute date).

If the argument is an absolute date/time value, then the resulting number is calculated from the present time. Fixed-time arguments in the past will result in a return value of 0; this function can only return a negative value if passed a relative date/time value.

Prototype

get_duration_microseconds(date) returns int (CONST)

Example
my int $us = get_duration_microseconds(PT2M15S3u); # returns 135000003

Table 3.48. Arguments and Return Values for get_duration_microseconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the the number of microseconds in the value of the date passed; note that the return value will be calculated from the present time if an absolute date/time value argument is passed, but in this case will never be negative; fixed-time arguments in the past will result in a value of 0 being returned.


3.3.10. get_duration_milliseconds()

Synopsis

Returns an integer value representing the the number of milliseconds in the value of the date passed (can be either a relative or absolute date).

If the argument is an absolute date/time value, then the resulting number is calculated from the present time. Fixed-time arguments in the past will result in a return value of 0; this function can only return a negative value if passed a relative date/time value.

Prototype

get_duration_milliseconds(date) returns int (CONST)

Example
my int $us = get_duration_milliseconds(PT2M15S3u); # returns 135000

Table 3.49. Arguments and Return Values for get_duration_milliseconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the the number of milliseconds in the value of the date passed; note that the return value will be calculated from the present time if an absolute date/time value argument is passed, but in this case will never be negative; fixed-time arguments in the past will result in a value of 0 being returned.


3.3.11. get_duration_seconds()

Synopsis

Returns an integer value representing the the number of seconds in the value of the date passed (can be either a relative or absolute date).

If the argument is an absolute date/time value, then the resulting number is calculated from the present time. Fixed-time arguments in the past will result in a return value of 0; this function can only return a negative value if passed a relative date/time value.

Prototype

get_duration_seconds(date) returns int (CONST)

Example
my int $us = get_duration_seconds(PT2M15S3u); # returns 135

Table 3.50. Arguments and Return Values for get_duration_seconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the the number of seconds in the value of the date passed; note that the return value will be calculated from the present time if an absolute date/time value argument is passed, but in this case will never be negative; fixed-time arguments in the past will result in a value of 0 being returned.


3.3.12. get_epoch_seconds()

Synopsis

Returns the number of seconds of the date and time in local time passed since Jan 1, 1970, 00:00:00 Z (UTC). Negative values are returned for dates before the epoch.

This function is equivalent to mktime().

Prototype

get_epoch_seconds(date) returns int (CONST)

get_epoch_seconds() returns nothing (RT_NOOP)

Example
$secs = get_epoch_seconds(2007-09-23T00:00:01);

Table 3.51. Arguments and Return Values for get_epoch_seconds()

Argument Type

Return Type

Description

date

int

The date argument should be in local time; the function returns the number of seconds passed since Jan 1, 1970 00:00:00 corresponding to this date.


This function does not throw any exceptions.

3.3.13. get_hours()

Synopsis

Returns an integer value representing the hours value of the date passed (can be either a relative or absolute date).

Prototype

get_hours(date) returns int (CONST)

get_hours() returns nothing (RT_NOOP)

Example
$hours = get_hours(2007-01-23T11:24:03); # returns 11

Table 3.52. Arguments and Return Values for get_hours()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the hours value of the date passed (can be either a relative or absolute date).


3.3.14. get_microseconds()

Synopsis

Returns an integer value representing the microseconds value of the date passed (can be either a relative or absolute date).

Prototype

get_microseconds(date) returns int (CONST)

get_microseconds() returns nothing (RT_NOOP)

Example
$ms = get_microseconds(2007-01-23T11:24:03.250); # returns 250

Table 3.53. Arguments and Return Values for get_microseconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the microseconds value of the date passed (can be either a relative or absolute date).


3.3.15. get_midnight()

Synopsis

Returns a date/time value representing midnight on the date passed (strips the time from the date passed and returns the new value)

Prototype

get_midnight(date) returns date (CONST)

get_midnight() returns nothing (RT_NOOP)

Example
$date = get_midnight(2007-01-23T11:24:03.250); # returns 2007-01-23T00:00:00.000

Table 3.54. Arguments and Return Values for get_midnight()

Argument Type

Return Type

Description

date

date

Returns a date/time value representing midnight on the date passed (strips the time from the date passed and returns the new value)


3.3.16. get_milliseconds()

Synopsis

Returns an integer value representing the milliseconds value of the date passed (can be either a relative or absolute date).

Prototype

get_milliseconds(date) returns int (CONST)

get_milliseconds() returns nothing (RT_NOOP)

Example
$ms = get_milliseconds(2007-01-23T11:24:03.250); # returns 250

Table 3.55. Arguments and Return Values for get_milliseconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the milliseconds value of the date passed (can be either a relative or absolute date).


3.3.17. get_minutes()

Synopsis

Returns an integer value representing the minutes value of the date passed (can be either a relative or absolute date).

Prototype

get_minutes(date) returns int (CONST)

get_minutes() returns nothing (RT_NOOP)

Examples
$minutes = get_minutes(2007-01-23T11:24:03); # returns 24

Table 3.56. Arguments and Return Values for get_minutes()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the minutes value of the date passed (can be either a relative or absolute date).


3.3.18. get_months()

Synopsis

Returns an integer value representing the months value of the date passed (can be either a relative or absolute date).

Prototype

get_months(date) returns int (CONST)

get_months() returns nothing (RT_NOOP)

Example
$months = get_months(2007-01-23); # returns 1

Table 3.57. Arguments and Return Values for get_months()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the months value of the date passed (can be either a relative or absolute date).


3.3.19. get_seconds()

Synopsis

Returns an integer value representing the seconds value of the date passed (can be either a relative or absolute date).

Prototype

get_seconds(date) returns int (CONST)

get_seconds() returns nothing (RT_NOOP)

Example
$secs = get_seconds(2007-01-23T11:24:03); # returns 3

Table 3.58. Arguments and Return Values for get_seconds()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the seconds value of the date passed (can be either a relative or absolute date).


3.3.20. get_years()

Synopsis

Returns an integer value representing the years value of the date passed (can be either a relative or absolute date).

Prototype

get_years(date) returns int (CONST)

get_years() returns nothing (RT_NOOP)

Example
$years = get_years(2007-01-23); # returns 2007

Table 3.59. Arguments and Return Values for get_years()

Argument Type

Return Type

Description

date

int

Returns an integer value representing the years value of the date passed (can be either a relative or absolute date).


3.3.21. getDateFromISOWeek()

Synopsis

Retuns an absolute date value for the ISO-8601 calendar week information passed (year, week number, optional: weekday, where 1=Monday, 7=Sunday) in the current time zone. If the weekday is omitted, Monday (1) is assumed; throws an exception if the arguments are invalid.

Prototype

getDateFromISOWeek(softint $year, softint $month, softint $wday = 1) returns date

Example
$date = getDateFromISOWeek(2007, 3); # returns 2007-01-15T00:00:00

Table 3.60. Arguments and Return Values for getDateFromISOWeek()

Argument Type

Return Type

Description

softint $year, softint $month, softint $wday = 1

date

Retuns an absolute date value in the local time zone for the ISO-8601 calendar week information passed (year, week number, optional: week day). If the week day is passed, it must be in the range 1 (Monday) - 7 (Sunday) inclusive.


Table 3.61. Exceptions Thrown by getDateFromISOWeek()

err

desc

ISO-8601-INVALID-WEEK

The week number is not valid for the given year.

ISO-8601-INVALID-DAY

The day number is not between 1 (Monday) and 7 (Sunday) inclusive.


3.3.22. getDayOfWeek()

Synopsis

Returns an integer representing the day of the week for the absolute date passed (0=Sunday, 6=Saturday)

Prototype

getDayOfWeek(date) returns int (CONST)

getDayOfWeek() returns nothing (RT_NOOP)

Prototype
$dow = getDayOfWeek(2007-05-15); # returns 2

Table 3.62. Arguments and Return Values for getDayOfWeek()

Argument Type

Return Type

Description

date

int

Returns an integer representing the day of the week for the absolute date passed (0=Sunday, 6=Saturday)


3.3.23. getDayNumber()

Synopsis

Returns an integer representing the ordinal day number in the year for the absolute date passed

Prototype

getDayNumber(date) returns int (CONST)

getDayNumber() returns nothing (RT_NOOP)

Example
$dn = getDayNumber(2007-05-15); # returns 135

Table 3.63. Arguments and Return Values for getDayNumber()

Argument Type

Return Type

Description

date

int

Returns an integer representing the ordinal day number in the year for the absolute date passed


3.3.24. getISODayOfWeek()

Synopsis

Returns an integer representing the ISO-8601 day of the week for the absolute date passed (1=Monday, 7=Sunday)

Prototype

getISODayOfWeek(date) returns int (CONST)

getISODayOfWeek() returns nothing (RT_NOOP)

Example
$dow = getISODayOfWeek(2007-05-15); # returns 2 for Tuesday

Table 3.64. Arguments and Return Values for getISODayOfWeek()

Argument Type

Return Type

Description

date

int

Returns an integer representing the ISO-8601 day of the week for the absolute date passed (1=Monday, 7=Sunday)


3.3.25. getISOWeekHash()

Synopsis

Returns a hash representing the ISO-8601 calendar week information for the absolute date passed (hash keys: year, week, day). Note that the ISO-8601 year does not always correspond with the calendar year at the end and the begin ning of every year (for example 2006-01-01 is ISO-8601 calendar week format is: year=2005, week=52, day=7)

Prototype

getISOWeekHash(date) returns hash (CONST)

getISOWeekHash() returns nothing (RT_NOOP)

Example
$h = getISOWeekHash(2007-05-15); # returns year=2007, week=20, day=2

Table 3.65. Arguments and Return Values for getISOWeekHash()

Argument Type

Return Type

Description

date

hash

Returns a hash of int representing the ISO-8601 calendar week information for the absolute date passed (hash keys: year, week, day)


3.3.26. getISOWeekString()

Synopsis

Returns a string representing the ISO-8601 calendar week information for the absolute date passed (ex: 2006-01-01 = "2005-W52-7"). Note that the ISO-8601 year does not always correspond with the calendar year at the end and the beginning of every year (for example 2006-01-01 is ISO-8601 calendar week format is: year=2005, week=52, day=7)

Prototype

getISOWeekString(date) returns string (CONST)

getISOWeekString() returns nothing (RT_NOOP)

Example
$str = getISOWeekString(2007-05-15); # returns "2007-W20-2"

Table 3.66. Arguments and Return Values for getISOWeekString()

Argument Type

Return Type

Description

date

string

Returns a string representing the ISO-8601 calendar week information for the absolute date passed (ex: 2006-01-01 = "2005-W52-7")


3.3.27. gmtime()

Synopsis

Returns the date and time in GMT; if no argument is passed, then the current UTC time with a resolution of a second is returned. Otherwise the single argument must be an integer giving the number of seconds since Jan 1, 1970, 00:00:00, or an absolute date/time value that will be returned as the sme time in UTC (GMT).

See also now_utc().

Prototype

gmtime(date $date) returns date (CONST)

gmtime(softint $epoch_seconds, softint $microseconds = 0) returns date (CONST)

gmtime() returns date (CONST)

Example
$date = gmtime(now_us());  # equivalent to now_utc()
$date = gmtime();          # also returns current UTC (GMT)

Table 3.67. Arguments and Return Values for gmtime()

Argument Type

Return Type

Description

date $date

date

The date argument is converted to UTC and returned.

softint $epoch_seconds, softint $microseconds = 0

date

$epoch_seconds must be the number of seconds passed since Jan 1, 1970, 00:00:00 UTC (see get_epoch_seconds() for a function that returns such a value). $microseconds will give the microsecond offset for the resulting time.

n/a

date

If no argument is passed, then the current date and time with resolution to the second in GMT is returned. See now_utc() for a similar function that returns the current UTC time with resolution to the microsecond.


This function does not throw any exceptions.

3.3.28. hours()

Synopsis

Returns a relative date/time value in hours to be used in date arithmetic.

Prototype

hours(softint) returns date (CONST)

hours() returns date (RT_NOOP)

Example
$h = hours(5 * 5); # returns 25h

Table 3.68. Arguments and Return Values for hours()

Argument Type

Return Type

Description

int

date

Returns a relative date/time value corresponding to the number of hours passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.29. is_date_absolute()

Synopsis

Returns True if the argument is an absolute date/time value, False if not.

Prototype

is_date_absolute(date) returns bool (CONST)

is_date_absolute(any) returns bool (RT_NOOP)

Example
my bool $b = is_date_absolute($date);

Table 3.69. Arguments and Return Values for is_date_absolute()

Argument Type

Return Type

Description

date

bool

Returns True if the argument is an absolute date/time value, False if not.


This function does not throw any exceptions.

3.3.30. is_date_relative()

Synopsis

Returns True if the argument is an relative date/time value, False if not.

Prototype

is_date_relative(date) returns bool (CONST)

is_date_relative(any) returns bool (RT_NOOP)

Example
my bool $b = is_date_relative($date);

Table 3.70. Arguments and Return Values for is_date_relative()

Argument Type

Return Type

Description

date

bool

Returns True if the argument is an relative date/time value, False if not.


This function does not throw any exceptions.

3.3.31. localtime()

Synopsis

Returns the date and time in local time corresponding to the integer argument passed, which must be the number of seconds since Jan 1, 1970, 00:00:00 Z (UTC). If no argument is passed, then the current local date and time are returned.

Prototype

localtime(date $date) returns date (CONST)

localtime(softint $epoch_seconds, softint $microseconds = 0) returns date (CONST)

localtime() returns date (CONST)

Example
$time = localtime(10);

Table 3.71. Arguments and Return Values for localtime()

Argument Type

Return Type

Description

date $date

date

The date argument is converted to the local time zone and returned.

softint $epoch_seconds, softint $microseconds = 0

date

$epoch_seconds must be the number of seconds passed since Jan 1, 1970, 00:00:00 UTC (see get_epoch_seconds() for a function that returns such a value). $microseconds will give the microsecond offset for the resulting time.

n/a

date

If no argument is passed, then the current date and time with resolution to the second in the local time zone is returned. See now_us() for a similar function that returns the current local time with resolution to the microsecond.


This function does not throw any exceptions.

3.3.32. microseconds()

Synopsis

Returns a relative date/time value in microseconds to be used in date arithmetic.

Prototype

microseconds(softint) returns date (CONST)

microseconds() returns date (RT_NOOP)

Example
$ms = millseconds(5 * 5); # returns 25ms

Table 3.72. Arguments and Return Values for microseconds()

Argument Type

Return Type

Description

softint

date

Returns a relative date/time value corresponding to the number of microseconds passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.33. milliseconds()

Synopsis

Returns a relative date/time value in milliseconds to be used in date arithmetic.

Prototype

milliseconds(softint) returns date (CONST)

milliseconds() returns date (RT_NOOP)

Example
$ms = millseconds(5 * 5); # returns 25ms

Table 3.73. Arguments and Return Values for milliseconds()

Argument Type

Return Type

Description

softint

date

Returns a relative date/time value corresponding to the number of milliseconds passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.34. minutes()

Synopsis

Returns a relative date/time value in minutes to be used in date arithmetic.

Prototype

minutes(softint) returns date (CONST)

minutes() returns date (RT_NOOP)

Example
$m = minutes(5 * 5); # returns 25m

Table 3.74. Arguments and Return Values for minutes()

Argument Type

Return Type

Description

softint

date

Returns a relative date/time value corresponding to the number of minutes passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.35. mktime()

Synopsis

Returns the number of seconds passed since Jan 1, 1970, 00:00:00 Z (UTC) for the date/time argument passed.

Without the RT_NOOP variant, this function is equivalent to get_epoch_seconds().

Prototype

mktime(date) returns int (CONST)

mktime() returns nothing (RT_NOOP)

Example
$secs = mktime(2007-09-23T00:00:01);

Table 3.75. Arguments and Return Values for mktime()

Argument Type

Return Type

Description

date

int

This function returns the number of seconds passed since Jan 1, 1970 00:00:00Z corresponding to the date/time argument.


This function does not throw any exceptions.

3.3.36. months()

Synopsis

Returns a relative date/time value in months to be used in date arithmetic.

Prototype

months(softint) returns date (CONST)

months() returns date (RT_NOOP)

Example
$m = months(5 * 5); # returns 25M

Table 3.76. Arguments and Return Values for months()

Argument Type

Return Type

Description

int

date

Returns a relative date/time value corresponding to the number of months passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.37. now()

Synopsis

Returns the current date and time in the local time zone with resolution to the second.

For similar functions returning the current date and time in the local time zone with millisecond and microsecond resolution, see now_ms() and now_us(). Note that there is no performance penalty for using now_ms() and now_us() versus this function, this function and now_ms() are kept for backwards-compatibility.

See also now_utc().

Prototype

now() returns date (CONST)

Example
$now = now();

Table 3.77. Arguments and Return Values for now()

Argument Type

Return Type

Description

n/a

date

Returns the current date and time in the local time zone with resolution to the second.


This function does not throw any exceptions.

3.3.38. now_ms()

Synopsis

Returns the current date and time in the local time zone with resolution to the millisecond.

For a similar function returning the current date and time in the local time zone with coarser granularity, when resolution only to the second is needed, see now(); for a similar function returning the current date and time with a resolution to the microsecond, see now_us(). Note that there is no performance penalty for using now_ms() and now_us() versus now(), now() and now_ms() are kept for backwards-compatibility.

See also now_utc().

Prototype
now_ms()
Example
$now_ms = now_ms();

Table 3.78. Arguments and Return Values for now_ms()

Argument Type

Return Type

Description

n/a

date

Returns the current date and time in the local time zone with resolution to the millisecond.


This function does not throw any exceptions.

3.3.39. now_us()

Synopsis

Returns the current date and time in the local time zone with resolution to the microsecond.

For similar functions returning the current date and time with coarser granularity, see now() and now_ms(). Note that there is no performance impact for using now_us() versus now() and now_ms(); now() and now_ms() are kept for backwards-compatibility.

See also now_utc().

Prototype
now_us()
Example
$now_us = now_us();

Table 3.79. Arguments and Return Values for now_us()

Argument Type

Return Type

Description

n/a

date

Returns the current date and time with resolution to the microsecond.


This function does not throw any exceptions.

3.3.40. now_utc()

Synopsis

Returns the current UTC date and time with resolution to the microsecond.

See also now_us() for a similar function that returns the current date and time in the local time zone.

Prototype
now_utc()
Example
$now_utc = now_utc();

Table 3.80. Arguments and Return Values for now_utc()

Argument Type

Return Type

Description

n/a

date

Returns the current UTC date and time with resolution to the microsecond.


This function does not throw any exceptions.

3.3.41. seconds()

Synopsis

Returns a relative date/time value in seconds to be used in date arithmetic.

Prototype

seconds(softint) returns date (CONST)

seconds() returns date (RT_NOOP)

Example
$time = now() + seconds(5 * 5); # 25 seconds from now

Table 3.81. Arguments and Return Values for seconds()

Argument Type

Return Type

Description

softint

date

Returns a relative date/time value corresponding to the number of seconds passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.3.42. timegm()

Synopsis

Returns the number of seconds since January 1, 1970 00:00:00 in the local time zone for the given date.

Prototype

timegm(date) returns int (CONST)

timegm() returns nothing (RT_NOOP)

Example
$secs = timegm(2007-05-01T11:34:01);

Table 3.82. Arguments and Return Values for timegm()

Argument Type

Return Type

Description

date

int

Returns the number of seconds since January 1, 1970 00:00:00 in the local time zone for the given date.


3.3.43. years()

Synopsis

Returns a relative date/time value in years to be used in date arithmetic.

Prototype

years(softint) returns date

years() returns date (RT_NOOP)

Example
$years = years(5 * 5); # returns 25Y

Table 3.83. Arguments and Return Values for years()

Argument Type

Return Type

Description

int

date

Returns a relative date/time value corresponding to the number of years passed as an argument, to be used in date arithmetic.


This function does not throw any exceptions.

3.4. Qore Type Functions

3.4.1. binary()

Synopsis

Returns a binary data type of the string passed; data types other than string will first be converted to a string and then returned as binary data.

This function is useful if, for some reason, a string type actually contains binary data; using this function will ensure that all data in the string (even if it contains embedded nulls) is maintained in the binary object (Qore strings must normally be terminated by a single null, so some Qore string operations do not work on binary data with embedded nulls).

Prototype

binary(string) returns binary (CONST)

binary(binary) returns binary (CONST)

binary(null) returns binary (CONST)

binary() returns binary (CONST)

Example
$bin = binary("hello");

Table 3.84. Arguments and Return Values for binary()

Argument Type

Return Type

Description

softstring

binary

A binary data type holding the string data passed.


This function does not throw any exceptions.

3.4.2. binary_to_string()

Synopsis

Returns a string created from the binary data passed, taking an optional second argument giving the string encoding. If no second argument is passed then the default encoding is assumed.

No checking is performed for embedded null characters or for character encoding violations; the data is simply copied from the binary value to the string (with any embedded nulls, if present), and the string is tagged with the given encoding or with the default encoding if no second argument is passed. See also string() and binary().

Prototype

binary_to_string(binary $bin) returns string

binary_to_string(binary $bin, string $encoding) returns string

Example
$str = binary_to_string($bin, "utf8");

Table 3.85. Arguments and Return Values for binary_to_string()

Argument Type

Return Type

Description

binary $bin, [string $encoding]

string

Returns a string corresponding to the binary data passed, taking an optional second argument giving the string encoding. If no second argument is passed then the default encoding is assumed.


3.4.3. boolean()

Synopsis

Converts the argument to a boolean value.

Prototype

boolean(softbool) returns bool (CONST)

boolean(null) returns bool (CONST)

boolean() returns bool (CONST)

Example
$bool = boolean(1); # returns True

Table 3.86. Arguments and Return Values for boolean()

Argument Type

Return Type

Description

softbool

bool

Converts the argument to an boolean, where any non-zero value is True, zero is False.


This function does not throw any exceptions.

3.4.4. date()

Synopsis

Converts the argument to a date and returns the date. When converting from an integer, the integer value represents the offset in seconds from 1970-01-01 in the local time zone.

See also date_ms(), date_us(), and localtime().

As of Qore 0.8.0, converting a date from a string is much more flexible; formats such as the following are now accepted (note that in the following examples, if the time zone/UTC offset is not explicitly specified, the local time zone is assumed):

Table 3.87. Examples Converting Date From String

String

Date

"2001-01-01T15:35:23"

2001-01-01 15:35:23 Mon +01:00 (CET)

"20010101 15:35:23Z"

2001-01-01 15:35:23 Mon Z (UTC)

"20010101 153523Z"

2001-01-01 15:35:23 Mon Z (UTC)

"20010101 153523-02"

2001-01-01 15:35:23 Mon -02:00 (-02:00)

"20010101 153523-02:00:00"

2001-01-01 15:35:23 Mon -02:00 (-02:00)

"2001-01-01-153523-020000"

2001-01-01 15:35:23 Mon -02:00 (-02:00)

"20010101-153523"

2001-01-01 15:35:23 Mon +01:00 (CET)


Prototype

date(string) returns date (CONST)

date(softint) returns date (CONST)

date(null) returns date (CONST)

date() returns date (CONST)

Example
$date = date(1); # return 1970-01-01T00:00:01

Table 3.88. Arguments and Return Values for date()

Argument Type

Return Type

Description

string

date

Converts the argument to a date and returns the date.

softint

date

The argument is assumed to be the number of seconds since 1970-01-01 in the local time zone; this value is used to produce the date value that is returned.


This function does not throw any exceptions.

3.4.5. float()

Synopsis

Converts the argument passed to a floating-point value.

Prototype

float(softfloat) returns float (CONST)

float(null) returns float (CONST)

float() returns float (CONST)

Example
$float = float("1.435"); # returns 1.435

Table 3.89. Arguments and Return Values for float()

Argument Type

Return Type

Description

softfloat

float

Converts argument passed to a floating-point value.


This function does not throw any exceptions.

3.4.6. hash()

Synopsis

Converts an object or a list to a hash; for any other argument, returns an empty hash (ignores any other arguments passed).

For an object argument, the hash returned is equal to the object members (excluding private members if called outside the class); a list is converted to a hash by taking even numbered list elements (starting with 0) and converting them to strings for the hash keys, and the odd numbered elements following the keys as the key value.

Prototype

hash(list $list) returns hash

hash(list $keys, list $values) returns hash

hash(hash $hash) returns hash (CONST)

hash(object $obj) returns hash

hash() returns hash (CONST)

Example
$h = hash($object); # creates a hash of the object's members

Table 3.90. Arguments and Return Values for hash()

Argument Type

Return Type

Description

list $keys, list $values

hash

Returns a hash by taking the first list as a list of keys, and the second list as a list of values. If the two lists are of unequal sizes, then the keys list takes precedence (if the values list is longer, excess values are ignored).

list $list

hash

Returns a hash by taking even numbered list elements (starting with 0) and converting them to strings for the hash keys, and the odd numbered elements following the keys as the key value.

hash $hash

hash

Returns the hash argument unmodified.

object $obj

hash

Returns a hash of the object's members (public members only if called outside the class).

any

hash

Returns an empty hash.


This function does not throw any exceptions.

3.4.7. int()

Synopsis

Converts the argument passed to an integer value if it is not already.

Prototype

int(softint) returns int (CONST)

int(null) returns int (CONST)

int() returns int (CONST)

Example
$int = int("200"); # returns 200

Table 3.91. Arguments and Return Values for int()

Argument Type

Return Type

Description

softint

int

Converts argument passed to an integer value.


This function does not throw any exceptions.

3.4.8. list()

Synopsis

Returns a list; if any arguments are passed, they are inserted as the first element in the list returned.

Prototype

list(...) returns list (CONST)

Example
$l = list(200);

Table 3.92. Arguments and Return Values for list()

Argument Type

Return Type

Description

any

list

Returns a list. If any arguments are passed, they are inserted as the first element in the list returned; if no argument is passed, and empty list is returned.


This function does not throw any exceptions.

3.4.9. string()

Synopsis

Converts the argument passed to a string value.

This function will not convert a binary value to a string; in order to do this, use the binary_to_string() function.

Prototype

string(softstring) returns string (CONST)

string() returns string (CONST)

Example
$str = string(200); # returns "200"

Table 3.93. Arguments and Return Values for string()

Argument Type

Return Type

Description

softstring

string

Converts the argument passed to a string value.


This function does not throw any exceptions.

3.4.10. type()

Synopsis

Returns the data type of the argument passed. See Type Constants for the values returned by this function..

Prototype

type(any) returns string (CONST)

Example
$type = type("hello"); # returns Type::String ("string")

Table 3.94. Arguments and Return Values for type()

Argument Type

Return Type

Description

any

string

Returns the data type of the argument passed. See Type_Constants for the values that can be returned by this function.


This function does not throw any exceptions.

3.4.11. typename()

Synopsis

deprecated: use type() instead.

Prototype
typename(expression)

Table 3.95. Arguments and Return Values for typename()

Argument Type

Return Type

Description

Any

string

deprecated: use type() instead.


This function does not throw any exceptions.

Note

This function will be removed in a future version of Qore.

3.5. Environment Functions

3.5.1. getenv()

Synopsis

Retrieves the environment variable passed as an argument.

Prototype

getenv(string) returns any (CONST)

getenv() returns nothing (RT_NOOP)

Example
$v = getenv("PATH");

Table 3.96. Arguments and Return Values for getenv()

Argument Type

Return Type

Description

string

any

The contents of the environment variable are returned as a string, if the environment variable exists, otherwise no value is returned.


This function does not throw any exceptions.

3.5.2. setenv()

Synopsis

Sets an environment variable to a value.

To unset or clear an environment variable, see unsetenv().

Prototype

setenv(string $var, softstring $value) returns int

setenv() returns nothing (RT_NOOP)

Example
setenv("PATH", "/bin:/usr/bin");

Table 3.97. Arguments and Return Values for setenv()

Argument Type

Return Type

Description

string $var, softstring $value

int

Sets the environment variable to a string value (the value is converted to a string if necessary).


This function does not throw any exceptions.

3.5.3. unsetenv()

Synopsis

Unsets an environment variable.

To set an environment variable, see setenv().

Prototype

unsetenv(string) returns int

unsetenv() returns nothing (RT_NOOP)

Example
unsetenv("PATH");

Table 3.98. Arguments and Return Values for unsetenv()

Argument Type

Return Type

Description

string

int

Unsets the environment variable given by the string passed.


This function does not throw any exceptions.

Note

This function is only supported on systems where the C library support for unsetenv() is present.

3.6. String Functions

3.6.1. bindex()

Synopsis

Retrieves the byte position of a substring within a string.

Prototype

bindex(softstring $string, softstring $substring, softint $offset = 0) returns int

bindex() returns int (RT_NOOP)

Example
$i = bindex("hello there", "the");

Table 3.99. Arguments and Return Values for bindex()

Argument Type

Return Type

Description

softstring $string, softstring $substring, softint $offset = 0

int

If the substring is found, returns the byte position of the substring within the string (starting at 0). If not found, returns -1. If an offset position is given, the search starts at the offset position. All values are byte positions, not character positions, which may differ for multi-byte character encodings.


This function does not throw any exceptions.

3.6.2. brindex()

Synopsis

Returns the starting byte position of a string in another, starting from the end of the string (-1 if not found) and takes an optional starting position.

Prototype

brindex(softstring $string, softstring $substring, softint $offset = -1) returns int

brindex() returns int (RT_NOOP)

Example
$i = brindex("hello there", "the");

Table 3.100. Arguments and Return Values for brindex()

Argument Type

Return Type

Description

softstring $string, softstring $substring, softint $offset = -1

int

Returns the starting byte position of a string in another, starting from the end of the string, or from position if given. If $offset is given, then the reverse search starts at that character position (searches always go from the end of the string toward the beginning). Returns -1 if the substring cannot be found. All values are byte positions, not character positions, which may differ for multi-byte character encodings.


This function does not throw any exceptions.

3.6.3. chomp()

Synopsis

Removes the trailing end-of-line indicator ('\n' or '\r\n') from a string and returns the new string (also see the chomp operator). If no EOL indicator is present in the string, this function simply returns the original string unmodified. This function accepts variable references, in which case it will modify the string in place and also return the modified string.

Prototype

chomp(string) returns string

chomp(reference) returns any

Example
$line = chomp("hello\n"); # returns "hello"

Table 3.101. Arguments and Return Values for chomp()

Argument Type

Return Type

Description

string

string

Returns the new string with any end-of-line character(s) removed.

reference

any

If the first argument is a variable reference and points to a string, then the string is modified in place and the new string is also returned. Otherwise if the reference is any other type, no action is taken and no value is returned.


This function does not throw any exceptions.

3.6.4. chr()

Synopsis

Returns a string containing a single ASCII character represented by the numeric value passed.

Prototype

chr(softint) returns string

chr(any) returns string (NOOP)

chr() returns nothing (RT_NOOP)

Example
$i = chr(65); # returns "A"

Table 3.102. Arguments and Return Values for chr()

Argument Type

Return Type

Description

softint

string

Returns a string containing a single ASCII character represented by the numeric value passed.


This function does not throw any exceptions.

3.6.5. convert_encoding()

Synopsis

Performs explicit string character encoding conversions.

Prototype

convert_encoding(string, string) returns string (CONST)

convert_encoding() returns nothing (RT_NOOP)

Example
$utf8_str = convert_encoding($iso_8859_1_str, "utf-8");

Table 3.103. Arguments and Return Values for convert_encoding()

Argument Type

Return Type

Description

string, string

string

Converts the string arguement to the encoding given and returns the new string.


Table 3.104. Exceptions Thrown by convert_encoding()

err

desc

STRING-ENCODING-CONVERSION-ERROR

There was an error converting to the target encoding (ex: conversion not supported, illegal character sequence, etc).


3.6.6. decode_url()

Synopsis

Decodes percent numeric codes in a URL string and returns the decoded string.

Prototype

decode_url(string) returns string (CONST)

decode_url() returns nothing (RT_NOOP)

Example
$decoded_url = decode_url($encoded_url);

Table 3.105. Arguments and Return Values for decode_url()

Argument Type

Return Type

Description

string

string

Returns a string with numeric percent codes decoded to characters.


This function does not throw any exceptions.

3.6.7. force_encoding()

Synopsis

Returns the first string argument tagged with the character encoding given as the second argument; does not actually change the string data; use only in the case that a string is tagged with the wrong encoding, for example, if a string from a File object has a different encoding than the File object.

Prototype

force_encoding(string, string) returns string (CONST)

force_encoding() returns nothing (RT_NOOP)

Example
$utf8_str = force_encoding($bad_str, "utf-8");

Table 3.106. Arguments and Return Values for convert_encoding()

Argument Type

Return Type

Description

string, string

string

Returns a string with identical byte data as the input string, but tagged with the new encoding.


This function does not throw any exceptions.

3.6.8. get_encoding()

Synopsis

Returns a string describing the character encoding of the string passed.

Prototype

get_encoding(string) returns string (CONST)

get_encoding() returns nothing (RT_NOOP)

Example
$enc = get_encoding($string);

Table 3.107. Arguments and Return Values for get_encoding()

Argument Type

Return Type

Description

string

string

Returns a string describing the character encoding of the string passed (ex: "UTF-8", "ISO-8850-1", "KOI8-R").


This function does not throw any exceptions.

3.6.9. index()

Synopsis

Retrieves the character position of a substring within a string.

Prototype

index(softstring $string, softstring $substring, softint $offset = 0) returns int (CONST)

index() returns int (RT_NOOP)

Example
$i = index("hello there", "the");

Table 3.108. Arguments and Return Values for index()

Argument Type

Return Type

Description

softstring $string, softstring $substring, softint $offset = 0

int

If the substring is found, returns the position of the substring within the string (starting at 0). If not found, returns -1. If an offset position is given, the search starts at the offset position. All values are character positions, not byte positions, which may differ for multi-byte character encodings.


This function does not throw any exceptions.

3.6.10. join()

Synopsis

Creates a string from a list and separator string.

Prototype

join(string, list) returns string (CONST)

join(string, ...) returns string (CONST)

join() returns nothing (RT_NOOP)

Example
$str = join(":", ("a", "b", "c")); # returns "a:b:c"

Table 3.109. Arguments and Return Values for join()

Argument Type

Return Type

Description

string, list or ...

string

Returns a string with each element of the list separated by the separator string.


This function does not throw any exceptions.

3.6.11. length()

Synopsis

Returns the length in characters for the string passed. Note that the byte length may differ from the character length with multi-byte character encodings. For byte length of a string, see strlen().

Prototype

length(softstring) returns int (CONST)

length(binary) returns int (CONST)

length(any) returns int (NOOP)

length() returns nothing (RT_NOOP)

Example
$len = length("hello"); # returns 5

Table 3.110. Arguments and Return Values for length()

Argument Type

Return Type

Description

softstring

int

Returns the length in characters for the string passed.

binary

int

Returns the number of bytes in the binary data passed.


This function does not throw any exceptions.

3.6.12. ord()

Synopsis

Gives the numeric value of the given byte in the string passed (the first byte if no offset is passed); if no string is passed or the offset is after the end of the string, -1 is returned.

Prototype

ord(softstring $string, softint $offset = 0) returns int (CONST)

ord() returns nothing (RT_NOOP)

Example
$i = ord("A"); # returns 65

Table 3.111. Arguments and Return Values for ord()

Argument Type

Return Type

Description

softstring $string, softint $offset = 0

int

Gives the numeric value of the given byte in the string passed (the first byte if no offset is passed); if no string is passed or the offset is after the end of the string, -1 is returned.


This function does not throw any exceptions.

3.6.13. regex()

Synopsis

Returns True if the regular expression matches the string passed, otherwise returns False.

Prototype

regex(string $string, string $pattern, int $options = 0) returns bool

regex() returns nothing (RT_NOOP)

Example
$bool = regex("hello", "^hel"); # returns True

Table 3.112. Arguments and Return Values for regex()

Argument Type

Return Type

Description

string $string, string $pattern, int $options = 0

bool

Returns True if the first argument matches pattern as the second argument, False if not. The third argument can be passed to give regex options; for valid options, see Regex Constants.


Table 3.113. Exceptions Thrown by regex()

err

desc

REGEX-COMPILATION-ERROR

There was an error compiling the regular expression.


For more information on regular expression processing, see Regular Expressions.

3.6.14. regex_extract()

Synopsis

Returns a list of substrings in a string based on matching patterns defined by a regular expression.

Prototype

regex_extract(string $string, string $pattern, int $options = 0) returns any

regex_extract() returns nothing (RT_NOOP)

Example
my any $rv = regex_extract("hello:there", "(\\w+):(\\w+)");

Table 3.114. Arguments and Return Values for regex_extract()

Argument Type

Return Type

Description

string $string, string $pattern, int $options = 0

list

Returns any patterns in parentheses in the second argument when applied tot he first argument as a list. If no matches are found, then NOTHING is returned. The third argument can be used to set regex options; for valid options, see Regex Constants


Table 3.115. Exceptions Thrown by regex_extract()

err

desc

REGEX-OPTION-ERROR

Invalid options were passed to the function.

REGEX-COMPILATION-ERROR

There was an error compiling the regular expression.


For more information on regular expression processing, see Regular Expressions.

3.6.15. regex_subst()

Synopsis

Returns a string with patterns substituted according to the arguments passed.

Prototype

regex_subst(string $string, string $pattern, string $new_string, int $options = 0) returns string

regex_subst() returns nothing (RT_NOOP)

Example
$str = regex_subst("hello there", "^there$", "you"); # returns "hello you"

Table 3.116. Arguments and Return Values for regex_subst()

Argument Type

Return Type

Description

string $string, string $pattern, string $new_string, int $options = 0

string

Returns the result of applying the second argument as a pattern to the first argument, with the 3rd argument as the replacement string. The fourth argument can be used to set regex options; for valid options, see Regex Constants


Table 3.117. Exceptions Thrown by regex_subst()

err

desc

REGEX-OPTION-ERROR

Invalid options were passed to the function.

REGEX-COMPILATION-ERROR

There was an error compiling the regular expression.


For more information on regular expression processing, see Regular Expressions.

3.6.16. replace()

Synopsis

Replaces all occurrances of a substring in a string with another string.

Prototype

replace(string $string, string $old, string $new) returns string

replace() returns nothing (RT_NOOP)

Example
$str = replace("hello there", "there", "you"); # returns "hello you"

Table 3.118. Arguments and Return Values for replace()

Argument Type

Return Type

Description

string $string, string $old, string $new

string

Replaces all occurrances of a the second string found in the first string with the third string and returns the new string.


This function does not throw any exceptions.

3.6.17. rindex()

Synopsis

Returns the starting character position of a string in another, starting from the end of the string (-1 if not found) and takes an optional starting position.

Prototype

rindex(softstring $string, softstring $substring, softint $offset = -1) returns int (CONST)

rindex() returns int (RT_NOOP)

Example
$i = rindex("hello there", "the");

Table 3.119. Arguments and Return Values for rindex()

Argument Type

Return Type

Description

softstring $string, softstring $substring, softint $offset = -1

int

Returns the starting character position of a string in another, starting from the end of the string, or from the third argument giving the character (not byte) position if given (negative values are offsets from the end of the string, -1 gives the last character of the string). If the thirs argument is given, then the reverse search starts at that character position (searches always go from the end of the string toward the beginning). Returns -1 if the substring cannot be found. All values are character positions, not byte positions, which may differ for multi-byte character encodings.


This function does not throw any exceptions.

3.6.18. split()

Synopsis

Splits a string into a list of components based on a separator string.

Prototype

split(string $separator, string $string) returns list (CONST)

split(binary $separator, binary $bin) returns list (CONST)

split() returns list (RT_NOOP)

Example
$list = split(":", "some:text:here"); # returns ("some", "text", "here")

Table 3.120. Arguments and Return Values for split()

Argument Type

Return Type

Description

string $separator, string $string

list of string

Returns a list of each component of a string separated by a separator string, with the separator removed.

binary $separator, binary $bin

list of binary

Returns a list of each component of thebinary object separated by the bytes identified by $separator, with the separator removed.


This function does not throw any exceptions.

3.6.19. strlen()

Synopsis

Returns the length in bytes of the string argument. Note that the byte length may differ from the character length with multi-byte character encodings. For the character length of a string, see length().

Prototype

strlen(softstring) returns int (CONST)

strlen(any) returns int (NOOP)

strlen() returns nothing (RT_NOOP)

Example
$len = strlen("hello"); # returns 5

Table 3.121. Arguments and Return Values for strlen()

Argument Type

Return Type

Description

softstring

int

Returns the length of the string passed. If the argument is not a string, then it is converted to a string.


This function does not throw any exceptions.

3.6.20. substr()

Synopsis

Returns a portion of a string starting from an integer offset, with an optional length. Arguments can be negative, giving offsets from the end of the string. All offsets are character positions, not byte positions.

Prototype

substr(softstring $string, softint $offset, softint $len) returns string (CONST)

substr(softstring $string, softint $offset) returns string (CONST)

substr() returns nothing (RT_NOOP)

Example
$str = substr("hello there", 6); # returns "there"

Table 3.122. Arguments and Return Values for substr()

Argument Type

Return Type

Description

softstring $string, softint $offset, [softint $len]

string

Returns the substring according to the arguments. If $offset is negative, it designates an offset from the end of the string. If $len is not present, all characters from the offset will be copied to the substring. If it is negative, the rest of the string without the trailing number characters given by the negative argument will be copied to the substring.


This function does not throw any exceptions.

3.6.21. tolower()

Synopsis

Converts the argument passed to a string value all in lower case.

Prototype

tolower(string) returns string (CONST)

tolower() returns nothing (RT_NOOP)

Example
$str = tolower("HELLO"); # returns "hello"

Table 3.123. Arguments and Return Values for tolower()

Argument Type

Return Type

Description

string

string

Converts argument passed to a string value, all in lower case.


This function does not throw any exceptions.

3.6.22. toupper()

Synopsis

Converts the argument passed to a string value all in upper case.

Prototype

toupper(string) returns string (CONST)

toupper() returns nothing (RT_NOOP)

Example
$str = toupper("hello"); # returns "HELLO"

Table 3.124. Arguments and Return Values for toupper()

Argument Type

Return Type

Description

string

string

Converts argument passed to a string value, all in upper case.


This function does not throw any exceptions.

3.6.23. trim()

Synopsis

Removes characters from the start and end of a string and returns the new string (also see the trim operator). This function accepts variable references, in which case it will modify the string in place and also return the modified string.

By default (if the second argument is omitted or passed as an empty string) the following whitespace characters are removed: ' ', '\n', '\r', '\t', '\v' (vertical tab, ASCII 11), and '\0' (null character). To trim other characters, pass a string as the second argument specifying the characters to be removed.

Prototype

trim(string $string, string $chars = "") returns string (CONST)

trim(reference $string_ref, string $chars = "") returns any

trim() returns nothing (RT_NOOP)

Example
$line = trim("   hello  \n"); # returns "hello"

Table 3.125. Arguments and Return Values for trim()

Argument Type

Return Type

Description

string $string, string $chars = ""

string

Returns the new string with characters removed from the beginning and end of the string; if the second argument is given then it defines the characters to be removed, otherwise whitespace is removed.

reference $string_ref, string $chars = ""

any

If the reference points to a string, the string is trimmed in place and the result is also returned; if the second argument is given then it defines the characters to be removed, otherwise whitespace is removed. If the reference is not a string then no value is returned.


This function does not throw any exceptions.

3.7. Operating System Functions

3.7.1. abort()

Synopsis

Aborts the current program (this function does not return).

Prototype

abort() returns nothing

Example
abort();
Restrictions

Not available with PO_NO_PROCESS_CONTROL

This function does not throw any exceptions.

3.7.2. basename()

Synopsis

Returns a string giving the last element of a file path.

Prototype

basename(string) returns string

basename() returns nothing (RT_NOOP)

Example
$str = basename("/usr/local/bin/file_name"); # returns "file_name"

Table 3.126. Arguments and Return Values for basename()

Argument Type

Return Type

Description

string

string

Returns the last element in a file path (meant to be the filename).


This function does not throw any exceptions.

3.7.3. errno()

Synopsis

Returns the error code of the last error that occurred in the current thread. See strerror() for a function that gives the string description for the error number returned by this function.

Prototype

errno() returns int

Example
$str = strerror(errno());

Table 3.127. Arguments and Return Values for errno()

Argument Type

Return Type

Description

n/a

int

The error code of the most recent error in the current thread is returned.


This function does not throw any exceptions.

3.7.4. exec()

Synopsis

Replaces the current process image with another. This function does not return.

Prototype

exec(string) returns nothing

exec() returns nothing (RT_NOOP)

Example
exec("/bin/ls -l");
Restrictions

Not available with PO_NO_PROCESS_CONTROL or PO_NO_EXTERNAL_PROCESS

Table 3.128. Arguments and Return Values for exec()

Argument Type

Return Type

Description

string

n/a

The process and any arguments to the process to execute. This function does not return.


This function does not throw any exceptions.

3.7.5. exit()

Synopsis

Exits the program with the return code passed (this function does not return).

Prototype

exit(any = 0) returns nothing

Example
exit(2);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.129. Arguments and Return Values for exit()

Argument Type

Return Type

Description

any

n/a

Exits the program with the return code set to the value of the argument passed converted to an integer if necessary.


This function does not throw any exceptions.

3.7.6. fork()

Synopsis

Creates a copy of the current process with a new PID. Returns 0 in the child process, the child's PID in the parent process. This function will throw an exception if more than one thread is running.

Prototype

fork() returns int

Example
$pid = fork();
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.130. Arguments and Return Values for fork()

Argument Type

Return Type

Description

n/a

int

The child's PID is returned in the parent process, 0 is returned in the child's process. If -1 is returned, then no child was started and the error number can be retrieved with the errno() function.


Table 3.131. Exceptions Thrown by fork()

err

desc

ILLEGAL-FORK

Cannot fork if more than one thread is running.


3.7.7. getegid()

Synopsis

Returns the effective group ID of the current process.

Prototype

getegid() returns int (CONST)

Example
$egid = getegid();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.132. Arguments and Return Values for getegid()

Argument Type

Return Type

Description

n/a

int

Returns the effective group ID of the current process.


This function does not throw any exceptions.

3.7.8. geteuid()

Synopsis

Returns the effective user ID of the current process.

Prototype

geteuid() returns int (CONST)

Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.133. Arguments and Return Values for geteuid()

Argument Type

Return Type

Description

n/a

int

Returns the effective user ID of the current process.


This function does not throw any exceptions.

3.7.9. getgid()

Synopsis

Returns the real group ID of the current process.

Prototype

getgid returns int (CONST)

Example
$gid = getgid();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.134. Arguments and Return Values for getgid()

Argument Type

Return Type

Description

n/a

int

Returns the real group ID of the current process.


This function does not throw any exceptions.

3.7.10. gethostbyaddr()

Synopsis

Returns the official hostname corresponding to the network addressed passed as an argument. If the second argument giving the address type is not passed, then AF_INET (IPv4) is assumed. See Network Address Type Constants for valid values for the second argument. If the address family is invalid or the address string is not a valid address for the given family an exception will be thrown.

For a version of this function that returns all host information, including all hostname aliases and all addresses, see gethostbyaddr_long().

Prototype

gethostbyaddr(string $addr, softint $type = AF_INET) returns any (CONST)

gethostbyaddr() returns nothing (RT_NOOP)

Example
$hostname = gethostbyaddr("192.168.0.33");
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.135. Arguments and Return Values for gethostbyaddr()

Argument Type

Return Type

Description

string $addr, softint $type = AF_INET

any

Returns the hostname of the system as a string or NOTHING if the address is unknown.


Table 3.136. Exceptions thrown by gethostbyaddr()

err

desc

GETHOSTBYADDR-ERROR

invalid address or invalid address family passed as arguments


3.7.11. gethostbyaddr_long()

Synopsis

Returns a hash representing all host and address information corresponding to the network addressed passed as an argument. See Host Information Hash for a description of the return value.

If the second argument giving the address type is not passed, then AF_INET (IPv4) is assumed. See Network Address Type Constants for valid values for the second argument. If the address family is invalid or the address string is not a valid address for the given family an exception will be thrown.

For a version of this function that returns just the official hostname corresponding to the address, see gethostbyaddr().

Prototype

gethostbyaddr_long(string $addr, softint $type = AF_INET) returns any (CONST)

gethostbyaddr_long() returns nothing (RT_NOOP)

Example
$hash = gethostbyaddr_long("192.168.0.33");
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.137. Arguments and Return Values for gethostbyaddr_long()

Argument Type

Return Type

Description

string $addr, softint $type = AF_INET

any

Returns a hash representing all host and address information corresponding to the network address passed or NOTHING if the address is unknown.


Table 3.138. Host Information Hash

Key

Type

Value

name

string

The official fully-qualified name of the host

aliases

list of string

Any hostname aliases for the host

typename

string

The type of network address (either "ipv4" or "ipv6")

type

int

One of the Network Address Type Constants (either AF_INET or AF_INET6) corresponding to the type of network addresses given.

len

int

The length of the addresses in bytes when represented in binary form.

addresses

list of string

All addresses corresponding to the host; the list should have at least 1 element


Table 3.139. Exceptions thrown by gethostbyaddr_long()

err

desc

GETHOSTBYADDR-ERROR

invalid address or invalid address family passed as arguments


3.7.12. gethostbyname()

Synopsis

Returns the first address corresponding to the hostname passed as an argument.

For a version of this function that returns all host information, including all hostname aliases and all addresses, see gethostbyname_long().

Prototype

gethostbyname(string $name) returns any (CONST)

gethostbyname() returns nothing (RT_NOOP)

Example
$addr = gethostbyname("host1");
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.140. Arguments and Return Values for gethostbyname()

Argument Type

Return Type

Description

string $name

any

Returns the first address corresponding to the hostname passed as a string or NOTHING if the host is unknown.


This function does not throw any exceptions.

3.7.13. gethostbyname_long()

Synopsis

Returns a hash representing all host and address information corresponding to the hostname passed as an argument. See Host Information Hash for a description of the return value.

For a version of this function that returns just the first network address corresponding to the hostname, see gethostbyname().

Prototype

gethostbyname_long(string $name) returns any (CONST)

Example
$hash = gethostbyname_long("host1");
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.141. Arguments and Return Values for gethostbyname_long()

Argument Type

Return Type

Description

string $name

any

Returns a hash representing all host and address information corresponding to the hostname passed or NOTHING if the host is unknown.


This function does not throw any exceptions.

3.7.14. gethostname()

Synopsis

Returns the hostname of the system.

Prototype

gethostname() returns string

Example
$host = gethostname();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.142. Arguments and Return Values for gethostname()

Argument Type

Return Type

Description

n/a

string

Returns the hostname of the system.


This function does not throw any exceptions.

3.7.15. getpid()

Synopsis

Returns the PID (process ID) of the current process.

Prototype

getpid() returns int (CONST)

Example
$pid = getpid();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.143. Arguments and Return Values for getpid()

Argument Type

Return Type

Description

n/a

int

Returns the PID (process ID) of the current process.


This function does not throw any exceptions.

3.7.16. getppid()

Synopsis

Returns the PID (process ID) of the parent process of the current process.

Prototype

getppid() returns int (CONST)

Example
$ppid = getppid();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.144. Arguments and Return Values for getppid()

Argument Type

Return Type

Description

n/a

int

Returns the PID (process ID) of the parent of the current process.


This function does not throw any exceptions.

3.7.17. getuid()

Synopsis

Returns the real user ID of the current process.

Prototype

getuid() returns int (CONST)

Example
$uid = getuid();
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.145. Arguments and Return Values for getuid()

Argument Type

Return Type

Description

n/a

int

Returns the real user ID of the current process.


This function does not throw any exceptions.

3.7.18. glob()

Synopsis

Returns a list of files matching the string argument or NOTHING if the call to glob() fails.

Prototype

glob(string) returns any

glob() returns nothing (RT_NOOP)

Example
$list = glob("*.txt");

Table 3.146. Arguments and Return Values for glob()

Argument Type

Return Type

Description

string

any

Returns a list of files matching the string argument or NOTHING if the call to glob() fails.


This function does not throw any exceptions.

3.7.19. kill()

Synopsis

Sends a signal to a process, if no signal number is given, then SIGHUP is sent by default.

Prototype

kill(softint $pid, softint $signal = SIGHUP) returns int

kill() returns nothing (RT_NOOP)

Example
kill($pid, SIGINT);
Restrictions

Not available with PO_NO_EXTERNAL_PROCESS

Table 3.147. Arguments and Return Values for kill()

Argument Type

Return Type

Description

int $pid, int $signal = SIGHUP

int

Sends a signal to a process, if the optional signal number is not given, then SIGHUP is sent. A 0 return value means that the signal was succesfully sent.


This function does not throw any exceptions.

3.7.20. setegid()

Synopsis

Changes the process effective group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno()). The availabilty of this function depends on the system's underlying C-library; the Qore function is only available if the constant HAVE_SETEGID is True. See Library Option Constants for a list of all option constants.

Prototype

setegid(softint) returns int

Example
setegid($egid);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.148. Arguments and Return Values for setegid()

Argument Type

Return Type

Description

softint

int

Changes the process effective group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())


Table 3.149. Exceptions thrown by setegid()

err

desc

SETEGID-ERROR

missing EGID argument to function

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SETEGID before calling this function.


3.7.21. seteuid()

Synopsis

Changes the process effective user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno()). The availabilty of this function depends on the system's underlying C-library; the Qore function is only available if the constant HAVE_SETEUID is True. See Library Option Constants for a list of all option constants.

Prototype

seteuid(softint) returns int

Example
seteuid($euid);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.150. Arguments and Return Values for seteuid()

Argument Type

Return Type

Description

softint

int

Changes the process effective user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())


Table 3.151. Exceptions thrown by seteuid()

err

desc

SETEUID-ERROR

missing EUID argument to function

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SETEUID before calling this function.


3.7.22. setgid()

Synopsis

Changes the process group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

Prototype

setgid(softint) returns int

Example
setgid($gid);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.152. Arguments and Return Values for setgid()

Argument Type

Return Type

Description

softint

int

Changes the process group ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())


Table 3.153. Exceptions thrown by setgid()

err

desc

SETGID-ERROR

missing GID argument to function


3.7.23. setsid()

Synopsis

Creates a new session lead by the calling process.

The calling process is the session leader of the new session, is the process group leader of a new process group and has no controlling terminal. The calling process is the only process in either the session or the process group.

Upon successful completion, the setsid() function returns the value of the process group ID of the new process group, which is the same as the process ID of the calling process.

Prototype

setsid() returns int

Example
my int $rc = setsid();
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.154. Arguments and Return Values for setsid()

Argument Type

Return Type

Description

n/a

int

Returns the current pid on success or -1 for errors (in which case the error code can be retrieved with errno())


3.7.24. setuid()

Synopsis

Changes the process user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())

Prototype

setuid(softint) returns int

Example
setuid($uid);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.155. Arguments and Return Values for setuid()

Argument Type

Return Type

Description

softint

int

Changes the process user ID according to the argument passed. Returns 0 for success, non-zero for errors (the error code can be retrieved with errno())


Table 3.156. Exceptions thrown by setuid()

err

desc

SETUID-ERROR

missing UID argument to function


3.7.25. sleep()

Synopsis

Causes the current thread to sleep for a certain number of seconds. Note that as with all Qore functions and methods accepting a timeout value, relative date/time values can be given instead of integers to make the source more readable (ie 5s), however as this function only supports a resolution of 1 second, milliseconds are ignored if passed to this function. See usleep() for a similar function supporting microsecond resolution.

Prototype

sleep(softint) returns int

sleep(date) returns int

sleep() returns nothing (RT_NOOP)

Example
sleep(5s); # sleeps for 5 seconds
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.157. Arguments and Return Values for sleep()

Argument Type

Return Type

Description

softint or date

int

Causes the current thread to sleep for a number of seconds equal to the argument passed. Returns 0 for success. An integer argument is interpreted as a number of seconds to sleep, relative date/time values are interpreted literally.


This function does not throw any exceptions.

3.7.26. stat()

Synopsis

Returns a list of filesystem values for the file passed, following any symbolic links. See also lstat() for a version of this function that does not follow symbolic links, and see hstat() for a version of this function that returns a user-friendly hash instead of a list.

Prototype

stat(string $path) returns any

stat() returns nothing (RT_NOOP)

Example
$mode = stat($filepath)[2];
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.158. Arguments and Return Values for stat()

Argument Type

Return Type

Description

string $path

any

Returns a list of filesystem values for the file passed, following symbolic links or NOTHING if the call fails. See Stat List below for a description of the list returned by this function.


This function does not throw any exceptions.

Table 3.159. Stat List Description

Position

Data Type

Description

0

int

device inode number the file is on

1

int

inode of the file

2

int

inode protection mode

3

int

number of hard links to this file

4

int

user ID of the owner

5

int

group ID of the owner

6

int

device type number

7

int

file size in bytes

8

date

last access time of the file

9

date

last modified time of the file

10

date

last change time of the file's inode

11

int

block size

12

int

blocks allocated for the file


3.7.27. strerror()

Synopsis

Returns the string corresponding to the error code passed (generally retrieved with errno()).

Prototype

strerror(softint $errno) returns string (CONST)

strerror() returns nothing (RT_NOOP)

Example
printf("%s\n", strerror(errno()));

Table 3.160. Arguments and Return Values for strerror()

Argument Type

Return Type

Description

softint $errno

string

Returns a string corresponding to the error code passed (normally retrieved with errno())


This function does not throw any exceptions.

3.7.28. system()

Synopsis

Executes an external program and returns the exit code of the process.

Prototype

system(string) returns int

system() returns nothing (RT_NOOP)

Example
$rc = system("ls -l");
Restrictions

Not available with PO_NO_EXTERNAL_PROCESS

Table 3.161. Arguments and Return Values for system()

Argument

Return Type

Description

string

int

If shell meta-characters are present in the string to be executed, Qore uses the C library system() call to execute the external program, otherwise a fork() and exec() is used. The exit code of the process is returned as an integer.


This function does not throw any exceptions.

3.7.29. usleep()

Synopsis

Causes the current thread to sleep for a certain number of microseconds (1/1000000 second). Note that as with all Qore functions and methods accepting a timeout value, relative date/time values can be given instead of integers to make the source more readable (ie 1250us). See sleep() for a similar function supporting second resolution.

Prototype

usleep(date $time) returns int

usleep(softint $microseconds) returns int

usleep() returns nothing (RT_NOOP)

Example
usleep(1250us); # sleeps for 1250 microseconds (1.25 milliseconds)
usleep(500);    # sleeps for 500 microseconds (0.5 milliseconds)
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.162. Arguments and Return Values for usleep()

Argument Type

Return Type

Description

softint $microseconds

int

Causes the current thread to sleep for the given number of microseconds (1/1000000 second). Returns 0 for success.

date $time

int

Causes the current thread to sleep for the given period of time with a resolution of microseconds (1/1000000 second). Returns 0 for success.


This function does not throw any exceptions.

3.8. Cryptographic Functions

Qore's cryptography support is provided by the OpenSSL library. Most of the encryption and decryption functions in this section accept an optional initialization vector, which is data used as initial input for the first block in chained encryption algorithms. Subsequent blocks take input from the last block encrypted/decrypted. If a function accepts an initialization vector and one is not supplied, then a default value of 8 zero bytes will be used.

Some functions require fixed-length keys, and some allow the use of variable-length keys. For functions requiring fixed-length keys any excess bytes are ignored. The same applies to initialization vector arguments.

The following is an example of a function that uses /dev/random to read in a random key for use with encryption functions:

# read a key from /dev/random and return the key
sub get_key($size)
{
    # throw an exception if an invalid key size was passed
    if (!$size || $size < 0)
        throw "GET-KEY-ERROR", sprintf("invalid size = %n", $size);
    my $f = new File();
    # File::open2() will throw an exception if /dev/random cannot be opened for reading
    $f.open2("/dev/random");
    return $f.readBinary($size);
}

3.8.1. blowfish_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for the blowfish algorithm using a variable-length key and an optional initialization vector. Returns a binary object of the encrypted data.

Prototype

blowfish_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = blowfish_encrypt_cbc("hello there", $key);

Table 3.163. Arguments and Return Values for blowfish_encrypt_cbc()

Argument Type

Return Type

Description

data $data, data $key, data $iv = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for the blowfish algorithm; accepts a variable-length key (recommended 16-bytes or more). The initialization vector must be at least 8 bytes long if present.


Table 3.164. Exceptions thrown by blowfish_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

BLOWFISH-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.2. blowfish_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for the blowfish algorithm using a variable-length key. This function returns a binary object, for an equivalent function that decrypts to a string, see blowfish_decrypt_cbc_to_string().

Prototype

blowfish_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = blowfish_decrypt_cbc($encrypted_binary_data, $key);

Table 3.165. Arguments and Return Values for blowfish_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for the blowfish algorithm using a variable-length key.


Table 3.166. Exceptions thrown by blowfish_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

BLOWFISH-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.3. blowfish_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for the blowfish algorithm using a variable-length key. This function returns a string, for an equivalent function that decrypts to a binary object, see blowfish_decrypt_cbc().

Prototype

blowfish_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = blowfish_decrypt_cbc_to_string($bin, $key);

Table 3.167. Arguments and Return Values for blowfish_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for the blowfish algorithm using a variable-length key.


Table 3.168. Exceptions thrown by blowfish_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

BLOWFISH-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.4. des_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for the DES algorithm using an 8-byte key. Returns a binary object of the encrypted data.

Prototype

des_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = des_encrypt_cbc($text, $key);

Table 3.169. Arguments and Return Values for des_encrypt_cbc()

Argument Type

Return Type

Description

data $data, data $key, data $iv = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for the DES algorithm. The key must be at least 8-bytes long (only the first 8 bytes will be used). If the init_vector is present it must also be at least 8 bytes long.


Table 3.170. Exceptions thrown by des_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.5. des_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for the DES algorithm using an 8 byte key. This function returns a binary object, for an equivalent function that decrypts to a string, see des_decrypt_cbc_to_string().

Prototype

des_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Table 3.171. Arguments and Return Values for des_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for the DES algorithm using an 8-byte key. If the init_vector is present it must also be at least 8 bytes long.


Table 3.172. Exceptions thrown by des_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.6. des_decrypt_cbc_to_string()

Synopsis

Decrypts data using the Cipher Block Chaining function for the DES algorithm using an 8-byte key. This function returns a string, for an equivalent function that decrypts to a binary object, see des_decrypt_cbc().

Prototype

des_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Table 3.173. Arguments and Return Values for des_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data using the Cipher Block Chaining function for the DES algorithm using an 8-byte key. If the init_vector is present it must also be at least 8 bytes long.


Table 3.174. Exceptions thrown by des_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.7. des_ede_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm using two eight-byte keys (set by a single 16-byte key argument). Returns a binary object of the encrypted data.

Prototype

des_ede_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = des_ede_encrypt_cbc($text, $key);

Table 3.175. Arguments and Return Values for des_ede_encrypt_cbc()

Argument Type

Return Type

Description

data $data, data $key, data $iv = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm. The key argument must be at least 16 bytes long; only the first 16 bytes of the key argument will be used for the two 8-byte keys. If the init_vector argument is present, it must be at least 8 bytes long.


Table 3.176. Exceptions thrown by des_ede_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.8. des_ede_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm using two eight-byte keys (set by a single 16-byte key argument). This function returns a binary object, for an equivalent function that decrypts to a string, see des_ede_decrypt_cbc_to_string().

Prototype

des_ede_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = des_ede_decrypt_cbc($data, $key);

Table 3.177. Arguments and Return Values for des_ede_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm. The key argument must be at least 16 bytes long; only the first 16 bytes of the key argument will be used for the two 8-byte keys. If the init_vector argument is present, it must be at least 8 bytes long.


Table 3.178. Exceptions thrown by des_ede_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.9. des_ede_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for the two-key triple DES algorithm using two eight-byte keys (set by a single 16-byte key argument). This function returns a string, for an equivalent function that decrypts to a binary object, see des_ede_decrypt_cbc().

Prototype

des_ede_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = des_ede_decrypt_cbc_to_string($data, $key);

Table 3.179. Arguments and Return Values for des_ede_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for the two-key triple DES algorithm. The key argument must be at least 16 bytes long; only the first 16 bytes of the key argument will be used for the two 8-byte keys. If the init_vector argument is present, it must be at least 8 bytes long.


Table 3.180. Exceptions thrown by des_ede_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.10. des_ede3_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm using three 8-byte keys (set by a single 24-byte key argument) and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.

Prototype

des_ede3_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = des_ede3_encrypt_cbc($data, $key);

Table 3.181. Arguments and Return Values for des_ede3_encrypt_cbc()

Argument Type

Return Type

Description

data $data, data $key, data $iv = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm using three 8-byte keys (set by a single 24-byte key argument) and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.


Table 3.182. Exceptions thrown by des_ede3_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.11. des_ede3_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm using three 8-byte keys (set by a single 24-byte key argument) and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see des_ede3_decrypt_cbc_to_string().

Prototype

des_ede3_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = des_ede3_decrypt_cbc($data, $key);

Table 3.183. Arguments and Return Values for des_ede3_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm.


Table 3.184. Exceptions thrown by des_ede3_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.12. des_ede3_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for the three-key triple DES algorithm using three 8-byte keys (set by a single 24-byte key argument) and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see des_ede3_decrypt_cbc().

Prototype

des_ede3_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = des_ede3_decrypt_cbc_to_string($data, $key);

Table 3.185. Arguments and Return Values for des_ede3_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for the three-key triple DES algorithm using three 8-byte keys (set by a single 24-byte key argument) and an optional 8-byte initialization vector.


Table 3.186. Exceptions thrown by des_ede3_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DES-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.13. desx_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.

Prototype

desx_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = desx_encrypt_cbc($data, $key);

Table 3.187. Arguments and Return Values for desx_encrypt_cbc()

Argument Type

Return Type

Description

data $data, data $key, data $iv = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector.


Table 3.188. Exceptions thrown by desx_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DESX-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.14. desx_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see desx_decrypt_cbc_to_string().

Prototype

desx_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
my binary $bin = desx_decrypt_cbc($data, $key);

Table 3.189. Arguments and Return Values for desx_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector.


Table 3.190. Exceptions thrown by desx_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DESX-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.15. desx_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see desx_decrypt_cbc().

Prototype

desx_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = desx_decrypt_cbc_to_string($data, $key);

Table 3.191. Arguments and Return Values for desx_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for RSA's DESX algorithm using a 24-byte key and an optional 8-byte initialization vector.


Table 3.192. Exceptions thrown by desx_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

DESX-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.16. rc2_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.

Prototype

rc2_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc2_encrypt_cbc($data, $key);

Table 3.193. Arguments and Return Values for rc2_encrypt_cbc()

Argument Type

Return Type

Description

data, data, data = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.194. Exceptions thrown by rc2_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC2-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.17. rc2_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see rc2_decrypt_cbc_to_string().

Prototype

rc2_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc2_decrypt_cbc($data, $key);

Table 3.195. Arguments and Return Values for rc2_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.196. Exceptions thrown by rc2_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC2-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.18. rc2_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see rc2_decrypt_cbc().

Prototype

rc2_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = rc2_decrypt_cbc_to_string($data, $key);

Table 3.197. Arguments and Return Values for rc2_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC2(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.198. Exceptions thrown by rc2_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC2-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.19. cast5_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.

Prototype

cast5_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = cast5_encrypt_cbc($data, $key);

Table 3.199. Arguments and Return Values for cast5_encrypt_cbc()

Argument Type

Return Type

Description

data, data, data = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.200. Exceptions thrown by cast5_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

CAST5-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.20. cast5_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see cast5_decrypt_cbc_to_string().

Prototype

cast5_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = cast5_decrypt_cbc($data, $key);

Table 3.201. Arguments and Return Values for cast5_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.202. Exceptions thrown by cast5_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

CAST5-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.21. cast5_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see cast5_decrypt_cbc().

Prototype

cast5_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = cast5_decrypt_cbc_to_string($data, $key);

Table 3.203. Arguments and Return Values for cast5_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for the CAST5 algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.204. Exceptions thrown by cast5_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

CAST5-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.22. rc4_encrypt()

Synopsis

Encrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. Returns a binary object of the encrypted data.

Prototype

rc4_encrypt(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc4_encrypt($data, $key);

Table 3.205. Arguments and Return Values for rc4_encrypt()

Argument Type

Return Type

Description

data, data, data = defaultIV

binary

Encrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.206. Exceptions thrown by rc4_encrypt()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC4-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.23. rc4_decrypt()

Synopsis

Decrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see rc4_decrypt_to_string().

Prototype

rc4_decrypt(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc4_decrypt($data, $key);

Table 3.207. Arguments and Return Values for rc4_decrypt()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.208. Exceptions thrown by rc4_decrypt()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC4-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.24. rc4_decrypt_to_string()

Synopsis

Decrypts data to a string using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see rc4_decrypt().

Prototype

rc4_decrypt_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = rc4_decrypt_to_string($data, $key);

Table 3.209. Arguments and Return Values for rc4_decrypt_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.210. Exceptions thrown by rc4_decrypt_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC4-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)


3.8.25. rc5_encrypt_cbc()

Synopsis

Encrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. Returns a binary object of the encrypted data. The availability of this function depends on the availability of the RC5 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_RC5 before running this function. See Library Option Constants for a list of all option constants.

Prototype

rc5_encrypt_cbc(data $data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc5_encrypt_cbc($data, $key);

Table 3.211. Arguments and Return Values for rc5_encrypt_cbc()

Argument Type

Return Type

Description

data, data, data = defaultIV

binary

Encrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.212. Exceptions thrown by rc5_encrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC5-ENCRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_RC5 before calling this function.


3.8.26. rc5_decrypt_cbc()

Synopsis

Decrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a binary object, for an equivalent function that decrypts to a string, see rc5_decrypt_cbc_to_string(). The availability of this function depends on the availability of the RC5 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_RC5 before running this function. See Library Option Constants for a list of all option constants.

Prototype

rc5_decrypt_cbc(binary $encrypted_data, data $key, data $iv = defaultIV) returns binary

Example
$bin = rc5_decrypt_cbc($data, $key);

Table 3.213. Arguments and Return Values for rc5_decrypt_cbc()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

binary

Decrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.214. Exceptions thrown by rc5_decrypt_cbc()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC5-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_RC5 before calling this function.


3.8.27. rc5_decrypt_cbc_to_string()

Synopsis

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector. This function returns a string, for an equivalent function that decrypts to a binary object, see rc5_decrypt_cbc(). The availability of this function depends on the availability of the RC5 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_RC5 before running this function. See Library Option Constants for a list of all option constants.

Prototype

rc5_decrypt_cbc_to_string(binary $encrypted_data, data $key, data $iv = defaultIV) returns string

Example
$str = rc5_decrypt_cbc_to_string($data, $key);

Table 3.215. Arguments and Return Values for rc5_decrypt_cbc_to_string()

Argument Type

Return Type

Description

binary $encrypted_data, data $key, data $iv = defaultIV

string

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC5(tm) algorithm using a variable-length key and an optional 8-byte initialization vector.


Table 3.216. Exceptions thrown by rc5_decrypt_cbc_to_string()

err

desc

PARAMETER-ERROR

missing data (string or binary) parameter to function, invalid data type (expecing string or binary)

RC5-DECRYPT-PARAM-ERROR

missing or invalid key parameter (ex: invalid size) or invalid initialization vector (less than 8 bytes, only raised if initialization vector present)

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_RC5 before calling this function.


3.9. Digest Functions

3.9.1. DSS()

Synopsis

Returns the DSS message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex characters.

Prototype

DSS(data) returns string

Example
$str = DSS("hello"); # returns "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"

Table 3.217. Arguments and Return Values for DSS()

Argument Type

Return Type

Description

data

string

Returns the DSS message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.218. Exceptions thrown by DSS()

err

desc

DSS-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.2. DSS_bin()

Synopsis

Returns the DSS message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object.

Prototype

DSS_bin(data) returns binary

Example
$bin = DSS_bin("hello"); # returns <aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d>

Table 3.219. Arguments and Return Values for DSS_bin()

Argument Type

Return Type

Description

data

binary

Returns the DSS message digest of the supplied argument (for strings, the trailing null character is not included in the digest).


Table 3.220. Exceptions thrown by DSS_bin()

err

desc

DSS-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.3. DSS1()

Synopsis

Returns the DSS1 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a hex string.

Prototype

DSS1(data) returns string

Example
$str = DSS1("hello"); # return "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"

Table 3.221. Arguments and Return Values for DSS1()

Argument Type

Return Type

Description

data

string

The DSS1 message digest of the supplied argument as a hex string (for strings, the trailing null character is not included in the digest)


Table 3.222. Exceptions thrown by DSS1()

err

desc

DSS1-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.4. DSS1_bin()

Synopsis

Returns the DSS1 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object.

Prototype

DSS1_bin(data) returns binary

Example
$bin = DSS1_bin("hello"); # returns <aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d>

Table 3.223. Arguments and Return Values for DSS1_bin()

Argument Type

Return Type

Description

data

binary

The DSS1 message digest of the supplied argument (for strings, the trailing null character is not included in the digest).


Table 3.224. Exceptions thrown by DSS1()

err

desc

DSS1-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.5. MD2()

Synopsis

Returns the MD2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex digits.

Prototype

MD2(data) returns string

Example
$str = MD2("hello"); # returns "a9046c73e00331af68917d3804f70655"

Table 3.225. Arguments and Return Values for MD2()

Argument Type

Return Type

Description

data

string

The MD2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.226. Exceptions thrown by MD2()

err

desc

MD2-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.6. MD2_bin()

Synopsis

Returns the MD2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex digits.

Prototype

MD2_bin(data) returns binary

Example
$bin = MD2_bin("hello"); # returns <a9046c73e00331af68917d3804f70655>

Table 3.227. Arguments and Return Values for MD2_bin()

Argument Type

Return Type

Description

data

binary

The MD2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.228. Exceptions thrown by MD2_bin()

err

desc

MD2-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.7. MD4()

Synopsis

Returns the MD4 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex characters.

Prototype

MD4(data) returns string

Example
$str = MD4("hello"); # returns "866437cb7a794bce2b727acc0362ee27"

Table 3.229. Arguments and Return Values for MD4()

Argument Type

Return Type

Description

data

string

The MD4 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.230. Exceptions thrown by MD4()

err

desc

MD4-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.8. MD4_bin()

Synopsis

Returns the MD4 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex characters.

Prototype

MD4_bin(data) returns binary

Example
$str = MD4_bin("hello"); # returns "866437cb7a794bce2b727acc0362ee27"

Table 3.231. Arguments and Return Values for MD4_bin()

Argument Type

Return Type

Description

data

binary

The MD4 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object


Table 3.232. Exceptions thrown by MD4_bin()

err

desc

MD4-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.9. MD5()

Synopsis

Returns the MD5 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex characters.

Prototype

MD5(data) returns string

Example
$str = MD5("hello"); # returns "5d41402abc4b2a76b9719d911017c592"

Table 3.233. Arguments and Return Values for MD5()

Argument Type

Return Type

Description

data

string

The MD5 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hext characters.


Table 3.234. Exceptions thrown by MD5()

err

desc

MD5-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.10. MD5_bin()

Synopsis

Returns the MD5 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object.

Prototype

MD5_bin(data) returns binary

Example
$str = MD5_bin("hello"); # returns <5d41402abc4b2a76b9719d911017c592>

Table 3.235. Arguments and Return Values for MD5_bin()

Argument Type

Return Type

Description

data

binary

The MD5 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object.


Table 3.236. Exceptions thrown by MD5_bin()

err

desc

MD5-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.11. MDC2()

Synopsis

Returns the MDC2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest). The availability of this function depends on the availability of the MDC2 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_MDC2 before running this function. See Library Option Constants for a list of all option constants.

Prototype

MDC2(data) returns string

Example
$str = MDC2("hello");

Table 3.237. Arguments and Return Values for MDC2()

Argument Type

Return Type

Description

data

string

Returns the MDC2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.238. Exceptions thrown by MDC2()

err

desc

MDC2-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_MDC2 before calling this function.


3.9.12. MDC2_bin()

Synopsis

Returns the MDC2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object. The availability of this function depends on the availability of the MDC2 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_MDC2 before running this function. See Library Option Constants for a list of all option constants.

Prototype

MDC2_bin(data) returns binary

Example
$bin = MDC2_bin("hello");

Table 3.239. Arguments and Return Values for MDC2_bin()

Argument Type

Return Type

Description

data

binary

Returns the MDC2 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.240. Exceptions thrown by MDC2_bin()

err

desc

MDC2-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_MDC2 before calling this function.


3.9.13. RIPEMD160()

Synopsis

Returns the RIPEMD160 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hex characters.

Prototype

RIPEMD160(data) returns string

Example
$str = RIPEMD160("hello"); # returns "108f07b8382412612c048d07d13f814118445acd"

Table 3.241. Arguments and Return Values for RIPEMD160()

Argument Type

Return Type

Description

data

string

Returns the RIPEMD160 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.242. Exceptions thrown by RIPEMD160()

err

desc

RIPEMD160-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.14. RIPEMD160_bin()

Synopsis

Returns the RIPEMD160 message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a binary object.

Prototype

RIPEMD160_bin(data) returns binary

Example
$str = RIPEMD160_bin("hello"); # returns "108f07b8382412612c048d07d13f814118445acd"

Table 3.243. Arguments and Return Values for RIPEMD160_bin()

Argument Type

Return Type

Description

data

binary

Returns the RIPEMD160 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.244. Exceptions thrown by RIPEMD160_bin()

err

desc

RIPEMD160-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.15. SHA()

Synopsis

Returns the SHA message digest of the supplied argument (for strings, the trailing null character is not included in the digest) as a string of hext characters.

Prototype

SHA(data) returns string

Example
$str = SHA("hello"); returns "ac62a630ca850b4ea07eda664eaecf9480843152"

Table 3.245. Arguments and Return Values for SHA()

Argument Type

Return Type

Description

data

string

Returns the SHA message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.246. Exceptions thrown by SHA()

err

desc

SHA-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.16. SHA_bin()

Synopsis

Returns the SHA message digest of the supplied argument (for strings, the trailing null character is not included in the digest)

Prototype

SHA_bin(data) returns binary

Example
$bin = SHA_bin("hello"); returns <ac62a630ca850b4ea07eda664eaecf9480843152>

Table 3.247. Arguments and Return Values for SHA_bin()

Argument Type

Return Type

Description

data

binary

Returns the SHA message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.248. Exceptions thrown by SHA_bin()

err

desc

SHA-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.17. SHA1()

Synopsis

Returns the SHA1 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest.

Prototype

SHA1(data) returns string

Example
$str = SHA1("hello"); # "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"

Table 3.249. Arguments and Return Values for SHA1()

Argument Type

Return Type

Description

data

string

Returns the SHA1 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.250. Exceptions thrown by SHA1()

err

desc

SHA1-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.18. SHA1_bin()

Synopsis

Returns the SHA1 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest.

Prototype

SHA1_bin(data) returns binary

Example
$bin = SHA1_bin("hello"); # <aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d>

Table 3.251. Arguments and Return Values for SHA1_bin()

Argument Type

Return Type

Description

data

string

Returns the SHA1 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.252. Exceptions thrown by SHA1_bin()

err

desc

SHA1-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest


3.9.19. SHA224()

Synopsis

Returns the SHA224 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA224 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA224 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA224(data) returns string

Example
$str = SHA224("hello"); # "ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193"

Table 3.253. Arguments and Return Values for SHA224()

Argument Type

Return Type

Description

data

string

Returns the SHA224 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.254. Exceptions thrown by SHA224()

err

desc

SHA224-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA224 before calling this function.


3.9.20. SHA224_bin()

Synopsis

Returns the SHA224 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA224 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA224 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA224_bin(data) returns binary

Example
$bin = SHA224_bin("hello");
# <ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193>

Table 3.255. Arguments and Return Values for SHA224_bin()

Argument Type

Return Type

Description

data

string

Returns the SHA224 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.256. Exceptions thrown by SHA224_bin()

err

desc

SHA224-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA224 before calling this function.


3.9.21. SHA256()

Synopsis

Returns the SHA256 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA256 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA256 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA256_bin(data) returns binary

Example
$str = SHA256("hello");
# "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

Table 3.257. Arguments and Return Values for SHA256()

Argument Type

Return Type

Description

data

string

Returns the SHA256 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.258. Exceptions thrown by SHA256()

err

desc

SHA256-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA256 before calling this function.


3.9.22. SHA256_bin()

Synopsis

Returns the SHA256 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA256 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA256 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA256_bin(data) returns binary

Example
$bin = SHA256_bin("hello");
# <2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824>

Table 3.259. Arguments and Return Values for SHA256_bin()

Argument Type

Return Type

Description

data

string

Returns the SHA256 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.260. Exceptions thrown by SHA256_bin()

err

desc

SHA256-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA256 before calling this function.


3.9.23. SHA384()

Synopsis

Returns the SHA384 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA384 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA384 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA384_bin(data) returns binary

Example
$str = SHA384("hello");
# "59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f"

Table 3.261. Arguments and Return Values for SHA384()

Argument Type

Return Type

Description

data

string

Returns the SHA384 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.262. Exceptions thrown by SHA384()

err

desc

SHA384-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA384 before calling this function.


3.9.24. SHA384_bin()

Synopsis

Returns the SHA384 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA384 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA384 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA384_bin(data) returns binary

Example
$bin = SHA384_bin("hello");
# <59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f>

Table 3.263. Arguments and Return Values for SHA384_bin()

Argument Type

Return Type

Description

data

string

Returns the SHA384 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.264. Exceptions thrown by SHA384_bin()

err

desc

SHA384-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA384 before calling this function.


3.9.25. SHA512()

Synopsis

Returns the SHA512 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA512 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA512 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA512_bin(data) returns binary

Example
$str = SHA512("hello");
# "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"

Table 3.265. Arguments and Return Values for SHA512()

Argument Type

Return Type

Description

data

string

Returns the SHA512 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.266. Exceptions thrown by SHA512()

err

desc

SHA512-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA512 before calling this function.


3.9.26. SHA512_bin()

Synopsis

Returns the SHA512 message digest of the supplied argument as a string of hex characters. For string arguments, the trailing null character is not included in the digest. The availability of this function depends on the availability of the SHA512 algorithm in the openssl library used to compile the Qore library; for maximum portability check the constant HAVE_SHA512 before running this function. See Library Option Constants for a list of all option constants.

Prototype

SHA512_bin(data) returns binary

Example
$bin = SHA512_bin("hello");
# <9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043>

Table 3.267. Arguments and Return Values for SHA512_bin()

Argument Type

Return Type

Description

data

string

Returns the SHA512 message digest of the supplied argument (for strings, the trailing null character is not included in the digest)


Table 3.268. Exceptions thrown by SHA512_bin()

err

desc

SHA512-DIGEST-ERROR

missing data parameter, invalid data parameter (expecing string or binary), error calculating digest

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_SHA512 before calling this function.


3.10. Filesystem Functions

The following functions return information about or are related to the filesystem. See the File class for a class enabling files to be created, read or written, and the Dir class allowing directories to be manipulated.

3.10.1. chdir()

Synopsis

Changes the current working directory.

Prototype

chdir(string) returns int

Example
chdir("/usr/share");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.269. Arguments and Return Values for chdir()

Argument Type

Return Type

Description

string

int

Changes the current working directory. Returns 0 if successful.


Table 3.270. Exceptions Thrown by chdir()

err

desc

CHDIR-PARAMETER-ERROR

The string for the new directory was missing from the call.


3.10.2. chmod()

Synopsis

Changes the mode of a file.

Prototype

chmod(string, int) returns int

Example
chmod("/bin/login", 0755);
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.271. Arguments and Return Values for chmod()

Argument Type

Return Type

Description

string, int

int

Sets the mode of the given file to the integer passed. Returns 0 if successful.


Table 3.272. Exceptions Thrown by chmod()

err

desc

CHMOD-PARAMETER-ERROR

Either the filename or the mode was missing from the call.


3.10.3. chown()

Synopsis

Changes the user and group owners of a file, if the current user has permission to do so (normally only the superuser can change the user owner), follows symbolic links. For a version of this function that does not follow symbolic links, see the lchown() function.

Prototype

chown(string, softint = -1, softint = -1) returns int

Example
chown("/bin/login", 0, 0);
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.273. Arguments and Return Values for chown()

Argument Type

Return Type

Description

string, int = -1, int = -1

int

Changes the owner and group of the file passed. Returns 0 if successful.


3.10.4. getcwd()

Synopsis

Returns a string giving the current working directory or NOTHING if the current working directory could not be read.

See getcwd2() for a similar function that throws an exception if an error occurs instead.

Prototype

getcwd() returns any

Example
my $cwd = getcwd();
Restrictions

Not available with PO_NO_FILESYSTEM or PO_NO_EXTERNAL_INFO

Table 3.274. Arguments and Return Values for getcwd()

Argument Type

Return Type

Description

n/a

any

Returns the complete path of the current working directory as a string or NOTHING if the current working directory could not be read.


3.10.5. getcwd2()

Synopsis

Returns a string giving the current working directory; throws an exception if the current directory cannot be read.

See getcwd() for a similar function that returns NOTHING instead of throwing an exception if an error occurs.

Prototype

getcwd2() returns string

Example
my string $cwd = getcwd2();
Restrictions

Not available with PO_NO_FILESYSTEM or PO_NO_EXTERNAL_INFO

Table 3.275. Arguments and Return Values for getcwd2()

Argument Type

Return Type

Description

n/a

string

Returns the complete path of the current working directory as a string.


Table 3.276. Exceptions Thrown by getcwd2()

err

desc

GETCWD2-ERROR

The operating system error is reported in the description string.


3.10.6. hlstat()

Synopsis

Returns a hash of filesystem values for the file passed; symbolic links are not followed; information is returned about symbolic links (see hstat() for a version of this function that follows symbolic links).

Prototype

hlstat(string $path) returns any

hlstat() returns nothing (RT_NOOP)

Example
$type = hlstat("/bin/sh").type; # returns "REGULAR"
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.277. Arguments and Return Values for hlstat()

Argument Type

Return Type

Description

string $path

hash or nothing

Returns a hash of filesystem values for the file passed or NOTHING if the stat() call fails; symbolic links are not followed (information is returned about symbolic links). See also hstat(). See Stat Hash below for a description of the hash returned by this function.


Table 3.278. Stat Hash Description

Key

Value Description

dev

device inode number the file is on

inode

inode of the file

mode

inode protection mode

nlink

number of hard links to this file

uid

user ID of the owner

gid

group ID of the owner

rdev

device type number

size

file size in bytes

atime

last access time of the file

mtime

last modified time of the file

ctime

last change time of the file's inode

blksize

block size

blocks

blocks allocated for the file

type

a string indicating the type of file: 'BLOCK-DEVICE', 'DIRECTORY', 'CHARACTER-DEVICE', 'FIFO', 'SYMBOLIC-LINK', 'SOCKET', 'CHARACTER-DEVICE', 'REGULAR', 'UNKNOWN'


This function does not throw any exceptions.

3.10.7. hstat()

Synopsis

Returns a hash of filesystem values for the file passed; symbolic links are followed; see hlstat() to retrieve information about a symbolic link.

Prototype

hstat(string $path) returns any

hstat() returns nothing (RT_NOOP)

Example
$type = hstat("/bin/sh").type; # returns "REGULAR"
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.279. Arguments and Return Values for hstat()

Argument Type

Return Type

Description

string $path

hash or nothing

Returns a hash of filesystem values for the file passed or NOTHING if the stat() call fails; symbolic links are followed. See also hlstat(). See Stat Hash for a description of the hash returned by this function.


This function does not throw any exceptions.

3.10.8. is_bdev()

Synopsis

Returns True if the string passed identifies a block device file on the filesystem.

Prototype

is_bdev(string $path) returns bool (CONST)

Example
$bool = is_bdev("/dev/sda");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.280. Arguments and Return Values for is_bdev()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a block device file on the filesystem.


3.10.9. is_cdev()

Synopsis

Returns True if the string passed identifies a character device file on the filesystem.

Prototype

is_cdev(string $path) returns bool (CONST)

Example
$bool = is_cdev("/dev/tty");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.281. Arguments and Return Values for is_cdev()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a character device file on the filesystem.


3.10.10. is_dev()

Synopsis

Returns True if the string passed identifies a device file (either block or character) on the filesystem.

Prototype

is_dev(string $path) returns bool (CONST)

Example
$bool = is_dev("/dev/sda");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.282. Arguments and Return Values for is_dev()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a device file (either block or character) on the filesystem.


3.10.11. is_dir()

Synopsis

Returns True if the string passed identifies a directory on the filesystem.

Prototype

is_dir(string $path) returns bool (CONST)

Example
$bool = is_dir("/usr/share");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.283. Arguments and Return Values for is_dir()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a directory on the filesystem.


3.10.12. is_executable()

Synopsis

Returns True if the string passed identifies an executable file.

Prototype

is_executable(string $path) returns bool (CONST)

Example
$bool = is_executable("/bin/sh");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.284. Arguments and Return Values for is_executable()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies an executable file.


3.10.13. is_file()

Synopsis

Returns True if the string passed identifies a regular file on the filesystem.

Prototype

is_file(string) returns bool (CONST)

Example
$bool = is_file("/etc/hosts");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.285. Arguments and Return Values for is_file()

Argument Type

Return Type

Description

string

bool

Returns True if the string passed identifies a regular file on the filesystem.


3.10.14. is_link()

Synopsis

Returns True if the string passed identifies a symbolic link on the filesystem.

Prototype

is_link(string $path) returns bool (CONST)

Example
$bool = is_link("/bin/sh");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.286. Arguments and Return Values for is_link()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a symbolic link on the filesystem.


3.10.15. is_pipe()

Synopsis

Returns True if the string passed identifies a pipe (FIFO) on the filesystem.

Prototype

is_pipe(string) returns bool (CONST)

Example
$bool = is_pipe("/bin/sh");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.287. Arguments and Return Values for is_pipe()

Argument Type

Return Type

Description

string

bool

Returns True if the string passed identifies a pipe (FIFO) on the filesystem.


3.10.16. is_readable()

Synopsis

Returns True if the string passed identifies a file readable by the current user.

Prototype

is_readable(string $path) returns bool (CONST)

Example
$bool = is_readable("/etc/hosts");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.288. Arguments and Return Values for is_readable()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a file readable by the current user.


3.10.17. is_socket()

Synopsis

Returns True if the string passed identifies a socket on the filesystem.

Prototype

is_socket(string $path) returns bool (CONST)

Example
$bool = is_socket("/tmp/X0");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.289. Arguments and Return Values for is_socket()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a socket on the filesystem.


3.10.18. is_writeable()

Synopsis

Returns True if the string passed identifies a file writable by the current user.

Prototype

is_writeable(string $path) returns bool (CONST)

Example
$bool = is_writeable("/etc/hosts");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.290. Arguments and Return Values for is_writeable()

Argument Type

Return Type

Description

string $path

bool

Returns True if the string passed identifies a file writable by the current user.


3.10.19. lchown()

Synopsis

Changes the user and group owners of a file, if the current user has permission to do so (normally only the superuser can change the user owner), does not follow symbolic links. For a version of this function that follows symbolic links, see the chown() function.

Prototype

lchown(string $path, softint $uid = -1, softint $gid = -1) returns int

Example
lchown("/bin/login", 0, 0);
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.291. Arguments and Return Values for lchown()

Argument Type

Return Type

Description

string $path, int $uid = -1, int $gid = -1

int

Changes the owner and group of the file passed. Returns 0 if successful. If either $uid or $gid are -1, the values are not changed.


3.10.20. lstat()

Synopsis

Returns a list of filesystem values for the file or symbolic link passed. Does not follow symbolic links, but rather returns filesystem information for symbolic links. See also stat() for a version of this function that follows symbolic links, and hlstat() for a version of this function that returns a user-friendly hash instead of a list.

Prototype

lstat(string $path) returns any

lstat() returns nothing (RT_NOOP)

Example
$list = lstat(("/bin/sh");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.292. Arguments and Return Values for lstat()

Argument Type

Return Type

Description

string $path

list

Returns a list of filesystem values for the file passed. See Stat List for a description of the list returned by this function.


This function does not throw any exceptions.

3.10.21. mkdir()

Synopsis

Creates a directory, optionally specifying the mode.

Prototype

mkdir(string $path, softint $mode = 0777) returns int

Example
mkdir("/tmp/newdir", 0755);
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.293. Arguments and Return Values for mkdir()

Argument Type

Return Type

Description

string $path, softint $mode = 0777

int

Creates a directory with the specified name. If the mode parameter is not sent, then 0777 is used by default (which is AND'ed with the umask). Returns 0 if no error occurred.


3.10.22. mkfifo()

Synopsis

Creates a named pipe file with an optional file mode (default = 0600).

Prototype

mkfifo(string $path, softint $mode = 0600) returns int

Example
mkfifo("/tmp/pipe");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.294. Arguments and Return Values for mkfifo()

Argument Type

Return Type

Description

string $path, softint $mode = 0600

int

Creates a named pipe with the supplied path and optional mode. If the second argument giving the mode is not supplied, then 0660 is used by default.


This function does not throw any exceptions.

3.10.23. readlink()

Synopsis

Returns the target of a symbolic link; throws an exception if an error occurs (ex: file does not exist or is not a symbolic link).

Prototype

readlink(string $path) returns string

Example
my string $str = readlink("/tmp/symbolic_link");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.295. Arguments and Return Values for readlink()

Argument Type

Return Type

Description

string $path) returns string

string

Returns the target of a symbolic link as string; throws an exception if an error occurs (ex: file does not exist or is not a symbolic link).


Table 3.296. Exceptions Thrown by readlink()

err

desc

READLINK-ERROR

Invalid arguments or a system error occured (ex: file does not exist or is not a symbolic link).


3.10.24. rename()

Synopsis

Renames (or moves) files or directories. Note that for this call to function properly, the Qore process must have sufficient permissions and access to the given filesystem objects or paths to execute the rename operation.

This function does not return any value; if any errors occur, an exception is thrown.

Prototype

rename(string $old_path, string $new_path) returns nothing

Example
rename("/tmp/temp_file", "/home/test/test_file.txt");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.297. Arguments and Return Values for rename()

Argument Type

Return Type

Description

string $old_path, string $new_path

n/a

Renames (or moves) the file ior directory indentified by old_path to the new name and/or location given by new_path


Table 3.298. Exceptions Thrown by rename()

err

desc

RENAME-ERROR

Invalid arguments or a system error occured.


3.10.25. rmdir()

Synopsis

Removes a directory.

Prototype

rmdir(string $path) returns int

Example
rmdir("/tmp/newdir");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.299. Arguments and Return Values for rmdir()

Argument Type

Return Type

Description

string $path

int

Removes an empty directory. Returns 0 if no error occurred.


3.10.26. umask()

Synopsis

Sets the file creation mask for the process.

Prototype

umask(softint $mask) returns int

umask() returns nothing (RT_NOOP)

Example
umask(0777);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.300. Arguments and Return Values for umask()

Argument Type

Return Type

Description

softint $mask

int

Sets the file creation mask for the process, returns 0 for success. If no argument is passed, no action is taken, and the function returns NOTHING.


This function does not throw any exceptions.

3.10.27. unlink()

Synopsis

Deletes a file and returns 0 for success.

Prototype

unlink(string $path) returns int

unlink() returns nothing (RT_NOOP)

Example
unlink("/tmp/tmp_file");
Restrictions

Not available with PO_NO_FILESYSTEM

Table 3.301. Arguments and Return Values for unlink()

Argument Type

Return Type

Description

string $path

int

Deletes a file and returns 0 for success.


This function does not throw any exceptions.

3.11. Data Compression Functions

This section documents functions for compressing and uncompressing data.

3.11.1. bunzip2_to_binary()

Synopsis

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary.

Prototype

bunzip2_to_binary(binary $bin) returns binary

bunzip2_to_binary() returns nothing (RT_NOOP)

Example
$bin = bunzip2_to_binary($data);

Table 3.302. Arguments and Return Values for bunzip2_to_binary()

Argument Type

Return Type

Description

binary $bin

binary

Uncompresses the input data and returns a binary object.


Table 3.303. Exceptions Thrown by bunzip2_to_binary()

err

desc

BZIP2-DECOMPRESS-ERROR

bzlib returned an error while processing.


3.11.2. bunzip2_to_string()

Synopsis

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a string. An optional second string argument may be passed to give the character encoding of the string; if not present, the default character encoding for the process is assumed.

Prototype

bunzip2_to_string(binary $bin, string $encoding = defaultEncoding) returns string

bunzip2_to_string() returns nothing (RT_NOOP)

Example
$str = bunzip2_to_string($bzip2_string);

Table 3.304. Arguments and Return Values for bunzip2_to_string()

Argument Type

Return Type

Description

binary $bin, [string $encoding]

binary

Uncompresses the input data and returns a string. The optional second argument sets the string encoding of the resulting string, otherwise the default encoding is assumed.


Table 3.305. Exceptions Thrown by bunzip_to_string()

err

desc

BZIP2-DECOMPRESS-ERROR

bzlib returned an error while processing.


3.11.3. bzip2()

Synopsis

Compresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary. The optional second argument specifies the compression level; if no second argument is given, a value of 9 is used, taking the most memory and proving the best compression ratio. The second argument if given must be a value from 1 - 9. Note that strings are compressed without the trailing null character.

Prototype
bzip2(data $bin, softint $level = 9) returns binary

bzip2() returns nothing> (RT_NOOP)

Example
$bin = compress("hello");

Table 3.306. Arguments and Return Values for bzip2()

Argument Type

Return Type

Description

data $bin, softint $level = 9

binary

Compresses the input data and returns a binary object. The optional level argument should be an integer between 1 and 9, 9 meaning the highest compression level. If this argument is not present then a default value of 9 is assumed.


Table 3.307. Exceptions Thrown by bzip2()

err

desc

BZIP2-COMPRESS-ERROR

The bzip2 library reported an error while performing the compression.

BZLIB2-LEVEL-ERROR

The level argument was not between 1 and 9 inclusive.


3.11.4. compress()

Synopsis

Performs zlib-based "deflate" data compression (RFC 1951) and returns a binary object of the compressed data. The optional second argument specifies the compression level; if no second argument is given, then a tradeoff between speed and compression size is taken (default: Z_DEFAULT_COMPRESSION, meaning to let zlib use its default compression ratio). Note that strings are compressed without the trailing null character.

Prototype

compress(data $bin, softint $level = Z_DEFAULT_COMPRESSION) returns binary

compress() returns nothing (RT_NOOP)

Example
$bin = compress("hello");

Table 3.308. Arguments and Return Values for compress()

Argument Type

Return Type

Description

data $bin, softint $level = Z_DEFAULT_COMPRESSION

binary

Compresses the input data and returns a binary object. The optional level argument should be an integer between 1 and 9, 9 meaning the highest compression level. If this argument is not present then a default value of -1 is assumed, meaning to let zlib use its default compression ratio.


Table 3.309. Exceptions Thrown by compress()

err

desc

ZLIB-LEVEL-ERROR

the compression level is invalid (must be between 1 - 9 inclusive).

ZLIB-ERROR

zlib returned an error while processing.


3.11.5. gunzip_to_binary()

Synopsis

Uncompresses gzipped data using zlib functions and returns a binary object of the uncompressed data.

Prototype

gunzip_to_binary(binary $bin) returns binary

gunzip_to_binary() returns nothing (RT_NOOP)

Example
$bin = gunzip_to_binary($data);

Table 3.310. Arguments and Return Values for gunzip_to_binary()

Argument Type

Return Type

Description

binary $bin

binary

Uncompresses the input data and returns a binary object.


Table 3.311. Exceptions Thrown by gunzip_to_binary()

err

desc

ZLIB-ERROR

zlib returned an error while processing.


3.11.6. gunzip_to_string()

Synopsis

Uncompresses gzipped data using zlib functions and returns a string of the uncompressed data. An optional second string argument may be passed to give the character encoding of the string; if not present, the default character encoding for the process is assumed.

Prototype

gunzip_to_string(binary $bin) returns string

gunzip_to_string(binary $bin, string $encoding) returns string

gunzip_to_string() returns nothing (RT_NOOP)

Example
$str = gunzip_to_string($gzipped_string);

Table 3.312. Arguments and Return Values for gunzip_to_string()

Argument Type

Return Type

Description

binary $bin, [string $encoding]

binary

Uncompresses the input data and returns a string. The optional second argument sets the string encoding of the resulting string, otherwise the default encoding is assumed.


Table 3.313. Exceptions Thrown by gunzip_to_string()

err

desc

ZLIB-ERROR

zlib returned an error while processing.


3.11.7. gzip()

Synopsis

Performs zlib-based "gzip" data compression (RFC 1952) and returns a binary object of the compressed data. The optional second argument specifies the compression level between 1 (lowest comperssion level) and 9 (highest compression level); if no second argument is given, then a tradeoff between speed and compression size is taken (default: Z_DEFAULT_COMPRESSION). Note that strings are compressed without the trailing null character.

Prototype

gzip(string $data, softint $level = Z_DEFAULT_COMPRESSION) returns binary

gzip() returns nothing (RT_NOOP)

Example
$bin = gzip($data);

Table 3.314. Arguments and Return Values for gzip()

Argument Type

Return Type

Description

data $data, softint $level = Z_DEFAULT_COMPRESSION

binary

Compresses the input data and returns a binary object of the gzipped data. The optional level argument should be an integer between 1 and 9, 9 meaning the highest compression level. If this argument is not present then the default value for the zlib library is assumed.


Table 3.315. Exceptions Thrown by gzip()

err

desc

ZLIB-LEVEL-ERROR

the compression level is invalid (must be between 1 - 9 inclusive).

ZLIB-ERROR

zlib returned an error while processing.


3.11.8. uncompress_to_binary()

Synopsis

Uncompresses data using zlib functions and returns a binary object of the uncompressed data.

Prototype

uncompress_to_binary(binary $bin) returns binary

uncompress_to_binary() returns nothing (RT_NOOP)

Example
$bin = uncompress_to_binary($compressed_data);

Table 3.316. Arguments and Return Values for uncompress_to_binary()

Argument Type

Return Type

Description

binary $bin

binary

Uncompresses the input data and returns a binary object.


Table 3.317. Exceptions Thrown by uncompress_to_binary()

err

desc

ZLIB-ERROR

zlib returned an error while processing.


3.11.9. uncompress_to_string()

Synopsis

Uncompresses data using zlib functions and returns a string of the uncompressed data. An optional second string argument may be passed to give the character encoding of the string; if not present, the default character encoding for the process is assumed.

Prototype

uncompress_to_string(binary $bin) returns string

uncompress_to_string(binary $bin, string $encoding) returns string

uncompress_to_string() returns nothing (RT_NOOP)

Example
$str = uncompress_to_string($compressed_data);

Table 3.318. Arguments and Return Values for uncompress_to_string()

Argument Type

Return Type

Description

binary $bin, [string $encoding]

binary

Uncompresses the input data and returns a string. The optional second argument sets the string encoding of the resulting string, otherwise the default encoding is assumed.


Table 3.319. Exceptions Thrown by uncompress_to_string()

err

desc

ZLIB-ERROR

zlib returned an error while processing.


3.12. Miscellaneous Functions

3.12.1. backquote()

Synopsis

Executes a process and returns a string of the output (stdout only)

Prototype

backquote(string $cmd) returns string

backquote() returns nothing (RT_NOOP)

Example
$files = backquote("ls");
Restrictions

Not available with PO_NO_EXTERNAL_PROCESS

Table 3.320. Arguments and Return Values for backquote()

Argument Type

Return Type

Description

string $cmd

string

Executes the string passed as a shell command in a subprocess and returns the stdout of the process as a string.


Table 3.321. Exceptions Thrown by backquote()

err

desc

BACKQUOTE-ERROR

An error occurred with the fork() or opening the stdout pipe.


3.12.2. call_builtin_function()

Synopsis

Calls a builtin function and returns the return value, passing the remaining arguments after the function name to the builtin function. This function can be used to override a builtin function's functionality with a custom implementation.

Prototype

call_builtin_function(string $name, ...) returns any

Example
$result = call_builtin_function("func_name", $arg1, $arg2);

Table 3.322. Arguments and Return Values for call_builtin_function()

Argument Type

Return Type

Description

string $name, ...

any

Executes the given builtin function with the remainder of the arguments as the arguments to the function.


Table 3.323. Exceptions Thrown by call_builtin_function()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow access to the function.

NO-FUNCTION

The builtin function does not exist.


3.12.3. call_builtin_function_args()

Synopsis

Calls a builtin function and returns the return value, using the optional second argument as a list of arguments for the function.

Prototype

call_builtin_function_args(string $name, list $args) returns any

call_builtin_function_args(string $name, any $arg) returns any

Example
call_builtin_function_args("func_name", $arg_list);

Table 3.324. Arguments and Return Values for call_builtin_function_args()

Argument Type

Return Type

Description

string $name, list or any $args

any

Executes the given builtin function using any second argument as the list of arguments; if the second argument is not a list it will be created as a list with one element.


Table 3.325. Exceptions Thrown by call_builtin_function_args()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow access to the function.

NO-FUNCTION

The builtin function does not exist.


3.12.4. call_function()

Synopsis

Calls a function, closure, or call reference and returns the return value, passing the remaining arguments after the function name to the function, closure, or call reference.

Prototype

call_function(string $name, ...) returns any

call_function(code $code, ...) returns any

Example
$result = call_function("func_name", $arg1, $arg2);
$result = call_function($call_ref, $arg1, $arg2);

Table 3.326. Arguments and Return Values for call_function()

Argument Type

Return Type

Description

string $name or code $code, ...

any

Executes the given function, closure, or call reference with the remainder of the arguments as the arguments to the function, closure, or call reference to be called.


Table 3.327. Exceptions Thrown by call_function()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow access to the function.

NO-FUNCTION

The function does not exist.


3.12.5. call_function_args()

Synopsis

Calls a function, closure, or call reference and returns the return value, using the optional second argument as a list of arguments for the function, closure, or call reference to be called.

Prototype

call_function_args(string $name, list $args) returns any

call_function_args(string $name, any $arg) returns any

call_function_args(code $code, list $args) returns any

call_function_args(code $code, any $arg) returns any

Example
call_function_args("func_name", $arg_list);
call_function_args($call_ref, $arg_list);

Table 3.328. Arguments and Return Values for call_function_args()

Argument Type

Return Type

Description

string $name or code $code, list or any $args

any

Executes the given function, closure, or call reference using any second argument as the list of arguments.


Table 3.329. Exceptions Thrown by call_function_args()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow access to the function.

NO-FUNCTION

The function does not exist.


3.12.6. callObjectMethod()

Synopsis

Calls a method of an object, passing the remainder of the arguments to the function as arguments to the method.

Prototype

callObjectMethod(object $obj, string $method, ...) returns any

callObjectMethod() returns nothing (RT_NOOP)

Example
$result = callObjectMethod($obj, "method", $arg1, $arg2);

Table 3.330. Arguments and Return Values for callObjectMethod()

Argument Type

Return Type

Description

object $obj, string $method, ...

any

Calls a method of an object, passing the remainder of the arguments to the function as arguments to the method, and returns the return value, if any.


Table 3.331. Exceptions Thrown by callObjectMethod()

err

desc

METHOD-DOES-NOT-EXIST

The named method does not exist in this class.

ILLEGAL-EXPLICIT-METHOD-CALL

The named method may not be called explicitly.

METHOD-IS-PRIVATE

The named method is private and therefore can only be called within the class.

BASE-CLASS-IS-PRIVATE

The named method is a member of a privately inherited base class.


3.12.7. callObjectMethodArgs()

Synopsis

Calls a method of an object, using the optional third argument as the argument list to the method.

Prototype

callObjectMethodArgs(object $obj, string $method, list $args) returns any

callObjectMethodArgs(object $obj, string $method, any $arg) returns any

callObjectMethodArgs() returns nothing (RT_NOOP)

Example
$result = callObjectMethodArgs($obj, "method", $arg_list);

Table 3.332. Arguments and Return Values for callObjectMethodArgs()

Argument Type

Return Type

Description

object $obj, string $method, list or any $args

any

Calls a method of an object, using the optional third argument as the argument list to the method, and returns the return value, if any.


Table 3.333. Exceptions Thrown by callObjectMethodArgs()

err

desc

METHOD-DOES-NOT-EXIST

The named method does not exist in this class.

ILLEGAL-EXPLICIT-METHOD-CALL

The named method may not be called explicitly.

METHOD-IS-PRIVATE

The named method is private and therefore can only be called within the class.

BASE-CLASS-IS-PRIVATE

The named method is a member of a privately inherited base class.


3.12.8. existsFunction()

Synopsis

Returns True if the function exists in the current program's function name space.

Prototype

existsFunction(string $name) returns bool (CONST)

existsFunction(code $code) returns bool (NOOP)

existsFunction() returns nothing (RT_NOOP)

Example
$bool = existsFunction("func_name");

Table 3.334. Arguments and Return Values for existsFunction()

Argument Type

Return Type

Description

string $name

bool

Returns True if the function exists in the current program's function name space, otherwise returns False.

code $code

bool

This version always returns True.


This function does not throw any exceptions.

3.12.9. functionType()

Synopsis

Returns "builtin", "user", or NOTHING according to the function name passed.

Prototype

functionType(string) returns any (CONST)

functionType() returns nothing (RT_NOOP)

Example
$type = functionType("print");

Table 3.335. Arguments and Return Values for functionType()

Argument Type

Return Type

Description

string

any

Returns "builtin" (for a builtin function), "user" (for a user function), or NOTHING (if the function cannot be found) according to the function name passed.


This function does not throw any exceptions.

3.12.10. get_byte()

Synopsis

Returns the byte value of the offset (starting with 0) in the object passed. Of no offset is passed, then the value of the first byte (offset 0) is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

Note that this function is identical to getByte() except that this version has no RT_NOOP variant.

Prototype

get_byte(data $data, softint $offset $offset = 0) returns any (CONST)

Example
$byte = get_byte($bin, 2); # returns the third byte of the binary object

Table 3.336. Arguments and Return Values for get_byte()

Arguments

Return Type

Description

data $data, softint $offset $offset = 0)

int

The value of the byte at the offset in the string or binary object. If no offset is passed, then the first byte is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.11. get_word_16()

Synopsis

Returns the 16-bit integer value at the 2-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 16-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes MSB byte order when retrieving the value from the data.

See also get_word_16_lsb().

Prototype

get_word_16(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_16($bin, 2); # returns the third 16-bit value in MSB format of the binary object

Table 3.337. Arguments and Return Values for get_word_16()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The MSB integer value of the data at the 2-byte offset given in the string or binary object. If no offset is passed, then the first 16-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.12. get_word_16_lsb()

Synopsis

Returns the 16-bit integer value at the 2-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 16-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes LSB byte order when retrieving the value from the data.

See also get_word_16().

Prototype

get_word_16_lsb(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_16_lsb($bin, 2); # returns the third 16-bit value in LSB format of the binary object

Table 3.338. Arguments and Return Values for get_word_16_lsb()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The LSB integer value of the data at the 2-byte offset given in the string or binary object. If no offset is passed, then the first 16-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.13. get_word_32()

Synopsis

Returns the 32-bit integer value at the 4-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 32-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes MSB byte order when retrieving the value from the data.

Note that this function is identical to getWord32() except that this version has no RT_NOOP variant.

See also get_word_32_lsb().

Prototype

get_word_32(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_32($bin, 2); # returns the third 32-bit value in MSB format of the binary object

Table 3.339. Arguments and Return Values for get_word_32()

Arguments

Return Type

Description

data, softint $offset = 0)

int

The MSB integer value of the data at the 4-byte offset given in the string or binary object. If no offset is passed, then the first 32-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.14. get_word_32_lsb()

Synopsis

Returns the 32-bit integer value at the 4-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 32-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes LSB byte order when retrieving the value from the data.

See also get_word_32().

Prototype

get_word_32_lsb(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_32_lsb($bin, 2); # returns the third 32-bit value in LSB format of the binary object

Table 3.340. Arguments and Return Values for get_word_32_lsb()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The LSB integer value of the data at the 4-byte offset given in the string or binary object. If no offset is passed, then the first 32-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.15. get_word_64()

Synopsis

Returns the 64-bit integer value at the 8-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 64-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes MSB byte order when retrieving the value from the data.

See also get_word_64_lsb().

Prototype

get_word_64(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_64($bin, 2); # returns the third 64-bit value in MSB format of the binary object

Table 3.341. Arguments and Return Values for get_word_64()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The MSB integer value of the data at the 8-byte offset given in the string or binary object. If no offset is passed, then the first 64-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.16. get_word_64_lsb()

Synopsis

Returns the 64-bit integer value at the 8-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 64-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes LSB byte order when retrieving the value from the data.

See also get_word_64().

Prototype

get_word_64_lsb(data $data, softint $offset = 0) returns any (CONST)

Example
$val = get_word_64_lsb($bin, 2); # returns the third 64-bit value in LSB format of the binary object

Table 3.342. Arguments and Return Values for get_word_64_lsb()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The LSB integer value of the data at the 8-byte offset given in the string or binary object. If no offset is passed, then the first 64-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.17. get_qore_library_info()

Synopsis

Returns a hash of library build and version info with the keys in the table Library Info Hash. For constants giving the same information, see Build and Version Constants.

Prototype

get_qore_library_info() returns hash (CONST)

Example
$info = get_qore_library_info();

Table 3.343. Arguments and Return Values for get_qore_library_info()

Arguments

Return Type

Description

n/a

hash

A hash of library build and version info with the keys in the table Library Info Hash. For constants giving the same information, see Build and Version Constants.


This function does not throw any exceptions.

Table 3.344. Library Info Hash

Key

Description

PlatformOS

The operating system used to build the Qore library.

PlatformCPU

The CPU used as a target for the Qore library build.

VersionString

The full version string for this version of the Qore library.

VersionMajor

An integer giving the Qore library's major version number.

VersionMinor

An integer giving the Qore library's minor version number.

VersionSub

An integer giving the Qore library's release version number.

Build

An integer giving the Qore library's subversion revision number.

BuildHost

A string giving information about the host used to compile the Qore library.

Compiler

The compiler used to build the Qore library.

ModuleDir

The module directory assumed by default in the Qore library.

CFLAGS

The compiler flags used to compile the Qore library.

LDFLAGS

The linker flags used to link the Qore library.


3.12.18. get_qore_option_list()

Synopsis

Returns a list of hashes giving information about Qore library options for the current build. See Library Option Hash for information about the elements in the list returned. See Library Options for information about Qore library options.

Prototype

get_qore_option_list() returns list (CONST)

Example
$list = get_qore_option_list();

Table 3.345. Arguments and Return Values for get_qore_option_list()

Arguments

Return Type

Description

n/a

list

A list of hashes giving information about Qore library options for the current build. See Library Option Hash for information about the elements in the list returned.


Table 3.346. Library Option Hash

Key

Description

option

The string description of the option

constant

A string giving the name of the constant that has the boolean value for this option.

type

The type of option.

value

The boolean value of the option.


This function does not throw any exceptions.

3.12.19. getByte()

Synopsis

Returns the byte value of the offset (starting with 0) in the object passed. Of no offset is passed, then the value of the first byte (offset 0) is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

Prototype

getByte(data $data, softint $offset = 0) returns any (CONST)

getByte() returns nothing (RT_NOOP)

Example
$byte = getByte($bin, 2); # returns the third byte of the binary object

Table 3.347. Arguments and Return Values for getByte()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The value of the byte at the offset in the string or binary object. If no offset is passed, then the first byte is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.20. getClassName()

Synopsis

Returns the class name of an object.

Prototype

getClassName(object) returns string (CONST)

getClassName() returns nothing (RT_NOOP)

Example
$name = getClassName($obj);

Table 3.348. Arguments and Return Values for getClassName()

Argument Type

Return Type

Description

object

string

Returns the class name of the object passed.


This function does not throw any exceptions.

3.12.21. getDBIDriverCapabilities()

Synopsis

Returns an integer representing the capabilities of a DBI driver corresponding to the driver name passed as an argument. See SQL constants for constants for names of drivers shipping with the qore distribution.

Prototype

getDBIDriverCapabilities(string) returns any

getDBIDriverCapabilities() returns nothing (RT_NOOP)

Example
$caps = getDBIDriverCapabilities("oracle");

Table 3.349. Arguments and Return Values for getDBIDriverCapabilities()

Argument Type

Return Type

Description

string

int

Returns an integer representing the capabilities of a DBI driver binary-OR'ed together (see DBI Capability Constants). Returns NOTHING if the driver cannot be found.


This function does not throw any exceptions.

3.12.22. getDBIDriverCapabilityList()

Synopsis

Returns a list of each capability supported by the given DBI driver. See SQL constants for constants giving names of drivers shipping with the Qore distribution.

Prototype

getDBIDriverCapabilityList(string) returns any

getDBIDriverCapabilityList() returns nothing (RT_NOOP)

Example
$list = getDBIDriverCapabilityList("mysql");

Table 3.350. Arguments and Return Values for getDBIDriverCapabilityList()

Argument Type

Return Type

Description

string

list

Returns a list of each capability supported by the given DBI driver (see DBI Capability Constants). Returns NOTHING if the driver cannot be found.


This function does not throw any exceptions.

3.12.23. getDBIDriverList()

Synopsis

Returns a list of strings of DBI drivers currently loaded.

Prototype

getDBIDriverList() returns any

Example
$list = getDBIDriverList();

Table 3.351. Arguments and Return Values for getDBIDriverList()

Argument Type

Return Type

Description

n/a

list

Returns a list of strings of DBI drivers currently loaded.


This function does not throw any exceptions.

3.12.24. getFeatureList()

Synopsis

Returns a list of strings of the builtin and module-supplied features of Qore.

Prototype

getFeatureList() returns list (CONST)

Example
$list = getFeatureList();

Table 3.352. Arguments and Return Values for getFeatureList()

Argument Type

Return Type

Description

n/a

list

Returns a list of strings of the builtin and module-supplied features of Qore.


This function does not throw any exceptions.

3.12.25. getMethodList()

Synopsis

Returns a list of strings of the names of the methods of the class of the object passed as a parameter.

Prototype

getMethodList(object) returns list (CONST)

getMethodList() returns nothing (RT_NOOP)

Example
$list = getMethodList($obj);

Table 3.353. Arguments and Return Values for getMethodList()

Argument Type

Return Type

Description

object

list

Returns all methods in the class, both private and public. Does not return inherited methods. If no object is passed to the function, NOTHING is returned.


This function does not normally throw any exceptions, however an OBJECT-ALREADY-DELETED exception could be raised if there is a race condition and a stale pointer to an object is accessed with this function.

3.12.26. getModuleList()

Synopsis

Returns a list of hashes describing the currently-loaded Qore modules.

Prototype

getModuleList() returns list (CONST)

Example
$list = getModuleList();

Table 3.354. Arguments and Return Values for getModuleList()

Argument Type

Return Type

Description

n/a

list

Each element in the list is a hash describing currently-loaded qore modules.


This function does not throw any exceptions.

3.12.27. get_default_encoding()

Synopsis

Returns the name of the default character encoding for the currently-running Qore process.

Prototype

get_default_encoding() returns string (CONST)

Example
$encoding = get_default_encoding();

Table 3.355. Arguments and Return Values for get_default_encoding()

Argument Type

Return Type

Description

n/a

string

Returns the name of the default character encoding.


This function does not throw any exceptions.

3.12.28. getgrgid()

Synopsis

Returns a group information hash representing the group information for the group ID passed; or, if the group ID does not exist NOTHING is returned.

For a similar function that throws an exception if the group ID is invalid, see getgrgid2().

Prototype

getgrgid(softint $gid) returns any (CONST)

Example
my hash $hash = getgrgid(0); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.356. Arguments and Return Values for getgrgid()

Argument Type

Return Type

Description

int $gid

hash or nothing

Returns a hash representing the group information for the group ID passed. If the gid does not exist, NOTHING is returned. See the Group Information Hash for information about the return value.


This function does not throw any exceptions.

Table 3.357. Group Information Hash

Key

Type

Description

gr_name

string

The name of the group.

gr_passwd

string

The encrypted password for the group.

gr_gid

int

The group id.

gr_mem

list

List of strings giving the usernames of members of the group.


3.12.29. getgrgid2()

Synopsis

Returns a group information hash representing the group information for the group ID passed. If the group ID does not exist, an exception is raised.

For a similar function that does not throw an exception if the group ID is invalid, see getgrgid().

Prototype

getgrgid2(softint $gid) returns hash (CONST)

Example
my hash $hash = getgrgid2(0); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.358. Arguments and Return Values for getgrgid2()

Argument Type

Return Type

Description

int $gid

hash

Returns a hash representing the group information for the group ID passed. If the gid does not exist, an exception is thrown. See the Group Information Hash for information about the return value.


Table 3.359. Exceptions Thrown by getgrgid2()

err

desc

GETGRGID2-ERROR

The group information could not be retrieved (group does not exist or other error in call)


3.12.30. getgrnam()

Synopsis

Returns a group information hash representing the group information for the group name passed; or, if the group name does not exist NOTHING is returned.

For a similar function that throws an exception if the group ID is invalid, see getgrnam2().

Prototype

getgrnam(string $group_name) returns any (CONST)

Example
my hash $hash = getgrnam("root"); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.360. Arguments and Return Values for getgrnam()

Argument Type

Return Type

Description

int $group_name

hash or nothing

Returns a hash representing the group information for the group name passed. If the group name does not exist, NOTHING is returned. See the Group Information Hash for information about the return value.


This function does not throw any exceptions.

3.12.31. getgrnam2()

Synopsis

Returns a group information hash representing the group information for the group name passed. If the group name does not exist, an exception is rasied.

For a similar function that does not throw an exception if the group ID is invalid, see getgrnam().

Prototype

getgrnam2(string $group_name) returns hash (CONST)

Example
my hash $hash = getgrnam2("root"); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.361. Arguments and Return Values for getgrnam2()

Argument Type

Return Type

Description

string $group_name

hash

Returns a hash representing the group information for the group name passed. If the group name does not exist, an exception is thrown. See the Group Information Hash for information about the return value.


Table 3.362. Exceptions Thrown by getgrnam2()

err

desc

GETGRNAM2-ERROR

The group information could not be retrieved (group does not exist or other error in call)


3.12.32. getpwnam()

Synopsis

Returns a password information hash representing the user information for the user name passed; or, if the user name does not exist NOTHING is returned.

For a similar function that throws an exception if the user ID is invalid, see getpwnam2().

Prototype

getpwnam(string $user_name) returns any (CONST)

Example
my hash $hash = getpwnam("root"); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.363. Arguments and Return Values for getpwnam()

Argument Type

Return Type

Description

int $user_name

hash or nothing

Returns a hash representing the user information for the user name passed. If the user name does not exist, NOTHING is returned. See the Password Information Hash for information about the return value.


This function does not throw any exceptions.

Table 3.364. Password Information Hash

Key

Type

Description

pw_name

string

The username of the user.

pw_passwd

string

The encrypted password for the user.

pw_gecos

string

The real name or description of the user.

pw_dir

string

The user's home directory.

pw_shell

string

The user's login shell.

pw_uid

int

The user's userid.

pw_gid

int

The group id of the user's primary group.


3.12.33. getpwnam2()

Synopsis

Returns a password information hash representing the user information for the user name passed. If the user name does not exist, an exception is rasied.

For a similar function that does not throw an exception if the user ID is invalid, see getpwnam().

Prototype

getpwnam2(string $user_name) returns hash (CONST)

Example
my hash $hash = getpwnam2("root"); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.365. Arguments and Return Values for getpwnam2()

Argument Type

Return Type

Description

string $user_name

hash

Returns a hash representing the user information for the user name passed. If the user name does not exist, an exception is thrown. See the Password Information Hash for information about the return value.


Table 3.366. Exceptions Thrown by getpwnam2()

err

desc

GETPWNAM2-ERROR

The user information could not be retrieved (user does not exist or other error in call)


3.12.34. getpwuid()

Synopsis

Returns a password information hash representing the user information for the user ID passed; or, if the user ID does not exist NOTHING is returned.

For a similar function that throws an exception if the user ID is invalid, see getpwuid2().

Prototype

getpwuid(softint $uid) returns any (CONST)

Example
my hash $hash = getpwuid(0); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.367. Arguments and Return Values for getpwuid()

Argument Type

Return Type

Description

int $uid

hash or nothing

Returns a hash representing the user information for the user ID passed. If the uid does not exist, NOTHING is returned. See the Password Information Hash for information about the return value.


This function does not throw any exceptions.

3.12.35. getpwuid2()

Synopsis

Returns a password information hash representing the user information for the user ID passed. If the user ID does not exist, an exception is raised.

For a similar function that does not throw an exception if the user ID is invalid, see getpwuid().

Prototype

getpwuid2(softint $uid) returns hash (CONST)

Example
my hash $hash = getpwuid2(0); # returns the login information for root
Restrictions

Not available with PO_NO_EXTERNAL_INFO

Table 3.368. Arguments and Return Values for getpwuid2()

Argument Type

Return Type

Description

int $uid

hash

Returns a hash representing the user information for the user ID passed. If the uid does not exist, an exception is thrown. See the Password Information Hash for information about the return value.


Table 3.369. Exceptions Thrown by getpwuid2()

err

desc

GETPWUID2-ERROR

The user information could not be retrieved (user does not exist or other error in call)


3.12.36. get_script_path()

Synopsis

Returns the path (directory and filename) of the current script. Returns NOTHING if unknown (i.e. no parent script, script read from stdin, etc).

Prototype

get_script_path() returns any (CONST)

Example
$path = get_script_path();

Table 3.370. Arguments and Return Values for get_script_path()

Argument Type

Return Type

Description

n/a

string or nothing

Returns the path name of the current script, or NOTHING if unknown.


This function does not throw any exceptions.

3.12.37. get_script_dir()

Synopsis

Returns the name of the directory from which the current script was executed. Returns NOTHING if the parent script is unknown (i.e. no parent script, script read from stdin, etc).

Prototype

get_script_dir() returns any (CONST)

Example
$dir = get_script_dir();

Table 3.371. Arguments and Return Values for get_script_dir()

Argument Type

Return Type

Description

n/a

string or nothing

Returns the name of the directory for the current script, or NOTHING if unknown.


This function does not throw any exceptions.

3.12.38. get_script_name()

Synopsis

Returns the filename of the current script if known; returns NOTHING if not (i.e. no parent script, script read from stdin, etc).

Prototype

get_script_name() returns any (CONST)

Example
$name = get_script_name();

Table 3.372. Arguments and Return Values for get_script_name()

Argument Type

Return Type

Description

n/a

string or nothing

Returns the filename of the current script, or NOTHING if unknown.


This function does not throw any exceptions.

3.12.39. getWord32()

Synopsis

Returns the 32-bit integer value at the 4-byte offset (starting with 0) in the data passed. Of no offset is passed, then the value of the first 32-bit position at offset 0 is returned. Note that the [] operator provides a more efficient way to retrieve a byte from a binary object.

This function assumes MSB byte order when retrieving the value from the data.

Note that this function is identical to get_word_32() except that this version has a RT_NOOP variant.

See also get_word_32_lsb().

Prototype

getWord32(data $data, softint $offset = 0) returns any (CONST)

getWord32() returns nothing (RT_NOOP)

Example
$val = getWord32($bin, 2); # returns the third 32-bit value in MSB format of the binary object

Table 3.373. Arguments and Return Values for getWord32()

Arguments

Return Type

Description

data $data, softint $offset = 0)

int

The MSB integer value of the data at the 4-byte offset given in the string or binary object. If no offset is passed, then the first 32-bit value is returned. If the object is empty or the offset is larger than the object's size, then no value is returned.


3.12.40. hash_values()

Synopsis

Returns a list of all the values in the hash argument passed.

Prototype

hash_values(hash) returns list (CONST)

hash_values() returns nothing (RT_NOOP)

Example
$list = hash_values($hash);

Table 3.374. Arguments and Return Values for hash_values()

Argument Type

Return Type

Description

hash

>

list

Returns a list of all the values in the hash argument passed.


This function does not throw any exceptions.

3.12.41. hextoint()

Synopsis

Returns an integer for a hexadecimal string value.

Prototype

hextoint(string) returns bigint

Example
$int = hextoint("ab3d4e0f12");

Table 3.375. Arguments and Return Values for hextoint()

Argument Type

Return Type

Description

string

int

Returns an integer for a hexadecimal string value.


This function does not throw any exceptions.

3.12.42. html_decode()

Synopsis

Returns a string with any HTML escape codes translated to the original characters.

Prototype

html_decode(string) returns string (CONST)

html_decode() returns nothing (RT_NOOP)

Example
html_decode("&lt;hello&gt;"); # returns "<hello>"

Table 3.376. Arguments and Return Values for html_decode()

Argument Type

Return Type

Description

string

string

Returns a string with any HTML escape codes (ie &amp; -> &, etc) translated to the original characters.


This function does not throw any exceptions.

3.12.43. html_encode()

Synopsis

Returns a string with any characters that can be escaped translated to HTML escape codes.

Prototype

html_encode(string) returns string (CONST)

html_encode() returns nothing (RT_NOOP)

Example
$str = html_encode("<hello>"); # returns "&lt;hello&gt;"

Table 3.377. Arguments and Return Values for html_encode()

Argument Type

Return Type

Description

string

string

Returns a string with characters needed HTML escape code transation (ie & -> &amp; etc) translated to the escape codes.


This function does not throw any exceptions.

3.12.44. inlist()

Synopsis

Tests if the first argument is a member of the second argument list; types are converted if necessary. If the second argument is NOTHING, then False is returned unconditionally (i.e. even if the first argument is NOTHING as well), however if the second argument is not a list then the return value of the function is the comparison of the two arguments. For a version of this function that requires types to be equal for the comparison to succeed, see inlist_hard().

Prototype

inlist(any $value, list $list) returns bool

inlist(any $value, any $other_value) returns bool

inlist() returns bool (RT_NOOP)

Example
my $bool = inlist(123, (True, "123", False); # this will return True

Table 3.378. Arguments and Return Values for inlist()

Argument Type

Return Type

Description

any $value, list $list

bool

Returns True if value is a member of list; types are converted if necessary.

any $value, nothing

bool

Always returns False, even if the first argument is NOTHING.

any $value, any $other_value

bool

Returns the value of the comparison of the first argument with the second argument; types are converted if necessary.


This function does not throw any exceptions.

3.12.45. inlist_hard()

Synopsis

Tests if the first argument is a member of the second argument list; no type conversions are performed (i.e. the comparison fails if types are not equal). If the second argument is NOTHING, then False is returned unconditionally (i.e. even if the first argument is NOTHING as well), however if the second argument is not a list then the return value of the function is the comparison of the two arguments (types must be equal). For a "soft" version of this function that performs type conversions when doing the comparison, see inlist().

Prototype

inlist_hard(any $value, list $list) returns bool

inlist_hard(any $value, any $other_value) returns bool

Example
my $bool = inlist_hard(123, (True, "123", False); # this will return False

Table 3.379. Arguments and Return Values for inlist_hard()

Argument Type

Return Type

Description

any $value, list $list

bool

Returns True if value is a member of list; no type conversions are performed (the comparison fails if types are not equal).

any $value, nothing

bool

Always returns False.

any $value, any $other_value

bool

Returns the value of the comparison of the first argument with the second argument; no type conversions are performed (the comparison fails if the types are not equal).


This function does not throw any exceptions.

3.12.46. load_module()

Synopsis

Loads in a Qore module at run-time. If a feature with the same name already exists, then this feature's code is imported into the current Program object if necessary and no further action is taken. Note that modules providing objects resolved at parse time (classes, constants, functions, etc) must be loaded with the %requires directive instead, unless all references to the objects provided by the module will be made in code embedded in Program objects.

See also getFeatureList() for a function providing a list of available features.

Prototype

load_module(string $path_or_name) returns nothing

load_module() returns nothing (RT_NOOP)

Example
load_module("pgsql");

Table 3.380. Arguments and Return Values for load_module()

Argument Type

Return Type

Description

string $path_or_name

nothing

Loads the module with the given name if possible, otherwise throws an exception. This function returns no value.


Table 3.381. Exceptions Thrown by load_module()

err

desc

LOAD-MODULE-ERROR

An error occurred loading the module (module not found, libraries not resolved, wrong module API, etc).


3.12.47. makeBase64String()

Synopsis

Returns a base64-encoded representation of a binary object or a string (see also makeHexString()).

Prototype

makeBase64String(data) returns string (CONST)

makeBase64String() returns nothing (RT_NOOP)

Example
$str = makeBase64String($bin);

Table 3.382. Arguments and Return Values for makeBase64String()

Argument Type

Return Type

Description

data

string

Returns a base64-encoded representation of a binary object or a string.


This function does not throw any exceptions.

3.12.48. makeHexString()

Synopsis

Returns a hex-encoded representation of a binary object or a string (see also makeBase64String()).

Prototype

makeHexString(data) returns string (CONST)

makeHexString() returns nothing (RT_NOOP)

Example
$str = makeHexString($bin);

Table 3.383. Arguments and Return Values for makeHexString()

Argument Type

Return Type

Description

data

string

Returns a hex-encoded representation of a binary object or a string.


This function does not throw any exceptions.

3.12.49. max()

Synopsis

Returns the maximum value in a list (see also min()). Without a callback, this function will only work on basic data types. A closure or call reference can be used to find the maximum value of a list of complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than, equal to, or greater than the second, respectively.

Prototype

max(...) returns any (CONST)

max(list $list) returns any (CONST)

max(list $list, string $func_name) returns any

max(list $list, code $code) returns any

Example
$max = max($complex_list, \callback_function());
$max = max(1, 2, 3, 4);

Table 3.384. Arguments and Return Values for max()

Argument Type

Return Type

Description

list $list, [code $code or string $fname]

any

Finds the maxmimum value in the list and returns that value. The list must be made up of basic data types unless a closure or call reference is used as described above.

...

any

Finds the maximum value in the list of simple data types passed as top-level arguments to the function and returns that value. No callback reference can be specified with this variant.


This function does not throw any exceptions (note a closure or call reference could throw an exception).

3.12.50. min()

Synopsis

Returns the minumum value in a list (see also max()). Without a callback, this function will only work on basic data types. A closure or call reference can be used to find the minimum value of a list of complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than, equal to, or greater than the second, respectively.

Prototype

min(...) returns any (CONST)

min(list $list) returns any (CONST)

min(list $list, string $func_name) returns any

min(list $list, code $code) returns any

Example
$min = min($complex_list, \callback_function());
$min = min(1, 10, 2, 3);

Table 3.385. Arguments and Return Values for min()

Argument Type

Return Type

Description

list $list, [code $code or string $func_name]

any

Finds the minimum value in the list and returns that value. The list must be made up of basic data types unless a closure or call reference is used as described above.

...

any

Finds the minimum value in the list of simple data types passed as top-level arguments to the function and returns that value. No callback reference can be specified with this variant.


This function does not throw any exceptions (note that a closure or call reference could throw an exception).

3.12.51. parse()

Synopsis

Adds the text passed to the current program's code.

Prototype

parse(string $code, string $label) returns nothing

parse() returns nothing (RT_NOOP)

Example
parse($code, "label");

Table 3.386. Arguments and Return Values for parse()

Argument Type

Return Type

Description

string $code, string $label

n/a

Parses the first string passed and adds the code to the current program with the second string as a label identifying the code or the code's source.


Table 3.387. Exceptions Thrown by parse()

err

desc

PARSE-ERROR

An error occurred parsing the text.


3.12.52. parse_url()

Synopsis

Parses a URL string and returns a hash of the components with the following keys (if data in the URL is present): protocol, path, username, password, host, port. If the URL cannot be parsed, an exception is thrown..

For a similar function that returns NOTHING instead of throwing an exception if the URL string cannot be parsed, see parseURL().

Prototype

parse_url(string $url) returns hash

Example
my hash $hash = parse_url($url_string);

Table 3.388. Arguments and Return Values for parseURL()

Argument Type

Return Type

Description

string $url

hash

Parses a URL string and returns a hash of the components. URLs have the format: protocol://username:password@host:port/path, where only host is mandatory. If the URL cannot be parsed an exception is thrown.


Table 3.389. Exceptions Thrown by parse_url()

err

desc

PARSE-URL-ERROR

The URL string given could not be parsed.


3.12.53. parseBase64String()

Synopsis

Parses a base64 encoded string and returns the binary object (see also parseHexString()).

Prototype

parseBase64String(string) returns binary

parseBase64String() returns nothing (RT_NOOP)

Example
$bin = parseBase64String($base64_string);

Table 3.390. Arguments and Return Values for parseBase64String()

Argument Type

Return Type

Description

string

binary

Parses a base64 encoded string and returns the binary object.


Table 3.391. Exceptions Thrown by parseBase64String()

err

desc

BASE64-PARSE-ERROR

A syntax error occurred parsing the base64 string (invalid character, etc).


3.12.54. parseDatasource()

Synopsis

Returns a hash of the components of a datasource string.

Prototype

parseDatasource(string) returns hash

parseDatasource() returns nothing (RT_NOOP)

Example
$hash = parseDatasource($ds_string);

Table 3.392. Arguments and Return Values for parseDatasource()

Argument Type

Return Type

Description

string

hash

Returns a hash of the components of a datasource string. A datasource string has the following structure: driver:user/pass@db(charset)%host:port{option=val,...}, where driver, charset, host, port, and options are optional. See parseDatasource() hash for a description of the output hash of this function.


Table 3.393. Exceptions Thrown by parseDatasource()

err

desc

DATASOURCE-PARSE-ERROR

A syntax error occurred parsing the datasource string (missing field, unexpected character, etc).


Table 3.394. parseDatasource() hash

Key

Description

type

the name of the driver, if present

user

the username given in the string

pass

the password for the connection

db

the database name for the connection

charset

The name of the DB-specific character encoding to use for the connection, if present in the string

host

the hostname for the connection, if present in the string

port

the port number to use for the connection, if present in the string

options

A hash of options given in the string, if present. Currently-supported options are min and max, which are respected by the DatasourcePool::constructor(hash) variant for setting the minimum and maximum connections in the pool, respectively.


3.12.55. parseHexString()

Synopsis

Parses a hex-encoded string and returns the binary object (see also parseBase64String()).

Prototype

parseHexString(string) returns binary

parseHexString() returns nothing (RT_NOOP)

Example
$bin = parseHexString($hex_string);

Table 3.395. Arguments and Return Values for parseHexString()

Argument Type

Return Type

Description

string

binary

Parses a hex-encoded string and returns the binary object.


Table 3.396. Exceptions Thrown by parseHexString()

err

desc

PARSE-HEX-ERROR

A syntax error occurred parsing the hex string (odd number of digits, invalid character, etc).


3.12.56. parseURL()

Synopsis

Parses a URL string and returns a hash of the components with the following keys (if data in the URL is present): protocol, path, username, password, host, port. If the URL cannot be parsed, no value is returned.

For a similar function that throws an exception instead of returning NOTHING if the URL string cannot be parsed, see parse_url().

Prototype

parseURL(string $url) returns any

parseURL() returns nothing (RT_NOOP)

Example
$hash = parseURL($url_string);

Table 3.397. Arguments and Return Values for parseURL()

Argument Type

Return Type

Description

string $url

hash or nothing

Parses a URL string and returns a hash of the components. URLs have the format: protocol://username:password@host:port/path, where only host is mandatory. If the URL cannot be parsed, no value is returned.


This function does not throw any exceptions.

3.12.57. rand()

Synopsis

Returns a random integer number (uses the C library function random() to generate the number).

Prototype

rand() returns int

Example
$num = rand();

Table 3.398. Arguments and Return Values for rand()

Argument Type

Return Type

Description

n/a

int

A random integer number is returned. See srand() for a function to seed the random number generator.


This function does not throw any exceptions.

3.12.58. remove_signal_handler()

Synopsis

Removes a signal handler and returns the signal handling state to the default. By the time this function returns, changes to the signal handling thread have already been effected. See Signal Handling for more information.

Prototype

remove_signal_handler(softint) returns nothing

Example
remove_signal_handler(SIGINT);
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.399. Arguments and Return Values for remove_signal_handler()

Argument Type

Return Type

Description

softint

n/a

The signal number to process.


This function does not throw any exceptions.

3.12.59. reverse()

Synopsis

Reverses a string or a list (depending on the argument) and returns the new string or list. Works properly on UTF-8 strings with multi-byte characters as well.

Prototype

reverse(string) returns string (CONST)

reverse(list) returns list (CONST)

reverse() returns nothing (RT_NOOP)

Example
$str = reverse("ABCDEF"); # returns "FEDCBA"

Table 3.400. Arguments and Return Values for reverse()

Argument Type

Return Type

Description

list

list

The list with its elements reversed.

string

string

The string with its characters reversed.


This function does not throw any exceptions.

3.12.60. set_signal_handler()

Synopsis

Sets or replaces a signal handler according to the signal number and closure or call reference (function or object method reference) passed. By the time this function returns, changes to the signal handling thread have already been effected. See Signal Handling for more information.

When a signal is raised and the signal handler code is called, the signal number is passed as an integer argument to the signal handling code.

Prototype

set_signal_handler(softint $signal, code $handler) returns nothing

Example
set_signal_handler(SIGINT, \signal_handler());
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.401. Arguments and Return Values for set_signal_handler()

Argument Type

Return Type

Description

softint $signal, code $handler

n/a

The signal number to process and reference to the code to execute when the signal is raised.


This function does not throw any exceptions.

3.12.61. sort()

Synopsis

Performs an unstable sort in ascending order and returns the new list (for a stable version see sortStable()). Without a callback, this function will only sort basic data types. A closure or call reference can be used to sort complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than the second, if the first and second are equal, or if the first is greater than the second, respectively.

Prototype

sort(list $list) returns list (CONST)

sort(list $list, code $code) returns list

sort(list $list, string $func_name) returns list

sort() returns nothing (RT_NOOP)

Example
$list = sort($complex_list, \callback());

Table 3.402. Arguments and Return Values for sort()

Argument Type

Return Type

Description

list $list, [code $code or string $func_name]

list

Sorts the list passed in ascending order and returns the sorted list. The list must be made up of basic data types unless a closure or call reference is used.


This function does not throw any exceptions.

3.12.62. sortDescending()

Synopsis

Performs an unstable sort in descending order and returns the new list (for a stable version see sortDescendingStable()). Without a closure or call reference, this function will only sort basic data types. A closure or call reference can be used to sort complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than the second, if the first and second are equal, or if the first is greater than the second, respectively.

Prototype

sortDescending(list $list) returns list (CONST)

sortDescending(list $list, code $code) returns list

sortDescending(list $list, string $func_name) returns list

sortDescending() returns nothing (RT_NOOP)

Example
$list = sortDescending($complex_list, \callback());

Table 3.403. Arguments and Return Values for sortDescending()

Argument Type

Return Type

Description

list $list, [code $code or string $func_name]

list

Sorts the list passed in descending order and returns the sorted list. The list must be made up of basic data types unless a closure or call reference is used.


This function does not throw any exceptions.

3.12.63. sortDescendingStable()

Synopsis

Performs a stable sort in descending order and returns the new list (for an unstable version see sortDescending()). Without a closure or call reference, this function will only sort basic data types. A closure or call reference can be used to sort complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than the second, if the first and second are equal, or if the first is greater than the second, respectively.

Prototype

sortDescendingStable(list $list) returns list (CONST)

sortDescendingStable(list $list, code $code) returns list

sortDescendingStable(list $list, string $func_name) returns list

sortDescendingStable() returns nothing (RT_NOOP)

Example
$list = sortDescendingStable($complex_list, \callback());

Table 3.404. Arguments and Return Values for sortDescendingStable()

Argument Type

Return Type

Description

list $list, [code $code or string $func_name]

list

Sorts the list passed in descending order and returns the sorted list. The list must be made up of basic data types unless a closure or call reference is used.


This function does not throw any exceptions.

3.12.64. sortStable()

Synopsis

Performs a stable sort in ascending order and returns the new list (for an unstable version see sort()). Without a closure or call reference, this function will only sort basic data types. A closure or call reference can be used to sort complex data types. The closure or call reference must accept two arguments and must return -1, 0, or 1 if the first is less than the second, if the first and second are equal, or if the first is greater than the second, respectively.

Prototype

sortStable(list $list) returns list (CONST)

sortStable(list $list, code $code) returns list

sortStable(list $list, string $func_name) returns list

sortStable() returns nothing (RT_NOOP)

Example
$list = sortStable($complex_list, \callback());

Table 3.405. Arguments and Return Values for sortStable()

Argument Type

Return Type

Description

list $list, [code $code or string $func_name]

list

Sorts the list passed in ascending order and returns the sorted list. The list must be made up of basic data types unless a closure or call reference is used.


This function does not throw any exceptions.

3.12.65. srand()

Synopsis

Seeds the random number generator with the integer passed (uses the C library function srandom()).

This function is tagged with PO_NO_PROCESS_CONTROL because it affects the process as a whole.

Prototype

srand(softint) returns nothing

srand() returns nothing (RT_NOOP)

Example
srand(now()); # seeds with current time
Restrictions

Not available with PO_NO_PROCESS_CONTROL

Table 3.406. Arguments and Return Values for srand()

Argument Type

Return Type

Description

softint

n/a

Seeds the random number generator with the integer passed. See rand() for a function to get a random number.


This function does not throw any exceptions.

3.12.66. strtoint()

Synopsis

Returns an integer corresponding to the string passed with the possibility to specify the base (default base 10).

Prototype

strtoint(softstring $string, int $base = 10) returns int (CONST)

strtoint() returns nothing (RT_NOOP)

Example
$int = strtoint("41", 8);

Table 3.407. Arguments and Return Values for strtoint()

Argument Type

Return Type

Description

softstring $string, int $base = 10

int

Returns an integer corresponding to the string value in the base specified. If no base is passed, then base 10 is assumed.


This function does not throw any exceptions.

3.13. Threading Functions

3.13.1. delete_all_thread_data()

Synopsis

Deletes all keys in the thread-local data hash.

Prototype

delete_all_thread_data()

Example
delete_all_thread_data();
Restrictions

Not available with PO_NO_THREAD_CONTROL

Table 3.408. Arguments and Return Values for delete_all_thread_data()

Argument Type

Return Type

Description

n/a

n/a

Deletes all keys in the thread-local data hash.


This function does not throw any exceptions.

3.13.2. delete_thread_data()

Synopsis

Deletes the data associated to one or more keys in the thread-local data hash; if the data is an object, then it is destroyed. See remove_thread_data() for a similar function that does not explicitly destroy objects in the thread-local data hash.

Prototype

delete_thread_data(list) returns nothing

delete_thread_data(...) returns nothing

Example
delete_thread_data("key1", "key2");
delete_thread_data($list_of_strings);
Restrictions

Not available with PO_NO_THREAD_CONTROL

Table 3.409. Arguments and Return Values for delete_thread_data()

Arguments

Return Values

Description

list

n/a

Deletes the data associated to one or more keys in the thread-local data hash corresponding to the elements of the list converted to a string (if necessary).

...

n/a

Deletes the data associated to one or more keys in the thread-local data hash corresonding to each string argument in the top-level argument list; arguments are converted to strings if necessary.


This function does not throw any exceptions, however any objects deleted could throw exceptions in their destructors.

3.13.3. get_all_thread_data()

Synopsis

Returns the entire thread-local data hash.

Prototype

get_all_thread_data() returns hash (CONST)

Example
$hash = get_all_thread_data();
Restrictions

Not available with PO_NO_THREAD_CONTROL or PO_NO_THREAD_INFO

Table 3.410. Arguments and Return Values for get_all_thread_data()

Argument Type

Return Type

Description

n/a

hash

Returns the entire thread-local data hash.


This function does not throw any exceptions.

3.13.4. getAllThreadCallStacks()

Synopsis

Returns a hash of call stacks keyed by each TID (thread ID). The availability of this function depends on an optional debugging feature in the Qore library (maintaining run-time thread call stacks incurrs a performance penalty, therefore this option is normally only available in debugging builds of Qore); the function is only available if the constant HAVE_RUNTIME_THREAD_STACK_TRACE is True. See Library Option Constants for a list of all option constants.

Prototype

getAllThreadCallStacks() returns hash

Example

getAllThreadCallStacks() returns hash

Restrictions

Not available with PO_NO_THREAD_CONTROL or PO_NO_THREAD_INFO

Table 3.411. Arguments and Return Values for getAllThreadCallStacks()

Argument Type

Return Type

Description

n/a

hash

Returns a hash of call stacks keyed by each TID (thread ID). See Call Stack Description for a description of the call stack format.


Table 3.412. Exceptions Thrown by getAllThreadCallStacks()

err

desc

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_RUNTIME_THREAD_STACK_TRACE before calling this function.


3.13.5. get_thread_data()

Synopsis

Returns the value of the thread-local data attached to the key passed.

Prototype

get_thread_data(string) returns any (CONST)

get_thread_data() returns nothing (RT_NOOP)

Example
$data = get_thread_data("key1");
Restrictions

Not available with PO_NO_THREAD_CONTROL or PO_NO_THREAD_INFO

Table 3.413. Arguments and Return Values for get_thread_data()

Argument Type

Return Type

Description

string

any

Returns the value of the thread-local data attached to the key passed.


This function does not throw any exceptions.

3.13.6. gettid()

Synopsis

Returns the Qore thread ID (TID) of the current thread.

Prototype

gettid() returns int (CONST)

Example
$tid = gettid();
Restrictions

Not available with PO_NO_THREAD_INFO

Table 3.414. Arguments and Return Values for gettid()

Argument Type

Return Type

Description

n/a

int

Returns the Qore thread ID (TID) of the current thread.


This function does not throw any exceptions.

3.13.7. num_threads()

Synopsis

Returns the current number of threads in the process (not including the special signal handling thread).

Prototype

num_threads() returns int (CONST)

Example
$num = num_threads();
Restrictions

Not available with PO_NO_THREAD_INFO

Table 3.415. Arguments and Return Values for num_threads()

Argument Type

Return Type

Description

n/a

int

Returns the current number of threads in the process.


This function does not throw any exceptions.

3.13.8. remove_thread_data()

Synopsis

Removes the data associated to one or more keys in the thread-local data hash. For a similar function that also explicitly destroys objects, see delete_thread_data.

Prototype

remove_thread_data(list) returns nothing

remove_thread_data(...) returns nothing

Example
remove_thread_data("key1", "key2");
remove_thread_data($list_of_strings);
Restrictions

Not available with PO_NO_THREAD_CONTROL

Table 3.416. Arguments and Return Values for remove_thread_data()

Arguments

Return Values

Description

list

n/a

Removes the data associated to one or more keys in the thread-local data hash corresponding to the elements of the list converted to a string (if necessary).

...

n/a

Removes the data associated to one or more keys in the thread-local data hash corresonding to each string argument in the top-level argument list; arguments are converted to strings if necessary.


This function does not throw any exceptions.

3.13.9. save_thread_data()

Synopsis

Saves the data passed against the key passed in thread-local storage.

Prototype

save_thread_data(hash $hash) returns nothing

save_thread_data(string $key, any $value) returns nothing

save_thread_data() returns nothing (RT_NOOP)

Example
save_thread_data("key1", $value);
Restrictions

Not available with PO_NO_THREAD_CONTROL

Table 3.417. Arguments and Return Values for save_thread_data()

Argument Type

Return Type

Description

string $key, any $value

n/a

Saves the data passed against the key passed in thread-local storage.

hash $hash

n/a

Saves the data passed in the hash giving key-value pairs in thread-local storage; the hash argument is added to the therad-local data, replacing any keys already present in the thread-local data.


This function does not throw any exceptions, however if a value is removed from the thread-local data hash by being overwritten with a new value, and the value is an object that goes out of scope, then such an object could throw an exception in its destructor.

3.13.10. thread_list()

Synopsis

Returns a list of all current thread IDs. Note that the special signal handling thread with TID 0 is never included in this list.

Prototype

thread_list() returns list (CONST)

Example
$list = thread_list();
Restrictions

Not available with PO_NO_THREAD_INFO

Table 3.418. Arguments and Return Values for thread_list()

Argument Type

Return Type

Description

n/a

list

Returns a list of all current thread IDs


This function does not throw any exceptions.

3.13.11. throwThreadResourceExceptions()

Synopsis

Immediately runs all thread resource cleanup routines for the current thread and throws all associated exceptions. This function is particularly useful when used in combination with embedded code in order to catch (and log, for example) thread resource errors (ex: uncommitted transactions, unlocked locks, etc).

Prototype

throwThreadResourceExceptions() returns nothing

Example
try {
    throwThreadResourceExceptions();
}
catch ($ex) {
    # ... log or handle exceptions
}
Restrictions

Not available with PO_NO_THREAD_CONTROL

Table 3.419. Arguments and Return Values for throwThreadResourceExceptions()

Argument Type

Return Type

Description

n/a

n/a

This function returns no value.


This function can throw any exception thrown by a thread resource handler.

3.14. XML Functions

XML functions allow serializing and deserializing between XML strings and qore data structures. There are also functions for XML-RPC support; see below for details and see the XmlRpcClient Class for a class supporting communication with this protocol.

3.14.1. makeFormattedXMLFragment()

Synopsis

Serializes a hash into an XML string with formatting without an XML header.

Prototype

makeFormattedXMLFragment(hash $data, string $encoding) returns string

makeFormattedXMLFragment(hash $data) returns string

makeFormattedXMLFragment() returns nothing (RT_NOOP)

Example
$xml = makeFormattedXMLFragment($hash);

Table 3.420. Arguments and Return Values for makeFormattedXMLFragment()

Argument Type

Return Type

Description

hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) without an XML header but with formatting. The hash must have only one top-level key or an exception will be thrown. The optional second argument can give the output string encoding, otherwise UTF-8 is used (not the default encoding for the process).


Table 3.421. Exceptions Thrown by makeFormattedXMLFragment()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.2. makeFormattedXMLRPCCallString()

Synopsis

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCCallString(string $method, ...) returns string

Example
$xml = makeFormattedXMLRPCCallString("method.name", $arg1, $arg2);

Table 3.422. Arguments and Return Values for makeFormattedXMLRPCCallString()

Argument Type

Return Type

Description

string $method, ...

string

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting. The encoding of the resulting string will always be the default encoding.


Table 3.423. Exceptions Thrown by makeFormattedXMLRPCCallString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.3. makeFormattedXMLRPCCallStringWithEncoding()

Synopsis

Serializes the arguments into an XML string for an XML-RPC call with whitespace formatting, taking an initial string argument to give the encoding for the created XML.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCCallStringWithEncoding(string $encoding, string $method, ...) returns string

Example
$xml = makeFormattedXMLRPCCallStringWithEncoding("ISO-8859-1", "method.name", $arg1, $arg2);

Table 3.424. Arguments and Return Values for makeFormattedXMLRPCCallStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, string $method, ...

string

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting. The encoding of the resulting string is given by the first argument.


Table 3.425. Exceptions Thrown by makeFormattedXMLRPCCallStringWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.4. makeFormattedXMLRPCCallStringArgs()

Synopsis

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting, taking a single argument following the XML-RPC method name for the argument list to the method.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCCallStringArgs(string $method, any $args) returns string

Example
$xml = makeFormattedXMLRPCCallStringArgs("method.name", $arg_list);

Table 3.426. Arguments and Return Values for makeFormattedXMLCallStringArgs()

Argument Type

Return Type

Description

string $method, list or any $args

string

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting, using a single argument following the XML-RPC method name as the argument list for the method. The encoding of the resulting string will always be the default encoding.


Table 3.427. Exceptions Thrown by makeFormattedXMLRPCCallStringArgs()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.5. makeFormattedXMLRPCCallStringArgsWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC call with whitespace formatting, taking an initial string argument to give the encoding for the created XML, followed by the method name, followed by a single list argument for the argument list.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCCallStringArgsWithEncoding(string $encoding, string $method, any $args) returns string

Example
$xml = makeFormattedXMLRPCCallStringArgsWithEncoding("ISO-8859-1", "method.name", $arg_list);

Table 3.428. Arguments and Return Values for makeFormattedXMLRPCCallStringArgsWithEncoding()

Argument Type

Return Type

Description

string $encoding, string $method, list or any $args

string

Serializes the arguments into an XML string in XML-RPC call format with whitespace formatting, using a single argument following the XML-RPC method name as the argument list for the method. The encoding of the resulting string will be the encoding given by the first argument.


Table 3.429. Exceptions Thrown by makeFormattedXMLRPCCallStringArgsWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.6. makeFormattedXMLRPCFaultResponseString()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCFaultResponseString(any $code, string $msg) returns string

Example
$xml = makeFormattedXMLRPCFaultResponseString(10, "oh no, big error");

Table 3.430. Arguments and Return Values for makeFormattedXMLRPCFaultResponseString()

Argument Type

Return Type

Description

any $code, string $msg

string

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting. The first argument is converted to an integer to give the XML-RPC error code. The encoding of the resulting string will always be the default encoding.


Table 3.431. Exceptions Thrown by makeFormattedXMLRPCCallStringArgs()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-XMLRPC-FAULT-RESPONSE-STRING-PARAMETER-ERROR

missing either the error code or the error string arguments.


3.14.7. makeFormattedXMLRPCFaultResponseStringWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting, taking an initial string argument to give the encoding for the created XML.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCFaultResponseStringWithEncoding(string $encoding, any $code, string $msg) returns string

Example
$xml = makeFormattedXMLRPCFaultResponseStringWithEncoding("ISO-8859-2", 10, "oh no, big error");

Table 3.432. Arguments and Return Values for makeFormattedXMLRPCFaultResponseStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, any $code, string $msg

string

Serializes the arguments into an XML string formatted for an XML-RPC fault response with whitespace formatting. The first argument give the XML-RPC fault code. The encoding of the resulting string will be the encoding given by the first argument.


Table 3.433. Exceptions Thrown by makeFormattedXMLRPCCallStringArgsWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-XMLRPC-FAULT-RESPONSE-STRING-PARAMETER-ERROR

missing either the error code or the error string arguments.


3.14.8. makeFormattedXMLRPCResponseString()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCResponseString(...) returns any

Example
$xml = makeFormattedXMLRPCResponseString($value);

Table 3.434. Arguments and Return Values for makeFormattedXMLRPCResponseString()

Argument Type

Return Type

Description

...

string

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting>. The encoding of the resulting string will always be the default encoding.


Table 3.435. Exceptions Thrown by makeFormattedXMLRPCResponseString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.9. makeFormattedXMLRPCResponseStringWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting, taking an initial string argument to give the encoding for the created XML.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCResponseStringWithEncoding(string $encoding, ...) returns any

Example
$xml = makeFormattedXMLRPCResponseStringWithEncoding("ISO-8859-1", $value);

Table 3.436. Arguments and Return Values for makeFormattedXMLRPCResponseStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, ...

string

Serializes the arguments into an XML string formatted for an XML-RPC response with whitespace formatting>. The encoding of the resulting string is given by the first argument.


Table 3.437. Exceptions Thrown by makeFormattedXMLRPCResponseStringWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.10. makeFormattedXMLRPCValueString()

Synopsis

Serializes the arguments into an XML string in XML-RPC value format with whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeFormattedXMLRPCValueString(any $data, string $encoding) returns string

makeFormattedXMLRPCValueString(any $data) returns string

Example
$xml = makeFormattedXMLRPCValueString($value);

Table 3.438. Arguments and Return Values for makeFormattedXMLRPCValueString()

Argument Type

Return Type

Description

any $data, [string $encoding]

string

Serializes the arguments into an XML string in XML-RPC value format with whitespace formatting. The optional second argument may be given to set the output string encoding, otherwise the encoding of the resulting string will be the default encoding.


Table 3.439. Exceptions Thrown by makeFormattedXMLRPCValueString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.11. makeFormattedXMLString()

Synopsis

Serializes a hash into an XML string with formatting and an XML header.

Prototype

makeFormattedXMLString(hash $data) returns string

makeFormattedXMLString(hash $data, string $encoding) returns string

makeFormattedXMLString(string $top_element, hash $data) returns string

makeFormattedXMLString(string, hash $data, string) returns string $encoding

Examples
$xml = makeFormattedXMLString($hash);
$xml = makeFormattedXMLString("key", $hash);

Table 3.440. Arguments and Return Values for makeFormattedXMLString()

Argument Type

Return Type

Description

hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) with an XML header and formatting. The hash must have only one top-level key or an exception will be thrown. The optional second argument may be given to specify the output string encoding, otherwise UTF-8 will be used.

string $top_element, hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) with an XML header and formatting. The first parameter will be the top-level XML element. The optional third argument may be given to specify the output string encoding, otherwise UTF-8 will be used.


Table 3.441. Exceptions Thrown by makeFormattedXMLString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-FORMATTED-XML-STRING-PARAMETER-EXCEPTION

Incorrect arguments passed.


3.14.12. makeXMLFragment()

Synopsis

Serializes a hash into an XML string without whitespace formatting and without an XML header.

Prototype

makeXMLFragment(hash $data, string $encoding) returns string

makeXMLFragment(hash $data) returns string

makeXMLFragment() returns nothing (RT_NOOP)

Example
$xml = makeXMLFragment($hash);

Table 3.442. Arguments and Return Values for makeXMLFragment()

Argument Type

Return Type

Description

hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) without an XML header and without whitespace formatting. The hash must have only one top-level key or an exception will be thrown. The optional second argument can give the output string encoding, otherwise the default encoding is used.


Table 3.443. Exceptions Thrown by makeXMLFragment()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.13. makeXMLRPCCallString()

Synopsis

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCCallString(string $method, ...) returns string

Example
$xml = makeXMLRPCCallString("method.name", $arg1, $arg2);

Table 3.444. Arguments and Return Values for makeXMLRPCCallString()

Argument Type

Return Type

Description

string $method, ...

string

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting. The encoding of the resulting string will always be the default encoding.


Table 3.445. Exceptions Thrown by makeXMLRPCCallString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.14. makeXMLRPCCallStringWithEncoding()

Synopsis

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting, taking an initial string argument to give the target character encoding for the XML string.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCCallStringWithEncoding(string $encoding, string $method, ...) returns string

Example
$xml = makeXMLRPCCallStringWithEncoding("ISO-8859-2", "method.name", $arg1, $arg2);

Table 3.446. Arguments and Return Values for makeXMLRPCCallStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, string $method, ...

string

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting. The encoding of the resulting string will correspond to the encoding given as the first argument.


Table 3.447. Exceptions Thrown by makeXMLRPCCallStringWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.15. makeXMLRPCCallStringArgs()

Synopsis

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting, taking a single argument following the XML-RPC method name for the argument list to the method.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCCallStringArgs(string $method, any $args) returns string

Example
$xml = makeXMLRPCCallStringArgs("method.name", $arg_list);

Table 3.448. Arguments and Return Values for makeXMLCallStringArgs()

Argument Type

Return Type

Description

string $method, list or any $args

string

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting, using a single argument following the XML-RPC method name as the argument list for the method. The encoding of the resulting string will always be the default encoding.


Table 3.449. Exceptions Thrown by makeXMLRPCCallStringArgs()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.16. makeXMLRPCCallStringArgsWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC call without whitespace formatting, taking an initial string argument to give the target character encoding for the XML string followed by a list argument for the argument list.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCCallStringArgsWithEncoding(string $encoding, string $method, any $args) returns string

Example
$xml = makeXMLRPCCallStringArgsWithEncoding("ISO-8859-2", "method.name", $arg_list);

Table 3.450. Arguments and Return Values for makeXMLCallStringArgsWithEncoding()

Argument Type

Return Type

Description

string $encoding, string $method>, list or any $args

string

Serializes the arguments into an XML string in XML-RPC call format without whitespace formatting, using a single argument following the XML-RPC method name as the argument list for the method. The encoding of the resulting string will correspond to the encoding given as the first argument to the function.


Table 3.451. Exceptions Thrown by makeXMLRPCCallStringArgsWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.17. makeXMLRPCFaultResponseString()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC fault response without whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCFaultResponseString(any $code, string $msg) returns string

Example
$xml = makeXMLRPCFaultResponseString(10, "oh no, an error occured");

Table 3.452. Arguments and Return Values for makeXMLRPCFaultResponseString()

Argument Type

Return Type

Description

any $code, string $msg

string

Serializes the arguments into an XML string formatted for an XML-RPC fault response without whitespace formatting. The encoding of the resulting string will always be the encoding of the fault string (2nd argument).


Table 3.453. Exceptions Thrown by makeXMLRPCFaultResponseString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-XMLRPC-FAULT-RESPONSE-STRING-PARAMETER-ERROR

missing either the error code or the error string arguments.


3.14.18. makeXMLRPCFaultResponseStringWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC fault response without whitespace formatting, taking an initial string argument to give the target character encoding for the XML string.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCFaultResponseStringWithEncoding(string $encoding, any $code, string $msg) returns string

Example
$xml = makeXMLRPCFaultResponseStringWithEncoding("ISO-8859-2", 10, "oh no, an error occured");

Table 3.454. Arguments and Return Values for makeXMLRPCFaultResponseStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, any $code, string $msg

string

Serializes the arguments into an XML string formatted for an XML-RPC fault response without whitespace formatting. The encoding of the resulting string will correspond to the encoding given as the first argument.


Table 3.455. Exceptions Thrown by makeXMLRPCFaultResponseStringWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-XMLRPC-FAULT-RESPONSE-STRING-PARAMETER-ERROR

missing either the error code or the error string arguments.


3.14.19. makeXMLRPCResponseString()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC response without whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCResponseString(...) returns any

Example
$xml = makeXMLRPCResponseString($response);

Table 3.456. Arguments and Return Values for makeXMLRPCResponseString()

Argument Type

Return Type

Description

...

string

Serializes the arguments into an XML string formatted for an XML-RPC response without whitespace formatting>. The encoding of the resulting string will always be the default encoding.


Table 3.457. Exceptions Thrown by makeXMLRPCResponseString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.20. makeXMLRPCResponseStringWithEncoding()

Synopsis

Serializes the arguments into an XML string formatted for an XML-RPC response without whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCResponseStringWithEncoding(string $encoding, ...) returns any

Example
$xml = makeXMLRPCResponseStringWithEncoding("ISO-8859-2", $response);

Table 3.458. Arguments and Return Values for makeXMLRPCResponseStringWithEncoding()

Argument Type

Return Type

Description

string $encoding, ...

string

Serializes the arguments into an XML string formatted for an XML-RPC response without whitespace formatting>. The encoding of the resulting string will correspond to the first argument.


Table 3.459. Exceptions Thrown by makeXMLRPCResponseStringWithEncoding()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.21. makeXMLRPCValueString()

Synopsis

Serializes the arguments into an XML string in XML-RPC value format without whitespace formatting.

For information about XML-RPC serialization, see XML-RPC Serialization.

Prototype

makeXMLRPCValueString(any, $data string $encoding) returns string

makeXMLRPCValueString(any $data) returns string

Example
$xml = makeXMLRPCValueString($value);

Table 3.460. Arguments and Return Values for makeXMLRPCValueString()

Argument Type

Return Type

Description

any $data, [string $encoding]

string

Serializes the arguments into an XML string in XML-RPC value format without whitespace formatting. The encoding of the resulting string will always be the default encoding.


Table 3.461. Exceptions Thrown by makeXMLRPCValueString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.


3.14.22. makeXMLString()

Synopsis

Serializes a hash into an XML string without whitespace formatting but with an XML header.

Prototype

makeXMLString(hash $data) returns string

makeXMLString(hash $data, string $encoding) returns string

makeXMLString(string $top_element, hash $data) returns string

makeXMLString(string, hash $data, string) returns string $encoding

Examples
$xml = makeXMLString($hash);
$xml = makeXMLString("key", $hash);

Table 3.462. Arguments and Return Values for makeXMLString()

Argument Type

Return Type

Description

hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) with an XML header but without whitespace formatting. The hash must have only one top-level key or an exception will be thrown. The optional second argument may be given to specify the output string encoding, otherwise UTF-8 will be used.

string $top_element, hash $data, [string $encoding]

string

Serializes the Qore hash to an XML string (see XML Integration for more information) with an XML header but without whitespace formatting. The first parameter will be the top-level XML element. The optional third argument may be given to specify the output string encoding, otherwise UTF-8 will be used.


Table 3.463. Exceptions Thrown by makeXMLString()

err

desc

MAKE-XML-ERROR

An error occurred serializing the Qore data to an XML string.

MAKE-XML-STRING-PARAMETER-EXCEPTION

Incorrect arguments passed.


3.14.23. parseXML()

Synopsis

Parses an XML string and returns a Qore hash structure. If duplicate, out-of-order XML elements are found in the input string, they are deserialized to Qore hash elements with the same name as the XML element but including a caret "^" and a numeric prefix to maintain the same key order in the Qore hash as in the input XML string.

This function should only be used when it is important to maintain the XML element order in the resulting Qore data structure (for example, when the data must be re-serialized to an XML string and the element order within a subelement must be maintained), for example, when parsing and reserializing an OSX property list in XML format. Otherwise parseXMLAsData() should be used instead.

Prototype

parseXML(string $xml_string) returns hash

parseXML(string $xml_string, string $encoding) returns hash

parseXML() returns nothing (RT_NOOP)

Example
$hash = parseXML($xml);

Table 3.464. Arguments and Return Values for parseXML()

Argument Type

Return Type

Description

string $xml_string, [string $encoding]

hash

Parses an XML string and returns a Qore hash structure. If no second argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.465. Exceptions Thrown by parseXML()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.


3.14.24. parseXMLAsData()

Synopsis

Parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list) and returns a Qore hash structure.

Note that data deserialized with this function may not be reserialized to an identical XML string to the input due to the fact that duplicate, out-of-order XML elements are collapsed into lists in the resulting Qore hash, thereby losing the order in the original XML string.

For a similar function preserving the order of keys in the XML in the resulting Qore hash by generating Qore hash element names with numeric suffixes, see parseXML().

Prototype

parseXMLAsData(string $xml_string) returns hash

parseXMLAsData(string $xml_string, string $encoding) returns hash

parseXMLAsData() returns nothing (RT_NOOP)

Example
$hash = parseXMLAsData($xml);

Table 3.466. Arguments and Return Values for parseXMLAsData()

Argument Type

Return Type

Description

string $xml_string, [string $encoding]

hash

Parses an XML string and returns a Qore hash structure. If no second argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.467. Exceptions Thrown by parseXMLAsData()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.


3.14.25. parseXMLAsDataWithRelaxNG()

Synopsis

Parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list), validates the XML string against a RelaxNG schema string, and returns a Qore hash structure. If any errors occur parsing the RelaxNG schema string, parsing the XML string, or validating the XML against the XSD, exceptions are thrown. If no encoding string argument is passed, then all strings in the resulting hash will be in UTF-8 encoding regardless of the input encoding of the XML string.

Please note that data deserialized with this function may not be reserialized to an identical XML string to the input due to the fact that duplicate, out-of-order XML elements are collapsed into lists in the resulting Qore hash, thereby losing the order in the original XML string.

For a similar function preserving the order of keys in the XML in the resulting Qore hash by generating Qore hash element names with numeric suffixes, see parseXMLWithRelaxNG(). See also parseXMLAsDataWithSchema() and parseXMLWithSchema().

The availability of this function depends on the presence of libxml2's xmlTextReaderRelaxNGSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHRELAXNG before running this function. See Library Option Constants for a list of all option constants.

Prototype

parseXMLAsDataWithRelaxNG(string $xml_string, string $relaxng_string) returns hash

parseXMLAsDataWithRelaxNG(string $xml_string, string $relaxng_string, string $encoding) returns hash

Example
$hash = parseXMLAsDataWithRelaxNG($xml, $rng);

Table 3.468. Arguments and Return Values for parseXMLAsDataWithRelaxNG()

Argument Type

Return Type

Description

string $xml_string, string $relaxng_string, [string $encoding]

hash

Parses an XML string (1st argument), validates against the RelaxNG string (2nd argument), and returns a Qore hash structure. If no third argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.469. Exceptions Thrown by parseXMLAsDataWithRelaxNG()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.

PARSE-XML-AS-DATA-WITH-RELAXNG-ERROR

Invalid arguments passed to the function.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHRELAXNG before calling this function.


3.14.26. parseXMLAsDataWithSchema()

Synopsis

Parses an XML string as data (does not preserve hash order with out-of-order duplicate keys: collapses all to the same list), validates the XML string against an XSD schema string, and returns a Qore hash structure. If any errors occur parsing the XSD string, parsing the XML string, or validating the XML against the XSD, exceptions are thrown. If no encoding string argument is passed, then all strings in the resulting hash will be in UTF-8 encoding regardless of the input encoding of the XML string.

Please note that data deserialized with this function may not be reserialized to an identical XML string to the input due to the fact that duplicate, out-of-order XML elements are collapsed into lists in the resulting Qore hash, thereby losing the order in the original XML string.

For a similar function preserving the order of keys in the XML in the resulting Qore hash by generating Qore hash element names with numeric suffixes, see parseXMLWithSchema(). See also parseXMLAsDataWithRelaxNG() and parseXMLWithRelaxNG().

The availability of this function depends on the presence of libxml2's xmlTextReaderSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHSCHEMA before running this function. See Library Option Constants for a list of all option constants.

Prototype

parseXMLAsDataWithSchema(string $xml_string, string $xsd) returns hash

parseXMLAsDataWithSchema(string $xml_string, string $xsd, string $encoding) returns hash

Example
$hash = parseXMLAsDataWithSchema($xml, $xsd);

Table 3.470. Arguments and Return Values for parseXMLAsDataWithSchema()

Argument Type

Return Type

Description

string $xml_string, string $xsd, [string $encoding]

hash

Parses an XML string (1st argument), validates against the XSD string (2nd argument), and returns a Qore hash structure. If no third argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.471. Exceptions Thrown by parseXMLAsDataWithSchema()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.

PARSE-XML-WITH-SCHEMA-ERROR

Invalid arguments passed to the function.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHSCHEMA before calling this function.


3.14.27. parseXMLRPCCall()

Synopsis

Deserializies an XML-RPC call string, returning a Qore data structure representing the call information.

Prototype

parseXMLRPCCall(string $xml_string) returns hash

parseXMLRPCCall(string $xml_string, string $encoding) returns hash

parseXMLRPCCall() returns nothing (RT_NOOP)

Example
$hash = parseXMLRPCCall($xml);

Table 3.472. Arguments and Return Values for parseXMLRPCCall()

Argument Type

Return Type

Description

string $xml_string, [string $encoding]

hash

Deserializies an XML-RPC call string, returning a Qore data structure representing the call information. The hash will have the following keys: methodName, params. If no second argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.473. Exceptions Thrown by parseXMLRPCCall()

err

desc

PARSE-XMLRPC-CALL-ERROR

Error parsing the XML-RPC call string.

PARSE-XMLRPC-VALUE-ERROR

Error parsing an XML-RPC value node.


3.14.28. parseXMLRPCResponse()

Synopsis

Deserializies an XML-RPC response string, returning a Qore data structure representing the response information.

Prototype

parseXMLRPCResponse(string $xml_string) returns hash

parseXMLRPCResponse(string $xml_string, string $encoding) returns hash

parseXMLRPCResponse() returns nothing (RT_NOOP)

Example
$hash = parseXMLRPCResponse($xml);

Table 3.474. Arguments and Return Values for parseXMLRPCResponse()

Argument Type

Return Type

Description

string $xml_string, [string $encoding]

hash

Deserializies an XML-RPC response string, returning a Qore data structure representing the response information. The hash will have either a "fault" or a "params" key, depending on if it's a fault response or a non-fault response. If no second argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.475. Exceptions Thrown by parseXMLRPCResponse()

err

desc

PARSE-XMLRPC-RESPONSE-ERROR

Error parsing the XML-RPC response string.

PARSE-XMLRPC-VALUE-ERROR

Error parsing an XML-RPC value node.


3.14.29. parseXMLRPCValue()

Synopsis

Deserializies an XML-RPC value tree, returning a Qore data structure representing the information.

Prototype

parseXMLRPCValue(string $xml_string) returns hash

parseXMLRPCValue(string $xml_string, string $encoding) returns hash

parseXMLRPCValue() returns nothing (RT_NOOP)

Example
my any $data = parseXMLRPCValue($xml);

Table 3.476. Arguments and Return Values for parseXMLRPCValue()

Argument Type

Return Type

Description

string $xml_string, [string $encoding]

any

Deserializies an XML-RPC value string, returning Qore data representing the value data. If no second argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.477. Exceptions Thrown by parseXMLRPCValue()

err

desc

PARSE-XMLRPC-VALUE-ERROR

Error parsing an XML-RPC value node.


3.14.30. parseXMLWithRelaxNG()

Synopsis

Parses an XML string, validates the XML string against a RelaxNG schema string, and returns a Qore hash structure. If any errors occur parsing the RelaxNG string, parsing the XML string, or validating the XML against the RelaxNG schema, exceptions are thrown. If no encoding string argument is passed, then all strings in the resulting hash will be in UTF-8 encoding regardless of the input encoding of the XML string.

If duplicate, out-of-order XML elements are found in the input string, they are deserialized to Qore hash elements with the same name as the XML element but including a caret "^" and a numeric prefix to maintain the same key order in the Qore hash as in the input XML string.

This function should only be used when it is important to maintain the XML element order in the resulting Qore data structure (for example, when the data must be re-serialized to an XML string and the element order within a subelement must be maintained), for example, when parsing and reserializing an OSX property list in XML format. Otherwise parseXMLAsDataWithRelaxNG() should be used instead.

See also parseXMLWithSchema() and parseXMLAsDataWithSchema().

The availability of this function depends on the presence of libxml2's xmlTextReaderRelaxNGSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHRELAXNG before running this function. See Library Option Constants for a list of all option constants.

Prototype

parseXMLWithRelaxNG(string $xml_string, string $relaxng_string) returns hash

parseXMLWithRelaxNG(string $xml_string, string $relaxng_string, string $encoding) returns hash

Example
$hash = parseXMLWithRelaxNG($xml, $rng);

Table 3.478. Arguments and Return Values for parseXMLWithRelaxNG()

Argument Type

Return Type

Description

string $xml_string, string $relaxng_string, [string $encoding]

hash

Parses an XML string (1st argument), validates against the RelaxNG schema string (2nd argument), and returns a Qore hash structure. If no third argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.479. Exceptions Thrown by parseXMLWithRelaxNG()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.

PARSE-XML-WITH-RELAXNG-ERROR

Invalid arguments passed to the function.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHRELAXNG before calling this function.


3.14.31. parseXMLWithSchema()

Synopsis

Parses an XML string, validates the XML string against an XSD schema string, and returns a Qore hash structure. If any errors occur parsing the XSD string, parsing the XML string, or validating the XML against the XSD, exceptions are thrown. If no encoding string argument is passed, then all strings in the resulting hash will be in UTF-8 encoding regardless of the input encoding of the XML string.

If duplicate, out-of-order XML elements are found in the input string, they are deserialized to Qore hash elements with the same name as the XML element but including a caret "^" and a numeric prefix to maintain the same key order in the Qore hash as in the input XML string.

This function should only be used when it is important to maintain the XML element order in the resulting Qore data structure (for example, when the data must be re-serialized to an XML string and the element order within a subelement must be maintained), for example, when parsing and reserializing an OSX property list in XML format. Otherwise parseXMLAsDataWithSchema() should be used instead.

See also parseXMLWithRelaxNG() and parseXMLAsDataWithRelaxNG().

The availability of this function depends on the presence of libxml2's xmlTextReaderSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHSCHEMA before running this function. See Library Option Constants for a list of all option constants.

Prototype

parseXMLWithSchema(string $xml_string, string $xsd) returns hash

parseXMLWithSchema(string $xml_string, string $xsd, string $encoding) returns hash

Example
$hash = parseXMLWithSchema($xml, $xsd);

Table 3.480. Arguments and Return Values for parseXMLWithSchema()

Argument Type

Return Type

Description

string $xml_string, string $xsd, [string $encoding]

hash

Parses an XML string (1st argument), validates against the XSD string (2nd argument), and returns a Qore hash structure. If no third argument is given, specifying the output string encoding, all strings will have the default encoding.


Table 3.481. Exceptions Thrown by parseXMLWithSchema()

err

desc

PARSE-XML-EXCEPTION

Error parsing the XML string.

PARSE-XML-WITH-SCHEMA-ERROR

Invalid arguments passed to the function.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHSCHEMA before calling this function.


3.15. JSON Functions

JSON (JavaScript Object Notation) functions allow serializing and deserializing between JSON strings and qore data structures. There are also functions for JSONRPC support for easier integration with JavaScript clients; see below for details.

3.15.1. makeFormattedJSONRPC11ErrorString()

Synopsis

Creates a JSON-RPC 1.1 error response string from the parameters passed, formatted with line breaks for easier readability. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The first code argument must be an integer between 100 and 999 (inclusive). The last argument can be of any Qore type (or complex data structure).

Prototype

makeFormattedJSONRPC11ErrorString(softint $code, string $error, any $id, any $error_response) returns string

Example
$json = makeFormattedJSONRPC11ErrorString(200, $msg, $id, $error);

Table 3.482. Arguments and Return Values for makeFormattedJSONRPC11ErrorString()

Argument Type

Return Type

Description

softint $code, string $error, [any $id, any $error_response]

string

Creates a JSON-RPC 1.1 error response string from the parameters passed, formatted with line breaks for easier readability.


Table 3.483. Exceptions Thrown by makeFormattedJSONRPC11ErrorString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.

MAKE-JSONRPC11-ERROR-STRING-ERROR

Invalid argument to method.


3.15.2. makeFormattedJSONRPCErrorString()

Synopsis

Creates a generic JSON-RPC error response string from the parameters passed, formatted with line breaks for easier readability. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeFormattedJSONRPCErrorString(any $json_version, any $id, any $response_msg) returns string

Example
$json = makeFormattedJSONRPCErrorString("1.1", $id, $response);

Table 3.484. Arguments and Return Values for makeFormattedJSONRPCErrorString()

Argument Type

Return Type

Description

any $json_version, any $id, any $response_msg

string

Creates a generic JSON-RPC error response string from the parameters passed, formatted with line breaks for easier readability.


Table 3.485. Exceptions Thrown by makeFormattedJSONRPCErrorString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.3. makeFormattedJSONRPCRequestString()

Synopsis

Creates a JSON-RPC request string from the parameters passed, formatted with line breaks for easier readability. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeFormattedJSONRPCRequestString(string $method_name, any $json_version, any $id, any $request_msg) returns string

Example
$json = makeFormattedJSONRPCRequestString("method_name", "1.1", $id, $request_data);

Table 3.486. Arguments and Return Values for makeFormattedJSONRPCRequestString()

Argument Type

Return Type

Description

string $method_name, any $json_version, any $id, any $request_msg

string

Creates a JSON-RPC request string from the parameters passed, formatted with line breaks for easier readability.


Table 3.487. Exceptions Thrown by makeFormattedJSONRPCRequestString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.

MAKE-JSONRPC-REQUEST-STRING-ERROR

missing method name as first parameter.


3.15.4. makeFormattedJSONRPCResponseString()

Synopsis

Creates a JSON-RPC response string from the parameters passed, formatted with line breaks for easier readability. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeFormattedJSONRPCResponseString(any $json_version, any $id, any $response_msg) returns string

Example
$json = makeFormattedJSONRPCResponseString("1.1", $id, $response);

Table 3.488. Arguments and Return Values for makeFormattedJSONRPCResponseString()

Argument Type

Return Type

Description

any $json_version, any $id, any $response_msg

string

Creates a JSON-RPC response string from the parameters passed, formatted with line breaks for easier readability.


Table 3.489. Exceptions Thrown by makeFormattedJSONRPCResponseString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.5. makeFormattedJSONString()

Synopsis

Serializes qore data into a JSON string, formatted with line breaks for easier readability. By default the string produced will be in UTF-8 encoding, but this can be overridden by the second argument.

Prototype

makeFormattedJSONString(any $data, string $encoding) returns string

makeFormattedJSONString(any $data) returns string

Example
$json = makeFormattedJSONString($value);

Table 3.490. Arguments and Return Values for makeFormattedJSONString()

Argument Type

Return Type

Description

any $data, [string $encoding]

string

Serializes qore data into a JSON string, formatted with line breaks for easier readability.


Table 3.491. Exceptions Thrown by makeFormattedJSONString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.6. makeJSONRPC11ErrorString()

Synopsis

Creates a JSON-RPC 1.1 error response string from the parameters passed, without any line breaks. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeJSONRPC11ErrorString(softint $code, string $error, any $id, any $error_response) returns string

Example
$json = makeJSONRPC11ErrorString(200, $msg, $id, $error);

Table 3.492. Arguments and Return Values for makeJSONRPC11ErrorString()

Argument Type

Return Type

Description

softint $code, string $error, any $id, any $error_response

string

Creates a JSON-RPC 1.1 error response string from the parameters passed, formatted with line breaks for easier readability.


Table 3.493. Exceptions Thrown by makeJSONRPC11ErrorString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.

MAKE-JSONRPC11-ERROR-STRING-ERROR

Invalid argument to method.


3.15.7. makeJSONRPCErrorString()

Synopsis

Creates a generic JSON-RPC error response string from the parameters passed, without any line breaks. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeJSONRPCErrorString(any $json_version, any $id, any $response_msg) returns string

Example
$json = makeJSONRPCErrorString("1.1", $id, $response);

Table 3.494. Arguments and Return Values for makeJSONRPCErrorString()

Argument Type

Return Type

Description

any $json_version, any $id, any $response_msg

string

Creates a generic JSON-RPC error response string from the parameters passed, without any line breaks.


Table 3.495. Exceptions Thrown by makeJSONRPCErrorString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.8. makeJSONRPCRequestString()

Synopsis

Creates a JSON-RPC request string from the parameters passed, without any line breaks. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeJSONRPCRequestString(string $method_name, any $json_version, any $id, any $request_msg) returns string

Example
$json = makeJSONRPCRequestString("method_name", "1.1", $id, $request_data);

Table 3.496. Arguments and Return Values for makeJSONRPCRequestString()

Argument Type

Return Type

Description

string $method_name, any $json_version, any $id, any $request_msg

string

Creates a JSON-RPC request string from the parameters passed, without any line breaks.


Table 3.497. Exceptions Thrown by makeJSONRPCRequestString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.

MAKE-JSONRPC-REQUEST-STRING-ERROR

missing method name as first parameter.


3.15.9. makeJSONRPCResponseString()

Synopsis

Creates a JSON-RPC response string from the parameters passed, without any line breaks. To follow JSON-RPC specifications, the generated string will always be in UTF-8 encoding. The last argument can be of any qore type (or complex data structure).

Prototype

makeJSONRPCResponseString(any $json_version, any $id, any $response_msg) returns string

Example
$json = makeJSONRPCResponseString("1.1", $id, $response);

Table 3.498. Arguments and Return Values for makeJSONRPCResponseString()

Argument Type

Return Type

Description

any $json_version, any $id, any $response_msg

string

Creates a JSON-RPC response string from the parameters passed, without any line breaks.


Table 3.499. Exceptions Thrown by makeJSONRPCResponseString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.10. makeJSONString()

Synopsis

Serializes qore data into a JSON string, without any line breaks. By default the string produced will be in UTF-8 encoding, but this can be overridden by the second argument.

Prototype

makeJSONString(any $data, string $encoding) returns string

makeJSONString(any $data) returns string

Example
$json = makeJSONString($value);

Table 3.500. Arguments and Return Values for makeJSONString()

Argument Type

Return Type

Description

any $data, [string $encoding]

string

Serializes qore data into a JSON string, without any line breaks.


Table 3.501. Exceptions Thrown by makeJSONString()

err

desc

JSON-SERIALIZATION-ERROR

Error serializing to JSON string.


3.15.11. parseJSON()

Synopsis

Parses a JSON string and returns the corresponding qore data structure.

Prototype

parseJSON(string $json_string) returns any

parseJSON() returns nothing (RT_NOOP)

Example
$data = parseJSON($json_string);

Table 3.502. Arguments and Return Values for parseJSON()

Argument Type

Return Type

Description

string $json_string

any

Parses a JSON string and returns the corresponding qore data structure.


Table 3.503. Exceptions Thrown by parseJSON()

err

desc

JSON-PARSE-ERROR

error parsing JSON string.


3.16. Debug Functions

3.17. String Formatting

This is the standard "printf" format string.

There are three types of objects in the format string:

  • Plain characters, which are copied as-is to the output string

  • Escape characters, which are converted and copied to the output string

  • Format specifications for arguments to be included in the output string, which are preceded by the percent sign "%" as follows:

After the "%" sign, there can be zero or more flags as follows:

Table 3.504. Printf Formatting Flags

Flag

Description

-

left-justify the field

+

include the sign for the number (+ or -)

0

use zero left padding rather than space padding

<space>

use space padding


Then a field width specifier can be given as a string of digits specifying the length of the field. With "field" functions (function names preceded by "f_"), these width specifiers are hard limits; that is; arguments longer than the width specified are limited to the specified width.

For floating-point arguments, a precision specifier may be given by including a period "." and another digit string, which indicates the number of digits to appear after the decimal point.

Then the format character is given as follows:

Table 3.505. Printf Formatting Characters

Character

Description

s

string

d

Integer, output in base 10 format

f

Floating point value

n

Any Qore value, formatted as a string, without any line breaks

N

Any Qore value, formatted as a string, with line breaks and whitespace formatting for complex objects

x

Integer, output in base 16 (hexadecimal) format with lower-case a-f

X

Integer, output in base 16 (hexadecimal) format with upper-case A-F


Table 3.506. String Escape Characters

Character

Description

\n

a newline character

\r

a carriage-return character

\t

a tab character

\b

a backspace character

\f

a form-feed character

\num

an 8-bit character whose value is the 1, 2, or 3 digit octal number num

\"

a double-quote character


Chapter 4. System Namespaces and Class Library

Table 4.1. Qore Class List

Name

Description

File

For reading and writing files.

Dir

For handling of directories, listing files, and creating/removing subdirectories.

FtpClient

For communicating with FTP servers.

GetOpt

For processing command-line options.

Program

For parsing and executing application-embedded or user-supplied logic.

Socket

For communication with IPv4 sockets with and without TSL/SSL encryption.

TermIOS

Used when getting or setting terminal settings.

HTTPClient

For communication with HTTP servers with and without TSL/SSL encryption.

XmlRpclient

For communication using the XML-RPC protocol with and without TSL/SSL encryption.

JsonRpclient

For communication using the JSON-RPC protocol with and without TSL/SSL encryption.

SSLCertificate

For working with X.509 certificates.

SSLPrivateKey

For working with private key data.

SQL::Datasource

For working with databases; provides the user interface to qore DBI drivers.

SQL::DatasourcePool

Provides transparent per-thread, per-transaction Datasource connection pooling.

Thread::AbstractSmartLock

The abstract base class for locks that support the internal API for use with the Condition class.

Thread::AutoGate

A helper class for the Gate class for exception-safe Gate handling.

Thread::AutoLock

A helper class for the Mutex class for exception-safe Mutex handling.

Thread::AutoReadLock

A helper class for the RWLock class for exception-safe read lock handling.

Thread::AutoWriteLock

A helper class for the RWLock class for exception-safe write lock handling.

Thread::Condition

For blocking a thread until a condition becomes true.

Thread::Counter

For blocking a thread until a counter becomes zero.

Thread::Gate

A reentrant thread lock.

Thread::Mutex

A simple thread lock.

Thread::Queue

A blocking, thread-safe queue class, useful for message passing (can also be used as a stack).

Thread::RMutex

DEPRECATED: A reentrant thread lock; use Gate instead.

Thread::RWLock

A read-write thread lock.

Thread::Sequence

A thread-safe integral counter.

Xml::XmlDoc

For analyzing and manipulating XML documents.

Xml::XmlNode

Gives information about XML data in an XML document.

Xml::XmlReader

For parsing or iterating through the elements of an XML document.


4.1. Qore Constants

The following constants are defined in the Qore namespace.

Table 4.2. Build and Version Constants

Key

Type

Description

PlatformOS

string

The operating system used to build the Qore library.

PlatformCPU

string

The CPU used as a target for the Qore library build.

VersionString

string

The full version string for this version of the Qore library.

VersionMajor

int

An integer giving the Qore library's major version number.

VersionMinor

int

An integer giving the Qore library's minor version number.

VersionSub

int

An integer giving the Qore library's release version number.

Build

int

An integer giving the Qore library's subversion revision number.

BuildHost

string

A string giving information about the host used to compile the Qore library.

Compiler

string

The compiler used to build the Qore library.

CFLAGS

string

The compiler flags used to compile the Qore library.

LDFLAGS

string

The linker flags used to link the Qore library.


Table 4.3. Machine Constants

Key

Type

Description

MACHINE_MSB

bool

If True the machine stores memory with MSB byte order, False if it uses LSB byte order.


Table 4.4. Library Options

Name

Type

Description

HAVE_ATOMIC_OPERATIONS

bool

Indicates if the Qore library supports fast atomic reference counting. Note that if this constant is False, atomic operations are supported by mutexes and are therefore slower than with native atomic reference counting operations.

HAVE_STACK_GUARD

bool

Indicates if protection against stack overruns is provided

HAVE_RUNTIME_THREAD_STACK_TRACE

bool

Indicates if active thread stack tracing has been enabled as a debugging option and if the getAllThreadCallStacks() function is available.

HAVE_ROUND

bool

Indicates if the round() function is available.

HAVE_TIMEGM

bool

Always True (as of qore 0.8.0+): indicates that the timegm() function is available.

HAVE_SETEUID

bool

Indicates if the seteuid() function is available.

HAVE_SETEGID

bool

Indicates if the setegid() function is available.

HAVE_PARSEXMLWITHRELAXNG

bool

Indicates if parseXMLWithRelaxNG() and XmlReader::relaxNGValidate() are available.

HAVE_PARSEXMLWITHSCHEMA

bool

Indicates if parseXMLWithSchema() and XmlReader::schemaValidate() are available.

HAVE_SHA224

bool

Indicates if the openssl library used to build the qore library supported the SHA224 algorithm and therefore if the SHA224() and SHA224_bin() functions are available.

HAVE_SHA256

bool

Indicates if the openssl library used to build the qore library supported the SHA256 algorithm and therefore if the SHA256() and SHA256_bin() functions are available.

HAVE_SHA384

bool

Indicates if the openssl library used to build the qore library supported the SHA384 algorithm and therefore if the SHA384() and SHA384_bin() functions are available.

HAVE_SHA512

bool

Indicates if the openssl library used to build the qore library supported the SHA512 algorithm and therefore if the SHA512() and SHA512_bin() functions are available.

HAVE_MDC2

bool

Indicates if the openssl library used to build the qore library supported the MDC2 algorithm and therefore if the MDC2() and MDC2_bin() functions are available.

HAVE_RC5

bool

Indicates if the openssl library used to build the qore library supported the RC5 encryption algorithm and therefore if the rc5_encrypt_cbc(), rc5_decrypt_cbc() and rc5_encrypt_cbc_to_string() functions are available.

HAVE_MD2

bool

Indicates if the openssl library used to build the qore library supported the MD2 algorithm and therefore if the MD2() and MD2_bin() functions are available.


Table 4.5. Boolean Constants in the Qore Namespace

Name

Type

Description

True

bool

True

False

bool

False


Table 4.6. I/O Constants in the Qore Namespace

Name

Type

Description

stdin

File Object

Standard input File object.

stdout

File Object

Standard output File object.

stderr

File Object

Standard error File object.


Table 4.7. Warning Constants

Name

Type

Description

WARN_NONE

int

No warnings are enabled with this constant

WARN_WARNING_MASK_UNCHANGED

int

This warning means that the embedded code tried to change the warning mask, but it was locked, so the warning mask was actually unchanged

WARN_DUPLICATE_LOCAL_VARS

int

Indicates that a local variable was redeclared with the same name in the same local scope

WARN_UNKNOWN_WARNING

int

Indicates that the embedded code tried to enable or disable an unknown warning

WARN_UNDECLARED_VAR

int

Indicates that the embedded code referenced an undeclared variable that will be assumed to be a global variable

WARN_DUPLICATE_GLOBAL_VARS

int

Indicates that the embedded code has declared the same global variable more than once

WARN_UNREACHABLE_CODE

int

Indicates that code cannot be reached (for example; code in the same local block after an unconditional return or thread_exit statement)

WARN_NONEXISTENT_METHOD_CALL

int

Indicates that the embedded code is calling an unknown method in a class; this may be vaild if the calling method is only called from a base class that actually implements the method

WARN_INVALID_OPERATION

int

Indicates that the embedded code performs some operation that is guaranteed to produce no result (for example, using the [] operator on an integer value)

WARN_ALL

int

Enables all warnings


Table 4.8. Event Constants

Name

Value

Description

EVENT_PACKET_READ

1

Raised when a network packet is received.

EVENT_PACKET_SENT

2

Raised when a network packet is sent.

EVENT_HTTP_CONTENT_LENGTH

3

Raised when the HTTP "Content-Length" header is received.

EVENT_HTTP_CHUNKED_START

4

Raised when HTTP chunked data is about to be received.

EVENT_HTTP_CHUNKED_END

5

Raised when all HTTP chunked data has been received.

EVENT_HTTP_REDIRECT

6

Raised when an HTTP redirect message is received.

EVENT_CHANNEL_CLOSED

7

Raised when a socket is closed.

EVENT_DELETED

8

Raised when the object being monitored is deleted.

EVENT_FTP_SEND_MESSAGE

9

Raised immediately before an FTP control message is sent.

EVENT_FTP_MESSAGE_RECEIVED

10

Raised when an FTP reply is received on the control channel.

EVENT_HOSTNAME_LOOKUP

11

Raised when a hostname lookup is attempted.

EVENT_HOSTNAME_RESOLVED

12

Raised when a hostname lookup is resolved.

EVENT_HTTP_SEND_MESSAGE

13

Raised when an HTTP message is sent.

EVENT_HTTP_MESSAGE_RECEIVED

14

Raised when an HTTP message is received.

EVENT_HTTP_FOOTERS_RECEIVED

15

Raised when HTTP footers are received.

EVENT_HTTP_CHUNKED_DATA_RECEIVED

16

Raised when a block of HTTP chunked data is received.

EVENT_HTTP_CHUNK_SIZE

17

Raised when the next chunk size for HTTP chunked data is known.

EVENT_CONNECTING

18

Raised right before a socket connection attempt is made.

EVENT_CONNECTED

19

Raised when the socket connection has been established.

EVENT_START_SSL

20

Raised when socket SSL negotiation starts.

EVENT_SSL_ESTABLISHED

21

Raised when SSL communication has been negotiated and established.

EVENT_OPEN_FILE

22

Raised right before a file is opened.

EVENT_FILE_OPENED

23

Raised when a file has been successfully opened.

EVENT_DATA_READ

24

Raised when data has been read from a file.

EVENT_DATA_WRITTEN

25

Raised when data has been written to a file.

EVENT_MAP

Event Map Hash

This constant is a hash that maps event numbers to string descriptions as described in this table.


Table 4.9. Event Map Hash Constant

Key

String Value

EVENT_PACKET_READ ("1")

"PACKET_READ"

EVENT_PACKET_SENT ("2")

"PACKET_SENT"

EVENT_HTTP_CONTENT_LENGTH ("3")

"HTTP_CONTENT_LENGTH"

EVENT_HTTP_CHUNKED_START ("4")

"HTTP_CHUNKED_START"

EVENT_HTTP_CHUNKED_END ("5")

"HTTP_CHUNKED_END"

EVENT_HTTP_REDIRECT ("6")

"HTTP_REDIRECT"

EVENT_CHANNEL_CLOSED ("7")

"CHANNEL_CLOSED"

EVENT_DELETED ("8")

"DELETED"

EVENT_FTP_SEND_MESSAGE ("9")

"FTP_SEND_MESSAGE"

EVENT_FTP_MESSAGE_RECEIVED ("10")

"FTP_MESSAGE_RECEIVED"

EVENT_HOSTNAME_LOOKUP ("11")

"HOSTNAME_LOOKUP"

EVENT_HOSTNAME_RESOLVED ("12")

"HOSTNAME_RESOLVED"

EVENT_HTTP_SEND_MESSAGE ("13")

"HTTP_SEND_MESSAGE"

EVENT_HTTP_MESSAGE_RECEIVED ("14")

"HTTP_MESSAGE_RECEIVED"

EVENT_HTTP_FOOTERS_RECEIVED ("15")

"HTTP_FOOTERS_RECEIVED"

EVENT_HTTP_CHUNKED_DATA_RECEIVED ("16")

"HTTP_CHUNKED_DATA_RECEIVED"

EVENT_HTTP_CHUNK_SIZE ("17")

"HTTP_CHUNK_SIZE"

EVENT_CONNECTING ("18")

"CONNECTING"

EVENT_CONNECTED ("19")

"CONNECTED"

EVENT_START_SSL ("20")

"START_SSL"

EVENT_SSL_ESTABLISHED ("21")

"SSL_ESTABLISHED"

EVENT_OPEN_FILE ("22")

"OPEN_FILE"

EVENT_FILE_OPENED ("23")

"FILE_OPENED"

EVENT_DATA_READ ("24")

"DATA_READ"

EVENT_DATA_WRITTEN ("25")

"DATA_WRITTEN"


Table 4.10. Event Source Constants

Name

Description

SOURCE_SOCKET

For events raised from the Socket class.

SOURCE_HTTPCLIENT

For events raised from the HTTPClient class.

SOURCE_FTPCLIENT

For events raised from the FtpClient class.

SOURCE_FILE

For events raised from the File class.


Table 4.11. Network Address Type Constants

Name

Description

AF_INET

Designates an IPv4 network addresses.

AF_INET6

Designates an IPv6 network addresses.

AF_UNIX

Designates a local socket file name (interchangeable with AF_LOCAL).

AF_LOCAL

POSIX synonym for AF_UNIX; designates a local socket file name.


Table 4.12. Terminal Attributes Local Mode Constants

Name

Description

ECHOKE

visual erase for line kill

ECHOE

visually erase chars

ECHO

enable echoing

ECHONL

echo NL even if ECHO is off

ECHOPRT

visual erase mode for hardcopy

ISIG

enable signals INTR, QUIT, [D]SUSP

ICANON

canonicalize input lines

IEXTEN

enable DISCARD and LNEXT

TOSTOP

stop background jobs from output

FLUSHO

output being flushed (state)

PENDIN

retype pending input (state)

NOFLSH

don't flush after interrupt

ALTWERASE

use alternate WERASE algorithm (this constant is only available on some systems; do not use in portable programs)

EXTPROC

external processing (this constant is only available on some systems; do not use in portable programs)

NOKERNINFO

no kernel output from VSTATUS (this constant is only available on some systems; do not use in portable programs)


Table 4.13. Terminal Attributes Control Mode Constants

Name

Description

CSIZE

character size mask

CS5

5 bits (pseudo)

CS6

6 bits

CS7

7 bits

CS8

8 bits

CSTOPB

send 2 stop bits

CREAD

enable receiver

PARENB

parity enable

PARODD

odd parity, else even

HUPCL

hang up on last close

CLOCAL

ignore modem status lines

CCTS_OFLOW

CTS flow control of output (this constant is only available on some systems; do not use in portable programs)

CRTSCTS

same as CCTS_OFLOW (this constant is only available on some systems; do not use in portable programs)

CRTS_IFLOW

RTS flow control of input (this constant is only available on some systems; do not use in portable programs)

MDMBUF

flow control output via Carrier (this constant is only available on some systems; do not use in portable programs)


Table 4.14. Terminal Attributes Output Mode Constants

Name

Description

OPOST

enable following output processing

ONLCR

map NL to CR-NL (ala CRMOD)

OCRNL

map CR to NL

ONOCR

No CR output at column 0

ONLRET

NL performs CR function

OXTABS

expand tabs to spaces (this constant is only available on some systems; do not use in portable programs)

ONOEOT

discard EOT's ctrl-D on output (this constant is only available on some systems; do not use in portable programs)

OLCUC

translate lower case to upper case (this constant is only available on some systems; do not use in portable programs)


Table 4.15. Terminal Attributes Input Mode Constants

Name

Description

IGNBRK

ignore BREAK condition

BRKINT

map BREAK to SIGINTR

IGNPAR

ignore (discard) parity errors

PARMRK

mark parity and framing errors

INPCK

enable checking of parity errors

ISTRIP

strip 8th bit off chars

INLCR

map NL into CR

IGNCR

ignore CR

ICRNL

map CR to NL (ala CRMOD)

IXON

enable output flow control

IXOFF

enable input flow control

IXANY

any char will restart after stop

IMAXBEL

ring bell on input queue full

IUCLC

translate upper case to lower case (this constant is only available on some systems; do not use in portable programs)


Table 4.16. Terminal Attributes Control Character Constants

Name

Special Character

Default Value

VEOF

EOF

^D

VEOL

EOL

_POSIX_VDISABLE

VEOL2

EOL2

_POSIX_VDISABLE

VERASE

ERASE

^? `177'

VWERASE

WERASE

^W

VKILL

KILL

^U

VINTR

INTR

^C

VQUIT

QUIT

^\ `34'

VSUSP

SUSP

^Z

VSTART

START

^Q

VSTOP

STOP

^S

VLNEXT

LNEXT

^V

VMIN

n/a

1

VTIME

n/a

0

VREPRINT

REPRINT

^R (this constant is only available on some systems; do not use in portable programs)

VDSUSP

DSUSP

^Y (this constant is only available on some systems; do not use in portable programs)

VDISCARD

DISCARD

^O (this constant is only available on some systems; do not use in portable programs)

VSTATUS

n/a

^T (this constant is only available on some systems; do not use in portable programs)


The X509_VerificationReasons_Hash is a constant in the Qore namespace that maps verfication code strings (as returned from FtpClient::verifyPeerCertificate() and Socket::verifyPeerCertificate()) to textual descriptions.

Table 4.17. X506_VerificationReasons Hash

Key

Value

X509_V_OK

"OK

X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT

"Unable to get issuer certificate"

X509_V_ERR_UNABLE_TO_GET_CRL

"Unable to get certificate CRL"

X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE

"Unable to decrypt certificate's signature. This means that the actual signature value could not be determined rather than it not matching the expected value; this is only meaningful for RSA"

X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE

"Unable to decrypt CRL's signature"

X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY

"Unable to decode issuer public key (SubjectPublicKeyInfo)"

X509_V_ERR_CERT_SIGNATURE_FAILURE

"Certificate signature failure; the signature of the certificate is invalid"

X509_V_ERR_CRL_SIGNATURE_FAILURE

"CRL signature failure; the signature of the certificate is invalid"

X509_V_ERR_CERT_NOT_YET_VALID

"Certificate is not yet valid"

X509_V_ERR_CERT_HAS_EXPIRED

"Certificate has expired"

X509_V_ERR_CRL_NOT_YET_VALID

"CRL is not yet valid"

X509_V_ERR_CRL_HAS_EXPIRED

"CRL has expired"

X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD

"Format error in certificate's notBefore field (invalid time)"

X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD

"Format error in certificate's notAfter field (invalid time)"

X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD

"Format error in CRL's lastUpdate field (invalid time)"

X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD

"Format error in CRL's nextUpdate field (invalid time)"

X509_V_ERR_OUT_OF_MEM

"Out of memory error"

X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT

"Certificate is self-signed and cannot be found in the trusted list"

X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN

"Self signed certificate in certificate chain"

X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY

"Unable to get local issuer certificate. This normally means the list of trusted certificates is not complete"

X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE

"Unable to verify the first certificate"

X509_V_ERR_CERT_CHAIN_TOO_LONG

"Certificate chain too long"

X509_V_ERR_CERT_REVOKED

"Certificate has been revoked"

X509_V_ERR_INVALID_CA

"Invalid CA certificate"

X509_V_ERR_PATH_LENGTH_EXCEEDED

"The basicConstraints pathlength parameter has been exceeded"

X509_V_ERR_INVALID_PURPOSE

"The certificate cannot be used for the specified purpose"

X509_V_ERR_CERT_UNTRUSTED

"Root CA is not marked as trusted for the specified purpose"

X509_V_ERR_CERT_REJECTED

"Root CA is marked to reject the specified purpose"

X509_V_ERR_SUBJECT_ISSUER_MISMATCH

"The current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate"

X509_V_ERR_AKID_SKID_MISMATCH

"The current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier of the current certificate"

X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH

"Issuer name and serial number of candidate certificate do not match the authority key identifier of the current certificate"

X509_V_ERR_KEYUSAGE_NO_CERTSIGN

"The keyUsage extension does not permit certificate signing"

X509_V_ERR_APPLICATION_VERIFICATION

"Verification failure"


The following gives a list of signal constants that may be present in Qore. Signal constants and their values are system-dependent; only signals that the host system defines will be present in Qore, therefore not all of the signals in the following list will be present in any given version of Qore. All signal constants are integers.

Table 4.18. Signal Constants in the Qore Namespace

Name

Description

SIGHUP

Hangup signal.

SIGINT

Interrupt signal.

SIGQUIT

Quit signal.

SIGILL

Illegal instruction signal.

SIGTRAP

Trace trap signal.

SIGABRT

Abort signal.

SIGPOLL

Pollable event signal.

SIGIOT

Synonym for SIBABRT

SIGEMT

EMT instruction signal.

SIGFPE

Floating-point exception signal.

SIGKILL

Kill signal (cannot be caught)

SIGBUS

Bus error signal.

SIGSEGV

Segmentation violation signal.

SIGSYS

Bad argument to a system call.

SIGPIPE

Write on pipe with no reader (this signal is always ignored in Qore).

SIGALRM

Alarm clock signal.

SIGTERM

Software termination signal.

SIGURG

Urgent condition on I/O channel.

SIGSTOP

Sendable stop signal (not from tty).

SIGTSTP

Stop signal from tty.

SIGCONT

Continue a stopped process.

SIGCHLD

To parent on child stop or exit.

SIGTTIN

To reader's process group on background tty read.

SIGTTOU

To writer's process group on background tty write.

SIGIO

Input/Output possible signal.

SIGXCPU

Exceeded CPU time limit.

SIGXFSZ

Exceeded file size limit.

SIGVTALRM

Virtual time alarm signal.

SIGPROF

Profiling time alarm signal.

SIGWINCH

Window size changes signal.

SIGINFO

Information request signal.

SIGUSR1

User-defined signal 1.

SIGUSR2

User-defined signal 2.

SIGSTKFLT

Stack fault on coprocessor.

SIGCLD

Synonym for SIGCHLD on some systems.

SIGPWR

Power failure signal.

SIGLOST

Resource (ex: file lock) lost signal.

SIGWAITING

(Solaris) Waiting signal.

SIGLWP

(Solaris) Light-weight process (thread) signal.

SIGFREEZE

(Solaris) Checkpoint freeze signal.

SIGTHAW

(Solaris) Checkpoint freeze thaw signal.

SIGCANCEL

(Solaris) Cancel signal.

SIGXRES

(Solaris) Resource control exceeded.

SIGJVM1

(Solaris) Java virtual machine 1 signal.

SIGJVM2

(Solaris) Java virtual machine 2 signal.


There are two special system-specific constants mapping signal names to signal number and vice-versa as given in the following table.

Table 4.19. Signal Mapping Hash Constants in the Qore Namespace

Name

Description

SignalToName

A hash mapping signal numbers to signal names (ex: SignalToName."1" gives the signal name corresponding to signal number 1).

NameToSignal

A hash mapping signal names to signal numbers (ex: NameToSignal."SIGINT" gives the signal number corresponding to "SIGINT").


The Err namespace contains error constants, returned by the errno() function.

Table 4.20. Error Constants in the Err Namespace

Name

Type

Description

Err::*

int

System-dependent integer ERRNO constants (ex: ENOMEM, etc)


Table 4.21. Exception Constants in the Qore Namespace

Name

Type

Description

ET_System

string

Exception Type System: used for system exceptions.

ET_User

string

Exception Type User: used for user exceptions (thrown using the throw statement.

CT_User

int

Call Type User: used for user function/method calls in a call stack.

CT_Builtin

int

Call Type Builtin: used for builtin function/method calls in a call stack.

CT_NewThread

int

Call Type New Thread: used in a call stack when a new thread is started with the background expression.

CT_Rethrow

int

Call Type Rethrow: a marker for a rethrown exception in a call stack.


Table 4.22. Regular Expression Option Constants in the Qore Namespace

Name

Type and Value

Description

RE_Caseless

int: 1

Ignores case when matching regular expressions, equivalent to /i

RE_MultiLine

int: 2

makes start-of-line (^) or end-of-line ($) match after or before any newline in the subject string, equivalent to /m

RE_DotAll

int: 4

makes a dot (.) match a newline character, equivalent to /s

RE_Extended

int: 8

ignores whitespace characters and enables comments prefixed by #, equivalent to /x


4.2. Type Namespace

The Type namespace only has constant definitions for basic Qore datatypes in it. There are no class definitions in the Type namespace. The type() function returns values in the set of the following constants. All of the following constants have string values.

Table 4.23. Type Constant Definitions

Name

Value

Corresponding Type

Type::Boolean

"bool"

Boolean

Type::Int

"integer"

Integer

Type::String

"string"

String

Type::Float

"float"

Float

Type::Date

"data"

Date

Type::Binary

"binary"

Binary

Type::Hash

"hash"

Hash

Type::List

"list"

List

Type::Object

"object"

Object

Type::NullType

"NULL"

SQL NULL

Type::NothingType

"nothing"

NOTHING

Type::CallReference

"call reference"

call references

Type::Closure

"closure"

closures


4.3. File Class

Note: This class is not available with the PO_NO_FILESYSTEM parse option.

The File class allows Qore programs to read, write, and create files.

File objects can be created and/or opened with a specific character encoding, meaning that any string read from the file will be tagged with the file's character encoding, and any string data written to the file will be transparently converted to that character encoding before being written (if necessary). If no character encoding is specified, then the default Qore character encoding is assumed for the file.

This class supports posting events to a Queue. See Event Handling for more information.

The events raised by this object are listed in the following table:

Table 4.24. File Events

Name

Description

EVENT_DATA_READ

Raised when data is read from the file.

EVENT_DATA_WRITTEN

Raised when data is written to the file.

EVENT_CHANNEL_CLOSED

Raised when the file is closed.

EVENT_DELETED

Raised when the object being monitored is deleted.

EVENT_OPEN_FILE

Raised right before an attempt to open a file is made.

EVENT_FILE_OPENED

Raised when the file has been successfully opened.


Table 4.25. File Method Overview

Method

Except?

Description

File::constructor()

File::constructor(string $encoding)

N

Creates the object and optionally sets the file's character encoding.

File::destructor()

N

Closes the file if it is open and destroys the file object.

File::copy()

N

Creates a new file object with the same character encoding specification as the original, otherwise no other information is copied.

File::chown(softint $uid, softint $gid = -1) returns nothing

N

Changes the user and group owners of the file on the filesystem (if the current user has sufficient permission to do so).

File::close() returns int

N

Closes the file object

File::f_printf(string $fmt, ...) returns int

File::f_printf() returns int (RT_NOOP)

Y

Writes a formatted string to a file, enforces hard field limits.

File::f_vprintf(string $fmt, any $args) returns int

File::f_vprintf() returns int (RT_NOOP)

Y

Writes a formatted string to a file, where the second argument is the formatting argument list, enforces hard field limits.

File::getchar() returns any

N

Reads one character from the file; returns NOTHING

if no data can be read from the file.

File::getCharset() returns string

N

Returns the character encoding for the file

File::getLockInfo() returns hash

Y

Returns a hash of lock information.

File::getPos() returns int

N

Gets the current file position (in bytes)

File::getTerminalAttributes(TermIOS $termios) returns nothing

Y

Saves the current terminal attributes for the file in the TermIOS object passed; changes the object passed to reflect the terminal attributes as set for the file.

File::isDataAvailable(softint $timeout_ms) returns bool

File::isDataAvailable(date $timeout) returns bool

File::isDataAvailable() returns bool

Y

Returns true if there is data available for reading from the file within the timeout period.

File::lock(softint $type = F_RDLCK, softint $start = 0, softint $len = 0, softint $whence = SEEK_SET) returns int

Y

Attempts to lock the file according to the arguments passed, does not block.

File::lockBlocking(softint $type = F_RDLCK, softint $start = 0, softint $len = 0, softint $whence = SEEK_SET) returns nothing

Y

Attempts to lock the file according to the arguments passed, blocking.

File::open(string $path, softint $flags = O_RDONLY, softint $mode = 0666) returns int

File::open(string $path, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns int

Y

Opens a file in a particular mode, returns an error code on failure.

File::open2(string $path, softint $flags = O_RDONLY, softint $mode = 0666) returns nothing

File::open2(string $path, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns nothing

Y

Opens a file in a particular mode; throws an exception on failure.

File::printf(string $fmt, ...) returns int

File::printf() returns int (RT_NOOP)

Y

Writes a formatted string to a file.

File::read(softint $size) returns any

File::read(softint $size, softint $timeout_ms) returns any

File::read(softint $size, date $timeout) returns any

Y

Reads a certain number of bytes from the file within an optional timeout period and returns a string of the data read or NOTHING if no data can be read.

File::readBinary(softint $size) returns any

File::readBinary(softint $size, softint $timeout_ms) returns any

File::readBinary(softint $size, date $timeout) returns any

Y

Reads a certain number of bytes from the file within an optional timeout period and returns binary data or NOTHING if no data can be read.

File::readi1() returns any

Y

Reads a 1-byte signed integer from the file or NOTHING if no data can be read.

File::readi2() returns any

Y

Reads a 2-byte signed integer from the file in big-endian format or NOTHING if no data can be read.

File::readi4() returns any

Y

Reads a 4-byte signed integer from the file in big-endian format or NOTHING if no data can be read.

File::readi8() returns any

Y

Reads an 8-byte signed integer from the file in big-endian format or NOTHING if no data can be read.

File::readi2LSB() returns any

Y

Reads a 2-byte signed integer from the file in little-endian format or NOTHING if no data can be read.

File::readi4LSB() returns any

Y

Reads a 4-byte signed integer from the file in little-endian format or NOTHING if no data can be read.

File::readi8LSB() returns any

Y

Reads an 8-byte signed integer from the file in little-endian format or NOTHING if no data can be read.

File::readu1() returns any

Y

Reads a 1-byte unsigned integer from the file or NOTHING if no data can be read.

File::readu2() returns any

Y

Reads a 2-byte unsigned integer from the file in big-endian format or NOTHING if no data can be read.

File::readu4() returns any

Y

Reads a 4-byte unsigned integer from the file in big-endian format or NOTHING if no data can be read.

File::readu2LSB() returns any

Y

Reads a 2-byte unsigned integer from the file in little-endian format or NOTHING if no data can be read.

File::readu4LSB() returns any

Y

Reads a 4-byte unsigned integer from the file in little-endian format or NOTHING if no data can be read.

File::readLine() returns any

Y

Reads until an EOL marker is found and returns the string read or NOTHING if no data can be read.

File::setCharset() returns nothing

File::setCharset(string $encoding) returns nothing

N

Sets the character encoding for the file; if passed with no argument, the default encoding is set.

File::setPos(softint $pos = 0) returns int

N

Sets the current file position (in bytes).

File::setTerminalAttributes(softint $action = TCSANOW, TermIOS $termios) returns nothing

Y

Sets the current terminal attributes for the file from the TermIOS object passed; does not change the object passed.

File::sync() returns int

N

Flushes the file's buffer to disk.

File::vprintf(string $fmt, any $args) returns int

File::vprintf() returns int (RT_NOOP)

Y

Writes a formatted string to a file, where the second argument is the formatting argument list.

File::write(data $data) returns int

Y

Writes string or binary data to a file

File::writei1(softint $i = 0) returns int

Y

Writes a 1-byte integer to the file.

File::writei2(softint $i = 0) returns int

Y

Writes a 2-byte integer in big-endian format.

File::writei4(softint $i = 0) returns int

Y

Writes a 4-byte integer in big-endian format.

File::writei8(softint $i = 0) returns int

Y

Writes an 8-byte integer in big-endian format.

File::writei2LSB(softint $i = 0) returns int

Y

Writes a 2-byte integer in little-endian format.

File::writei4LSB(softint $i = 0) returns int

Y

Writes a 4-byte integer in little-endian format.

File::writei8LSB(softint $i = 0) returns int

Y

Writes an 8-byte integer in little-endian format.


Table 4.26. File Constants in the Qore Namespace

Name

Description

O_RDONLY

Open the file read-only.

O_WRONLY

Open the file write-only.

O_CREAT

Create the file if it doesn't exist.

O_APPEND

Open the file in append mode.

O_RDWR

Open for reading and writing.

O_TRUNC

Truncate the size to zero.


Table 4.27. File Locking Constants in the Qore Namespace

Name

Description

F_RDLCK

Use for read-only locking.

F_WRLCK

Use for exclusive write locking.

F_UNLCK

Use for unlocking a lock.


Table 4.28. File Seek Constants in the Qore Namespace

Name

Description

SEEK_SET

Indicates that the offset is from the start of the file.

SEEK_CUR

Indicates that the offset is from the current position in the file.

SEEK_END

Indicates that the offset is from the end of the file.


4.3.1. File::constructor()

Synopsis

Creates the File object. It accepts one optional argument that will set the default character encoding for the file (only affects reading and writing string data).

Prototype

File::constructor()

File::constructor(string $encoding)

Example
my File $f("ISO-8859-1"); # specify ISO-8859-1 encoding for the file

Table 4.29. Arguments for File::constructor()

Argument

Type

Description

encoding

string

The character encoding for the file. Any strings written to the file will be converted to this character encoding if necessary.


4.3.2. File::destructor()

Synopsis

Closes the file if it's open and destroys the File object.

Example
delete $f;
Events

EVENT_CHANNEL_CLOSED, EVENT_DELETED

4.3.3. File::copy()

Synopsis

Creates a new File object with the same character encoding specification as the original.

Example
my File $f1 = $f.copy();

4.3.4. File::chown()

Synopsis

Changes the file's user and group owner (if the user has sufficient permissions to do so).

Prototype

File::chown(softint $uid, softint $gid = -1) returns nothing

Example
$f.chown(0, 0);

Table 4.30. Arguments for File::chown()

Argument

Description

softint $uid

The user id of the user to change to; -1 means do not change uid.

softint $gid

The group id of the user to change to; -1 means do not change gid.


Table 4.31. Return Value for File::chown()

Return Type

Description

n/a

This method does not return a value; if an error occurs, an exception is thrown.


Table 4.32. Exceptions Thrown by File::chown()

err

desc

FILE-CHOWN-ERROR

File is not open or the chown operation failed.


4.3.5. File::close()

Synopsis

Closes the file object if it's open. Note that this is automatically called by File::destructor().

Prototype

File::close() returns int

Example
$f.close();
Events

EVENT_CHANNEL_CLOSED

Table 4.33. Return Value for File::close()

Return Type

Description

int

0 for success, -1 for an error (see errno() and strerror() for the error information)


4.3.6. File::f_printf()

Synopsis

Writes a formatted string to a file, enforces hard field limits (similar to the f_printf() function). See String Formatting for more information about the format string.

Prototype

File::f_printf(string $fmt, ...) returns int

File::f_printf() returns int (RT_NOOP)

Example
$f.f_printf("%5s\n", "long string"); # will print "long \n", respecting the 5-character field width

Table 4.34. Arguments for File::f_printf()

Argument

Description

string $fmt

The format string, see String Formatting for a specification.

...

The remainder of the arguments are arguments to the format string.


Table 4.35. Return Value for File::f_printf()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.36. Exceptions Thrown by File::f_printf()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.7. File::f_vprintf()

Synopsis

Writes a formatted string to a file, where the second argument is the formatting argument list, enforces hard field limits. See String Formatting for more information about the format string.

Prototype

File::f_vprintf(string $fmt, any $args) returns int

File::f_vprintf() returns int (RT_NOOP)

Example
$f.f_vprintf("%5s %3d\n", ("a long string", 5000)); # outputs "a lon 500", truncating output

Table 4.37. Arguments for File::f_vprintf()

Argument

Description

string $fmt

The format string, see String Formatting for a specification.

any $args

This single argument or list of arguments will be used as the argument list or the format string. If a single argument is passed instead of a list, it will be used as the first argument as if a list were passed.


Table 4.38. Return Value for File::f_vprintf()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.39. Exceptions Thrown by File::f_vprintf()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.8. File::getchar()

Synopsis

Reads one character from the file and returns it as a one-character string. Returns NOTHING if no data can be read from the file.

Prototype

File::getchar() returns any

Example
$char = $f.getchar();

Table 4.40. Return Value for File::getchar()

Return Type

Description

string or nothing

The single character read from the file or NOTHING if no data can be read from the file.


4.3.9. File::getCharset()

Synopsis

Returns the character encoding for the file.

Prototype

File::getCharset() returns string

Example
$encoding = $f.getCharset();

Table 4.41. Return Value for File::getCharset()

Return Type

Description

string

The character encoding for the file.


4.3.10. File::getLockInfo()

Synopsis

Returns a hash of lock information for the file. The hash contains the following keys: start, len, pid, type, whence. If no lock is set on the file, the key type has the value F_UNLCK.

Prototype

File::getLockInfo() returns hash

Example
my hash $hash = $f.getLockInfo();

Table 4.42. Return Value for File::getLockInfo()

Return Type

Description

hash

The hash contains the following keys: start, len, pid, type, whence. If no lock is set on the file, the key type has the value F_UNLCK.


Table 4.43. Exceptions Thrown by File::getLockInfo()

err

desc

FILE-LOCK-ERROR

File is not open or the fcntl operation failed.


4.3.11. File::getPos()

Synopsis

Gets the current file position as an integer giving the offset in bytes from the beginning of the file (starting from zero).

Prototype

File::getPos() returns int

Example
$pos = $f.getPos();

Table 4.44. Return Value for File::getPos()

Return Type

Description

int

The byte position in the file starting at 0.


4.3.12. File::getTerminalAttributes()

Synopsis

Saves the current terminal attributes for the file in the TermIOS object passed; changes the object passed to reflect the terminal attributes as set for the file. Do not pass a reference to the TermIOS object; pass the object itself.

Prototype

File::getTerminalAttributes(TermIOS $termios) returns nothing

Example
my TermIOS $termios();
stdin.getTerminalAttributes($termios);

Table 4.45. Arguments for File::getTerminalAttributes()

Argument

Description

TermIOS $termios

The method writes the current terminal attributes for the file to the object passed.


Table 4.46. Exceptions Thrown by File::getTerminalAttributes()

err

desc

FILE-OPERATION-ERROR

The file is not open.

TERMIOS-GET-ERROR

Error reading terminal attributes from the file descriptor.


4.3.13. File::isDataAvailable()

Synopsis

Returns True is data becomes available for reading on the file within a timeout period. With a timeout of zero (the default if no timeout value is passed), this method can be used for non-blocking polling the file for data. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear (ex: 25ms).

Prototype

File::isDataAvailable(softint $timeout_ms) returns bool

File::isDataAvailable(date $timeout) returns bool

File::isDataAvailable() returns bool

Example
my bool $b = $file.isDataAvailable(0); # returns True if data is available now

Table 4.47. Arguments for File::isDataAvailable()

Argument

Description

softint $timeout_ms

An optional timeout in milliseconds (1/1000 second).

date $timeout

An optional timeout respecint resolution to the millisecond (1/1000 second).

n/a

If no timeout is given, the method assumes a timeout of zero and returns immediately.


Table 4.48. Return Values for File::isDataAvailable()

Return Type

Description

bool

True if data becomes available for reading from the file within the timeout period, False if not.


Table 4.49. Exceptions Thrown by File::isDataAvailable()

err

desc

FILE-READ-ERROR

The file is not open.


4.3.14. File::lock()

Synopsis

Locks or unlocks a portion of the file or the entire file, for reading or writing, non-blocking. The file must be opened in the appropriate mode before this call or the call will fail with an exception. For a blocking version of this method, see File::lockBlocking().

Prototype

File::lock(softint $type = F_RDLCK, softint $start = 0, softint $len = 0, softint $whence = SEEK_SET) returns int

Example
# lock the entire file exclusively
$f.lock(F_WRLCK);

# lock a section of the file for reading, start byte 512, 2K range
$f.lock(F_RDLCK, 512, 2048);

# release all locks
$f.lock(F_UNLCK);

Table 4.50. Arguments for File::lock()

Argument

Description

softint $type = F_RDLCK

Type of lock (or unlock); see File locking constants.

softint $start = 0

Start byte for lock, 0 is the default (start of file).

softint $len = 0

Length in bytes for range to lock, 0 is the default (rest of file).

softint $whence = SEEK_SET

Indicates how the relative offset of the file should be calculated for the lock; see File seek constants.


Table 4.51. Return Value for File::lock()

Return Type

Description

int

Returns 0 for success, EACCES if the lock would block (only in the case that the lock would block is no exception thrown and EACCES returned).


Table 4.52. Exceptions Thrown by File::lock()

err

desc

FILE-LOCK-ERROR

File is not open, lock length is negative, or the fcntl operation failed.


4.3.15. File::lockBlocking()

Synopsis

Locks or unlocks a portion of the file or the entire file, for reading or writing, blocking. The file must be opened in the appropriate mode before this call or the call will fail with an exception. For a non-blocking version of this method, see File::lock().

Prototype

File::lockBlocking(softint $type = F_RDLCK, softint $start = 0, softint $len = 0, softint $whence = SEEK_SET) returns nothing

Example
# lock the entire file exclusively
$f.lockBlocking(F_WRLCK);

# lock a section of the file for reading, start byte 512, 2K range
$f.lockBlocking(F_RDLCK, 512, 2048);

# release all locks
$f.lockBlocking(F_UNLCK);

Table 4.53. Arguments for File::lockBlocking()

Argument

Description

softint $type = F_RDLCK

Type of lock (or unlock), see File locking constants.

softint $start = 0

Start byte for lock, 0 is the default (start of file).

softint $len = 0

Length in bytes for range to lock, 0 is the default (rest of file).

softint $whence = SEEK_SET

Indicates how the relative offset of the file should be calculated for the lock; see File seek constants.


Table 4.54. Return Value for File::lockBlocking()

Return Type

Description

n/a

This method does not return a value; exceptions are thrown if errors occur.


Table 4.55. Exceptions Thrown by File::lockBlocking()

err

desc

FILE-LOCK-ERROR

File is not open, lock length is negative, or the fcntl operation failed.


4.3.16. File::printf()

Synopsis

Writes a formatted string with soft field widths to the file. See File::f_printf() for a similar method that enforces field widths. See String Formatting for more information about the format string.

Prototype

File::printf(string $fmt, ...) returns int

File::printf() returns int (RT_NOOP)

Example
$f.printf("%5s\n", "hello there"); # outputs "hello there\n", exceeding field width
Events

EVENT_DATA_WRITTEN

Table 4.56. Arguments for File::printf()

Argument

Description

string $fmt

The format string, see String Formatting for a specification.

...

The remainder of the arguments are arguments to the format string.


Table 4.57. Return Value for File::printf()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.58. Exceptions Thrown by File::printf()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.17. File::open()

Synopsis

Opens the file in the mode given. Aditionally, the file permissions can be given if the file is to be created, and optionally the file's default character encoding can be specified.

Note that if no encoding is specified, the file will be tagged with the default character encoding for the process. Any string data written to the file will be converted to the file's encoding, and any string data read from the file will be automatically tagged with the file's encoding.

For a version of this method that throws an exception when errors occur opening the file, see File::open2().

Prototype

File::open(string $path, softint $flags = O_RDONLY, softint $mode = 0666) returns int

File::open(string $path, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns int

Example
# open a file for writing, truncate data if already exists, create the file if doesn't exist
# set 0644 permissions, and convert all string data to ISO-8859-1 encoding
$f.open("new_file.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644, "ISO-8859-1");
Events

EVENT_OPEN_FILE, EVENT_FILE_OPENED

Table 4.59. Arguments for File::open()

Argument

Description

string $path

The path to the file.

softint $flags = O_RDONLY

Flags that determine the way the file is accessed, see File Constants for more information. If this argument is not given, O_RDONLY will be used as the default value.

softint $mode = 0666

Permission bits for when the file is to be created (default: 0666)

[string $encoding]

The name of the default character encoding for this file; if this argument is not given, the file will be tagged with the default character encoding for the process.


Table 4.60. Return Values for File::open()

Return Type

Description

int

0 = no error, -1 = see errno() and strerror() for the error message


Table 4.61. Exceptions Thrown by File::open()

err

desc

FILE-OPEN-PARAMETER-ERROR

Missing filename argument.


4.3.18. File::open2()

Synopsis

Opens the file in the mode given. Aditionally, the file permissions can be given if the file is to be created, and optionally the file's default character encoding can be specified.

Note that if no encoding is specified, the file will be tagged with the default character encoding for the process. Any string data written to the file will be converted to the file's encoding, and any string data read from the file will be automatically tagged with the file's encoding.

If an error occurs, a FILE-OPEN2-ERROR exception is thrown. For a version of this method that returns an error code, see File::open().

Prototype

File::open2(string $path, softint $flags = O_RDONLY, softint $mode = 0666) returns nothing

File::open2(string $path, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns nothing

Example
# open a file for writing, truncate data if already exists, create the file if doesn't exist
# set 0644 permissions, and convert all string data to ISO-8859-1 encoding
$f.open2("new_file.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644, "ISO-8859-1");
Events

EVENT_OPEN_FILE, EVENT_FILE_OPENED

Table 4.62. Arguments for File::open2()

Argument

Description

string $path

The path to the file.

softint $flags = O_RDONLY

Flags that determine the way the file is accessed, see File Constants for more information. If this argument is not given, O_RDONLY will be used as the default value.

softint $mode = 0666

Permission bits for when the file is to be created (default: 0666)

[string $encoding]

The name of the default character encoding for this file; if this argument is not given, the file will be tagged with the default character encoding for the process.


Table 4.63. Exceptions Thrown by File::open2()

err

desc

FILE-OPEN2-PARAMETER-ERROR

Missing filename argument.

FILE-OPEN2-ERROR

Error opening the file; attempted to reopen a system file (I/O constants).


4.3.19. File::read()

Synopsis

Reads a certain amount of string data from the file; the size argument is required. To read binary data, use the File::readBinary() method.

Note that the amount of data read from the file may be less than the size given, for example if the file does not contain enough data to fulfill the request. In this case, only the data available in the file is returned.

An optional timeout period in milliseconds can be passed as well (or a relative time value may be passed instead of an integer to make the timeout units clear; ex: 25ms). If a timeout value is passed and the data cannot be read within the timeout period, then a FILE-READ-TIMEOUT exception is thrown. If no timeout value is passed or a negative value is given, then the call will never timeout until either the requested amount of data has been read from the file or an end-of-file condition has been reached.

Prototype

File::read(softint $size) returns any

File::read(softint $size, softint $timeout_ms) returns any

File::read(softint $size, date $timeout) returns any

Example
$data = $f.read(-1); # read an entire text file into a variable
Events

EVENT_DATA_READ

Table 4.64. Arguments for File::read()

Argument

Description

softint $size

The number of bytes to read of the file, -1 will read the entire file.

[softint $timeout_ms or date $timeout]

A timeout period with a resolution of milliseconds (an integer argument will be assumed to be milliseconds)); if not given or negative the call will never time out and will only return when the data has been read.


Table 4.65. Return Value for File::read()

Return Type

Description

string

The data read from the file, returned as a string. NOTHING is returned if end-of-file is encountered, however, if data has been read before EOF, the data read will be returned and NOTHING (signifying EOF) will be returned on the next call to this method.


Table 4.66. Exceptions Thrown by File::read()

err

desc

FILE-READ-PARAMETER-ERROR

Missing size argument.

FILE-READ-ERROR

File is not open; timeout limit exceeded.


4.3.20. File::readi1()

Synopsis

Reads a 1-byte signed integer from the file and returns the integer value read.

Prototype

File::readi1() returns any

Example
my any $i = $f.readi1();
Events

EVENT_DATA_READ

Table 4.67. Return Value for File::readi1()

Return Type

Description

int or nothing

Returns a 1-byte signed integer as read from the file in binary format or NOTHING if no data can be read.


Table 4.68. Exceptions Thrown by File::readi1()

err

desc

FILE-READ-ERROR

File is not open.


4.3.21. File::readi2()

Synopsis

Reads a 2-byte signed integer from the file in big-endian (MSB, network byte order) format. See File::readi2LSB() for an equivalent method reading a 2-byte signed integer in little-endian (LSB) format.

Prototype

File::readi2() returns any

Example
my any $i = $f.readi2();
Events

EVENT_DATA_READ

Table 4.69. Return Value for File::readi2()

Return Type

Description

int or nothing

Returns a 2-byte signed integer as read from the file in big-endian format or NOTHING if no data can be read.


Table 4.70. Exceptions Thrown by File::readi2()

err

desc

FILE-READ-ERROR

File is not open.


4.3.22. File::readi4()

Synopsis

Reads a 4-byte signed integer from the file in big-endian format. See File::readi4LSB() for an equivalent method reading a 4-byte signed integer in little-endian (LSB) format.

Prototype

File::readi4() returns any

Example
my any $i = $f.readi4();
Events

EVENT_DATA_READ

Table 4.71. Return Value for File::readi4()

Return Type

Description

int or nothing

Returns a 4-byte signed integer as read from the file in big-endian format or NOTHING if no data can be read.


Table 4.72. Exceptions Thrown by File::readi4()

err

desc

FILE-READ-ERROR

File is not open.


4.3.23. File::readi8()

Synopsis

Reads a 4-byte signed integer from the file in big-endian format. See File::readi8LSB() for an equivalent method reading a 4-byte signed integer in little-endian (LSB) format.

Prototype

File::readi8() returns any

Example
$i = $f.readi8();
Events

EVENT_DATA_READ

Table 4.73. Return Value for File::readi8()

Return Type

Description

int or nothing

Returns a 4-byte signed integer as read from the file in big-endian format or NOTHING if no data can be read.


Table 4.74. Exceptions Thrown by File::readi8()

err

desc

FILE-READ-ERROR

File is not open.


4.3.24. File::readi2LSB()

Synopsis

Reads a 2-byte signed integer from the file in little-endian (LSB) format. See File::readi2() for an equivalent method reading a 2-byte signed integer in big-endian (MSB, network byte order) format.

Prototype

File::readi2LSB() returns any

Example
my any $i = $f.readi2LSB();
Events

EVENT_DATA_READ

Table 4.75. Return Value for File::readi2LSB()

Return Type

Description

int or nothing

Reads a 2-byte signed integer from the file in little-endian format or NOTHING if no data can be read.


Table 4.76. Exceptions Thrown by File::readi2LSB()

err

desc

FILE-READ-ERROR

File is not open.


4.3.25. File::readi4LSB()

Synopsis

Reads a 4-byte signed integer from the file in little-endian format. See File::readi4() for an equivalent method reading a 4-byte signed integer in big-endian (MSB, network byte order) format.

Prototype

File::readi4LSB() returns any

Example
my any $i = $f.readi4LSB();
Events

EVENT_DATA_READ

Table 4.77. Return Value for File::readi4LSB()

Return Type

Description

int or nothing

Reads a 4-byte signed integer from the file in little-endian format or NOTHING if no data can be read.


Table 4.78. Exceptions Thrown by File::readi4LSB()

err

desc

FILE-READ-ERROR

File is not open.


4.3.26. File::readi8LSB()

Synopsis

Reads an 8-byte signed integer from the file in little-endian format. See File::readi8() for an equivalent method reading a 8-byte signed integer in big-endian (MSB, network byte order) format.

Prototype

File::readi8LSB() returns any

Example
my any $i = $f.readi8LSB();
Events

EVENT_DATA_READ

Table 4.79. Return Value for File::readi8LSB()

Return Type

Description

int or nothing

Reads a 4-byte signed integer from the file in little-endian format or NOTHING if no data can be read.


Table 4.80. Exceptions Thrown by File::readi8LSB()

err

desc

FILE-READ-ERROR

File is not open.


4.3.27. File::readu1()

Synopsis

Reads a 1-byte unsigned integer from the file and returns the integer value read.

Prototype

File::readu1() returns any

Example
my any $i = $f.readu1();
Events

EVENT_DATA_READ

Table 4.81. Return Value for File::readu1()

Return Type

Description

int or nothing

Returns a 1-byte unsigned integer as read from the file in binary format or NOTHING if no data can be read.


Table 4.82. Exceptions Thrown by File::readu1()

err

desc

FILE-READ-ERROR

File is not open.


4.3.28. File::readu2()

Synopsis

Reads a 2-byte signed integer from the file in big-endian (MSB, network byte order) format. See File::readu2LSB() for an equivalent method reading a 2-byte signed integer in little-endian (LSB) format.

Prototype

File::readu2() returns any

Example
my any $i = $f.readu2();
Events

EVENT_DATA_READ

Table 4.83. Return Value for File::readu2()

Return Type

Description

int or nothing

Returns a 2-byte signed integer as read from the file in big-endian format or NOTHING if no data can be read.


Table 4.84. Exceptions Thrown by File::readu2()

err

desc

FILE-READ-ERROR

File is not open.


4.3.29. File::readu4()

Synopsis

Reads a 4-byte signed integer from the file in big-endian format. See File::readu4LSB() for an equivalent method reading a 4-byte signed integer in little-endian (LSB) format.

Prototype

File::readu4() returns any

Example
my any $i = $f.readu4();
Events

EVENT_DATA_READ

Table 4.85. Return Value for File::readu4()

Return Type

Description

int or nothing

Returns a 4-byte signed integer as read from the file in big-endian format or NOTHING if no data can be read.


Table 4.86. Exceptions Thrown by File::readu4()

err

desc

FILE-READ-ERROR

File is not open.


4.3.30. File::readu2LSB()

Synopsis

Reads a 2-byte signed integer from the file in little-endian (LSB) format. See File::readu2() for an equivalent method reading a 2-byte signed integer in big-endian (MSB, network byte order) format.

Prototype

File::readu2LSB() returns any

Example
my any $i = $f.readu2LSB();
Events

EVENT_DATA_READ

Table 4.87. Return Value for File::readu2LSB()

Return Type

Description

int or nothing

Reads a 2-byte signed integer from the file in little-endian format or NOTHING if no data can be read.


Table 4.88. Exceptions Thrown by File::readu2LSB()

err

desc

FILE-READ-ERROR

File is not open.


4.3.31. File::readu4LSB()

Synopsis

Reads a 4-byte unsigned integer from the file in little-endian format. See File::readu4() for an equivalent method reading a 4-byte signed integer in big-endian (MSB, network byte order) format or NOTHING if no data can be read.

Prototype

File::readu4LSB() returns any

Example
my any $i = $f.readu4LSB();
Events

EVENT_DATA_READ

Table 4.89. Return Value for File::readu4LSB()

Return Type

Description

int or nothing

Reads a 4-byte unsigned integer from the file in little-endian format or NOTHING if no data can be read.


Table 4.90. Exceptions Thrown by File::readu4LSB()

err

desc

FILE-READ-ERROR

File is not open.


4.3.32. File::readBinary()

Synopsis

Read a certain amount of data and return a binary object; the size parameter is mandatory.

Note that the amount of data read from the file may be less than the size given, for example if the file does not contain enough data to fulfill the request. In this case, only the data available in the file is returned.

An optional timeout period in milliseconds can be passed as well (or a relative time value may be passed instead of an integer to make the timeout units clear; ex: 25ms). If a timeout value is passed and the data cannot be read within the timeout period, then a FILE-READ-TIMEOUT exception is thrown. If no timeout value is passed or a negative value is given, then the call will never timeout until either the requested amount of data has been read from the file or an end-of-file condition has been reached.

Prototype

File::readBinary(softint $size) returns any

File::readBinary(softint $size, softint $timeout_ms) returns any

File::readBinary(softint $size, date $timeout) returns any

Example
$data = $f.readBinary(-1); # reads an entire binary file into a variable
Events

EVENT_DATA_READ

Table 4.91. Arguments for File::readBinary()

Argument

Type

Description

size

int

The number of bytes to read of the file.

[timeout_ms]

Integer or Relative Date/Time

A timeout period in milliseconds; if not given or negative the call will never time out and will only return when the data has been read.


Table 4.92. Return Value for File::readBinary()

Return Type

Description

binary

A binary object containing the data read from the file. NOTHING is returned if end-of-file is encountered, however, if data has been read before EOF, the data read will be returned and NOTHING (signifying EOF) will be returned on the next call to this method.


Table 4.93. Exceptions Thrown by File::readBinary()

err

desc

FILE-READ-BINARY-PARAMETER-ERROR

Missing size argument.

FILE-READ-ERROR

File is not open; timeout limit exceeded.


4.3.33. File::readLine()

Synopsis

Reads until an EOL marker is found and returns a string containing the EOL marker. Returns NOTHING on end of file.

Prototype

File::readLine() returns any

Example
while (exists (my $line = $f.readLine())) {
    # remove EOL marker
    chomp $line;
    # print out the line just read
    printf("%s\n", $line);
}
Events

EVENT_DATA_READ

Table 4.94. Return Value for File::readLine()

Return Type

Description

string

The line read from the file. NOTHING is returned if end-of-file is encountered, however, if data has been read before EOF, the data read will be returned and NOTHING (signifying EOF) will be returned on the next call to this method.


Table 4.95. Exceptions Thrown by File::readLine()

err

desc

FILE-READLINE-ERROR

File is not open.


4.3.34. File::setCharset()

Synopsis

Sets the characte encoding for the file.

Prototype

File::setCharset() returns nothing

File::setCharset(string $encoding) returns nothing

Example
$f.setCharset("ISO-8859-1");

Table 4.96. Arguments for File::setCharset()

Argument

Description

[string $encoding]

The character encoding for the file.


4.3.35. File::setPos()

Synopsis

Sets the current file position in bytes starting with zero.

Prototype

File::setPos(softint $pos = 0) returns int

Example
$f.setPos(0); # go to the beginning of the file

Table 4.97. Arguments for File::setPos()

Argument

Description

softint $pos = 0

The position in the file as offset from position 0.


Table 4.98. Return Value for File::setPos()

Return Type

Description

int

Returns the new offset in the file, -1 for error.


4.3.36. File::setTerminalAttributes()

Synopsis

Sets the terminal attributes for the file from the TermIOS object passed; does not change the object passed.

Prototype

File::setTerminalAttributes(softint $action = TCSANOW, TermIOS $termios) returns nothing

Example
my TermIOS $termios();
stdin.getTerminalAttributes($termios);
my TermIOS $orig = $termios.copy();
on_exit
    stdin.setTerminalAttributes(TCSADRAIN, $orig);

my $lflag = $termios.getLFlag();
$lflag &= ~ICANON;
$lflag &= ~ECHO;
$lflag &= ~ISIG;
$termios.setLFlag($lflag);
$termios.setCC(VMIN, 1);
$termios.setCC(VTIME, 0);
stdin.setTerminalAttributes(TCSADRAIN, $termios);

Table 4.99. Arguments for File::setTerminalAttributes()

Argument

Description

softint $action = TCSANOW, TermIOS $termios

Sets the current terminal attributes for the file from the TermIOS object passed.


Table 4.100. Return Value for File::setTerminalAttributes()

Return Type

Description

int

Always returns 0; if an error is encountered, an exception is raised.


Table 4.101. Exceptions Thrown by File::setTerminalAttributes()

err

desc

FILE-OPERATION-ERROR

The file is not open.

TERMIOS-GET-ERROR

Error setting terminal attributes on the file descriptor.


4.3.37. File::sync()

Synopsis

Flushes the file's buffer to disk.

Prototype

File::sync() returns int

Example
$f.sync();

Table 4.102. Return Value for File::sync()

Return Type

Description

int

Returns 0 for success, -1 for error.


4.3.38. File::vprintf()

Synopsis

Writes a formatted string to a file, where the first argument is a format string,and the second argument is the formatting argument list.

Prototype

File::vprintf(string $fmt, any $args) returns int

File::vprintf() returns int (RT_NOOP)

Example
$f.vprintf("%5s\n", "hello");
Events

EVENT_DATA_WRITTEN

Table 4.103. Arguments for File::vprintf()

Argument

Description

 

string $fmt

The format string, see String Formatting for a specification.

 

any $args

This single argument or list of arguments will be used as the argument list or the format string. If a single argument is passed instead of a list, it will be used as the first argument as if a list were passed.

 

Table 4.104. Return Value for File::vprintf()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.105. Exceptions Thrown by File::vprintf()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.39. File::write()

Synopsis

Writes string or binary data to a file. String data will be converted to the file's character encoding if necessary before writing.

Prototype

File::write(data $data) returns int

Example
$f.write($data);
Events

EVENT_DATA_WRITTEN

Table 4.106. Arguments for File::write()

Argument

Description

data $data

Writes the data to the file.


Table 4.107. Return Value for File::write()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.108. Exceptions Thrown by File::write()

err

desc

FILE-WRITE-PARAMETER-ERROR

Missing string or binary argument.

FILE-WRITE-ERROR

File is not open.


4.3.40. File::writei1()

Synopsis

Writes a 1-byte integer to the file.

Prototype

File::writei1(softint $i = 0) returns int

Example
$f.writei1($val);
Events

EVENT_DATA_WRITTEN

Table 4.109. Arguments for File::writei1()

Argument

Description

softint $i = 0

The integer to write; only the least-significant 8 bits will be written to the file.


Table 4.110. Return Value for File::writei1()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.111. Exceptions Thrown by File::writei1()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.41. File::writei2()

Synopsis

Writes a 2-byte integer in big-endian format.

Prototype

File::writei2(softint $i = 0) returns int

Example
$f.writei2($val);
Events

EVENT_DATA_WRITTEN

Table 4.112. Arguments for File::writei2()

Argument

Description

softint $i = 0

The integer to write; writes a 2-byte integer in big-endian format.


Table 4.113. Return Value for File::writei2()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.114. Exceptions Thrown by File::writei2()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.42. File::writei4()

Synopsis

Writes a 4-byte integer in big-endian format.

Prototype

File::writei4(softint $i = 0) returns int

Example
$f.writei4($val);
Events

EVENT_DATA_WRITTEN

Table 4.115. Arguments for File::writei4()

Argument

Description

softint $i = 0

The integer to write; writes a 4-byte integer in big-endian format.


Table 4.116. Return Value for File::writei4()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.117. Exceptions Thrown by File::writei4()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.43. File::writei8()

Synopsis

Writes an 8-byte integer in big-endian format.

Prototype

File::writei8(softint $i = 0) returns int

Example
$f.writei8($val);
Events

EVENT_DATA_WRITTEN

Table 4.118. Arguments for File::writei8()

Argument

Description

softint $i = 0

The integer to write; writes an 8-byte integer in big-endian format.


Table 4.119. Return Value for File::writei8()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.120. Exceptions Thrown by File::writei8()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.44. File::writei2LSB()

Synopsis

Writes a 2-byte integer in little-endian format.

Prototype

File::writei2LSB(softint $i = 0) returns int

Example
$f.writei2LSB($val);
Events

EVENT_DATA_WRITTEN

Table 4.121. Arguments for File::writei2LSB()

Argument

Description

softint $i = 0

The integer to write; writes a 2-byte integer in little-endian format.


Table 4.122. Return Value for File::writei2LSB()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.123. Exceptions Thrown by File::writei2LSB()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.45. File::writei4LSB()

Synopsis

Writes a 4-byte integer in little-endian format.

Prototype

File::writei4LSB(softint $i = 0) returns int

Example
$f.writei4LSB($val);
Events

EVENT_DATA_WRITTEN

Table 4.124. Arguments for File::writei4LSB()

Argument

Description

softint $i = 0

The integer to write; writes a 4-byte integer in little-endian format.


Table 4.125. Return Value for File::writei4LSB()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.126. Exceptions Thrown by File::writei4LSB()

err

desc

FILE-WRITE-ERROR

File is not open.


4.3.46. File::writei8LSB()

Synopsis

Writes an 8-byte integer to the file in little-endian (LSB) format.

Prototype

File::writei8LSB(softint $i = 0) returns int

Example
$f.writei8LSB($val);
Events

EVENT_DATA_WRITTEN

Table 4.127. Arguments for File::writei8LSB()

Argument

Description

softint $i = 0

The integer to write; writes an 8-byte integer in little-endian format.


Table 4.128. Return Value for File::writei8LSB()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.129. Exceptions Thrown by File::writei8LSB()

err

desc

FILE-WRITE-ERROR

File is not open.


4.4. Dir Class

Note: This class is not available with the PO_NO_FILESYSTEM parse option.

The Dir class allows Qore programs to list and manipulate directories.

Directory objects can be created/opened with a specific character encoding. This means that any entry read from the directory will be tagged with the directory's character encoding. If no character encoding is given the default Qore character encoding is assumed.

Table 4.130. Dir Method Overview

Method

Except?

Description

Dir::constructor()

Dir::constructor(string $encoding)

N

Create a Directory object with optional character encoding. It points to the directory the script is started.

Dir::destructor()

N

Destroys the directory object.

Dir::copy()

N

Creates a new directory object with the same character encoding specification and the same path as the original.

Dir::chdir(string $path) returns bool

N

Change the path of the directory. The path specification can be relative or absolute (with leading '/'). This path does not necessarily need to exist.

Dir::path() returns any

N

Returns a string giving the current path of the object, stripped of all '.' and '..' entries or NOTHING if no path is set.

Dir::exists() returns bool

N

Checks if the path in the object is an openable directory.

Dir::create(softint $mode = 0777) returns int

Y

Try to create all directories of the object if they do not exist yet; if any errors occur an exception is thrown.

Dir::chown(softint $uid) returns nothing

Dir::chown(string $username) returns nothing

Y

Change the ownership of the directory to the given user.

Dir::chgrp(softint $gid) returns nothing

Dir::chgrp(string $groupname) returns nothing

Y

Change the group membership of the directory to the given group.

Dir::chmod(softint $mode) returns nothing

Y

Change the permissions of the directory to the given mode; if any errors occur an exception is thrown.

Dir::mkdir(string $name, softint $mode = 0777) returns nothing

Y

Create a subdirectory with the name in the directory; if any errors occur an exception is thrown.

Dir::rmdir(string $subdir) returns nothing

Y

Delete an empty subdirectory with the name in the directory; if any errors occur an exception is thrown.

Dir::list() returns list

Dir::list(string $regex) returns list

Dir::list(string $regex, int $options) returns list

Y

Get all entries in this directory, except '.' and '..' directories (takes an optional regular expression filter); if any errors occur an exception is thrown.

Dir::listFiles() returns list

Dir::listFiles(string $regex) returns list

Dir::listFiles(string $regex, int $options) returns list

Y

Get all entries in the directory which are not subdirectories (takes an optional regular expression filter); if any errors occur an exception is thrown.

Dir::listDirs() returns list

Dir::listDirs(string $regex) returns list

Dir::listDirs(string $regex, int $options) returns list

Y

Get all entries in the directory which are subdirectories, except '.' and '..' directories (takes an optional regular expression filter); if any errors occur an exception is thrown.

Dir::openDir(string $subdir) returns Dir

Dir::openDir(string $subdir, string $encoding) returns Dir

Y

Get a Dir object as an subdir entry of the current directory.

Dir::openFile(string $name, softint $flags = O_RDONLY, softint $mode = 0666) returns File

Dir::openFile(string $name, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns File

Y

Get a File object which represents a file in the directory.

Dir::removeFile(string $name) returns bool

Y

Remove (unlink) a file in this directory.


4.4.1. Dir::constructor()

Synopsis

Creates a Dir object. It accepts one optional argument that will set the default character encoding encoding for the directory.

Prototype

Dir::constructor()

Dir::constructor(string $encoding)

Example
my Dir $d("UTF-8");

Table 4.131. Arguments for Dir::constructor()

Argument

Description

[string $encoding

The character encoding for the directory. Any entry of the directory will be converted to this character encoding if necessary, and entries read will be tagged with this encoding. If no encoding is given, the default encoding is used.


4.4.2. Dir::destructor()

Synopsis

Destroys the Dir object.

Example
delete $d;

4.4.3. Dir::copy()

Synopsis

Creates a new Dir object with the same character encoding specification and path as the original.

Example
my Dir $d2 = $d.copy();

4.4.4. Dir::chdir()

Synopsis

Change the directory of the Dir object to the path; you can use either an absolute path (leading with '/') or a directory realtive to the actual path.

Prototype

Dir::chdir(string $path) returns bool

Example
if ($d.chdir("../doc")) {
   printf("the directory does not exist or is not readable\n");
}

Table 4.132. Arguments for Dir::chdir()

Argument

Description

string $path

The new directory name.


Table 4.133. Return Value for Dir::chdir()

Return Type

Description

bool

True if the new path is openable as directory (see exists()).


4.4.5. Dir::path()

Synopsis

Return the path of the Dir object or NOTHING if no path is set. This path does not necessarily need to exist. '.' and '..' str stripped from the path if present.

Prototype

Dir::path() returns any

Example
my any $mypath = $d.path();

Table 4.134. Return Value for Dir::path()

Return Type

Description

any

The path of the Dir object or NOTHING if no path is set.


4.4.6. Dir::exists()

Synopsis

Returns True if the path in the Dir object points to a directory that already exists and is openable by the current user.

Prototype

Dir::exists() returns bool

Example
if (!$d.exists()) {
   printf("the directory %s does not exist or cannot be opened\n", $d.path());
   exit(-1);
}

Table 4.135. Return Value for Dir::exists()

Return Type

Description

bool

True if the directory exists and is openable.


4.4.7. Dir::create()

Synopsis

Create the whole directory tree the Dir object points to, if it does not exist till now.

Prototype

Dir::create(softint $mode = 0777) returns int

Example
if (!$d.exists()) {
   printf("directory '%s' does not exist; creating...\n", $d.path());
   $cnt = $d.create();
}

Table 4.136. Arguments for Dir::create()

Argument

Description

softint $mode = 0777

The mode of the directory.


Table 4.137. Return Value for Dir::create()

Return Type

Description

int

Number directories created.


Table 4.138. Exceptions Thrown by Dir::create()

err

desc

DIR-CREATE-ERROR

One of the directories in the path could not be created.


4.4.8. Dir::chown()

Synopsis

Change the ownership of the directory.

Prototype

Dir::chown(softint $uid) returns nothing

Dir::chown(string $username) returns nothing

Example
$d.chown("nobody");

Table 4.139. Arguments for Dir::chown()

Argument

Description

softint $uid

The userid to be used.

string $username

A username which is known by the system.


Table 4.140. Exceptions Thrown by Dir::chown()

err

desc

DIR-CHOWN-PARAMETER-ERROR

Parameter error.

DIR-CHOWN-ERROR

The error occoured in the chown() call.


4.4.9. Dir::chgrp()

Synopsis

Change the group membership of the directory.

Prototype

Dir::chgrp(softint $gid) returns nothing

Dir::chgrp(string $groupname) returns nothing

Example
$d.chgrp("nogroup");

Table 4.141. Arguments for Dir::chgrp()

Argument

Description

softint $gid

The groupid to be set for the directory.

string $groupname

The name of the group to be set. Must be known in the system.


Table 4.142. Exceptions Thrown by Dir::chgrp()

err

desc

DIR-CHGRP-PARAMETER-ERROR

Parameter error.

DIR-CHGRP-ERROR

Error occoured during the change group chown() system call.


4.4.10. Dir::chmod()

Synopsis

Change the mode of the directory.

Prototype

Dir::chmod(softint $mode) returns nothing

Example
$d.chmod(0711); # set mode to u(rwx) and go(x)

Table 4.143. Arguments for Dir::chmod()

Argument

Description

softint $mode

The mode of the directory.


Table 4.144. Exceptions Thrown by Dir::chmod()

err

desc

DIR-CHMOD-PARAMETER-ERROR

Parameter error.

DIR-CHMOD-ERROR

The error returned from the chmod() system call.


4.4.11. Dir::mkdir()

Synopsis

Make a subdirectory in the Dir object's path. There are no path info allowed (the '/'). If no mode is given the mode 0777 is used.

Prototype

Dir::mkdir(string $name, softint $mode = 0777) returns nothing

Example
$d.mkdir("newSubDir", 0755);

Table 4.145. Arguments for Dir::mkdir()

Argument

Description

string $name, softint $mode = 0777

The name and mode of the subdirectory.


Table 4.146. Exceptions Thrown by Dir:mkdir()

err

desc

DIR-MKDIR-PARAMETER-ERROR

Parameter error.

DIR-MKDIR-ERROR

The error returned from the mkdir() system call.


4.4.12. Dir::rmdir()

Synopsis

Remove a subdirectory from the Dir object's path. There is no pathinfo allowed in the name (the '/' delimiter).

Prototype

Dir::rmdir(string $subdir) returns nothing

Example
$d.rmdir("emptySubdir");

Table 4.147. Arguments for Dir::rmdir()

Argument

Description

string $subdir

The name of the directory to be removed.


Table 4.148. Exceptions Thrown by Dir::rmdir()

err

desc

DIR-RMDIR-PARAMETER-ERROR

Parameter error.

DIR-RMDIR-ERROR

The error returned from the rmdir() system call.


4.4.13. Dir::list()

Synopsis

List all entries in the directory of the Dir object. It supresses the '.' and '..' directory. An optional regular expression string can be passed to filter the values returned; if this argument is given then only entries that match the regular expression will be returned.

Prototype

Dir::list() returns list

Dir::list(string $regex) returns list

Dir::list(string $regex, int $options) returns list

Example
foreach my string $e in ($d.list()) {
   printf("entry: %s\n");
}

Table 4.149. Arguments for Dir::list()

Argument

Description

[string $regex, [int $options]]

An optional regular expression string used to filter the arguments followed by bitwise-or'ed regex option constants.


Table 4.150. Return Value for Dir::list()

Return Type

Description

list

A list of Strings with the directories content.


Table 4.151. Exceptions Thrown by Dir::list()

err

desc

DIR-READ-ERROR

The error returned from the readdir() system call.


4.4.14. Dir::listFiles()

Synopsis

List all entries in the directory of the Dir object, which are not subdirectories. An optional regular expression string can be passed to filter the values returned; if this argument is given then only entries that match the regular expression will be returned.

Prototype

Dir::listFiles() returns list

Dir::listFiles(string $regex) returns list

Dir::listFiles(string $regex, int $options) returns list

Example
foreach my string $e in ($d.listFiles()) {
   printf("entry: %s\n");
}

Table 4.152. Arguments for Dir::listFiles()

Argument

Description

[string $regex, [int $options]]

An optional regular expression string used to filter the arguments followed by bitwise-or'ed regex option constants.


Table 4.153. Return Value for Dir::listFiles()

Return Type

Description

list

A list of strings with the file names as elements.


Table 4.154. Exceptions Thrown by Dir::listFiles()

err

desc

DIR-READ-ERROR

The error returned from the readdir() system call.


4.4.15. Dir::listDirs()

Synopsis

List all entries in the directory of the Dir object that are subdirectories, not including the '.' and '..' directories. An optional regular expression string can be passed to filter the values returned; if this argument is given then only entries that match the regular expression will be returned.

Prototype

Dir::listDirs() returns list

Dir::listDirs(string $regex) returns list

Dir::listDirs(string $regex, int $options) returns list

Example
foreach my string $e in ($d.listDirs()) {
   printf("entry: %s\n");
}

Table 4.155. Arguments for Dir::listDirs()

Argument

Description

[string $regex, [int $options]]

An optional regular expression string used to filter the arguments followed by bitwise-or'ed regex option constants.


Table 4.156. Return Value for Dir::listDirs()

Return Type

Description

list

A list of strings with the directory names found.


Table 4.157. Exceptions Thrown by Dir::listDirs()

err

desc

DIR-READ-ERROR

The error returned from the readdir() system call.


4.4.16. Dir::openDir()

Synopsis

Return a Dir object in the directory of the Dir object. The dirname does not allow path information (the '/').

Prototype

Dir::openDir(string $subdir) returns Dir

Dir::openDir(string $subdir, string $encoding) returns Dir

Example
# open a subdir for working with
my Dir $sd = $d.openDir("mysubdir", "ISO-8859-1");
my list $sd_list = $sd.list();

Table 4.158. Arguments for Dir::openDir()

Argument

Description

string $subdir, [string $encoding]

The name of the subdirectory. The directory must not exist and can be created with create() afterwards. If no encoding is given, the default encoding is used.


Table 4.159. Return Value for Dir::openDir()

Return Type

Description

Dir

The Dir object created for the directory.


Table 4.160. Exceptions Thrown by Dir::openDir()

err

desc

DIR-OPENDIR-PARAMETER-ERROR

The directory name to be opened contains path information ('/').


4.4.17. Dir::openFile()

Synopsis

Create or open a File object in the directory of the Dir object. The filename does not allow path information (the '/'). Uses the File::open2() method.

Prototype

Dir::openFile(string $name, softint $flags = O_RDONLY, softint $mode = 0666) returns File

Dir::openFile(string $name, softint $flags = O_RDONLY, softint $mode = 0666, string $encoding) returns File

Example
# open a file for writing in the directory and set the mode to
# 0644 and the encoding to UTF-8
my $f = $d.openFile("myfile.txt", O_CREAT|O_WRONLY, 0644, "UTF-8");

Table 4.161. Arguments for Dir::openFile()

Argument

Description

string name

The name of the file in the current directory.

softint $flags = O_RDONLY

Flags that determine the way the file is accessed, see File Constants for more information. If this argument is not given, O_RDONLY will be used as the default value.

softint $mode = 0666

Permission bits for when the file is to be created (default: 0666)

[string $encoding]

The name of the default character encoding for this file; if this argument is not given, the file will be tagged with the default character encoding for the process.


Table 4.162. Return Value for Dir::openFile()

Return Type

Description

Object

The File object created or opened in the directory.


Table 4.163. Exceptions Thrown by Dir::openFile()

err

desc

DIR-OPENFILE-PARAMETER-ERROR

The file name to be opened contains path information ('/').

File Exceptions

Exceptions thrown by the File::open2() call.


4.4.18. Dir::removeFile()

Synopsis

Remove the file with the given name in the Dir object's directory.

Prototype

Dir::removeFile(string $name) returns bool

Example
$d.removeFile("myTestFile.dat");

Table 4.164. Arguments for Dir::removeFile()

Argument

Description

string $name

The name of the file in the directory.


Table 4.165. Return Value for Dir::removeFile()

Return Type

Description

bool

True if the file was present and could be removed. False if the file did not exist. If any errors occur unlinking an existing file, then an exception occurs.


Table 4.166. Exceptions Thrown by Dir::removeFile()

err

desc

DIR-REMOVEFILE-PARAMETER-ERROR

Parameter error.

DIR-REMOVEFILE-ERROR

The error returned by the unlink() system call.


4.5. TermIOS Class

Note: This class is not available with the PO_NO_TERMINAL_IO parse option.

This class contains the data structure used to read and set terminal attributes on terminal I/O constants.

This class is used with File::getTerminalAttributes(), File::setTerminalAttributes(), and the terminal I/O constants to manipulate terminal attributes.

For example, here is some code to set terminal attributes, read in a character from stanrdard input with a timeout, and reset the terminal attributes:

my TermIOS $t();
stdin.getTerminalAttributes($t);
my TermIOS $orig = $t.copy();
on_exit
    stdin.setTerminalAttributes(TCSADRAIN, $orig);

my $lflag = $t.getLFlag();
$lflag &= ~ICANON;
$lflag &= ~ECHO;
$lflag &= ~ISIG;
$t.setLFlag($lflag);
$t.setCC(VMIN, 1);
$t.setCC(VTIME, 0);
stdin.setTerminalAttributes(TCSADRAIN, $t);

stdout.printf("Press any key: ");
while (!stdin.isDataAvailable(20ms)) {
    stdout.printf(".");
    stdout.sync();
    usleep(1ms);
}
my $c = stdin.read(1);
stdout.printf(" GOT ASCII 0x%02x (%d) '%s'\n", ord($c), ord($c), $c);

For more information on terminal attributes, see your system's manual pages for "termios".

Table 4.167. TermIOS Method Overview

Method

Except?

Description

TermIOS::constructor()

Y

Creates the TermIOS object.

TermIOS::destructor()

N

Destroys the TermIOS object.

TermIOS::copy()

N

Returns a copy of the object.

TermIOS::getLFlag() returns int

N

Gets the local mode value of the object.

TermIOS::getCFlag() returns int

N

Gets the control mode value of the object.

TermIOS::getOFlag() returns int

N

Gets the output mode value of the object.

TermIOS::getIFlag() returns int

N

Gets the input mode value of the object.

TermIOS::setLFlag(softint $val = 0) returns nothing

N

Sets the local mode of the object.

TermIOS::setCFlag(softint $val = 0) returns nothing

N

Sets the control mode of the object.

TermIOS::setOFlag(softint $val = 0) returns nothing

N

Sets the output mode of the object.

TermIOS::setIFlag(softint $val = 0) returns nothing

N

Sets the input mode of the object.

TermIOS::getCC(softint $offset = 0) returns int

Y

Gets the value of a control character for the object.

TermIOS::setCC(softint $offset = 0, softint $value = 0) returns nothing

Y

Sets the value of a control character for the object.

TermIOS::isEqual(TermIOS $other) returns bool

Y

Returns true if the object passed is equal to the current object, false if not.

static TermIOS::getWindowSize()

Y

Returns a hash giving the current terminal window size in hash keys rows and columns.


4.5.1. TermIOS::constructor()

Synopsis

Creates the TermIOS object with random contents. Use File::getTerminalAttributes() with a terminal I/O constant to initialize the object with terminal settings.

Prototype

TermIOS::constructor()

Example
my TermIOS $termios();
stdin.getTerminalAttributes($termios);

4.5.2. TermIOS::destructor()

Synopsis

Destroys the TermIOS object.

Example
delete $termios;

This method does not throw any exceptions.

4.5.3. TermIOS::copy()

Synopsis

Returns a copy of the object.

Example
my TermIOS $t2 = $t.copy();

This method does not throw any exceptions.

4.5.4. TermIOS::getLFlag()

Synopsis

Returns the local mode flag for the object

Prototype

TermIOS::getLFlag() returns int

Table 4.168. Return Values for TermIOS::getLFlag()

Return Type

Description

int

The local mode flag for the object


4.5.5. TermIOS::getCFlag()

Synopsis

Returns the control mode flag for the object

Prototype

TermIOS::getCFlag() returns int

Table 4.169. Return Values for TermIOS::getCFlag()

Return Type

Description

int

The control mode flag for the object


4.5.6. TermIOS::getIFlag()

Synopsis

Returns the input mode flag for the object

Prototype

TermIOS::getIFlag() returns int

Table 4.170. Return Values for TermIOS::getIFlag()

Return Type

Description

int

The input mode flag for the object


4.5.7. TermIOS::getOFlag()

Synopsis

Returns the output mode flag for the object

Prototype

TermIOS::getOFlag() returns int

Table 4.171. Return Values for TermIOS::getOFlag()

Return Type

Description

int

The output mode flag for the object


4.5.8. TermIOS::setLFlag()

Synopsis

Sets the local mode flag for the object

Prototype

TermIOS::setLFlag(softint $val = 0) returns nothing

Table 4.172. Arguments for TermIOS::setLFlag()

Argument

Description

softint $val = 0

The local mode to set for the object.


4.5.9. TermIOS::setCFlag()

Synopsis

Sets the control mode flag for the object

Prototype

TermIOS::setCFlag(softint $val = 0) returns nothing

Table 4.173. Arguments for TermIOS::setCFlag()

Argument

Description

softint $val = 0

The control mode to set for the object.


4.5.10. TermIOS::setIFlag()

Synopsis

Sets the input mode flag for the object

Prototype

TermIOS::setIFlag(softint $val = 0) returns nothing

Table 4.174. Arguments for TermIOS::setIFlag()

Argument

Description

softint $val = 0

The input mode to set for the object.


4.5.11. TermIOS::setOFlag()

Synopsis

Sets the output mode flag for the object

Prototype

TermIOS::setOFlag(softint $val = 0) returns nothing

Table 4.175. Arguments for TermIOS::setOFlag()

Argument

Description

softint $val = 0

The output mode to set for the object.


4.5.12. TermIOS::getCC()

Synopsis

Returns the value of the control character corresponding to the argument passed.

Prototype

TermIOS::getCC(softint $offset = 0) returns int

Table 4.176. Arguments for TermIOS::getCC()

Argument

Description

softint $offset = 0

The control character to get from th object.


Table 4.177. Return Values for TermIOS::getCC()

Return Type

Description

int

The value of the given control character.


4.5.13. TermIOS::setCC()

Synopsis

Sets the control character corresponding to the first argument to the value of the second argument.

Prototype

TermIOS::setCC(softint $offset = 0, softint $value = 0) returns nothing

Table 4.178. Arguments for TermIOS::setCC()

Argument

Description

softint $offset = 0

The control character to set.

softint value = 0

The value to set


4.5.14. TermIOS::isEqual()

Synopsis

Returns True if the TermIOS object passed as an argument is equal to the current object; false if not. If the argument passed to this method is not a TermIOS object, an exception is raised

Prototype

TermIOS::isEqual(TermIOS $other) returns bool

Table 4.179. Arguments for TermIOS::isEqual()

Argument

Description

TermIOS $other

The object to compare to the current object.


Table 4.180. Return Values for TermIOS::isEqual()

Return Type

Description

bool

The result of comparing the current object to the argument


Table 4.181. Exceptions thrown by TermIOS::isEqual()

err

desc

TERMIOS-ISEQUAL-ERROR

argument passed is not a TermIOS object


4.5.15. static TermIOS::getWindowSize()

Synopsis

Returns a hash giving the current terminal window size in hash keys rows and columns.

Prototype

static TermIOS::getWindowSize() returns hash

Example
$hash = TermIOS::getWindowSize()

Table 4.182. Return Values for TermIOS::getWindowSize()

Return Type

Description

hash

Returns a hash giving the current terminal window size in hash keys rows and columns.


4.6. GetOpt Class

The GetOpt class provides an easy way to process POSIX-style command-line options in Qore scripts/programs.

Table 4.183. GetOpt Method Overview

Method

Except?

Description

GetOpt::constructor(hash $options)

Y

Creates the GetOpt object with the option hash passed.

GetOpt::destructor()

N

Destroys the object.

GetOpt::copy()

Y

Throws an exception; objects of this class cannot be copied.

GetOpt::parse(reference $list_ref) returns hash

GetOpt::parse(list $list) returns hash

N

Parses the argument list passed and retuns a hash of the results; if there are any errors, they are returned in the "_ERRORS_" key of the hash returned.

GetOpt::parse2(reference $list_ref) returns hash

GetOpt::parse2(list $list) returns hash

N

Parses the argument list passed and retuns a hash of the results; if there are any errors, an exception is thrown.


4.6.1. GetOpt::constructor()

Synopsis

Creates the GetOpt object and sets the option hash with the single required argument.

Prototype

GetOpt::constructor(hash $options)

Example
const program_options =
    ( "url"  : "url,u=s",
      "xml"  : "xml,x",
      "lxml" : "literal-xml,X",
      "verb" : "verbose,v",
      "help" : "help,h" );

my GetOpt $getopt(program_options);

Table 4.184. Arguments for GetOpt::constructor()

Argument

Description

hash $options

Each key defines the key value for the return hash if any arguments are given corresponding to the string value of the key.


The string value of each hash follows the following pattern:

opts[=|:type[modifier]]

Table 4.185. Option Hash Value String

Component

Description

opts

At least one short option and/or a long option name; if both are present, then they must be separated by a comma. The short option must be a single character.

[=:type]

if "=" is used, then the option takes a mandatory argument, if ":" is used, then the argument is optional. Types are specified as follows: s=string, i=integer, f=float, d=date, b=boolean

modifier

@ specifies a list, + an additive value (sum; must be integer or float type)


Table 4.186. Exceptions Thrown by GetOpt::constructor()

err

desc

GETOPT-OPTION-ERROR

There was a syntax or format error in the option specification.


4.6.2. GetOpt::destructor()

Synopsis

Destroys the GetOpt object.

Example
delete $getopt;

4.6.3. GetOpt::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.187. Exceptions Thrown by GetOpt::copy()

err

desc

GETOPT-COPY-ERROR

Objects of this class cannot be copied.


4.6.4. GetOpt::parse()

Synopsis

Parses the list of parameters according to the option hash passed to the constructor. If a reference to a list is passed to this function, then all arguments parsed will be removed from the list, leaving only unparsed arguments (for example, file names).

If any errors are encountered, the return value hash will have a key "_ERRORS_" giving a list of error messages pertaining to the options parsed.

See GetOpt::parse2() for a similar method that throws an exception instead of putting error information in the _ERRORS_ key of the hash value returned.

Prototype

GetOpt::parse(reference $list_ref) returns hash

GetOpt::parse(list $list) returns hash

Example
my hash $o = $getopt.parse(\$ARGV);
if (exists $o."_ERRORS_") {
   stderr.printf("%s\n", $o."_ERRORS_"[0]);
   exit(1);
}

Table 4.188. Arguments for GetOpt::parse()

Argument

Description

list $list

The entire command line to process (ex: $ARGV).

reference $list_ref

The reference should point to a list of arguments to process; any argument accepted by the object will be removed from the list.


Table 4.189. Return Values for GetOpt::parse()

Return Type

Description

hash

A hash keyed by option names (as given in the hash to the GetOpt constructor), where each key's value is the value of the arguments passed in the list argument. The hash key "_ERRORS_" will contain any errors.


4.6.5. GetOpt::parse2()

Synopsis

Parses the list of parameters according to the option hash passed to the constructor. If a reference to a list is passed to this function, then all arguments parsed will be removed from the list, leaving only unparsed arguments (for example, file names).

If any errors are encountered, an appropriate exception will be thrown.

See GetOpt::parse() for a similar method that puts error information in the "_ERRORS_" key of the hash value returned instead of throwing an exception.

Prototype

GetOpt::parse2(reference $list_ref) returns hash

GetOpt::parse2(list $list) returns hash

Example
try {
   my hash $o = $getopt.parse2(\$ARGV);
}
catch ($ex) {
   stderr.printf("%s\n", $ex.desc);
   exit(1);
}

Table 4.190. Arguments for GetOpt::parse2()

Argument

Description

list $list

The entire command line to process (ex: $ARGV).

reference $list_ref

The reference should point to a list of arguments to process; any argument accepted by the object will be removed from the list.


Table 4.191. Return Values for GetOpt::parse2()

Return Type

Description

hash

A hash keyed by option names (as given in the hash to the GetOpt constructor), where each key's value is the value of the arguments passed in the list argument. If any errors are encountered processing the arguments, an appropriate exception will be thrown.


Table 4.192. Exceptions Thrown by GetOpt::parse2()

err

desc

GETOPT-ERROR

The description varies according to the error encountered.


4.7. FtpClient Class

Note: This class is not available with the PO_NO_NETWORK parse option.

The FtpClient class allows Qore programs to communicate with FTP servers. The constructor takes an optional URL with the following format:

[(ftp|ftps)://][username[:password]@]hostname[:port]

If the URL is not set with the constructor, then the connection parameters must be set with the FtpClient::set*() methods. At the very minimum the hostname must be set. If any path name is given in the URL, it is ignored. See the following table for default URL parameters.

Table 4.193. FtpClient::constructor() Default URL Parameters

Field

Default Value

protocol

ftp (unencrypted)

username

anonymous

password

qore@nohost.com

port

21


Once the URL (at least the hostname) has been set, the FtpClient::connect() method must be called to connect and login to the FTP server.

Objects of this class are capable of making encrypted FTPS connections according to RFC-4217. TLS/SSL encrypted control and data connection will be attempted if the protocol is set to 'ftps' or the FtpClient::setSecure() method is called before connecting.

Note that 'sftp', or FTP over ssh, is not supported with this class; FTPS is an extension of the FTP protocol to allow for secure connections; while 'sftp' is FTP over an encrypted ssh connection. For sftp and ssh support, use the ssh2 module.

When a data connection is required, by default the following modes are tried in series: EPSV (Extended Passive Mode), PASV (Passive Mode), and PORT (Port mode). If the FTP server does not support one of these methods, or network conditions do not allow a data connection of any of these types to be established, then an exception is thrown.

To manually control which modes are tried, see the FtpClient::setModeEPSV(), FtpClient::setModePASV(), and FtpClient::setModePORT() methods.

This class supports posting network events to a Queue, either events on the control or data channels or both can be monitored. See Event Handling for more information.

The events raised by this object are listed in the following table:

Table 4.194. FtpClient Events

Name

Value

Description

EVENT_FTP_SEND_MESSAGE

9

Raised immediately before an FTP control message is sent.

EVENT_FTP_MESSAGE_RECEIVED

10

Raised when an FTP reply is received on the control channel.


Table 4.195. FtpClient Method Overview

Method

Except?

Description

FtpClient::constructor()

FtpClient::constructor(string $url)

Y

Creates object and optionally initializes URL

FtpClient::destructor()

N

Destroys the object.

FtpClient::copy()

Y

Throws an exception to prevent copying of objects this class.

FtpClient::connect() returns nothing

Y

Connects and logs in to FTP server

FtpClient::disconnect() returns nothing

N

Disconnects from the FTP server.

FtpClient::setSecure(softbool $secure = True) returns nothing

Y

Make an FTPS connection to the server on the next connect if the argument is True.

FtpClient::setInsecure() returns nothing

Y

Make a non-encrypted connection to the server on the next connect.

FtpClient::setInsecureData() returns nothing

Y

Make a non-encrypted data connection to the server on the next connect even if the control connection is secure.

FtpClient::isSecure() returns bool

N

Returns True if the control connection is a secure TLS/SSL connection.

FtpClient::isDataSecure() returns bool

N

Returns True if the data connections are secure TLS/SSL connections.

FtpClient::getSSLCipherName() returns any

N

Returns the name of the cipher for an encrypted connection or NOTHING if no encrypted connection has been established.

FtpClient::getSSLCipherVersion() returns any

N

Returns the version string of the cipher for encrypted connections or NOTHING if no encrypted connection has been established.

FtpClient::verifyPeerCertificate() returns any

N

Returns a string code giving the result of verifying the remote certificate or NOTHING if no encrypted connection has been established.

FtpClient::setModeAuto() returns nothing

N

Sets the object to automatically try to negotiate the data connections in EPSV, PASV, and PORT modes, in this order.

FtpClient::setModeEPSV() returns nothing

N

Sets the object to only try to make data connections using EPSV (RFC-2428 extended passive) mode.

FtpClient::setModePASV() returns nothing

N

Sets the object to only try to make data connections using PASV (RFC-959 passive) mode.

FtpClient::setModePORT() returns nothing

N

Sets the object to only try to make data connections using PORT mode.

FtpClient::list() returns any

FtpClient::list(string $path) returns any

Y

Gets a list of files from the FTP server in the server's long format; returns NOTHING if the path cannot be found.

FtpClient::nlst() returns any

FtpClient::nlst(string $path) returns any

Y

Gets a list of file names from the FTP server; returns NOTHING if the path cannot be found.

FtpClient::pwd() returns string

Y

Returns the server-side current working directory.

FtpClient::cwd(string $dir) returns nothing

Y

Changes the current working directory on the server.

FtpClient::get(string $remote_file) returns nothing

FtpClient::get(string $remote_file, string $local_file) returns nothing

Y

Gets a file from the FTP server and stores it on the local filesystem; if any errors occur, an exception is thrown..

FtpClient::getAsBinary(string $remote_file) returns binary

Y

Gets a file from the FTP server and returns it as a binary value.

FtpClient::getAsString(string $remote_file) returns string

Y

Gets a file from the FTP server and returns it as a string.

FtpClient::put(string $local_file) returns nothing

FtpClient::put(string $local_file, string $remote_file) returns nothing

Y

Transfers a file to the FTP server; if any errors occur, an exception is thrown.

FtpClient::del(string $remote_file) returns nothing

Y

Deletes a file from the FTP server

FtpClient::setUserName(string $user) returns nothing

N

Sets the user name to use

FtpClient::setPassword(string $pass) returns nothing

N

Sets the password to use

FtpClient::setHostName(string $host) returns nothing

N

Sets the hostname to connect to

FtpClient::setPort(softint $port) returns nothing

Y

Sets the port to connect to; throws an exception if the port is <= 0.

FtpClient::setURL(string $url) returns nothing

Y

Sets the URL

FtpClient::getUserName() returns any

N

Gets the current user name or NOTHING if not yet set.

FtpClient::getPassword() returns any

N

Gets the current password or NOTHING if not yet set.

FtpClient::getHostName() returns any

N

Gets the current hostname or NOTHING if not yet set.

FtpClient::getPort() returns int

N

Gets the current port number.

FtpClient::getURL() returns string

N

Gets the current FTP URL.

FtpClient::setEventQueue() returns nothing

FtpClient::setEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive socket and FtpClient events on both the data and control connections. Calling with no argument clears the queue.

FtpClient::setDataEventQueue() returns nothing

FtpClient::setDataEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive socket and FtpClient events on the data connection. Calling with no argument clears the queue.

FtpClient::setControlEventQueue() returns nothing

FtpClient::setControlEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive socket and FtpClient events on the control connection. Calling with no argument clears the queue.


4.7.1. FtpClient::constructor()

Synopsis

Creates the FtpClient object. It accepts one optional argument that will set the URL for the FTP connection; the path is ignored in the URL, however the username, password, hostname and port are respected; additionally if the protocol is "ftps", the client will attempt to establish a secure connection to the server according to RFC-4217 when the first connection is established.

A call to FtpClient::connect() must be made explicitly before any actions requiring a connection to the server are made; connections are not made implicitly by this class.

Prototype

FtpClient::constructor()

FtpClient::constructor(string $url)

Example
my FtpClient $ftp("ftp://user:pass@hostname");

Table 4.196. Arguments for FtpClient::constructor()

Argument

Description

string $url

The URL of the server to connect to; must have at least the hostname to connect to.


Table 4.197. Exceptions Thrown by FtpClient::constructor()

err

desc

UNSUPPORTED-PROTOCOL

Only "ftp" or "ftps" are allowed as the protocol in the URL.

FTP-URL-ERROR

No hostname given in the URL.


4.7.2. FtpClient::destructor()

Synopsis

Destroys the object.

Example
delete $ftp;
Events

EVENT_CHANNEL_CLOSED, EVENT_DELETED

4.7.3. FtpClient::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.198. Exceptions Thrown by FtpClient::copy()

err

desc

FTPCLIENT-COPY-ERROR

Objects of this class cannot be copied.


4.7.4. FtpClient::connect()

Synopsis

Connects to the FTP server and attempts a login; if any errors occur, an exception is thrown.

Prototype

FtpClient::connect() returns nothing

Example
$ftp.connect(); # connects to the URL set in the constructor
Events

EVENT_CONNECTING, EVENT_CONNECTED,EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED, EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.199. Exceptions Thrown by FtpClient::connect()

err

desc

FTP-RESPONSE-ERROR

Invalid response received from FTP server.

FTP-CONNECT-ERROR

Cannot establish connection on data port, no hostname set, FTP server reported an error, etc.

FTP-LOGIN-ERROR

Login denied by FTP server.


4.7.5. FtpClient::disconnect()

Synopsis

Disconnects from an FTP server.

Prototype

FtpClient::disconnect() returns nothing

Example
$ftp.disconnect();
Events

EVENT_CHANNEL_CLOSED

4.7.6. FtpClient::setSecure()

Synopsis

Make an FTPS connection to the server on the next connect. This method can only be called before a connection is established; if called when a connection has already been established, an exception will be thrown.

Prototype

FtpClient::setSecure(softbool $secure = True) returns nothing

Example
$ftp.setSecure();

Table 4.200. Arguments for FtpClient::setSecure()

Argument

Description

softbool $secure = True

if True, will try to make an FTPS connection on the next connect, if False, will try to make a cleartext FTP connection on the next connect.


Table 4.201. Exceptions thrown by FtpClient::setSecure()

err

desc

SET-SECURE-ERROR

cannot be called while a control connection has already been established.


4.7.7. FtpClient::setInsecure()

Synopsis

Make a non-encrypted connection to the server on the next connect.

Prototype

FtpClient::setInsecure() returns nothing

Example
$ftp.setInsecure();

Table 4.202. Exceptions thrown by FtpClient::setInsecure()

err

desc

SET-INSECURE-ERROR

cannot be called while a control connection has already been established.


4.7.8. FtpClient::setInsecureData()

Synopsis

Make a non-encrypted data connection to the server on the next connect even if the control connection is secure.

Prototype

FtpClient::setInsecureData() returns nothing

Example
$ftp.setInsecureData();

Table 4.203. Exceptions thrown by FtpClient::setInsecureData()

err

desc

SET-INSECUREDATA-ERROR

cannot be called while a control connection has already been established.


4.7.9. FtpClient::isSecure()

Synopsis

Returns True if the control connection is a secure TLS/SSL connection.

Prototype

FtpClient::isSecure() returns bool

Example
my bool $b = $ftp.isSecure();

Table 4.204. Return Values for FtpClient::isSecure()

Return Type

Description

bool

True if the control connection is encrypted, False if not.


4.7.10. FtpClient::isDataSecure()

Synopsis

Returns True if the data connections are secure TLS/SSL connections.

Prototype

FtpClient::isDataSecure() returns bool

Example
my bool $b = $ftp.isDataSecure();

Table 4.205. Return Values for FtpClient::isDataSecure()

Return Type

Description

bool

True if data connections are encrypted, False if not.


4.7.11. FtpClient::getSSLCipherName()

Synopsis

Returns the name of the cipher for an encrypted connection.

Prototype

FtpClient::getSSLCipherName() returns any

Example
my any $str = $ftp.getSSLCipherName();

Table 4.206. Return Values for FtpClient::getSSLCipherName()

Return Type

Description

string or nothing

The name of the cipher for an encrypted connection or NOTHING if an excrypted connection has not been established.


4.7.12. FtpClient::getSSLCipherVersion()

Synopsis

Returns the version string of the cipher for encrypted connections.

Prototype

FtpClient::getSSLCipherVersion() returns any

Example
my any $str = $ftp.getSSLCipherVersion();

Table 4.207. Return Values for FtpClient::getSSLCipherVersion()

Return Type

Description

string or nothing

The version string of the cipher for encrypted connections or NOTHING if an excrypted connection has not been established.


4.7.13. FtpClient::verifyPeerCertificate()

Synopsis

Returns a string code giving the result of verifying the remote certificate for secure (FTPS) connections. Return value are the keys described in the X509_VerificationReasons hash constant. This hash can also be used to generate a textual description of the verification result.

Prototype

FtpClient::verifyPeerCertificate() returns any

Example
my any $str = $ftp.verifyPeerCertificate();

Table 4.208. Return Values for FtpClient::verifyPeerCertificate()

Return Type

Description

string or nothing

A string code giving the result of verifying the peer's certificate. No value is returned if a secure connection has not been established.


4.7.14. FtpClient::setModeAuto()

Synopsis

Sets the object to automatically try to negotiate the data connections in EPSV, PASV, and PORT modes, in this order.

Prototype

FtpClient::setModeAuto() returns nothing

Example
$ftp.setModeAuto();

4.7.15. FtpClient::setModeEPSV()

Synopsis

Sets the object to only try to make data connections using EPSV (RFC-2428 extended passive) mode.

Prototype

FtpClient::setModeEPSV() returns nothing

Example
$ftp.setModeEPSV();

4.7.16. FtpClient::setModePASV()

Synopsis

Sets the object to only try to make data connections using PASV (RFC-959 passive) mode.

Prototype

FtpClient::setModePASV() returns nothing

Example
$ftp.setModePASV();

4.7.17. FtpClient::setModePORT()

Synopsis

Sets the object to only try to make data connections using PORT mode.

Prototype

FtpClient::setModePORT() returns nothing

Example
$ftp.setModePORT();

4.7.18. FtpClient::list()

Synopsis

Gets a string giving the list of files from the FTP server in the server's long format in the current working directory; returns NOTHING if the path cannot be found.

Prototype

FtpClient::list() returns any

FtpClient::list(string $path) returns any

Example
my any $str = $ftp.list();
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.209. Arguments for FtpClient::list()

Argument

Description

[string $path]

The optional path or argument (filter) to list.


Table 4.210. Return Values for FtpClient::list()

Return Type

Description

string or nothing

The string returned by the server without any translations or processing or NOTHING if the path cannot be found.


Table 4.211. Exceptions Thrown by FtpClient::list()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-LIST-ERROR

FTP server returned an error in response to the LIST command.


4.7.19. FtpClient::nlst()

Synopsis

Gets a list of file names in the current working directory from the FTP server.

Prototype

FtpClient::nlst() returns any

FtpClient::nlst(string $path) returns any

Example
my any $str = $ftp.nlst();
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.212. Arguments for FtpClient::nlst()

Argument

Description

[string $path]

The optional path or argument (filter) to list.


Table 4.213. Return Values for FtpClient::nlst()

Return Type

Description

string or nothing

The string returned by the server without any translations or processing or NOTHING if the path cannot be found.


Table 4.214. Exceptions Thrown by FtpClient::nlst()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-LIST-ERROR

FTP server returned an error in response to the NSLT command.


4.7.20. FtpClient::pwd()

Synopsis

Returns the server-side current working directory.

Prototype

FtpClient::pwd() returns string

Example
my string $str = $ftp.pwd();
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.215. Return Values for FtpClient::pwd()

Return Type

Description

string

The server-side current working directory.


Table 4.216. Exceptions Thrown by FtpClient::pwd()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-PWD-ERROR

FTP server returned an error to the PWD command.


4.7.21. FtpClient::cwd()

Synopsis

Changes the current working directory on the server.

Prototype

FtpClient::cwd(string $dir) returns nothing

Example
$ftp.cwd("/pub/gnu");
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.217. Arguments for FtpClient::cwd()

Argument

Description

string $dir

The directory to change to.


Table 4.218. Exceptions Thrown by FtpClient::cwd()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-CWD-ERROR

FTP server returned an error to the CWD command.

FTPCLIENT-CWD-PARAMETER-ERROR

Missing argument to the method.


4.7.22. FtpClient::get()

Synopsis

Gets a file from the FTP server and stores it on the local system. If any errors occur, an exception is thrown.

This method accesses the filesystem, so it is not available if PO_NO_FILESYSTEM is set.

Prototype

FtpClient::get(string $remote_file) returns nothing

FtpClient::get(string $remote_file, string $local_file) returns nothing

Example
$ftp.get("file.txt", "/tmp/file-1.txt");
Restrictions

Not available with PO_NO_FILESYSTEM

Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.219. Arguments for FtpClient::get()

Argument

Description

string $remote_file

The path on the server to the file to get.

[string $local_file]

If given, where to save the local file.


Table 4.220. Exceptions Thrown by FtpClient::get()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-FILE-OPEN-ERROR

Could not create the local file.

FTP-GET-ERROR

There was an error retrieving the file.

FTPCLIENT-GET-PARAMETER-ERROR

Missing argument to the method.


4.7.23. FtpClient::getAsBinary()

Synopsis

Gets a file from the FTP server and returns the file's contents as a binary value. For a similar function returning the file's contents as a string, see FtpClient::getAsString(); for a function that will get a remote file and save it on the local filesystem, see FtpClient::get().

Prototype

FtpClient::getAsBinary(string $remote_file) returns binary

Example
my binary $b = $ftp.getAsBinary("file.bin");
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.221. Arguments for FtpClient::getAsBinary()

Argument

Description

string $remote_file

The path on the server to the file to get.


Table 4.222. Return Values for FtpClient::getAsBinary()

Return Type

Description

binary

The file retrieved; if any errors occur an exception is raised.


Table 4.223. Exceptions Thrown by FtpClient::getAsBinary()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-FILE-OPEN-ERROR

Could not create the local file.

FTP-GET-ERROR

There was an error retrieving the file.

FTPCLIENT-GET-PARAMETER-ERROR

Missing argument to the method.


4.7.24. FtpClient::getAsString()

Synopsis

Gets a file from the FTP server and returns the file's contents as a string. For a similar function returning the file's contents as a binary, see FtpClient::getAsBinary(); for a function that will get a remote file and save it on the local filesystem, see FtpClient::get().

Prototype

FtpClient::getAsString(string $remote_file) returns string

Example
my string $str = $ftp.getAsString("file.txt");
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.224. Arguments for FtpClient::getAsString()

Argument

Description

string $remote_file

The path on the server to the file to get.


Table 4.225. Return Values for FtpClient::getAsString()

Return Type

Description

string

The file retrieved; if any errors occur an exception is raised.


Table 4.226. Exceptions Thrown by FtpClient::getAsString()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-FILE-OPEN-ERROR

Could not create the local file.

FTP-GET-ERROR

There was an error retrieving the file.

FTPCLIENT-GET-PARAMETER-ERROR

Missing argument to the method.


4.7.25. FtpClient::put()

Synopsis

Transfers a file to the FTP server. If any errors occur, an exception is thrown.

This method accesses the filesystem, so it is not available if PO_NO_FILESYSTEM is set.

Prototype

FtpClient::put(string $local_file) returns int

FtpClient::put(string $local_file, string $remote_file) returns int

Example
$ftp.put("/tmp/file-1.txt", "file.txt");
Restrictions

Not available with PO_NO_FILESYSTEM

Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.227. Arguments for FtpClient::put()

Argument

Description

string local_file

The path on the local system of the file to send.

[string $remote_file]

If given, where to save the file on the server.


Table 4.228. Exceptions Thrown by FtpClient::put()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-FILE-OPEN-ERROR

Could not open local file for reading.

FTP-FILE-PUT-ERROR

Could not determine file size of local file (stat() failed).

FTP-PUT-ERROR

An error occurred while sending the file.

FTPCLIENT-PUT-PARAMETER-ERROR

Missing argument to the method.


4.7.26. FtpClient::del()

Synopsis

Deletes a file on the FTP server; if any errors occur, an exception is thrown.

Prototype

FtpClient::del(string $remote_file) returns nothing

Example
$ftp.del("file-2.txt");
Events

EVENT_FTP_SEND_MESSAGE, EVENT_FTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_PACKET_SENT

Table 4.229. Arguments for FtpClient::del()

Argument

Description

string $remote_file

The path on the server to the file to delete.


Table 4.230. Return Values for FtpClient::del()

Return Type

Description

int

Always returns 0, on errors exceptions are raised.


Table 4.231. Exceptions Thrown by FtpClient::del()

err

desc

FTP-RECEIVE-ERROR

Incomplete message received on control port.

FTP-NOT-CONNECTED

Not connected to FTP server (call FtpClient::connect() first).

FTP-DELETE-ERROR

FTP server returned an error to the DELE command.

FTPCLIENT-DEL-PARAMETER-ERROR

Missing argument to the method.


4.7.27. FtpClient::setUserName()

Synopsis

Sets the username for logging in to the FTP server.

Prototype

FtpClient::setUserName(string $user) returns nothing

Example
$ftp.setUserName("ftp");

Table 4.232. Arguments for FtpClient::setUserName()

Argument

Description

string $user

The username to use when logging in to the FTP server.


Table 4.233. Exceptions Thrown by FtpClient::setUserName()

err

desc

FTPCLIENT-SETUSERNAME-PARAMETER-ERROR

Missing argument to the method.


4.7.28. FtpClient::setPassword()

Synopsis

Sets the login password for the FTP server to connect to.

Prototype

FtpClient::setPassword(string $pass) returns nothing

Example
$ftp.setPassword("ftp");

Table 4.234. Arguments for FtpClient::setPassword()

Argument

Description

string $pass

The password to use when logging in to the FTP server.


Table 4.235. Exceptions Thrown by FtpClient::setPassword()

err

desc

FTPCLIENT-SETPASSWORD-PARAMETER-ERROR

Missing argument to the method.


4.7.29. FtpClient::setHostName()

Synopsis

Sets the hostname value for the FTP server to connect to.

Prototype

FtpClient::setHostName(string $host) returns nothing

Example
$ftp.setHostName("hostname");

Table 4.236. Arguments for FtpClient::setHostName()

Argument

Description

string $host

The hostname to use when connecting to the FTP server.


Table 4.237. Exceptions Thrown by FtpClient::setHostName()

err

desc

FTPCLIENT-SETHOSTNAME-PARAMETER-ERROR

Missing argument to the method.


4.7.30. FtpClient::setPort()

Synopsis

Sets the control port value (default is 21).

Prototype

FtpClient::setPort(softint $port) returns nothing

Example
$ftp.setPort(21);

Table 4.238. Arguments for FtpClient::setPort()

Argument

Description

softint $port

The port to use when connecting to the FTP server.


Table 4.239. Exceptions Thrown by FtpClient::setPort()

err

desc

FTPCLIENT-SETPORT-PARAMETER-ERROR

Missing argument to the method.


4.7.31. FtpClient::setURL()

Synopsis

Sets the connection and login parameters based on the URL passed as an argument.

Prototype

FtpClient::setURL(string $url) returns nothing

Example
$ftp.setURL("ftps://user:pass@host");

Table 4.240. Arguments for FtpClient::setURL()

Argument

Description

string $url

The URL to use to set connection and login parameters for the FTP server.


Table 4.241. Exceptions Thrown by FtpClient::setURL()

err

desc

UNSUPPORTED-PROTOCOL

Only "ftp" is allowed as the protocol in the URL.

FTP-URL-ERROR

No hostname given in the URL.

FTPCLIENT-SETURL-PARAMETER-ERROR

Missing argument to the method.


4.7.32. FtpClient::getUserName()

Synopsis

Retrieves the current username.

Prototype

FtpClient::getUserName() returns any

Example
my any $user = $ftp.getUserName();

Table 4.242. Return Values for FtpClient::getUserName()

Return Type

Description

string or nothing

The current username value.


4.7.33. FtpClient::getPassword()

Synopsis

Retrieves the current login password value for this object.

Prototype

FtpClient::getPassword() returns any

Example
my any $pass = $ftp.getPassword();

Table 4.243. Return Values for FtpClient::getPassword()

Return Type

Description

string or nothing

The current password value.


4.7.34. FtpClient::getHostName()

Synopsis

Retrieves the current hostname value for this object.

Prototype

FtpClient::getHostName() returns any

Example
my any $host = $ftp.getHostName();

Table 4.244. Return Values for FtpClient::getHostName()

Return Type

Description

string or nothing

The current hostname value.


4.7.35. FtpClient::getPort()

Synopsis

Retrieves the current connection port value for this object.

Prototype

FtpClient::getPort() returns int

Example
my int $port = $ftp.getPort();

Table 4.245. Return Values for FtpClient::getPort()

Return Type

Description

int

The current connection port value.


4.7.36. FtpClient::getURL()

Synopsis

Retrieves the current connection URL string for this object.

Prototype

FtpClient::getURL() returns string

Example
my string $url = $ftp.getURL();

Table 4.246. Return Values for FtpClient::getURL()

Return Type

Description

string

The current URL value.


4.7.37. FtpClient::setEventQueue()

Synopsis

Sets a Queue object to receive socket and FtpClient events on both the data and control connections.

To remove the event queue and stop monitoring socket events, pass NOTHING to the method. See Event Handling for more information.

To control monitoring of network events on just the data connection or just the control connection, use FtpClient::setDataEventQueue or FtpClient::setControlEventQueue respectively

Prototype

FtpClient::setEventQueue() returns nothing

FtpClient::setEventQueue(Queue $queue) returns nothing

Example
$ftp.setEventQueue($queue);

Table 4.247. Arguments for FtpClient::setEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.7.38. FtpClient::setDataEventQueue()

Synopsis

Sets a Queue object to receive socket and FtpClient events on the data connection when retrieving data from an FTP server.

To remove the event queue and stop monitoring network events, pass NOTHING to the method. See Event Handling for more information.

To control monitoring of network events on just the control connection or on both connections with the same queue, use FtpClient::setControlEventQueue or FtpClient::setEventQueue respectively.

Prototype

FtpClient::setDataEventQueue() returns nothing

FtpClient::setDataEventQueue(Queue $queue) returns nothing

Example
$ftp.setDataEventQueue($queue);

Table 4.248. Arguments for FtpClient::setDataEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.7.39. FtpClient::setControlEventQueue()

Synopsis

Sets a Queue object to receive socket and FtpClient events on both the control connection.

To remove the event queue and stop monitoring network events, pass NOTHING to the method. See Event Handling for more information.

To control monitoring of network events on just the data connection or for both data and control connections simultaneously, use FtpClient::setDataEventQueue or FtpClient::setEventQueue respectively

Prototype

FtpClient::setControlEventQueue() returns nothing

FtpClient::setControlEventQueue(Queue $queue) returns nothing

Example
$ftp.setControlEventQueue($queue);

Table 4.249. Arguments for FtpClient::setControlEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.8. Program Class

Program objects allow Qore programs to support subprograms with restricted capabilities, for example, to support user-defined logic for application actions.

Parsing in Qore happens in two steps; first all code is parsed to pending data structures, and then in the second stage, all references are resolved, and, if there are no errors, then all changes are committed to the Program object. Note that all parse actions (Program::parse(), Program::parsePending(), Program::parseCommit(), and Program::parseRollback()) are atomic; there is a thread lock on each Program object to ensure atomicity, and if any parse errors occur in any stage of parsing, any pending changes to the Program object are automatically rolled back. However parse actions that affect only one stage of the two stages of parsing (Program::parsePending(), Program::parseCommit() and Program::parseRollback()) are atomic within themselves, but not between calls, so one thread may inadvertently commit changes to a Program object if two or more threads are trying to perform transaction-safe two-stage parsing on a Program object without explicit user locking.

The constants in the following table can be used to limit the capabilities of a Program object. These options should be binary-OR'ed together and passed to the Program object's constructor. Also see Command-Line Parsing for equivalent command-line options, and Parse Directives for equivalent parse directives.

Note that a program can provide controlled access to functionality otherwise restricted by parse options by exporting a custom API into the child program object using either the Program::importFunction() or Program::importGlobalVariable() method. This is possible because code (functions or object methods) imported into and called from a subprogram will run in the parent's space and therefore with the parent's capabilities.

The following constants are all in the Qore namespace.

Table 4.250. Parse Options

Constant

Details

Description

PO_NO_GLOBAL_VARS

%no-global-vars

Disallows the use of global variables.

PO_DEFAULT

no parse options

This option is the empty option, meaning no options are set.

PO_NO_SUBROUTINE_DEFS

%no-subroutine-defs

Disallows subroutine (function) definitions.

PO_NO_THREADS

%no-threads

Disallows any thread operations (the background operator and the thread_exit statement, for example) and the use of thread-relevant classes and functions (equivalent to PO_NO_THREAD_CLASSES | PO_NO_THREAD_CONTROL).

PO_NO_THREAD_CLASSES

%no-thread-classes

Disallows access to any thread classes.

PO_NO_THREAD_CONTROL

%no-thread-control

Disallows access to any thread-control functions and thread-relevant statements and operators (for example the background operator and the thread_exit statement).

PO_NO_TOP_LEVEL_STATEMENTS

%no-top-level

Disallows top level code.

PO_NO_CLASS_DEFS

%no-class-defs

Disallows class definitions.

PO_NO_NAMESPACE_DEFS

%no-namespace-defs

Disallows new namespace definitions.

PO_NO_CONSTANT_DEFS

%no-constant-defs

Disallows constant definitions.

PO_NO_NEW

%no-new

Disallows use of the new operator.

PO_NO_SYSTEM_CLASSES

n/a

Prohibits system classes from being imported into the new Program object.

PO_NO_USER_CLASSES

n/a

Prohibits user classes from being imported into the new Program object.

PO_NO_CHILD_PO_RESTRICTIONS

%no-child-restrictions

Allows child program objects to have fewer parse restrictions than the parent object.

PO_NO_EXTERNAL_INFO

%no-external-info

Disallows access to functionality that provides information about the computing environment.

PO_NO_EXTERNAL_PROCESS

%no-external-process

Disallows any access to external processes (with system(), backquote(), exec(), etc).

PO_REQUIRE_OUR

%require-our

Requires global variables to be declared with our before use.

PO_NO_PROCESS_CONTROL

%no-process-control

Disallows access to functions that would affect the current process (exit(), exec(), fork(), etc).

PO_LOCK_WARNINGS

%lock-warnings

Prohibits the warning mask from being changed.

PO_NO_NETWORK

%no-network

Disallows access to network functions.

PO_NO_FILESYSTEM

%no-filesystem

Disallows access to the filesystem.

PO_LOCK_WARNINGS

%lock-warnings

Disallows changes to the warning mask.

PO_NO_DATABASE

%no-database

Disallows access to database functionality.

PO_NO_GUI

%no-gui

Disallows access to functionality that draws graphics to the display.

PO_NO_TERMINAL_IO

%no-terminal-io

Disallows access to reading from and/or writing to the terminal.

PO_NO_THREAD_INFO

%no-thread-info

Disallows access to functionality that provides information about threading.

PO_NO_LOCALE_CONTROL

%no-locale-control

Disallows access to functionality that can change locale parameters.

PO_REQUIRE_PROTOTYPES

%require-prototypes

Requires all function and method parameters and return types to have type declarations. Variables and object members are not required to have type declarations.

PO_REQUIRE_TYPES

%require-types

Requires all function and method parameters, return types, variables, and object members to have type declarations. Additionally, this option implies PO_STRICT_ARGS.

PO_STRICT_ARGS

%strict-args

Prohibits access to builtin functions and methods flagged with RT_NOOP and also causes errors to be raised if excess arguments are given to functions that do not access excess arguments.


Table 4.251. Program Method Overview

Method

Except?

Description

Program::constructor(softint $options = PO_DEFAULT)

N

Creates the program object and optionally sets program capabilities (parse options)

Program::destructor()

N

Destroys the object. Blocks until all threads have terminated.

Program::copy()

Y

Throws an exception to prevent objects of this class from being copied.

Program::callFunction(string $func, ...) returns any

Y

Calls a function in the program object and returns the return value.

Program::callFunctionArgs(string $func, list $args) returns any

Program::callFunctionArgs(string $func, any $args) returns any

Y

Calls a function in the program object with the arguments given as a list

Program::disableParseOptions(int $options = PO_DEFAULT) returns nothing

Y

Removes the given parse options to the current parse option mask.

Program::existsFunction(string $func) returns bool

Program::existsFunction() returns nothing (RT_NOOP)

N

Checks if a user function exists in the program object

Program::getGlobalVariable(string $name) returns any

Program::getGlobalVariable(string $name, reference $found) returns any

N

Returns a the value of the global variable identified by the first string argument.

Program::getParseOptions() returns int

N

Returns a code of parse options set in the object.

Program::getScriptDir() returns any

N

Returns the current script directory as a string or NOTHING if not set.

Program::getScriptName() returns any

N

Returns the current script name as a string or NOTHING if not set.

Program::getScriptPath() returns any

N

Returns the current script directory and filename as a string or NOTHING if not set.

Program::getTimeZone() returns TimeZone

N

Returns the default local time zone for the object.

Program::getUserFunctionList() returns list

N

Returns a list of strings of all user functions defined in the program object.

Program::importFunction(string $name) returns nothing

Program::importFunction(string $name, string $new_name) returns nothing

Y

Imports a user function into the program object's space; any calls to the function will run in the parent's space.

Program::importGlobalVariable(string $name, bool $readonly = False) returns nothing

Y

Imports a global variable into the Program object's space. If the variable is an object, then any methods called will run in the parent's space.

Program::lockOptions() returns nothing

N

Locks parse options so that they cannot be changed.

Program::parse(string $code, string $label) returns nothing

Program::parse(string $code, string $label, softint $warn_mask) returns any

Y

Performs a complete parse and commit of the string passed; if a warning mask is given and warnings are raised, then the method returns an exception hash.

Program::parseCommit() returns nothing

Program::parseCommit(softint $warn_mask) returns any

Y

Commits all pending changes to the program object; if a warning mask is given and warnings are raised, then the method returns an exception hash.

Program::parsePending(string $code, string $label) returns nothing

Program::parsePending(string $code, string $label, softint $warn_mask) returns any

Y

Performs a 1st stage parse of the string passed; if a warning mask is given and warnings are raised, then the method returns an exception hash.

Program::parseRollback() returns nothing

N

Rolls back all pending changes to the program object

Program::run() returns any

Y

Runs the top-level code of the program object

Program::setParseOptions(int $options = PO_DEFAULT) returns nothing

Y

Adds the given parse options to the current parse option mask.

Program::setScriptPath(string $path) returns nothing

Program::setScriptPath() returns nothing

N

Sets (or clears) the script path (directory and filename) for the object.

Program::setTimeZone(TimeZone $zone) returns nothing

N

Sets the default local time zone for the object.

Program::setTimeZoneRegion(string $region) returns nothing

Y

Sets the default local time zone for the object from a path to a zoneinfo time zone region file.

Program::setTimeZoneUTCOffset(softint $secs_east) returns nothing

N

Sets the default local time zone for the object from a UTC offset in seconds east of UTC; for zones west of UTC, use negative numbers.


4.8.1. Program::constructor()

Synopsis

Creates the Program object. It accepts one optional argument that will set the program capabilities for the program object.

Prototype

Program::constructor(softint $options = PO_DEFAULT)

Example
my Program $pgm();

Table 4.252. Arguments for Program::constructor()

Argument

Description

softint $options = PO_DEFAULT

A binary OR'ed product of parse options.


4.8.2. Program::destructor()

Synopsis

Destroys the object. If any threads are running in the program, the destructor will block until the threads terminate.

Example
delete $pgm;

4.8.3. Program::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.253. Exceptions Thrown by Program::copy()

err

desc

PROGRAM-COPY-ERROR

Objects of this class cannot be copied.


4.8.4. Program::callFunction()

Synopsis

Calls a function in the program object and returns the return value. The function runs with the permissions of the Program object containing the function.

Prototype

Program::callFunction(string $func, ...) returns any

Example
$result = $pgm.callFunction("func_name", $arg1, $arg2);

Table 4.254. Arguments for Program::callFunction()

Argument

Description

string $func

The name of the function to call.

[...]

The remaining arguments passed to the method are passed to the function to be called.


Table 4.255. Return Values for Program::callFunction()

Return Type

Description

any

Depends on the function being called.


Table 4.256. Exceptions Thrown by Program::callFunction()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow this builtin function to be called.

NO-FUNCTION

The function does not exist.


4.8.5. Program::callFunctionArgs()

Synopsis

Calls a function in the program object and returns the return value, using the second argument as the argument list for the function call. The function runs with the permissions of the Program object containing the function.

Prototype

Program::callFunctionArgs(string $func, list $args) returns any

Program::callFunctionArgs(string $func, any $args) returns any

Example
$result = $pgm.callFunctionArgs("func_name", $arg_list);

Table 4.257. Arguments for Program::callFunctionArgs()

Argument

Description

string $func

The name of the function to call.

list or any $args

Argument list to be passed to the function; is a single non-list argument is passed, it will be treated as if it were the sole argument to the function.


Table 4.258. Return Values for Program::callFunctionArgs()

Return Type

Description

any

Depends on the function being called.


Table 4.259. Exceptions Thrown by Program::callFunctionArgs()

err

desc

INVALID-FUNCTION-ACCESS

Parse options do not allow this builtin function to be called.

NO-FUNCTION

The function does not exist.


4.8.6. Program::disableParseOptions()

Synopsis

Disables parse options in the parse option mask for the Program object. An exception is thrown if parse options have been locked (for example with Program::lockOptions()). For a reciprocal method that sets parse options, see Program::setParseOptions().

Prototype

Program::disableParseOptions(int $options = PO_DEFAULT) returns nothing

Example
# allow threading and GUI operations
$pgm.disableParseOptions(PO_NO_THREADS | PO_NO_GUI);

Table 4.260. Arguments for Program::disableParseOptions()

Argument

Description

int $options = PO_DEFAULT

A single parse option or binary-or combination of parse options to disable in the parse option mask for the current object.


Table 4.261. Exceptions Thrown by Program::disableParseOptions()

err

desc

OPTIONS-LOCKED

Parse options have been locked and cannot be changed.


4.8.7. Program::existsFunction()

Synopsis

Checks if a user function exists in the program object.

Prototype
Program::existsFunction(function_name)
Example

Program::existsFunction(string $func) returns bool

Program::existsFunction() returns nothing (RT_NOOP)

Table 4.262. Arguments for Program::existsFunction()

Argument

Description

string $func

The name of the function to check.


Table 4.263. Return Values for Program::existsFunction()

Return Type

Description

bool

Returns True if the function exists, False if not.


4.8.8. Program::getGlobalVariable()

Synopsis

Returns the value of the global variable identified by the first string argument giving the name of the variable (without any leading "$" symbol. An lvalue reference can be passed as the second argument in order to determine if the global variable exists (because this method could return NOTHING when the variable exists as well as when it does not).

Prototype

Program::getGlobalVariable(string $name) returns any

Program::getGlobalVariable(string $name, reference $found) returns any

Example
$val = $pgm.getGlobalVariable("error_count", \$exists);

Table 4.264. Arguments for Program::getGlobalVariable()

Argument

Description

string $name

The string name of the variable to find, not including the leading "$" character.

reference $found

If a reference is passed in this position, it will contain a boolean value after the method exits: if this value is True, that means that the variable exists in the Program object, False means that the variable does not exist.


Table 4.265. Return Values for Program::getParseOptions()

Return Type

Description

any

The value of the global variable (or NOTHING if it does not exist; note that also the variable could exist and return NOTHING as well; use a reference as the second argument to the method to determine if the variable exists or not).


This method does not throw any exceptions.

4.8.9. Program::getParseOptions()

Synopsis

Returns the current binary-or parse option mask for the Program object.

Prototype

Program::getParseOptions() returns int

Example
$mask = $pgm.getParseOptions();

Table 4.266. Return Values for Program::getParseOptions()

Return Type

Description

int

A mask of all parse options set (combined with binary or) for the current object.


4.8.10. Program::getScriptDir()

Synopsis

Gets the script directory set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_dir() function if called from within the Program. The value returned should normally include the trailing '/' character.

Prototype

Program::getScriptDir() returns any

Example
my any $dir = $pgm.getScriptDir();

Table 4.267. Return Values for Program::getScriptDir()

Return Type

Description

string or nothing

The current script directory or NOTHING if not set.


This method does not throw any exceptions.

4.8.11. Program::getScriptName()

Synopsis

Gets the script filename set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_path() function if called from within the Program.

Prototype

Program::getScriptName() returns any

Example
my any $name = $pgm.getScriptName();

Table 4.268. Return Values for Program::getScriptName()

Return Type

Description

string or nothing

The current script name if known, otherwise returns NOTHING.


This method does not throw any exceptions.

4.8.12. Program::getScriptPath()

Synopsis

Gets the script directory and filename set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_path() function if called from within the Program.

Prototype

Program::getScriptPath() returns any

Example
my any $path = $pgm.getScriptPath();

Table 4.269. Return Values for Program::getScriptPath()

Return Type

Description

string or nothing

The current script directory and filename if known, otherwise returns NOTHING.


This method does not throw any exceptions.

4.8.13. Program::getTimeZone()

Synopsis

Returns the default local time zone for the object.

See also TimeZone::get()

Prototype

Program::getTimeZone() returns TimeZone

Example
my TimeZone $zone = $pgm.getTimeZone();

Table 4.270. Return Values for Program::getTimeZone()

Return Type

Description

TimeZone

Returns the default local time zone for the object.


This method does not throw any exceptions.

4.8.14. Program::getUserFunctionList()

Synopsis

Returns a list of all user functions defined in the Program object.

Prototype

Program::getUserFunctionList() returns list

Example
my list $l = $pgm.getUserFunctionList();

Table 4.271. Return Values for Program::getUserFunctionList()

Return Type

Description

list

A list of strings giving the names of all functions implemented in the program object.


4.8.15. Program::importFunction()

Synopsis

Imports a user function into the program object's space; any calls to the imported function will run in the parent's space. This allows a user-defined API with greater capabilities than the embedded Program object to be imported into the embedded code.

Prototype

Program::importFunction(string $name) returns nothing

Program::importFunction(string $name, string $new_name) returns nothing

Example
$pgm.importFunction("function");

Table 4.272. Arguments for Program::importFunction()

Argument

Description

string $name, [string $new_name]

The name of the function to import and an optional new name for it to be registered under in the target Program.


Table 4.273. Exceptions Thrown by Program::importFunction()

err

desc

PROGRAM-IMPORTFUNCTION-PARAMETER-ERROR

No function name was passed to the method.

PROGRAM-IMPORTFUNCTION-PARAMETER-ERROR

Cannot import a function into the same Program object.

PROGRAM-IMPORTFUNCTION-NO-FUNCTION

The function does not exist.


4.8.16. Program::importGlobalVariable()

Synopsis

Imports a global variable into the program object's space. If the variable is an object, then any methods called from the subprogram will run in the parent's space.

Prototype

Program::importGlobalVariable(string $name, bool $readonly = False) returns nothing

Example
$pgm.importGlobalVariable("var");

Table 4.274. Arguments for Program::importGlobalVariable()

Argument

Description

string $name

The name of the global variable without the $

bool $readonly = False

If this argument is present and is True, then the variable will be imported read-only, and cannot be changed by the subprogram.


Table 4.275. Exceptions Thrown by Program::importGlobalVariable()

err

desc

PROGRAM-IMPORTGLOBALVARIABLE-PARAMETER-ERROR

No variable name was passed to the method.

PROGRAM-IMPORTGLOBALVARIABLE-EXCEPTION

The global variable does not exist.


4.8.17. Program::lockOptions()

Synopsis

Locks parse options so they cannot be changed.

Prototype

Program::lockOptions() returns nothing

Example
$pgm.lockOptions();

This method does not throw any exceptions.

4.8.18. Program::parse()

Synopsis

Parses the string argument and adds the code to the program object.

If a warning mask is given and masked warnings are raised during parsing, this method will return a hash with warning information.

Prototype

Program::parse(string $code, string $label) returns nothing

Program::parse(string $code, string $label, softint $warn_mask) returns any

Example
$pgm.parse($code, "label");

Table 4.276. Arguments for Program::parse()

Argument

Description

string $code

The code to parse.

string $label

A label identifying the code.

[softint $warn_mask]

An optional warning mask of bitwise-ORed warning values; if this option is non-zero and any warnings are raised during parsing, then a hash is returned of warning information.


Table 4.277. Return Values for Program::parse()

Return Type

Description

hash or nothing

If a warning mask is set and any masked warnings are raised during parsing, then an exception hash is returned of warning information (multiple warnings are linked in the hash through the "next" key, as with chained exceptions).


Table 4.278. Exceptions Thrown by Program::parse()

err

desc

PARSE-ERROR

An error occurred parsing the text.


4.8.19. Program::parseCommit()

Synopsis

Commits and pending code processed with Program::parsePending() to the Program object and resolves all outstanding references in the pending code. An exception in this method causes all pending code to be rolled back immediately.

If a warning mask is given and masked warnings are raised during parsing, this method will return a hash with warning information.

Prototype

Program::parseCommit() returns nothing

Program::parseCommit(softint $warn_mask) returns any

Example
$pgm.parseCommit();

Table 4.279. Arguments for Program::parseCommit()

Argument

Description

[softint $warn_mask]

An optional warning mask of bitwise-ORed warning values; if this option is non-zero and any warnings are raised during parsing, then a hash is returned of warning information.


Table 4.280. Return Values for Program::parseCommit()

Return Type

Description

hash or nothing

If a warning mask is set and any masked warnings are raised during parsing, then an exception hash is returned of warning information (multiple warnings are linked in the hash through the "next" key, as with chained exceptions).


Table 4.281. Exceptions Thrown by Program::parseCommit()

err

desc

PARSE-ERROR

An error occurred parsing the text.


4.8.20. Program::parsePending()

Synopsis

Parses the text passed to pending lists in the Program object; does not resolve all references or commit the code to the Program object. References are resolved in the Program::parseCommit() method. If an exception occurs in this method, all pending code is backed out, not just code parsed by this method.

If a warning mask is given and masked warnings are raised during parsing, this method will return a hash with warning information.

Prototype

Program::parsePending(string $code, string $label) returns nothing

Program::parsePending(string $code, string $label, softint $warn_mask) returns any

Example
$pgm.parsePending($code, "label");

Table 4.282. Arguments for Program::parsePending()

Argument

Description

string $code

The code to parse.

string $label

A label identifying the code.

[softint $warn_mask]

An optional warning mask of bitwise-ORed warning values; if this option is non-zero and any warnings are raised during parsing, then a hash is returned of warning information.


Table 4.283. Return Values for Program::parsePending()

Return Type

Description

hash or nothing

If a warning mask is set and any masked warnings are raised during parsing, then an exception hash is returned of warning information (multiple warnings are linked in the hash through the "next" key, as with chained exceptions).


Table 4.284. Exceptions Thrown by Program::parsePending()

err

desc

PARSE-ERROR

An error occurred parsing the text.


4.8.21. Program::parseRollback()

Synopsis

Rolls back any pending code processed with Program::parsePending() that has not yet been committed to the Program object with Program::parseCommit()

Prototype

Program::parseRollback() returns nothing

Example
$pgm.parseRollback();

4.8.22. Program::run()

Synopsis

Runs the program and optionally returns a value if the top-level code exits with a return statement.

Prototype

Program::run() returns any

Example
$pgm.run();

Table 4.285. Return Values for Program::run()

Return Type

Description

any

Depends on the program; any return statement at the top level of the program will return a value to this method.


4.8.23. Program::setParseOptions()

Synopsis

Sets parse options in the parse option mask for the Program object. An exception is thrown if parse options have been locked (for example with Program::lockOptions()). For a reciprocal method that disables parse options, see Program::disableParseOptions().

Prototype

Program::setParseOptions(int $options = PO_DEFAULT) returns nothing

Example
# disallow threading and GUI operations
$pgm.setParseOptions(PO_NO_THREADS | PO_NO_GUI);

Table 4.286. Arguments for Program::setParseOptions()

Argument

Description

int $options = PO_DEFAULT

A single parse option or binary-or combination of parse options to set in the parse option mask for the current object.


Table 4.287. Exceptions Thrown by Program::setParseOptions()

err

desc

OPTIONS-LOCKED

Parse options have been locked and cannot be changed.


4.8.24. Program::setScriptPath()

Synopsis

Sets the script path (directory and filename) for later retrieval with Program::getScriptPath(), Program::getScriptDir(), or Program::getScriptName() calls, or from code within the Program object with the get_script_path(), get_script_dir(), or get_script_name() functions.

Prototype

Program::setScriptPath(string $path) returns nothing

Program::setScriptPath() returns nothing

Example
$pgm.setScriptPath("/users/test/test.q");

Table 4.288. Arguments for Program::setScriptPath()

Argument

Description

string $path

The path (directory and filename) for the current script. If the directory component is missing, then "./" is assumed.


This method does not throw any exceptions.

4.8.25. Program::setTimeZone()

Synopsis

Sets the default local time zone for the object.

See also TimeZone::set().

Prototype

Program::setTimeZone(TimeZone $zone) returns nothing

Example
$pgm.setTimeZone($zone);

Table 4.289. Arguments for Program::setTimeZone()

Argument

Description

TimeZone $zone

The time zone to set as the local time zone for the Program object.


This method does not throw any exceptions.

4.8.26. Program::setTimeZoneRegion()

Synopsis

Sets the default local time zone for the object from a path to a zoneinfo time zone region file; if there are errors reading or parsing the file, an exception is thrown.

See also TimeZone::setRegion().

Prototype

Program::setTimeZoneRegion(string $region) returns nothing

Example
$pgm.setTimeZoneRegion("Europe/Prague");

Table 4.290. Arguments for Program::setTimeZoneRegion()

Argument

Description

string $region

The path to the zoneinfo file for the time zone region to set as the local time zone for the Program object.


Table 4.291. Exceptions Thrown by Program::setTimeZoneRegion()

err

desc

TZINFO-ERROR

Unable to read zoneinfo file; invalid file magic; error parsing zoneinfo file, etc


4.8.27. Program::setTimeZoneUTCOffset()

Synopsis

Sets the default time zone for the Program object based on the number of seconds east of UTC; for zones west of UTC, use negative numbers.

Time zones set with this method cannot have any daylight savings time information; to set a zone with daylight savings time information, use Program::setTimeZoneRegion() instead.

See also TimeZone::setUTCOffset().

Prototype

Program::setTimeZoneUTCOffset(softint $secs_east) returns nothing

Example

The following examples are all equivalent, setting the time zone to +02 UTC:

$pgm.setTimeZoneUTCOffset(7200);
$pgm.setTimeZoneUTCOffset(2h);
$pgm.setTimeZoneUTCOffset(PT2H);

Table 4.292. Arguments for Program::setTimeZone()

Argument

Description

softint $secs_east

The number of seconds east of UTC; for zones west of UTC, use negative numbers


This method does not throw any exceptions.

4.9. Socket Class

Note: This class is not available with the PO_NO_NETWORK parse option.

Socket objects allow Qore programs safe access to network sockets. Non-blocking socket I/O can be performed by appending a timeout value in milliseconds to all Socket::recv*() methods, or by using the Socket::isDataAvailable() method with a timeout value in milliseconds (1000 ms = 1 second). Note that as with all Qore functions and methods accepting a timeout value, relative date/time values can be given instead of integers to make the source more readable, for example:

my $rc = $socket.isDataAvailable(1250ms); # times out in 1.25 seconds

Socket objects can automatically convert character encodings if desired when sending string data with Socket::send(). Use the Socket::setCharset() method to set the character encoding for the socket. If a character encoding is set, and string data is read with the Socket::recv() method, then it will be tagged with the encoding of the socket as well.

Client applications should call Socket::connect() to connect to a remote port or a UNIX domain socket (socket file on the local server). However, if the remote end is expecting a TLS/SSL connection, use Socket::connectSSL() instead.

Server applications should call Socket::bind(), Socket::listen(), and Socket::accept() in this order to accept incoming connections. Normally a new thread should be started after the Socket::accept() call to handle the new connection in a separate thread (Socket::accept() returns a new Socket object for the accepted connection).

To support TLS/SSL server connections, first set the certificate and private key with the Socket::setCertificate() and Socket::setPrivateKey() methods (see the SSLCertificate Class and the SSLPrivateKey Class for more information on the parameters required for these methods). Then Socket::acceptSSL() should be called after the socket is in a listening state to accept client connections and negotiate a TLS/SSL connection.

This class supports posting events to a Queue. See Event Handling for more information.

The events raised by this object are listed in the following table:

Table 4.293. Socket Events

Name

Description

EVENT_PACKET_READ

Raised when a network packet is received.

EVENT_PACKET_SENT

Raised when a network packet is sent.

EVENT_CHANNEL_CLOSED

Raised when a socket is closed.

EVENT_DELETED

Raised when the object being monitored is deleted.

EVENT_HOSTNAME_LOOKUP

Raised when a hostname lookup is attempted.

EVENT_HOSTNAME_RESOLVED

Raised when a hostname lookup is resolved.

EVENT_HTTP_SEND_MESSAGE

Raised when an HTTP message is sent.

EVENT_HTTP_MESSAGE_RECEIVED

Raised when an HTTP message is received.

EVENT_CONNECTING

Raised right before a socket connection attempt is made.

EVENT_CONNECTED

Raised when the socket connection has been established.

EVENT_START_SSL

Raised when socket SSL negotiation starts.

EVENT_SSL_ESTABLISHED

Raised when SSL communication has been negotiated and established.


Table 4.294. Socket Method Overview

Method

Except?

Description

Socket::constructor()

N

Creates the socket object

Socket::destructor()

N

Closes the socket if it's open and destroys the object.

Socket::copy()

N

Creates a new Socket object, not based on the parent.

Socket::connect(string $dest, softint $timeout_ms = -1) returns nothing

Socket::connect(string $dest, date $timeout) returns nothing

Y

Connects to a remote port (if the string has a format "host:port") or UNIX domain socket file with an optional timeout value with a millisecond resolution.

Socket::connectINET(string $host, softint $port, softint $timeout_ms = -1) returns nothing

Socket::connectINET(string $host, softint $port, date $timeout) returns nothing

Y

Connects to the given host and port with an optional timeout value with a millisecond resolution.

Socket::connectUNIX(string $file) returns nothing

Y

Connects to the UNIX domain socket file.

Socket::connectSSL(string $dest, softint $timeout_ms = -1) returns nothing

Socket::connectSSL(string $dest, date $timeout) returns nothing

Y

Connects to a remote socket and attempts to establish a TLS/SSL connection; accepts an optional timeout value with a millisecond resolution.

Socket::connectINETSSL(string $host, softint $port, softint $timeout_ms = -1) returns nothing

Socket::connectINETSSL(string $host, softint $port, date $timeout) returns nothing

Y

Connects to the given host and port and attempts to establish a TLS/SSL connection; accepts an optional timeout value with a millisecond resolution.

Socket::connectUNIXSSL(string $file) returns nothing

Y

Connects to the UNIX domain socket file and attempts to establish a TLS/SSL connection.

Socket::bind(string $bind_to, bool $reuseaddr = False) returns int

Socket::bind(int $port, bool $reuseaddr = False) returns int

N

Binds the socket to a port, interface and port (if the $bind_to string has a format "host:port"), or UNIX domain socket file. If the second parameter is True, then the socket will set the SO_REUSEADDR option, which will allow the socket to be bound to a port that is not yet closed (for example, in a TIME_WAIT state).

Socket::accept() returns Socket

Y

Accepts connections on a listening socket.

Socket::acceptSSL() returns Socket

Y

Accepts a remote connection and attempts to negotiate a TLS/SSL connection.

Socket::shutdownSSL() returns nothing

Y

Shuts down the SSL connection on a secure connection.

Socket::listen() returns int

Y

Listens for connections on the socket; sets the socket in a listening state.

Socket::isDataAvailable(softint $timeout_ms = 0) returns bool

Socket::isDataAvailable(date $timeout) returns bool

N

Returns True or False depending on whether there is data to be read on the socket.

Socket::isWriteFinished(softint $timeout_ms = 0) returns bool

Socket::isWriteFinished(date $timeout) returns bool

N

Returns True or False depending on whether all data has been written to the socket.

Socket::send(data $data) returns int

Y

Sends string or binary data over the socket; string data is converted to the socket's encoding if necessary.

Socket::sendBinary(data $data) returns int

Y

Sends string or binary data over the socket; string data is not converted to the socket's encoding, but sent exactly as-is.

Socket::sendi1(softint $i = 0) returns int

Y

Sends a 1-byte integer over the socket.

Socket::sendi2(softint $i = 0) returns int

Y

Sends a 2-byte (16-bit) integer in big-endian format (network byte order) over the socket.

Socket::sendi4(softint $i = 0) returns int

Y

Sends a 4-byte (32-bit) integer in big-endian format (network byte order) over the socket.

Socket::sendi8(softint $i = 0) returns int

Y

Sends an 8-byte (64-bit) integer in big-endian format (network byte order) over the socket.

Socket::sendi2LSB(softint $i = 0) returns int

Y

Sends a 2-byte (16-bit) integer in little-endian format over the socket.

Socket::sendi4LSB(softint $i = 0) returns int

Y

Sends a 4-byte (32-bit) integer in little-endian format over the socket.

Socket::sendi8LSB(softint $i = 0) returns int

Y

Sends an 8-byte (64-bit) integer in little-endian format over the socket.

Socket::sendHTTPMessage(string $method, string $path, string $http_version, hash $headers, data $body = binary()) returns nothing

Y

Sends an HTTP message with a method and user-defined headers given as a hash and an optional message body.

Socket::sendHTTPResponse(softint $status_code, string $desc, string $http_version, hash $headers, data $body = binary())

Y

Sends an HTTP response with user-defined headers given as a hash and an optional message body.

Socket::recv(softint $size = 0, softint $timeout_ms = -1) returns string

Socket::recv(softint $size = 0, date $timeout) returns string

Y

Receives data from the socket and returns a string.

Socket::recvi1(softint $timeout_ms = -1) returns int

Socket::recvi1(date $timeout) returns int

Y

Receives a 1-byte signed integer from the socket.

Socket::recvi2(softint $timeout_ms = -1) returns int

Socket::recvi2(date $timeout) returns int

Y

Receives a 2-byte (16-bit) signed integer in big-endian format (network byte order) from the socket.

Socket::recvi4(softint $timeout_ms = -1) returns int

Socket::recvi4(date $timeout) returns int

Y

Receives a 4-byte (32-bit) signed integer in big-endian format (network byte order) from the socket.

Socket::recvi8(softint $timeout_ms = -1) returns int

Socket::recvi8(date $timeout) returns int

Y

Receives an 8-byte (64-bit) signed integer in big-endian format (network byte order) from the socket.

Socket::recvi2LSB(softint $timeout_ms = -1) returns int

Socket::recvi2LSB(date $timeout) returns int

Y

Receives a 2-byte (16-bit) signed integer in little-endian format from the socket.

Socket::recvi4LSB(softint $timeout_ms = -1) returns int

Socket::recvi4LSB(date $timeout) returns int

Y

Receives a 4-byte (32-bit) signed integer in little-endian format from the socket.

Socket::recvi8LSB(softint $timeout_ms = -1) returns int

Socket::recvi8LSB(date $timeout) returns int

Y

Receives an 8-byte (64-bit) signed integer in little-endian format from the socket.

Socket::recvu1(softint $timeout_ms = -1) returns int

Socket::recvu1(date $timeout) returns int

Y

Receives a 1-byte unsigned integer from the socket.

Socket::recvu2(softint $timeout_ms = -1) returns int

Socket::recvu2(date $timeout) returns int

Y

Receives a 2-byte (16-bit) unsigned integer in big-endian format (network byte order) from the socket.

Socket::recvu4(softint $timeout_ms = -1) returns int

Socket::recvu4(date $timeout) returns int

Y

Receives a 4-byte (32-bit) unsigned integer in big-endian format (network byte order) from the socket.

Socket::recvu2LSB(softint $timeout_ms = -1) returns int

Socket::recvu2LSB(date $timeout) returns int

Y

Receives a 2-byte (16-bit) unsigned integer in little-endian format from the socket.

Socket::recvu4LSB(softint $timeout_ms = -1) returns int

Socket::recvu4LSB(date $timeout) returns int

Y

Receives a 4-byte (32-bit) unsigned integer in little-endian format from the socket.

Socket::recvBinary(softint $size = 0, softint $timeout_ms = -1) returns binary

Socket::recvBinary(softint $size = 0, date $timeout) returns binary

Y

Receives data on a socket and returns a binary object

Socket::readHTTPHeader(softint $timeout_ms = -1) returns any

Y

Retuns a hash representing the data in the HTTP header read, or, if the data cannot be parsed as an HTTP header, the data read is returned as a string.

Socket::getPort() returns int

N

Returns the port number of the socket for INET sockets.

Socket::shutdown() returns int

N

Ensures that a socket will be closed even if shared with other processes.

Socket::close() returns int

N

Closes the socket.

Socket::getCharset() returns string

N

Returns the character encoding for the socket.

Socket::setCharset(string $encoding) returns nothing

N

Sets the character encoding for the socket.

Socket::getNoDelay() returns bool

N

Returns the TCP_NODELAY setting for the socket.

Socket::setNoDelay(bool $nodelay = True) returns int

N

Sets the TCP_NODELAY setting for the socket.

Socket::getSocket() returns int

N

Returns the socket file descriptor number.

Socket::getSSLCipherName() returns any

N

Returns the name of the cipher for an encrypted connection or NOTHING is a secure connection has not been established.

Socket::getSSLCipherVersion() returns any

N

Returns the version string of the cipher for encrypted connections or NOTHING is a secure connection has not been established.

Socket::isSecure() returns bool

N

Returns True if the connection is a secure TLS/SSL connection.

Socket::isOpen() returns bool

N

Returns True if the socket is open.

Socket::setCertificate(SSLCertificate $cert) returns nothing

Socket::setCertificate(string $cert_pem) returns nothing

Socket::setCertificate(binary $cert_der) returns nothing

N

Sets the X.509 certificate to use for negotiating encrypted connections.

Socket::setPrivateKey(SSLPrivateKey $key) returns nothing

Socket::setPrivateKey(string $key_pem, string $pass) returns nothing

Socket::setPrivateKey(string $key_pem) returns nothing

Socket::setPrivateKey(binary $key_der) returns nothing

N

Sets the private key to use for negotiating encrypted connections along with the X.509 certificate.

Socket::verifyPeerCertificate() returns any

N

Returns a string code giving the result of verifying the remote certificate or NOTHING if an encrypted connection is not currently established.

Socket::setEventQueue() returns nothing

Socket::setEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive socket events, or clears the queue when called with no argument..


4.9.1. Socket::constructor()

Synopsis

Creates the socket object.

Prototype

Socket::constructor()

Example
my Socket $sock();

4.9.2. Socket::destructor()

Synopsis

Closes the socket if it's open and destroys the object. If the socket was a UNIX domain socket, and was created with Socket::bind(), then the socket file will be deleted as well.

Example
delete $sock;
Events

EVENT_CHANNEL_CLOSED, EVENT_DELETED

4.9.3. Socket::copy()

Synopsis

Creates a new Socket object, not based on the original.

Example
my Socket $new_sock = $sock.copy();

4.9.4. Socket::bind()

Synopsis

Binds the socket to a port, interface and port (if the $bind_to string has a format "host:port"), or UNIX domain socket file. If the second parameter is True, then the socket will set the SO_REUSEADDR option, which will allow the socket to be bound to a port that is not yet closed (for example, in a TIME_WAIT state).

Prototype

Socket::bind(string $bind_to, bool $reuseaddr = False) returns int

Socket::bind(int $port, bool $reuseaddr = False) returns int

Examples
# bind to port 80 on all interfaces on the local system and reuse the address
$sock.bind(80, True);
# bind to interface 192.168.2.23 port 8080 and do not reuse the address
$sock.bind("192.168.2.23:8080");
# bind to UNIX domain socket file "/tmp/socket"
$sock.bind("/tmp/socket");

Table 4.295. Arguments for Socket::bind(string $bind_to, bool $reuseaddr = False) Variant

Argument

Description

string $bind_to

If a colon appears in the string, the string will be assumed to be a hostname:port specification, and the port on the named IP address will be bound, otherwise, if the string contains no colon, the socket will be bound to a UNIX domain socket file on the local filesystem with the given name.

bool $reuseaddr = False

If this optional argument evaluates to True, the SO_REUSEADDR option will be set on the socket, which will allow the socket to be bound to a port that is not yet closed (for example, in a TIME_WAIT state).


Table 4.296. Arguments for Socket::bind(int $port, bool $reuseaddr = False) Variant

Argument

Description

int $port, bool $reuseaddr = False

The first argument gives the port number on the local machine; all network interfaces will be bound with this port number.

bool $reuseaddr = False

If this optional argument evaluates to True, the SO_REUSEADDR option will be set on the socket, which will allow the socket to be bound to a port that is not yet closed (for example, in a TIME_WAIT state).


Table 4.297. Return Values for Socket::bind()

Return Type

Description

int

Returns 0 for success, -1 for error.


4.9.5. Socket::accept()

Synopsis

Accepts connections on a listening socket (see Socket::listen()). As this method does not accept a timeout, use Socket::isDataAvailable() to check if data is available on the socket before calling if necessary.

Prototype

Socket::accept() returns Socket

Example
my Socket $new_socket = $sock.accept();

Table 4.298. Return Values for Socket::accept()

Return Type

Description

Socket

When a new connection has been accepted, a new Socket object is returned for the new connection.


Table 4.299. Exceptions Thrown by Socket::accept()

err

desc

SOCKET-NOT-OPEN

The socket is not bound.


4.9.6. Socket::acceptSSL()

Synopsis

Accepts a remote connection and attempts to negotiate a TLS/SSL connection. As this method does not accept a timeout, use Socket::isDataAvailable() to check if data is available on the socket before calling if necessary.

Prototype

Socket::acceptSSL() returns Socket

Example
my Socket $new_sock = $sock.acceptSSL();
Events

EVENT_START_SSL, EVENT_SSL_ESTABLISHED

Table 4.300. Return Values for Socket::acceptSSL()

Return Type

Description

Socket

A new socket object is returned for the new connection.


Table 4.301. Exceptions thrown by Socket::acceptSSL()

err

desc

SOCKET-SSL-ERROR

An error occurred establishing the TLS/SSL connection.


4.9.7. Socket::connect()

Synopsis

Connects the socket to a remote (or local) port or UNIX domain socket file, for network (INET) connections, accepts an optional timeout value in milliseconds (relative date/time values can be given instead of an integer in milliseconds to make the source more readable; ex: 20s). If any errors occur, an exception is thrown.

See also Socket::connectUNIX(), Socket::connectUNIX(), Socket::connectSSL(), Socket::connectINETSSL(), and Socket::connectUNIXSSL().

Prototype

Socket::connect(string $dest, softint $timeout_ms = -1) returns nothing

Socket::connect(string $dest, date $timeout) returns nothing

Examples
$sock.connect("192.168.1.45:8080", 30s); # connect to 192.168.1.45 port 8080 with a 30 second timeout
$sock.connect("/tmp/socket");            # connect to UNIX domain socket file "/tmp/socket"
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED

Table 4.302. Arguments for Socket::connect()

Argument

Description

string $dest

If a colon appears in the string, the string will be assumed to be a hostname:port specification to connect to. If the string contains no colon, the socket will try to connect to a UNIX domain socket file on the local filesystem with the given name.

softint $timeout_ms = -1 or date $timeout

If a timeout value is passed and the connection takes longer to establish than the timeout, an exception is thrown.


Table 4.303. Exceptions Thrown by Socket::connect()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket (cannot resolve hostname, no listener, timeout exceeded, etc).


4.9.8. Socket::connectINET()

Synopsis

Connects the socket to a remote (or local) port; accepts an optional timeout value in milliseconds (relative date/time values can be given instead of an integer in milliseconds to make the source more readable; ex: 20s). If any errors occur, an exception is thrown.

See also Socket::connect(), Socket::connectUNIX(), Socket::connectSSL(), Socket::connectINETSSL(), and Socket::connectUNIXSSL().

Prototype

Socket::connectINET(string $host, softint $port, softint $timeout_ms = -1) returns nothing

Socket::connectINET(string $host, softint $port, date $timeout) returns nothing

Examples
# connect to 192.168.1.45 port 8080 with a 30 second timeout
$sock.connectINET("192.168.1.45", 8080, 30s);
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED

Table 4.304. Arguments for Socket::connectINET()

Argument

Description

string $host

The host name or IP address to connect to.

softint $port

The port number to connect to.

softint $timeout_ms = -1 or date $timeout

If a timeout value is passed and the connection takes longer to establish than the timeout, an exception is thrown.


Table 4.305. Exceptions Thrown by Socket::connectINET()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket (cannot resolve hostname, no listener, timeout exceeded, etc).


4.9.9. Socket::connectINETSSL()

Synopsis

Connects the socket to a remote (or local) port and attempts to establish a TLS/SSL connection; accepts an optional timeout value in milliseconds (relative date/time values can be given instead of an integer in milliseconds to make the source more readable; ex: 20s). If any errors occur, an exception is thrown.

See also Socket::connect(), Socket::connectUNIX(), Socket::connectSSL(), Socket::connectINET(), and Socket::connectUNIXSSL().

Prototype

Socket::connectINETSSL(string $host, softint $port, softint $timeout_ms = -1) returns nothing

Socket::connectINETSSL(string $host, softint $port, date $timeout) returns nothing

Examples
# connect to 192.168.1.45 port 8080 with a 30 second timeout
$sock.connectINETSSL("192.168.1.45", 8080, 30s);
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED

Table 4.306. Arguments for Socket::connectINETSSL()

Argument

Description

string $host

The host name or IP address to connect to.

softint $port

The port number to connect to.

softint $timeout_ms = -1 or date $timeout

If a timeout value is passed and the connection takes longer to establish than the timeout, an exception is thrown.


Table 4.307. Exceptions Thrown by Socket::connectINETSSL()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket (cannot resolve hostname, no listener, timeout exceeded, etc).


4.9.10. Socket::connectUNIX()

Synopsis

Connects the socket to a UNIX domain socket file. If any errors occur, an exception is thrown.

See also Socket::connect(), Socket::connectINET(), Socket::connectSSL(), Socket::connectINETSSL(), and Socket::connectUNIXSSL().

Prototype

Socket::connectUNIX(string $file) returns nothing

Examples
# connect to UNIX domain socket file "/tmp/socket"
$sock.connectUNIX("/tmp/socket");
Events

EVENT_CONNECTING, EVENT_CONNECTED

Table 4.308. Arguments for Socket::connectUNIX()

Argument

Description

string $file

The socket will try to connect to a UNIX domain socket file on the local filesystem with the given name.


Table 4.309. Exceptions Thrown by Socket::connectUNIX()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket.


4.9.11. Socket::connectUNIXSSL()

Synopsis

Connects the socket to a UNIX domain socket file and attempts to establish a TLS/SSL connection. If any errors occur, an exception is thrown.

See also Socket::connect(), Socket::connectUNIX(), Socket::connectSSL(), Socket::connectINETSSL(), and Socket::connectINET().

Prototype

Socket::connectUNIXSSL(string $file) returns nothing

Examples
# connect to UNIX domain socket file "/tmp/socket"
$sock.connectUNIXSSL("/tmp/socket");
Events

EVENT_CONNECTING, EVENT_CONNECTED

Table 4.310. Arguments for Socket::connectUNIXSSL()

Argument

Description

string $file

The socket will try to connect to a UNIX domain socket file on the local filesystem with the given name.


Table 4.311. Exceptions Thrown by Socket::connectUNIXSSL()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket.


4.9.12. Socket::connectSSL()

Synopsis

Connects to a remote socket and attempts to establish a TLS/SSL connection, for network (INET) connections, accepts an optional timeout value in milliseconds (relative date/time values can be given instead of an integer in milliseconds to make the source more readable; ex: 20s). If any errors occur, an exception is thrown.

See also Socket::connect(), Socket::connectUNIX(), Socket::connectUNIXSSL(), Socket::connectINETSSL(), and Socket::connectINET().

Prototype

Socket::connectSSL(string $dest, softint $timeout_ms = -1) returns nothing

Socket::connectSSL(string $dest, date $timeout) returns nothing

Examples
$sock.connectSSL("192.168.1.45:8080", 30s); # connect to 192.168.1.45 port 8080 with a 30-second timeout
$sock.connectSSL("/tmp/socket");            # connect to UNIX domain socket file "/tmp/socket"
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED

Table 4.312. Arguments for Socket::connectSSL()

Argument

Description

string $dest

If a colon appears in the string, the string will be assumed to be a hostname:port specification to connect to. If the string contains no colon, the socket will try to connect to a UNIX domain socket file on the local filesystem with the given name.

softint $timeout_ms = -1 or date $timeout

If a timeout value is passed and the connection takes longer to establish than the timeout, an exception is thrown.


Table 4.313. Exceptions thrown by Socket::connectSSL()

err

desc

SOCKET-CONNECT-ERROR

An error occured connecting to the remote socket (cannot resolve hostname, no listener, timeout exceeded, etc).

SOCKET-SSL-ERROR

An error occurred establishing the TLS/SSL connection.


4.9.13. Socket::listen()

Synopsis

Listens for new connections on a bound socket (see Socket::bind())

Prototype

Socket::listen() returns int

Example
$sock.listen();

Table 4.314. Return Values for Socket::listen()

Return Type

Description

int

Returns 0 for success, -1 for error.


Table 4.315. Exceptions Thrown by Socket::listen()

err

desc

SOCKET-NOT-OPEN

The socket is not bound.


4.9.14. Socket::shutdownSSL()

Synopsis

Shuts down the SSL connection on a secure connection; if any errors occur, an exception is raised.

Prototype

Socket::shutdownSSL() returns nothing

Example
$sock.shutdownSSL();

Table 4.316. Exceptions thrown by Socket::shutdownSSL()

err

desc

SOCKET-SSL-ERROR

An error occurred shutting down the TLS/SSL connection.


4.9.15. Socket::getSSLCipherName()

Synopsis

Returns the name of the cipher for an encrypted connection or NOTHING if an encrypted connection has not been established.

Prototype

Socket::getSSLCipherName() returns any

Example
my any $str = $sock.getSSLCipherName();

Table 4.317. Return Values for Socket::getSSLCipherName()

Return Type

Description

string or nothing

The name of the cipher for an encrypted connection or NOTHING if an encrypted connection has not been established.


4.9.16. Socket::getSSLCipherVersion()

Synopsis

Returns the version string of the cipher for encrypted connections or NOTHING if an encrypted connection has not been established.

Prototype

Socket::getSSLCipherVersion() returns any

Example
my any $str = $sock.getSSLCipherVersion();

Table 4.318. Return Values for Socket::getSSLCipherVersion()

Return Type

Description

string or nothing

The version string of the cipher for encrypted connections or NOTHING if an encrypted connection has not been established.


4.9.17. Socket::isSecure()

Synopsis

Returns True if the connection is a secure TLS/SSL connection.

Prototype

Socket::isSecure() returns bool

Example
my bool $b = $sock.isSecure();

Table 4.319. Return Values for Socket::isSecure()

Return Type

Description

bool

True if the connection is encrypted, False if not.


4.9.18. Socket::isOpen()

Synopsis

Returns True if the socket is open.

Prototype

Socket::isOpen() returns bool

Example
my bool $b = $sock.isOpen();

Table 4.320. Return Values for Socket::isOpen()

Return Type

Description

bool

True if the socket is open, False if not.


4.9.19. Socket::setCertificate()

Synopsis

Sets the X.509 certificate to use for negotiating encrypted connections. Requires an SSLCertificate object as the only argument to the method or the PEM or DER-encoded form of the certificate.

Prototype

Socket::setCertificate(SSLCertificate $cert) returns nothing

Socket::setCertificate(string $cert_pem) returns nothing

Socket::setCertificate(binary $cert_der) returns nothing

Example
$sock.setCertificate($cert);

Table 4.321. Arguments for Socket::setCertificate()

Argument

Description

SSLCertificate $cert

This must be an SSL Certificate object.

string $cert_pem

The PEM-encoded string for the SSL Certificate.

binary $cert_der

The DER-encoded binary for the SSL Certificate.


4.9.20. Socket::setPrivateKey()

Synopsis

Sets the private key to use for negotiating encrypted connections along with the X.509 certificate. Requires an SSLPrivateKey object as the only argument to the method or the PEM or DER-encoded form of the private key.

Prototype

Socket::setPrivateKey(SSLPrivateKey $key) returns nothing

Socket::setPrivateKey(string $key_pem, string $pass) returns nothing

Socket::setPrivateKey(string $key_pem) returns nothing

Socket::setPrivateKey(binary $key_der) returns nothing

Example
$sock.setPrivateKey($pkey);

Table 4.322. Arguments for Socket::setPrivateKey()

Argument

Description

SSLPrivateKey $key

The private key for the certificate.

string $key_pem, [string $pass]

The PEM-encoded string for the private key for the certificate and optionally the password if required.

binary $key_der

The DER-encoded binary form of the private key for the certificate.


4.9.21. Socket::verifyPeerCertificate()

Synopsis

Returns a string code giving the result of verifying the remote certificate. Return value are the keys described in the X509_VerificationReasons hash constant. This hash can also be used to generate a textual description of the verification result.

Prototype

Socket::verifyPeerCertificate() returns any

Example
my any $str = $sock.verifyPeerCertificate();

Table 4.323. Return Values for Socket::verifyPeerCertificate()

Return Type

Description

string or nothing

A string code giving the result of verifying the peer's certificate. No value is returned if a secure connection has not been established.


4.9.22. Socket::setEventQueue()

Synopsis

Sets a Queue object to receive socket events. To remove the event queue and stop monitoring socket events; call with no arguments or pass NOTHING to the method. See Event Handling for more information.

Prototype

Socket::setEventQueue() returns nothing

Socket::setEventQueue(Queue $queue) returns nothing

Example
$sock.setEventQueue($queue);

Table 4.324. Arguments for Socket::setEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.9.23. Socket::isDataAvailable()

Synopsis

Returns True is data is available on the socket, takes an optional timeout. With a timeout of zero this method can be used for non-blocking polling the socket for data (can also be used to poll for new connections before Socket::accept()).

Prototype

Socket::isDataAvailable(softint $timeout_ms = 0) returns bool

Socket::isDataAvailable(date $timeout) returns bool

Example
my bool $b = $sock.isDataAvailable(); # returns True if data is available now

Table 4.325. Arguments for Socket::isDataAvailable()

Argument

Description

softint $timeout_ms = 0 or date $timeout

An optional timeout in milliseconds (1/1000 second). If no timeout is given, the method returns immediately.


Table 4.326. Return Values for Socket::isDataAvailable()

Return Type

Description

bool

True if data is available on the socket, False if not.


4.9.24. Socket::isWriteFinished()

Synopsis

Returns True if all data has been written to the socket, takes an optional timeout. With a timeout of zero this method returns immediately.

Prototype

Socket::isWriteFinished(softint $timeout_ms = 0) returns bool

Socket::isWriteFinished(date $timeout) returns bool

Example
my bool $b = $sock.isWriteFinished(0);

Table 4.327. Arguments for Socket::isWriteFinished()

Argument

Description

softint $timeout_ms = 0 or date $timeout

An optional timeout in milliseconds (1/1000 second). If no timeout is given, the method returns immediately.


Table 4.328. Return Values for Socket::isWriteFinished()

Return Type

Description

bool

True if the send action is complete, False if not.


4.9.25. Socket::send()

Synopsis

Sends string or binary data over a connected socket. String data will be converted to the encoding set for the socket if necessary. If an error occurs, -1 will be returned; in this case check errno() for the error number.

See also Socket::sendBinary().

Prototype

Socket::send(data $data) returns int

Example
if ($sock.send($data) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.329. Arguments for Socket::send()

Argument

Description

string $data

Sends the string data over the socket without the trailing null ('\0') character; the string's encoding is converted to the socket's encoding if necessary.

binary $data

Sends the binary data over the socket.


Table 4.330. Return Values for Socket::send()

Return Type

Description

int

0 for success, -1 for error; in this case check errno() for the error number.


Table 4.331. Exceptions Thrown by Socket::send()

err

desc

SOCKET-SEND-PARAMETER-ERROR

No argument was passed to the method.

SOCKET-NOT-OPEN

The socket is not connected.


4.9.26. Socket::sendBinary()

Synopsis

Sends string or binary data over a connected socket. String data will not be converted to the encoding set for the socket, but rather will be sent as-is, even if the string's encoding is different from the socket's encoding. If an error occurs, -1 will be returned; in this case check errno() for the error number.

See also Socket::send().

Prototype

Socket::sendBinary(data $data) returns int

Example
if ($sock.sendBinary($data) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.332. Arguments for Socket::sendBinary()

Argument

Description

string $data

Sends the string data over the socket without the trailing null ('\0') character; the string's encoding is not converted to the socket's encoding, even if it is different.

binary $data

Sends the binary data over the socket.


Table 4.333. Return Values for Socket::sendBinary()

Return Type

Description

int

0 for success, -1 for error; in this case check errno() for the error number.


Table 4.334. Exceptions Thrown by Socket::sendBinary()

err

desc

SOCKET-SEND-PARAMETER-ERROR

No argument was passed to the method.

SOCKET-NOT-OPEN

The socket is not connected.


4.9.27. Socket::sendi1()

Synopsis

Sends a 1-byte integer over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi1(softint $i = 0) returns int

Example
if ($sock.sendi1($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.335. Arguments for Socket::sendi1()

Argument

Description

softint $i = 0

The integer to send; only the least-significant byte will be sent.


Table 4.336. Return Values for Socket::sendi1()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.337. Exceptions Thrown by Socket::sendi1()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.28. Socket::sendi2()

Synopsis

Sends a 2-byte integer in big-endian format (network byte order) over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi2(softint $i = 0) returns int

Example
if ($sock.sendi2($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.338. Arguments for Socket::sendi2()

Argument

Description

softint $i = 0

The integer to send; only the least-significant 2-bytes will be sent.


Table 4.339. Return Values for Socket::sendi2()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.340. Exceptions Thrown by Socket::sendi2()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.29. Socket::sendi4()

Synopsis

Sends a 4-byte integer in big-endian format (network byte order) over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi4(softint $i = 0) returns int

Example
if ($sock.sendi4($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.341. Arguments for Socket::sendi4()

Argument

Description

softint $i = 0

The integer to send; only the least-significant 4-bytes will be sent.


Table 4.342. Return Values for Socket::sendi4()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.343. Exceptions Thrown by Socket::sendi4()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.30. Socket::sendi8()

Synopsis

Sends an 8-byte (64-bit) integer in big-endian format (network byte order) over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi8(softint $i = 0) returns int

Example
if ($sock.sendi8($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.344. Arguments for Socket::sendi8()

Argument

Description

softint $i = 0

The integer to send.


Table 4.345. Return Values for Socket::sendi8()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.346. Exceptions Thrown by Socket::sendi8()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.31. Socket::sendi2LSB()

Synopsis

Sends a 2-byte integer in little-endian format over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi2LSB(softint $i = 0) returns int

Example
if ($sock.sendi2LSB($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.347. Arguments for Socket::sendi2LSB()

Argument

Description

softint $i = 0

The integer to send; only the least-significant 2-bytes will be sent.


Table 4.348. Return Values for Socket::sendi2LSB()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.349. Exceptions Thrown by Socket::sendi2LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.32. Socket::sendi4LSB()

Synopsis

Sends a 4-byte integer in little-endian format over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi4LSB(softint $i = 0) returns int

Example
if ($sock.sendi4LSB($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.350. Arguments for Socket::sendi4LSB()

Argument

Description

softint $i = 0

The integer to send; only the least-significant 4-bytes will be sent.


Table 4.351. Return Values for Socket::sendi4LSB()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.352. Exceptions Thrown by Socket::sendi4LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.33. Socket::sendi8LSB()

Synopsis

Sends an 8-byte (64-bit) integer in little-endian format over the socket. If an error occurs, -1 will be returned; in this case check errno() for the error number.

Prototype

Socket::sendi8LSB(softint $i = 0) returns int

Example
if ($sock.sendi8LSB($val) == -1)
    printf("error sending data: %s\n", strerror(errno()));
Events

EVENT_PACKET_SENT

Table 4.353. Arguments for Socket::sendi8LSB()

Argument

Description

softint $i = 0

The integer to send.


Table 4.354. Return Values for Socket::sendi8LSB()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


Table 4.355. Exceptions Thrown by Socket::sendi8LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.


4.9.34. Socket::sendHTTPMessage()

Synopsis

Creates a properly-formatted HTTP message and sends it over the Socket.

Prototype

Socket::sendHTTPMessage(string $method, string $path, string $http_version, hash $headers, data $body = binary()) returns nothing

Example
$sock.sendHTTPMessage("POST", "/RPC2", "1.1", ("Content-Type" : "text/xml"), $xml);
Events

EVENT_PACKET_SENT, EVENT_HTTP_SEND_MESSAGE

Table 4.356. Arguments for Socket::sendHTTPMessage()

Argument

Description

string $method

The HTTP method name to send (i.e. POST, HEAD, etc)

string $path

The path component of the URL.

string $http_version

The HTTP protocol version (1.0 or 1.1).

hash $headers

A hash of additional headers to send (key-value pairs).

data $body = binary()

If present (and does not have a length of zero), the body to be sent with the message (if present, the Content-Length header will be automatically set).


Table 4.357. Exceptions Thrown by Socket::sendHTTPMessage()

err

desc

SOCKET-SENDHTTPMESSAGE-PARAMETER-ERROR

One or more of the required arguments is missing.

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-SEND-ERROR

Send failed.


4.9.35. Socket::sendHTTPResponse()

Synopsis

Creates a properly-formatted HTTP response message and sends it over the Socket.

Prototype

Socket::sendHTTPResponse(softint $status_code, string $desc, string $http_version, hash $headers, data $body = binary()) returns nothing

Example
$sock.sendHTTPResponse(200, "OK", "1.1", ("Connection":"Keep-Alive"));
Events

EVENT_PACKET_SENT, EVENT_HTTP_SEND_MESSAGE

Table 4.358. Arguments for Socket::sendHTTPResponse()

Argument

Description

softint $status_code

The HTTP status code to send (i.e. 200, 404, etc)

string $desc

The descriptive text for the status code.

string $http_version

The HTTP protocol version (1.0 or 1.1).

hash $headers

A hash of additional headers to send (key-value pairs).

data $body = binary()

If present (and does not have a length of zero), the body to be sent with the message (if present, the Content-Length header will be automatically set).


Table 4.359. Exceptions Thrown by Socket::sendHTTPResponse()

err

desc

SOCKET-SENDHTTPRESPONSE-PARAMETER-ERROR

One or more of the required arguments is missing.

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-SEND-ERROR

Send failed.


4.9.36. Socket::recv()

Synopsis

Receives data from the socket and returns a string. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recv(softint $size = 0, softint $timeout_ms = -1) returns string

Socket::recv(softint $size = 0, date $timeout) returns string

Example
$data = $sock.recv(-1); # read all data available
Events

EVENT_PACKET_READ

Table 4.360. Arguments for Socket::recv()

Argument

Description

softint $size = 0

The amount of data to read in bytes. To read until the remote closes the connection, use -1.

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.361. Return Values for Socket::recv()

Return Type

Description

string

The data read, returned as a string. If any errors occur reading from the socket, an exception is raised.


Table 4.362. Exceptions Thrown by Socket::recv()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.37. Socket::recvBinary()

Synopsis

Receives data from the socket and returns a binary object. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvBinary(softint $size = 0, softint $timeout_ms = -1) returns binary

Socket::recvBinary(softint $size = 0, date $timeout) returns binary

Example
my binary $bin = $sock.recvBinary(-1); # read all data available
Events

EVENT_PACKET_READ

Table 4.363. Arguments for Socket::recvBinary()

Argument

Description

softint $size = 0

The amount of data to read in bytes. To read until the remote closes the connection, use -1.

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.364. Return Values for Socket::recvBinary()

Return Type

Description

binary

The data read, returned as a binary object. If any errors occur reading from the socket, an exception is raised.


Table 4.365. Exceptions Thrown by Socket::recvBinary()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.38. Socket::recvi1()

Synopsis

Receives a 1-byte signed integer from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi1(softint $timeout_ms = -1) returns int

Socket::recvi1(date $timeout) returns int

Example
my int $val = $sock.recvi1();
Events

EVENT_PACKET_READ

Table 4.366. Arguments for Socket::recvi1()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.367. Return Values for Socket::recvi1()

Return Type

Description

int

The 1-byte signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.368. Exceptions Thrown by Socket::recvi1()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.39. Socket::recvi2()

Synopsis

Receives a 2-byte signed integer in big-endian format (network byte order) from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi2(softint $timeout_ms = -1) returns int

Socket::recvi2(date $timeout) returns int

Example
my int $val = $sock.recvi2();
Events

EVENT_PACKET_READ

Table 4.369. Arguments for Socket::recvi2()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.370. Return Values for Socket::recvi2()

Return Type

Description

int

The 2-byte signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.371. Exceptions Thrown by Socket::recvi2()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.40. Socket::recvi4()

Synopsis

Receives a 4-byte signed integer in big-endian format (network byte order) from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi4(softint $timeout_ms = -1) returns int

Socket::recvi4(date $timeout) returns int

Example
my int $val = $sock.recvi4();
Events

EVENT_PACKET_READ

Table 4.372. Arguments for Socket::recvi4()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.373. Return Values for Socket::recvi4()

Return Type

Description

int

The 4-byte signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.374. Exceptions Thrown by Socket::recvi4()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.41. Socket::recvi8()

Synopsis

Receives an 8-byte (64-bit) signed integer in big-endian format (network byte order) from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi8(softint $timeout_ms = -1) returns int

Socket::recvi8(date $timeout) returns int

Example
my int $val = $sock.recvi8();
Events

EVENT_PACKET_READ

Table 4.375. Arguments for Socket::recvi8()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection. A relative date/time value can be used as well (i.e. 1250ms) for clarity.


Table 4.376. Return Values for Socket::recvi8()

Return Type

Description

int

The 8-byte (64-bit) signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.377. Exceptions Thrown by Socket::recvi8()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.42. Socket::recvi2LSB()

Synopsis

Receives a 2-byte signed integer in little-endian format from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi2LSB(softint $timeout_ms = -1) returns int

Socket::recvi2LSB(date $timeout) returns int

Example
my int $val = $sock.recvi2LSB();
Events

EVENT_PACKET_READ

Table 4.378. Arguments for Socket::recvi2LSB()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.379. Return Values for Socket::recvi2LSB()

Return Type

Description

int

The 2-byte signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.380. Exceptions Thrown by Socket::recvi2LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.43. Socket::recvi4LSB()

Synopsis

Receives a 4-byte signed integer in little-endian format from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi4LSB(softint $timeout_ms = -1) returns int

Socket::recvi4LSB(date $timeout) returns int

Example
my int $val = $sock.recvi4LSB(1250ms); # timeout in 1.25 seconds
Events

EVENT_PACKET_READ

Table 4.381. Arguments for Socket::recvi4LSB()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.382. Return Values for Socket::recvi4LSB()

Return Type

Description

int

The 4-byte signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.383. Exceptions Thrown by Socket::recvi4LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.44. Socket::recvi8LSB()

Synopsis

Receives an 8-byte (64-bit) signed integer in little-endian format from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvi8LSB(softint $timeout_ms = -1) returns int

Socket::recvi8LSB(date $timeout) returns int

Example
my int $val = $sock.recvi8LSB();
Events

EVENT_PACKET_READ

Table 4.384. Arguments for Socket::recvi8LSB()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection. A relative date/time value can be used as well (i.e. 1250ms) for clarity.


Table 4.385. Return Values for Socket::recvi8LSB()

Return Type

Description

int

The 8-byte (64-bit) signed integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.386. Exceptions Thrown by Socket::recvi8LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.45. Socket::recvu1()

Synopsis

Receives a 1-byte unsigned integer from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvu1(softint $timeout_ms = -1) returns int

Socket::recvu1(date $timeout) returns int

Example
my int $val = $sock.recvu1();
Events

EVENT_PACKET_READ

Table 4.387. Arguments for Socket::recvu1()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.388. Return Values for Socket::recvu1()

Return Type

Description

int

The 1-byte unsigned integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.389. Exceptions Thrown by Socket::recvu1()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.46. Socket::recvu2()

Synopsis

Receives a 2-byte unsigned integer in big-endian format (network byte order) from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype
Socket::recvu2([timeout_ms])
Example

Socket::recvu2(softint $timeout_ms = -1) returns int

Socket::recvu2(date $timeout) returns int

Events

EVENT_PACKET_READ

Table 4.390. Arguments for Socket::recvu2()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.391. Return Values for Socket::recvu2()

Return Type

Description

int

The 2-byte unsigned integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.392. Exceptions Thrown by Socket::recvu2()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.47. Socket::recvu4()

Synopsis

Receives a 4-byte unsigned integer in big-endian format (network byte order) from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvu4(softint $timeout_ms = -1) returns int

Socket::recvu4(date $timeout) returns int

Example
my int $val = $sock.recvu4();
Events

EVENT_PACKET_READ

Table 4.393. Arguments for Socket::recvu4()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.394. Return Values for Socket::recvu4()

Return Type

Description

int

The 4-byte unsigned integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.395. Exceptions Thrown by Socket::recvu4()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.48. Socket::recvu2LSB()

Synopsis

Receives a 2-byte unsigned integer in little-endian format from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvu2LSB(softint $timeout_ms = -1) returns int

Socket::recvu2LSB(date $timeout) returns int

Example
my int $val = $sock.recvu2LSB();
Events

EVENT_PACKET_READ

Table 4.396. Arguments for Socket::recvu2LSB()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.397. Return Values for Socket::recvu2LSB()

Return Type

Description

int

The 2-byte unsigned integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.398. Exceptions Thrown by Socket::recvu2LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.49. Socket::recvu4LSB()

Synopsis

Receives a 4-byte unsigned integer in little-endian format from the socket. If any errors occur reading from the socket, an exception is raised.

Prototype

Socket::recvu4LSB(softint $timeout_ms = -1) returns int

Socket::recvu4LSB(date $timeout) returns int

Example
my int $val = $sock.recvu4LSB();
Events

EVENT_PACKET_READ

Table 4.399. Arguments for Socket::recvu4LSB()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.400. Return Values for Socket::recvu4LSB()

Return Type

Description

int

The 4-byte unsigned integer read. If any errors occur reading from the socket, an exception is raised.


Table 4.401. Exceptions Thrown by Socket::recvu4LSB()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.50. Socket::readHTTPHeader()

Synopsis

Reads an HTTP header and returns a hash representing the data read. If any errors occur reading from the socket, an exception is raised. Accepts an optional timeout value in milliseconds.

This method sets the keys in the following table in the hash returned as well to give additional information about the HTTP header received.

Table 4.402. Special Keys in Hash Returned By Socket::readHTTPHeader()

Key

Description of Value

http_version

A string giving the HTTP version set in the header

status_code

An integer giving the status code; this key is only set in HTTP responses

status_message

If present in an HTTP response, this key will be set to the message after the status code

method

A string giving the HTTP method (i.e. GET, POST, etc); this key is only set when a request header is received

path

A string giving the path in a request without any decoding; use decode_url() to decode if necessary.


Prototype

Socket::readHTTPHeader(softint $timeout_ms = -1) returns any

Socket::readHTTPHeader(date $timeout) returns any

Example
my hash $hash = $sock.readHTTPHeader();
Events

EVENT_PACKET_READ, EVENT_HTTP_MESSAGE_RECEIVED

Table 4.403. Arguments for Socket::readHTTPHeader()

Argument

Description

softint $timeout_ms = -1 or date $timeout

The timeout in milliseconds (1/1000 second). If no timeout is passed, then the call will not time out and will not return until all the data has been read or the remote end closes the connection.


Table 4.404. Return Values for Socket::readHTTPHeader()

Return Type

Description

hash

The return hash will contain keys for each header, plus an http_version key, giving the HTTP protocol version. For HTTP responses, the following keys will be returned: status_code, status_message. For outgoing HTTP messages, the following keys will be populated: method, path. If any errors occur reading from the socket, an exception is raised.


Table 4.405. Exceptions Thrown by Socket::readHTTPHeader()

err

desc

SOCKET-NOT-OPEN

The socket is not connected.

SOCKET-CLOSED

The remote end has closed the connection.

SOCKET-RECV-ERROR

There was an error receiving the data.


4.9.51. Socket::getPort()

Synopsis

Returns the port number of the socket for INET sockets.

Prototype

Socket::getPort() returns int

Example
$port = $sock.getPort();

Table 4.406. Return Values for Socket::getPort()

Return Type

Description

int

Returns the port number for an INET connection, -1 if no INET connection has been established.


4.9.52. Socket::shutdown()

Synopsis

Ensures that a socket will be closed even if the file descriptor is shared with other processes (for example, after a call to fork()). Returns 0 for success, -1 for error; in this case check errno() for the error number.

Prototype

Socket::shutdown() returns int

Example
$sock.shutdown();

Table 4.407. Return Values for Socket::shutdown()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


4.9.53. Socket::close()

Synopsis

Closes an open socket. Also deletes the UNIX domain socket file if it was created by a call to Socket::bind(). Returns 0 for success, -1 for error; in this case check errno() for the error number.

Prototype

Socket::close() returns int

Example
$sock.close();
Events

EVENT_CHANNEL_CLOSED

Table 4.408. Return Values for Socket::close()

Return Type

Description

int

Returns 0 for success, -1 for error; in this case check errno() for the error number.


4.9.54. Socket::getCharset()

Synopsis

Returns the character encoding for the socket.

Prototype

Socket::getCharset() returns string

Example
$enc = $sock.getCharset();

Table 4.409. Return Value for Socket::getCharset()

Return Type

Description

string

The character encoding for the socket.


4.9.55. Socket::setCharset()

Synopsis

Sets the character encoding for the socket. If any string data is sent over the socket with Socket::send(), then the character encoding will be automatically converted if needed.

Prototype

Socket::setCharset(string $encoding) returns nothing

Example
$sock.setCharset("ISO-8859-1");

Table 4.410. Arguments for Socket::setCharset()

Argument

Description

string $encoding

The character encoding for the socket.


4.9.56. Socket::getNoDelay()

Synopsis

Returns the TCP_NODELAY setting for the socket. See also Socket::setNoDelay().

Prototype

Socket::getNoDelay() returns bool

Example
$nodelay = $sock.getNoDelay();

Table 4.411. Return Value for Socket::getNoDelay()

Return Type

Description

bool

The TCP_NODELAY setting for the socket.


4.9.57. Socket::setNoDelay()

Synopsis

Sets the TCP_NODELAY setting for the socket; when this setting is True, then data will be immediately sent out over the socket, when it is False, then data transmission may be delayed to be packaged with other data for the same target.

Delayed data transmissions may cause problems when the sender immediately closes the socket after sending data; in this case the receiver may not get the data even though the send succeeded.

Note that if no value is given to the method, the argument will be assumed to be False, and output buffering will be turned on for the socket, which may be the opposite of what the programmer intends, therefore it's recommended to always pass an argument to this method.

See also Socket::getNoDelay().

Prototype

Socket::setNoDelay(bool $nodelay = True) returns int

Example
$sock.setNoDelay(True);

Table 4.412. Arguments for Socket::setNoDelay()

Argument

Description

bool $nodelay = True

The TCP_NODELAY setting for the socket.


Table 4.413. Return Value for Socket::setNoDelay()

Return Type

Description

int

0 for success, non-zero for errors. To get error information, see errno() and strerror().


4.9.58. Socket::getSocket()

Synopsis

Returns the file descriptor number associated with the socket.

Prototype

Socket::getSocket() returns int

Example
$sock = $sock.getSocket();

Table 4.414. Return Values for Socket::getSocket()

Return Type

Description

int

The file descriptor associated to the socket.


4.10. HTTPClient Class

Note: This class is not available with the PO_NO_NETWORK parse option.

The HTTPClient class can be used to communicate with HTTP servers using the HTTP or HTTPS (HTTP using an SSL/TLS encrypted connection) protocol.

By default 'Connection: Keep-Alive' is always sent regardless of the HTTP protocol level set for the object, however if a server response contains 'Connection: close', the connection will be closed as soon as the full response (including any message body if present) has been read.

HTTP redirect responses are supported and can be limited with the max_redirects constructor hash key or by using the HTTPClient::setMaxRedirects() method. The default number of redirects is 5.

HTTP basic authentication is supported; set the username and password in the URL (ex: http://username:password@host:port/path). To change the URL from the one set by the constructor, call HTTPClient::setURL().

HTTP proxies and basic proxy authentication are supported by setting the proxy constructor hash key to the proxy URL (with a proxy username and password if required) or by calling the HTTPClient::setProxyURL() method.

Objects of this class are thread-safe and support serializing multiple simultaneous requests from many threads. If a request is in progress and another thread attempts to make a request at the same time, the second thread will block until the first is complete. Therefore the total amount of time a thread could wait for a response in a multi-threaded context could be greater than the read timeout value.

This class understands and automatically decodes "deflate", "gzip", and "bzip2" content encodings as well.

The default read timeout value is 300,000 milliseconds (5 minutes). Note that the read timeout value applies to individual packets; for this reason for large transfers the overall read time could exceed the read timeout value.

When an exception is thrown (for example, a response code of < 200 or >= 400 is received from the server), any message body returned will be in the "arg" key of the exception hash.

This class understands the protocols in the following table.

Table 4.415. HTTPClient Class Protocols

Protocol

Default Port

SSL?

Description

http

80

No

Unencrypted HTTP protocol

https

443

Yes

HTTP protocol with SSL/TLS encryption


Whenever using an HTTPClient method where a hash of headers can be passed to the method, some headers are generated by default by the class and can be overridden, and some are cannot be overridden and are ignored if passed by the client. See the following tables for details.

Table 4.416. HTTPClient Mandatory Headers

Header

Description

Content-Length

This header is only sent if a message body is send, and, if so, the length is calculated automatically.


Table 4.417. HTTPClient Default, but Overridable Headers

Header

Default Value

Accept

text/html

Content-Type

text/html

User-Agent

Qore HTTP Client v0.8.0

Connection

Keep-Alive

Accept-Encoding

deflate,gzip,bzip2


This class supports posting network events to a Queue. See Event Handling for more information.

The events raised by this object are listed in the following table:

Table 4.418. HTTPClient Events

Name

Description

EVENT_HTTP_CONTENT_LENGTH

Raised when the HTTP "Content-Length" header is received.

EVENT_HTTP_CHUNKED_START

Raised when HTTP chunked data is about to be received.

EVENT_HTTP_CHUNKED_END

Raised when all HTTP chunked data has been received.

EVENT_HTTP_REDIRECT

Raised when an HTTP redirect message is received.

EVENT_HTTP_SEND_MESSAGE

Raised when an HTTP message is sent.

EVENT_HTTP_MESSAGE_RECEIVED

Raised when an HTTP message is received.

EVENT_HTTP_FOOTERS_RECEIVED

Raised when HTTP footers are received.

EVENT_HTTP_CHUNKED_DATA_RECEIVED

Raised when a block of HTTP chunked data is received.

EVENT_HTTP_CHUNK_SIZE

Raised when the next chunk size for HTTP chunked data is known.


The following table gives an overview of the methods available in the HTTPClient class.

Table 4.419. HTTPClient Class Method Overview

Method

Except?

Description

HTTPClient::constructor()

HTTPClient::constructor(hash $opts)

Y

Creates the HTTPClient object based on the parameters passed.

HTTPClient::destructor()

N

Destroys the HTTPClient object and closes any open connections.

HTTPClient::copy()

Y

Copying objects of this class is not supported, an exception will be thrown.

HTTPClient::getURL() returns string

N

Returns the current URL.

HTTPClient::setURL(string $url) returns nothing

Y

Sets a new URL value for the next connection.

HTTPClient::getProxyURL() returns any

N

Returns the current proxy URL as a string or NOTHING if no proxy URL is set.

HTTPClient::setProxyURL() returns nothing

HTTPClient::setProxyURL(string $url) returns nothing

Y

Sets or clears (in case called with no argument) a new proxy URL value for the next connection.

HTTPClient::clearProxyURL() returns nothing

N

Clears the proxy URL value.

HTTPClient::setProxySecure(softbool $secure = True) returns nothing

N

Sets the SSL/TLS flag for the next connection to the proxy.

HTTPClient::isProxySecure() returns bool

N

Returns the SSL/TLS flag.

HTTPClient::getMaxRedirects() returns int

N

Returns the current max_redirects value.

HTTPClient::setMaxRedirects(softint $max = 0) returns nothing

N

Updates the max_redirects value.

HTTPClient::connect() returns nothing

N

Connects to the remote socket; SSL/TLS negotiation is performed if required.

HTTPClient::disconnect() returns nothing

N

Disconnects from the remote socket

HTTPClient::get(string $path, hash $headers = hash(), reference $info) returns any

HTTPClient::get(string $path, hash $headers = hash()) returns any

Y

Sends an HTTP GET request and returns the message body received as a string or NOTHING if no message body is received. In order to get the headers and the body, use the HTTPClient::send() method instead. If no connection is established, an internal call to HTTPClient::connect() will be made before sending the message.

HTTPClient::head(string $path, hash $headers = hash(), reference $info) returns hash

HTTPClient::head(string $path, hash $headers = hash()) returns hash

Y

Sends an HTTP HEAD request and returns as hash of the headers received. If no connection is established, an internal call to HTTPClient::connect() will be made before sending the message.

HTTPClient::post(string $path, data $body, hash $headers = hash(), reference $info) returns any

HTTPClient::post(string $path, data $body, hash $headers = hash()) returns any

Y

Sends an HTTP POST request with a message body and returns the message body received as a string or NOTHING if no message body is received. In order to get the headers and the body in the response, use the HTTPClient::send() method instead. If no connection is established, an internal call to HTTPClient::connect() will be made before sending the message.

HTTPClient::send(data $body = binary(), string $method, string $path = "", hash $headers = hash(), bool $getbody = False, reference $info) returns hash

HTTPClient::send(data $body = binary(), string $method, string $path = "", hash $headers = hash(), bool $getbody = False) returns hash

Y

Sends an HTTP request with the specified method and optional message body and returns headers and any body received as a response in a hash format. If no connection is established, an internal call to HTTPClient::connect() will be made before sending the message.

HTTPClient::setConnectTimeout(softint $timeout_ms = -1) returns nothing

HTTPClient::setConnectTimeout(date $timeout) returns nothing

N

Sets the connect timeout in milliseconds. Negative numbers mean use the default system connect timeout. Note that like all Qore functions and methods taking timeout values, a relative date/time value can be used to make the units clear (i.e. 30s = 30 seconds, etc.).

HTTPClient::setTimeout(softint $timeout_ms = -1) returns nothing

HTTPClient::setTimeout(date $timeout) returns nothing

N

Sets the default read timeout in milliseconds. Zero means immediate timeout (will return data only if it is already available), and negative numbers mean never timeout (wait forever for data). Note that like all Qore functions and methods taking timeout values, a relative date/time value can be used to make the units clear (i.e. 2m = two minutes, etc.).

HTTPClient::getConnectTimeout() returns int

N

Returns the connect timeout as an integer in milliseconds. Negative numbers mean the system default timeout is used.

HTTPClient::getTimeout() returns int

N

Returns the default read timeout as an integer in milliseconds. Zero means immediate timeout (only returns data if it is already available), and negative numbers mean never timeout (wait forever for data).

HTTPClient::setHTTPVersion(string $ver) returns nothing

Y

Sets the HTTP protocol version string for headers in outgoing messages, allowed values are '1.0' and '1.1'.

HTTPClient::getHTTPVersion() returns string

N

Returns the HTTP protocol version string used in outgoing messages.

HTTPClient::setSecure(softbool $secure = True) returns nothing

N

Sets the object to make a secure SSL/TLS connection on the next connect if the passed argument is True, or an unencrypted cleartext connection if it is False. This method overrides the default behaviour for the protocol set for the object.

HTTPClient::isSecure() returns bool

N

Returns True if the current connection is encrypted, False if not.

HTTPClient::verifyPeerCertificate() returns any

N

Returns a string code giving the result of verifying the remote certificate or NOTHING if a secure connection is not established. Return value are the keys described in the X509_VerificationReasons hash constant. This hash can also be used to generate a textual description of the verification result.

HTTPClient::getSSLCipherName() returns any

N

Returns the name of the cipher as a string for an encrypted connection or NOTHING if a secure connection is not established.

HTTPClient::getSSLCipherVersion() returns any

N

Returns the version of the cipher as a string for an encrypted connection or NOTHING if a secure connection is not established.

HTTPClient::setEncoding(string $encoding) returns nothing

Y

Sets the string encoding for the object; any strings deserialized with this object will be tagged with this character encoding.

HTTPClient::getEncoding() returns string

N

Returns the character encoding used for the object

HTTPClient::setEventQueue() returns nothing

HTTPClient::setEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive HTTPClient and Socket events or clears the queue if no argument is passed.

HTTPClient::getNoDelay() returns bool

N

Returns the TCP_NODELAY setting for the object.

HTTPClient::setNoDelay(softbool $nodelay = True) returns int

N

Sets the TCP_NODELAY setting for the object.

HTTPClient::isConnected() returns bool

N

Returns True or False giving the current connection state.


4.10.1. HTTPClient::constructor()

Synopsis

Creates the HTTPClient object based on the parameters passed. To connect, call any method that requires a connection and an implicit connection is established, or call HTTPClient::connect().

Prototype

HTTPClient::constructor()

HTTPClient::constructor(hash $opts)

Example
my HTTPClient $httpclient(("url":"http://hostname:8080/path"));

Table 4.420. Arguments for HTTPClient::constructor()

Argument

Description

[hash $opts]

sets options and changes default behaviour for the object, etc. See the table below for information on valid keys and their mening. Note that the key names are case-sensitive and therefore must all be in lower-case.


Table 4.421. HTTPClient::constructor() Option Hash Keys

Key

Description

url

A string giving the URL to connect to.

default_port

The default port number to connect to if none is given in the URL.

protocols

A hash describing new protocols, the key is the protocol name and the value is either an integer giving the default port number or a hash with 'port' and 'ssl' keys giving the default port number and a boolean value to indicate that an SSL connection should be established.

http_version

Either '1.0' or '1.1' for the claimed HTTP protocol version compliancy in outgoing message headers.

default_path

The default path to use for new connections if a path is not otherwise specified in the connection URL.

max_redirects

The maximum number of redirects before throwing an exception (the default is 5).

proxy

The proxy URL for connecting through a proxy.

timeout

The timeout value in milliseconds (also can be a relative date-time value for clarity, ex: 5m)

connect_timeout

The timeout value in milliseconds for establishing a new socket connection (also can be a relative date-time value for clarity, ex: 30s)


Table 4.422. Exceptions thrown by HTTPClient::constructor()

err

desc

HTTP-CLIENT-CONSTRUCTOR-ERROR

invalid or unknown option passed in option hash

HTTP-CLIENT-URL-ERROR

invalid URL string

HTTP-CLIENT-UNKNOWN-PROTOCOL

unknown protocol passed in URL


4.10.2. HTTPClient::destructor()

Synopsis

Destroys the HTTPClient object and closes any open connections.

Example
delete $httpclient;
Events

EVENT_CHANNEL_CLOSED, EVENT_DELETED

4.10.3. HTTPClient::copy()

Synopsis

Copying objects of this class is not supported, an exception will be thrown.

Table 4.423. Exceptions thrown by HTTPClient::copy()

err

desc

HTTP-CLIENT-COPY-ERROR

objects of this class may not be copied


4.10.4. HTTPClient::getURL()

Synopsis

Returns the current URL value for the object. To set the URL, use the HTTPClient::setURL() method.

Prototype

HTTPClient::getURL() returns string

Example
$url = $httpclient.getURL();

Table 4.424. Return Values for HTTPClient::getURL()

Return Type

Description

string

The current URL value.


4.10.5. HTTPClient::setURL()

Synopsis

Sets the URL value for the object. To retrieve the current URL value, use the HTTPClient::getURL() method.

Prototype

HTTPClient::setURL(string $url) returns nothing

Example
$httpclient.setURL("https://user:password@hostname:8080/path");

Table 4.425. Arguments for HTTPClient::setURL()

Argument

Description

string $url

The new URL for the object.


Table 4.426. Exceptions thrown by HTTPClient::setURL()

err

desc

HTTP-CLIENT-URL-ERROR

invalid URL string

HTTP-CLIENT-UNKNOWN-PROTOCOL

unknown protocol passed in URL


4.10.6. HTTPClient::getProxyURL()

Synopsis

Returns the current proxy URL value for the object (NOTHING if no proxy URL is set). To set the proxy URL, use the HTTPClient::setProxyURL() method.

Prototype

HTTPClient::getProxyURL() returns any

Example
$proxy_url = $httpclient.getProxyURL();

Table 4.427. Return Values for HTTPClient::getProxyURL()

Return Type

Description

string or nothing

The current proxy URL value or NOTHING if it is not set.


4.10.7. HTTPClient::setProxyURL()

Synopsis

Sets the proxy URL value for the object; call with no argument or NOTHING to clear. To retrieve the current URL value, use the HTTPClient::getProxyURL() method.

Prototype

HTTPClient::setProxyURL() returns nothing

HTTPClient::setProxyURL(string $url) returns nothing

Example
$httpclient.setProxyURL("http://user:password@proxy_host:8080/path");

Table 4.428. Arguments for HTTPClient::setProxyURL()

Argument

Description

[string $url]

The new proxy URL for the object; call with no argument or NOTHING to clear.


Table 4.429. Exceptions thrown by HTTPClient::setProxyURL()

err

desc

HTTP-CLIENT-URL-ERROR

invalid URL string

HTTP-CLIENT-SET-PROXY-ERROR

invalid authorization credentials in proxy URL (username without password or vice-versa)

HTTP-CLIENT-PROXY-PROTOCOL-ERROR

unknown protocol passed in URL


4.10.8. HTTPClient::clearProxyURL()

Synopsis

Clears the current proxy URL

Prototype

HTTPClient::clearProxyURL() returns nothing

Example
$httpclient.clearProxyURL();

4.10.9. HTTPClient::setProxySecure()

Synopsis

Sets the SSL/TLS flag for the next proxy connection. To check the flag, use the HTTPClient::isProxySecure() method.

Prototype

HTTPClient::setProxySecure(softbool $secure = True) returns nothing

Example
$httpclient.setProxySecure(True);

Table 4.430. Arguments for HTTPClient::setProxySecure()

Argument

Description

softbool $secure = True

sets the SSL/TLS flag for the next proxy connection


4.10.10. HTTPClient::isProxySecure()

Synopsis

Returns the SSL/TLS flag for proxy connection. To set the flag, use the HTTPClient::setProxySecure() method.

Prototype

HTTPClient::isProxySecure() returns bool

Example
$bool = $httpclient.isProxySecure();

Table 4.431. Return Values for HTTPClient::isProxySecure()

Return Type

Description

bool

The value of the SSL/TLS flag for the proxy connection.


4.10.11. HTTPClient::getMaxRedirects()

Synopsis

Returns the maximum number of redirects allowed for the object. To set this value, use the HTTPClient::setMaxRedirects() method.

Prototype

HTTPClient::getMaxRedirects() returns int

Example
$num = $httpclient.getMaxRedirects();

Table 4.432. Return Values for HTTPClient::getMaxRedirects()

Return Type

Description

int

The current value of the max_redirects setting.


4.10.12. HTTPClient::setMaxRedirects()

Synopsis

Sets the maximum number of redirects allowed for the object. To retrieve this value, use the HTTPClient::getMaxRedirects() method.

Prototype

HTTPClient::setMaxRedirects(softint $max = 0) returns nothing

Example
$httpclient.setMaxRedirects(0); # disable redirections

Table 4.433. Arguments for HTTPClient::setMaxRedirects()

Argument

Description

softint $max = 0

The maximum number of HTTP redirects allowed for the object before an exception is thrown.


4.10.13. HTTPClient::connect()

Synopsis

Connects to the remote socket. If the protocol indicates that a secure connection should be established (or HTTPClient::setSecure() was called previsouly), SSL/TLS negotiation will be attempted. Note: For possible exceptions, see the Socket::connect() method (or Socket::connectSSL() for secure connections).

If the TCP_NODELAY flag has been set (see HTTPClient::setNoDelay()), then after a successful connection to the remote socket, this option will be set on the socket. If an error occurs setting the TCP_NODELAY option, the internal flag is set to false (use HTTPClient::getNoDelay() to check the flag's state) and the error code can be retrieved with errno().

Prototype

HTTPClient::connect() returns nothing

Example
$httpclient.connect();
Events

EVENT_CONNECTING, EVENT_CONNECTED,EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED

Table 4.434. Exceptions thrown by HTTPClient::connect()

err

desc

HTTP-CLIENT-MAXIMUM-.REDIRECTS-EXCEEDED

The attempt to connect exceeeded the maximum number of redirects allowed for the object.

HTTP-CLIENT-RECEIVE-ERROR

There was an error receiving data on the socket

HTTP-CLIENT-TIMEOUT

The receive attempt timed out.


4.10.14. HTTPClient::disconnect()

Synopsis

Disconnects from the remote socket if a connection is established (otherwise does nothing).

Prototype

HTTPClient::disconnect() returns nothing

Example
$httpclient.disconnect();
Events

EVENT_CHANNEL_CLOSED

4.10.15. HTTPClient::get()

Synopsis

Sends an HTTP GET request and returns the message body received. In order to get the headers and the body, use the HTTPClient::send() method instead. If necessary, a connection will be established via an implicit call to HTTPClient::connect() before sending the message.

Prototype

HTTPClient::get(string $path, hash $headers = hash(), reference $info) returns any

HTTPClient::get(string $path, hash $headers = hash()) returns any

Example
$html = $httpclient.get("/path/file.html");
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED, EVENT_HTTP_SEND_MESSAGE, EVENT_PACKET_SENT, EVENT_HTTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_HTTP_CONTENT_LENGTH, EVENT_HTTP_CHUNKED_START, EVENT_HTTP_CHUNKED_END, EVENT_HTTP_CHUNKED_DATA_RECEIVED, EVENT_HTTP_CHUNK_SIZE, EVENT_HTTP_FOOTERS_RECEIVED, EVENT_HTTP_REDIRECT

Table 4.435. Arguments for HTTPClient::get()

Argument

Description

string $path

The path for the message (i.e. '/path/resource?method&param=value')

hash $headers = hash()

An optional hash of headers to include in the message.

[reference $info]

An optional reference to an lvalue that will be used as an output variable giving a hash of request headers and other information about the HTTP request.


Table 4.436. Return Values for HTTPClient::get()

Return Type

Description

string or nothing

The message body returned; NOTHING in case of an erroneous reply by the server with no body.


Table 4.437. Exceptions thrown by HTTPClient::get()

err

desc

HTTP-CLIENT-TIMEOUT

timeout on response from HTTP server

HTTP-CLIENT-RECEIVE-ERROR

error communicating with HTTP server


4.10.16. HTTPClient::head()

Synopsis

Sends an HTTP HEAD request and returns the headers received. If necessary, a connection will be established via an implicit call to HTTPClient::connect() before sending the message.

Prototype

HTTPClient::head(string $path, hash $headers = hash(), reference $info) returns hash

HTTPClient::head(string $path, hash $headers = hash()) returns hash

Example
$response = $httpclient.head("/path");
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED, EVENT_HTTP_SEND_MESSAGE, EVENT_PACKET_SENT, EVENT_HTTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_HTTP_CONTENT_LENGTH, EVENT_HTTP_CHUNKED_START, EVENT_HTTP_CHUNKED_END, EVENT_HTTP_CHUNKED_DATA_RECEIVED, EVENT_HTTP_CHUNK_SIZE, EVENT_HTTP_FOOTERS_RECEIVED, EVENT_HTTP_REDIRECT

Table 4.438. Arguments for HTTPClient::head()

Argument

Description

string $path

The path for the message (i.e. '/path/resource?method&param=value')

hash $headers = hash()

An optional hash of headers to include in the message.

[reference $info]

An optional reference to an lvalue that will be used as an output variable giving a hash of request headers and other information about the HTTP request.


Table 4.439. Return Values for HTTPClient::head()

Return Type

Description

hash

The headers received from the HTTP server with all key names converted to lower-case.


Table 4.440. Exceptions thrown by HTTPClient::head()

err

desc

HTTP-CLIENT-TIMEOUT

timeout on response from HTTP server

HTTP-CLIENT-RECEIVE-ERROR

error communicating with HTTP server


4.10.17. HTTPClient::post()

Synopsis

Sends an HTTP POST request with a message body and returns the message body received as a response. In order to get the headers and the body, use HTTPClient::send() instead. If necessary, a connection will be established via an implicit call to HTTPClient::connect() before sending the message.

Prototype

HTTPClient::post(string $path, data $body, hash $headers = hash(), reference $info) returns any

HTTPClient::post(string $path, data $body, hash $headers = hash()) returns any

Table 4.441. Arguments for HTTPClient::post()

Argument

Description

string $path

The path for the message (i.e. '/path/resource?method&param=value')

data $body

The message body to send.

hash $headers = hash()

An optional hash of headers to include in the message.

[reference $info]

An optional reference to an lvalue that will be used as an output variable giving a hash of request headers and other information about the HTTP request.


Table 4.442. Return Values for HTTPClient::post()

Return Type

Description

string or nothing

The message body returned; NOTHING in case of an erroneous reply by the server with no body.


Table 4.443. Exceptions thrown by HTTPClient::post()

err

desc

HTTP-CLIENT-TIMEOUT

timeout on response from HTTP server

HTTP-CLIENT-RECEIVE-ERROR

error communicating with HTTP server


4.10.18. HTTPClient::send()

Synopsis

Sends an HTTP request with the specified method and optional message body and returns headers and optionally the body received as a response in a hash format. If necessary, a connection will be established via an implicit call to HTTPClient::connect() before sending the message.

Prototype

HTTPClient::send(data $body = binary(), string $method, string $path = "", hash $headers = hash(), bool $getbody = False, reference $info) returns hash

HTTPClient::send(data $body = binary(), string $method, string $path = "", hash $headers = hash(), bool $getbody = False) returns hash

Example
$msg = $httpclient.send($body, "POST", "/path", ("Connection":"Keep-Alive"));
Events

EVENT_CONNECTING, EVENT_CONNECTED, EVENT_HOSTNAME_LOOKUP, EVENT_HOSTNAME_RESOLVED, EVENT_START_SSL, EVENT_SSL_ESTABLISHED, EVENT_HTTP_SEND_MESSAGE, EVENT_PACKET_SENT, EVENT_HTTP_MESSAGE_RECEIVED, EVENT_PACKET_READ, EVENT_HTTP_CONTENT_LENGTH, EVENT_HTTP_CHUNKED_START, EVENT_HTTP_CHUNKED_END, EVENT_HTTP_CHUNKED_DATA_RECEIVED, EVENT_HTTP_CHUNK_SIZE, EVENT_HTTP_FOOTERS_RECEIVED, EVENT_HTTP_REDIRECT

Table 4.444. Arguments for HTTPClient::send()

Argument

Description

data $body

The message body to send; use NOTHING to send to body.

string $method

The name of the HTTP method ('GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', or 'CONNECT').

string $path

The path for the message (i.e. '/path/resource?method&param=value')

hash $headers = hash()

An optional hash of headers to include in the message.

bool $getbody = False

If this argument is true, then the object will try to receive a message body even if no Content-Length header is present in the response. Use this only with broken servers that send messages bodies without a 'Content-Length' header.

[reference $info]

An optional reference to an lvalue that will be used as an output variable giving a hash of request headers and other information about the HTTP request.


Table 4.445. Return Values for HTTPClient::send()

Return Type

Description

hash

The headers received from the HTTP server with all key names converted to lower-case. The message body, if any, will be assigned to the value of the 'body' key.


Table 4.446. Exceptions thrown by HTTPClient::send()

err

desc

HTTP-CLIENT-TIMEOUT

timeout on response from HTTP server

HTTP-CLIENT-RECEIVE-ERROR

error communicating with HTTP server

HTTP-CLIENT-METHOD-ERROR

invalid HTTP method passed


4.10.19. HTTPClient::setConnectTimeout()

Synopsis

Sets the default connect timeout in milliseconds. Negative numbers mean use the default system timeout. Note that like all Qore functions and methods taking timeout values, a relative date/time value can be used to make the units clear (i.e. 2m = two minutes, etc.).

Prototype

HTTPClient::setConnectTimeout(softint $timeout_ms = -1) returns nothing

HTTPClient::setConnectTimeout(date $timeout) returns nothing

Example
$httpclient.setConnectTimeout(2m); # sets timeout to 2 minutes

Table 4.447. Arguments for HTTPClient::setConnectTimeout()

Argument

Description

softint $timeout_ms = -1 or date $timeout

Connect timeout in milliseconds, 0 = immediate timeout (do not use), negative numbers = use system default connect timeout.


4.10.20. HTTPClient::setTimeout()

Synopsis

Sets the default read timeout in milliseconds. Zero means immediate timeout (will return data only if it is already available), and negative numbers mean never timeout (wait forever for data). Note that like all Qore functions and methods taking timeout values, a relative date/time value can be used to make the units clear (i.e. 2m = two minutes, etc.).

Prototype

HTTPClient::setTimeout(softint $timeout_ms = -1) returns nothing

HTTPClient::setTimeout(date $timeout) returns nothing

Example
$httpclient.setTimeout(2m); # sets timeout to 2 minutes

Table 4.448. Arguments for HTTPClient::setTimeout()

Argument

Description

softint $timeout_ms = -1 or date $timeout

Read timeout in milliseconds, 0 = immediate timeout, negative numbers = never timeout.


4.10.21. HTTPClient::getConnectTimeout()

Synopsis

Returns the connect timeout as an integer in milliseconds. Negative numbers mean the default system timeout is used instead.

Prototype

HTTPClient::getConnectTimeout() returns int

Example
$timeout = $httpclient.getConnectTimeout();

Table 4.449. Return Values for HTTPClient::getConnectTimeout()

Return Type

Description

int

The connect timeout value in milliseconds


4.10.22. HTTPClient::getTimeout()

Synopsis

Returns the default read timeout as an integer in milliseconds. Zero means immediate timeout (only returns data if it is already available), and negative numbers mean never timeout (wait forever for data).

Prototype

HTTPClient::getTimeout() returns int

Example
$timeout = $httpclient.getTimeout();

Table 4.450. Return Values for HTTPClient::getTimeout()

Return Type

Description

int

The read timeout value in milliseconds


4.10.23. HTTPClient::setHTTPVersion()

Synopsis

Sets the HTTP protocol version string for headers in outgoing messages, allowed values are '1.0' and '1.1'.

Prototype

HTTPClient::setHTTPVersion(string $ver) returns nothing

Example
$httpclient.setHTTPVersion("1.1");

Table 4.451. Arguments for HTTPClient::setHTTPVersion()

Argument

Description

string $ver

either '1.0' or '1.1' for the HTTP protocol compliance version.


Table 4.452. Exceptions thrown by HTTPClient::setHTTPVersion()

err

desc

HTTP-VERSION-ERROR

invalid HTTP version passed (allowed values: '1.0', '1.1').


4.10.24. HTTPClient::getHTTPVersion()

Synopsis

Returns the HTTP protocol version string used in outgoing messages.

Prototype

HTTPClient::getHTTPVersion() returns string

Example
$version = $httpclient.getHTTPVersion();

Table 4.453. Return Values for HTTPClient::getHTTPVersion()

Return Type

Description

string

The HTTP protocol version string used in outgoing messages (either '1.0' or '1.1').


4.10.25. HTTPClient::setSecure()

Synopsis

Sets the object to make a secure SSL/TLS connection on the next connect if the passed argument is True, or an unencrypted cleartext connection if it is False. This method overrides the default behaviour for the protocol set for the object.

Note that the behavior of this method when called with no argument changed in version 0.8.0; prior to version 0.8.0 calling this method with no argument would turn off secure mode; the behavior was changed to the current functionality in order to make the usage of this method consistent with other methods of the same name and to make it more logical.

Prototype

HTTPClient::setSecure(softbool $secure = True) returns nothing

Example
$httpclient.setSecure(True);

Table 4.454. Arguments for HTTPClient::setSecure()

Argument

Description

softbool $secure = True

If True, a SSL/TLS connection will be attempted on the next connection. If False, an unencrypted cleartext connection will be established.


4.10.26. HTTPClient::isSecure()

Synopsis

Returns True if the current connection is encrypted, False if not.

Prototype

HTTPClient::isSecure() returns bool

Example
$bool = $httpclient.isSecure();

Table 4.455. Return Values for HTTPClient::isSecure()

Return Type

Description

bool

Returns True if the current connection is encrypted, False if not.


4.10.27. HTTPClient::verifyPeerCertificate()

Synopsis

Returns a string code giving the result of verifying the remote certificate or NOTHING if an encrypted connection is not established. Return value are the keys described in the X509_VerificationReasons hash constant. This hash can also be used to generate a textual description of the verification result.

Prototype

HTTPClient::verifyPeerCertificate() returns any

Example
my any $str = $httpclient.verifyPeerCertificate();

Table 4.456. Return Values for HTTPClient::verifyPeerCertificate()

Return Type

Description

string or nothing

A string code giving the result of verifying the peer's certificate. No value is returned if a secure connection has not been established.


4.10.28. HTTPClient::getSSLCipherName()

Synopsis

Returns the name of the cipher for an encrypted connection.

Prototype

HTTPClient::getSSLCipherName() returns any

Example
my any $str = $httpclient.getSSLCipherName();

Table 4.457. Return Values for HTTPClient::getSSLCipherName()

Return Type

Description

string or nothing

The name of the cipher for a secure connection. No value is returned if no secure connection has been established.


4.10.29. HTTPClient::getSSLCipherVersion()

Synopsis

Returns the version of the cipher for an encrypted connection.

Prototype

HTTPClient::getSSLCipherVersion() returns any

Example
my any $str = $httpclient.getSSLCipherVersion();

Table 4.458. Return Values for HTTPClient::getSSLCipherVersion()

Return Type

Description

string or nothing

The version of the cipher for a secure connection. No value is returned if no secure connection has been established.


4.10.30. HTTPClient::setEncoding()

Synopsis

Sets the string encoding for the object; any strings deserialized with this object will be tagged with this character encoding.

Prototype

HTTPClient::setEncoding(string $encoding) returns nothing

Example
$httpclient.setEncoding("ISO-8859-1");

Table 4.459. Arguments for HTTPClient::setEncoding()

Argument

Description

string $encoding

The string encoding to use for this object.


Table 4.460. Exceptions thrown by HTTPClient::setEncoding()

err

desc

HTTP-CLIENT-SETSTRINGENCODING-ERROR

missing encoding parameter from method call


4.10.31. HTTPClient::getEncoding()

Synopsis

Returns the character encoding used for the object

Prototype

HTTPClient::getEncoding() returns string

Example
$str = $httpclient.getEncoding();

Table 4.461. Return Values for HTTPClient::getEncoding()

Return Type

Description

string

The character encoding used for the object.


4.10.32. HTTPClient::setEventQueue()

Synopsis

Sets a Queue object to receive HTTPClient and Socket events. To remove the event queue and stop monitoring events, pass NOTHING to the method. See Event Handling for more information.

Prototype

HTTPClient::setEventQueue() returns nothing

HTTPClient::setEventQueue(Queue $queue) returns nothing

Example
$httpclient.setEventQueue($queue);

Table 4.462. Arguments for HTTPClient::setEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.10.33. HTTPClient::getNoDelay()

Synopsis

Returns the TCP_NODELAY setting for the HTTPClient object. See also HTTPClient::setNoDelay().

Prototype

HTTPClient::getNoDelay() returns bool

Example
$nodelay = $httpclient.getNoDelay();

Table 4.463. Return Value for HTTPClient::getNoDelay()

Return Type

Description

bool

The TCP_NODELAY setting for the HTTPClient object.


4.10.34. HTTPClient::setNoDelay()

Synopsis

Sets the TCP_NODELAY setting for the HTTPClient object; when this setting is True, then data will be immediately sent out over the HTTPClient object's socket, when it is False, then data transmission may be delayed to be packaged with other data for the same target.

Delayed data transmissions may cause problems when the sender immediately closes the socket after sending data; in this case the receiver may not get the data even though the send succeeded.

Note that if no value is given to the method, the argument will be assumed to be False, and output buffering will be turned on for the HTTPClient object, which may be the opposite of what the programmer intends, therefore it's recommended to always pass an argument to this method.

If the socket is not connected when this call is made, then an internal flag is set and the TCP_NODELAY option is enabled when the next connection is established. If the socket is connected, then if an error occurs setting the TCP_NODELAY option on the socket, this method will return a non-zero error code; the actual error can be checked with the errno() function.

See also HTTPClient::getNoDelay().

Prototype

HTTPClient::setNoDelay(softbool $nodelay = True) returns int

Example
$httpclient.setNoDelay(True);

Table 4.464. Arguments for HTTPClient::setNoDelay()

Argument

Description

softbool $nodelay = True

The TCP_NODELAY setting for the HTTPClient.


Table 4.465. Return Value for HTTPClient::setNoDelay()

Return Type

Description

int

0 for success, non-zero for errors. To get error information, see errno() and strerror().


4.10.35. HTTPClient::isConnected()

Synopsis

Returns the connection state of the HTTPClient object. Connections are implicitly established whenever a method is callde requiring a connection; to explicitly establish a connection, see HTTPClient::connect().

Prototype

HTTPClient::isConnected() returns bool

Example
my bool $connected = $httpclient.isConnected();

Table 4.466. Return Value for HTTPClient::isConnected()

Return Type

Description

bool

The connection state of the HTTPClient object.


4.11. XmlRpcClient Class

Note: This class is not available with the PO_NO_NETWORK parse option.

The XmlRpcClient class provides easy access to XML-RPC web services. This class inherits all public methods of the HTTPClient class. The inherited HTTPClient methods are not listed in this section, see the section on the HTTPClient class for more information on methods provided by the parent class. For low-level XML-RPC functions, see the XML-RPC functions in XML Functions.

The XmlRpcClient class understands the following protocols in addition to the protocols supported by the HTTPClient class:

Table 4.467. XmlRpcClient Class Protocols

Protocol

Default Port

SSL?

Description

xmlrpc

80

No

Unencrypted XML-RPC protocol over HTTP

xmlrpcs

443

Yes

XML-RPC protocol over HTTP with SSL/TLS encryption


The XmlRpcClient supplies default values for HTTP headers as follows:

Table 4.468. XmlRpcClient Default, but Overridable Headers

Header

Default Value

Accept

text/xml

Content-Type

text/xml

User-Agent

Qore XML-RPC Client v0.8.0

Connection

Keep-Alive


Table 4.469. XmlRpcClient Class Method Overview

Method

Except?

Description

XmlRpcClient::constructor(softbool $no_connect = False)

XmlRpcClient::constructor(hash $opts, softbool $no_connect = False)

Y

Creates the XmlRpcClient object based on the parameters passed.

XmlRpcClient::destructor

N

Destroys the XmlRpcClient object and closes any open connections.

XmlRpcClient::copy()

Y

Copying objects of this class is not supported, an exception will be thrown.

XmlRpcClient::call(string $method, ...) returns hash

Y

Calls a remote method using a variable number of arguments for the method arguments and returns the response as qore data structure.

XmlRpcClient::callArgs(string $method, any $args) returns hash

Y

Calls a remote method using a single value after the method name for the method arguments and returns the response as qore data structure.

XmlRpcClient::callWithInfo(reference $info, string $method, ...) returns hash

Y

Same as the XmlRpcClient::call() except the first argument must be an lvalue reference, which is used as an output variable, where information about the HTTP request and response is written.

XmlRpcClient::callArgsWithInfo(reference $info, string $method, hash $args) returns any

Y

Same as the XmlRpcClient::callArgs() except the first argument must be an lvalue reference, which is used as an output variable, where information about the HTTP request and response is written.

XmlRpcClient::setEventQueue() returns nothing

XmlRpcClient::setEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive HTTPClient and Socket events or clears the queue if no argument is passed.


4.11.1. XmlRpcClient::constructor()

Synopsis

Creates the XmlRpcClient object based on the parameters passed and by default immediately attempts to establish a connection to the server (pass a boolean True value as the second argument to establish a connection on demand). See HTTPClient::constructor() and HTTPClient::connect() for information on possible exceptions.

Prototype

XmlRpcClient::constructor(softbool $no_connect = False)

XmlRpcClient::constructor(hash $opts, softbool $no_connect = False)

Example
my XmlRpcClient $xrc(("url":"http://hostname/RPC2"));

Table 4.470. Arguments for XmlRpcClient::constructor()

Argument

Description

hash $opts

an option hash, see HTTPClient::constructor() Option Hash Keys for valid keys in this hash.

softbool $no_connect = False

If this optional argument is passed with a value of True, then the object will not attempt to make a connection immediately to the remote socket, but instead will wait until a connection is required and made implicitly or manually established with the parent class' HTTPClient::connect() method.


4.11.2. XmlRpcClient::destructor()

Synopsis

Destroys the XmlRpcClient object and closes any open connections.

Example
delete $xrc;

4.11.3. XmlRpcClient::copy()

Synopsis

Copying objects of this class is not supported, an exception will be thrown.

Table 4.471. Exceptions thrown by XmlRpcClient::copy()

err

desc

XMLRPCCLIENT-COPY-ERROR

objects of this class may not be copied


4.11.4. XmlRpcClient::call()

Synopsis

Calls a remote method using a variable number of arguments for the method arguments and returns the response as qore data structure. See HTTPClient::send(), makeXMLRPCCallString(), and parseXMLRPCResponse() for information on possible exceptions.

Prototype

XmlRpcClient::call(string $method, ...) returns hash

Example
$result = $xrc.call("method.name", $arg1, $arg2);

Table 4.472. Arguments for XmlRpcClient::call()

Argument

Description

string $method

The XML-RPC method name to call

...

Optional arguments for the method.


Table 4.473. Return Values for XmlRpcClient::call()

Return Type

Description

hash

If the call was successful, the response information will be found in the key 'params'. If an error occurred then the error information can be found under the 'fault' key.


4.11.5. XmlRpcClient::callArgs()

Synopsis

Calls a remote method using a single value after the method name for the method arguments and returns the response as qore data structure. See HTTPClient::send(), makeXMLRPCCallString(), and parseXMLRPCResponse() for information on possible exceptions.

Prototype

XmlRpcClient::callArgs(string $method, any $args) returns hash

Example
$result = $xrc.callArgs("method.name", $arg_list);

Table 4.474. Arguments for XmlRpcClient::callArgs()

Argument

Description

string $method

The XML-RPC method name to call

any $args

An optional list of arguments (or single argument) for the method.


Table 4.475. Return Values for XmlRpcClient::callArgs()

Return Type

Description

hash

If the call was successful, the response information will be found in the key 'params'. If an error occurred then the error information can be found under the 'fault' key.


4.11.6. XmlRpcClient::callWithInfo()

Synopsis

Like the XmlRpcClient::call() method, except requires an lvalue reference as the first argument that will be used as an output variable providing information about the HTTP request and response made to effect the XML-RPC call.

Prototype

XmlRpcClient::callWithInfo(reference $info, string $method, ...) returns hash

Example
$result = $xrc.callWithInfo(\$info, "method.name", $arg1, $arg2);

Table 4.476. Arguments for XmlRpcClient::callWithInfo()

Argument

Description

reference $info

A reference to an lvalue that will be used as an output variable providing information about the HTTP request and response made to effect the XML-RPC call.

string $method

The XML-RPC method name to call

...

Optional arguments for the method.


Table 4.477. Return Values for XmlRpcClient::callWithInfo()

Return Type

Description

hash

If the call was successful, the response information will be found in the key 'params'. If an error occurred then the error information can be found under the 'fault' key.


4.11.7. XmlRpcClient::callArgsWithInfo()

Synopsis

Like the XmlRpcClient::callArgs() method, except requires an lvalue reference as the first argument that will be used as an output variable providing information about the HTTP request and response made to effect the XML-RPC call.

Prototype

XmlRpcClient::callArgsWithInfo(reference $info, string $method, any $args) returns hash

Example
$result = $xrc.callArgsWithInfo(\$info, "method.name", $arg_list);

Table 4.478. Arguments for XmlRpcClient::callArgsWithInfo()

Argument

Description

reference $info

A reference to an lvalue that will be used as an output variable providing information about the HTTP request and response made to effect the XML-RPC call.

string $method

The XML-RPC method name to call

any $args

An optional list of arguments (or single argument) for the method.


Table 4.479. Return Values for XmlRpcClient::callArgswithInfo()

Return Type

Description

hash

If the call was successful, the response information will be found in the key 'params'. If an error occurred then the error information can be found under the 'fault' key.


4.11.8. XmlRpcClient::setEventQueue()

Synopsis

Sets a Queue object to receive HTTPClient and Socket events. To remove the event queue and stop monitoring events, pass NOTHING to the method. See Event Handling for more information.

Prototype

XmlRpcClient::setEventQueue() returns nothing

XmlRpcClient::setEventQueue(Queue $queue) returns nothing

Example
$xrc.setEventQueue($queue);

Table 4.480. Arguments for XmlRpcClient::setEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.12. JsonRpcClient Class

Note: This class is not available with the PO_NO_NETWORK parse option.

The JsonRpcClient class provides easy access to JSON-RPC web services. This class inherits all public methods of the HTTPClient class. The inherited HTTPClient methods are not listed in this section, see the section on the HTTPClient class for more information on methods provided by the parent class. For low-level JSON-RPC functions, see the JSON-RPC functions in JSON Functions.

The JsonRpcClient class understands the following protocols in addition to the protocols supported by the HTTPClient class:

Table 4.481. JsonRpcClient Class Protocols

Protocol

Default Port

SSL?

Description

jsonrpc

80

No

Unencrypted JSON-RPC protocol over HTTP

jsonrpcs

443

Yes

JSON-RPC protocol over HTTP with SSL/TLS encryption


The JsonRpcClient supplies default values for HTTP headers as follows:

Table 4.482. JsonRpcClient Default, but Overridable Headers

Header

Default Value

Accept

application/json

Content-Type

application/json

User-Agent

Qore JSON-RPC Client v0.8.0

Connection

Keep-Alive


Table 4.483. JsonRpcClient Class Method Overview

Method

Except?

Description

JsonRpcClient::constructor(softbool $no_connect = False)

JsonRpcClient::constructor(hash $opts, bool $no_connect = False)

N

Creates the JsonRpcClient object based on the parameters passed.

JsonRpcClient::destructor()

N

Destroys the JsonRpcClient object and closes any open connections.

JsonRpcClient::copy()

Y

Copying objects of this class is not supported, an exception will be thrown.

JsonRpcClient::call(string $method, ...) returns any

Y

Calls a remote method using a variable number of arguments for the method arguments and returns the response as qore data structure.

JsonRpcClient::callArgs(string $method, any $args) returns any

Y

Calls a remote method using a single value after the method name for the method arguments and returns the response as qore data structure.

JsonRpcClient::callWithInfo(reference $info, string $method, ...) returns any

Y

Same as the JsonRpcClient::call() except the first argument must be an lvalue reference, which is used as an output variable, where information about the HTTP request and response is written.

JsonRpcClient::callArgsWithInfo(reference $info, string $method, any $args) returns any

Y

Same as the JsonRpcClient::callArgs() except the first argument must be an lvalue reference, which is used as an output variable, where information about the HTTP request and response is written.

JsonRpcClient::setEventQueue() returns nothing

JsonRpcClient::setEventQueue(Queue $queue) returns nothing

N

Sets a Queue object to receive HTTPClient and Socket events or clears the queue if no argument is passed.


4.12.1. JsonRpcClient::constructor()

Synopsis

Creates the JsonRpcClient object based on the parameters passed and by default immediately attempts to establish a connection to the server (pass a boolean True value as the second argument to establish a connection on demand). See HTTPClient::constructor() and HTTPClient::connect() for information on possible exceptions.

Prototype

JsonRpcClient::constructor(softbool $no_connect = False)

JsonRpcClient::constructor(hash $opts, bool $no_connect = False)

Example
my JsonRpcClient $jrc(("url":"http://hostname/json"));

Table 4.484. Arguments for JsonRpcClient::constructor()

Argument

Description

hash $opts

an option hash, see HTTPClient::constructor() Option Hash Keys for valid keys in this hash.

softbool $no_connect = False

If this optional argument is passed with a value of True, then the object will not attempt to make a connection immediately to the remote socket, but instead will wait until a connection is required and made implicitly or manually established with the parent class' HTTPClient::connect() method.


4.12.2. JsonRpcClient::destructor()

Synopsis

Destroys the JsonRpcClient object and closes any open connections.

Example
delete $jrc;

4.12.3. JsonRpcClient::copy()

Synopsis

Copying objects of this class is not supported, an exception will be thrown.

Table 4.485. Exceptions thrown by JsonRpcClient::copy()

err

desc

JSONRPCCLIENT-COPY-ERROR

objects of this class may not be copied


4.12.4. JsonRpcClient::call()

Synopsis

Calls a remote method using a variable number of arguments for the method arguments and returns the response as qore data structure. See HTTPClient::send(), makeJSONRPCRequestString(), and parseJSON() for information on possible exceptions.

Prototype

JsonRpcClient::call(string $method, ...) returns any

Example
$result = $jrc.call("method_name", $arg1, $arg2);

Table 4.486. Arguments for JsonRpcClient::call()

Argument

Description

string $method

The JSON-RPC method name to call

...

Optional arguments for the method.


Table 4.487. Return Values for JsonRpcClient::call()

Return Type

Description

hash

The information returned by the JSON-RPC method.


4.12.5. JsonRpcClient::callArgs()

Synopsis

Calls a remote method using a single value after the method name for the method arguments and returns the response as qore data structure. See HTTPClient::send(), makeJSONRPCRequestString(), and parseJSON() for information on possible exceptions.

Prototype

JsonRpcClient::callArgs(string $method, any $args) returns any

Example
$result = $jrc.callArgs("method_name", $arg_list);

Table 4.488. Arguments for JsonRpcClient::callArgs()

Argument

Description

string $method

The JSON-RPC method name to call

any $args

An optional list of arguments (or single argument) for the method.


Table 4.489. Return Values for JsonRpcClient::callArgs()

Return Type

Description

any

The information returned by the JSON-RPC method.


4.12.6. JsonRpcClient::callWithInfo()

Synopsis

Like the JsonRpcClient::call() method, except requires an lvalue reference as the first argument that will be used as an output variable providing information about the HTTP request and response made to effect the JSON-RPC call.

Prototype

JsonRpcClient::callWithInfo(reference $info, string $method, ...) returns any

Example
$result = $jrc.callWithInfo(\$info, "method_name", $arg1, $arg2);

Table 4.490. Arguments for JsonRpcClient::callWithInfo()

Argument

Description

reference $info

A reference to an lvalue that will be used as an output variable providing information about the HTTP request and response made to effect the JSON-RPC call.

string $method

The JSON-RPC method name to call

...

Optional arguments for the method.


Table 4.491. Return Values for JsonRpcClient::callWithInfo()

Return Type

Description

hash

The information returned by the JSON-RPC method.


4.12.7. JsonRpcClient::callArgswithInfo()

Synopsis

Like the JsonRpcClient::callArgs() method, except requires an lvalue reference as the first argument that will be used as an output variable providing information about the HTTP request and response made to effect the JSON-RPC call.

Prototype

JsonRpcClient::callArgsWithInfo(reference $info, string $method, any $args) returns any

Example
$result = $jrc.callArgsWithInfo(\$info, "method_name", $arg_list);

Table 4.492. Arguments for JsonRpcClient::callArgsWithInfo()

Argument

Description

reference $info

A reference to an lvalue that will be used as an output variable providing information about the HTTP request and response made to effect the JSON-RPC call.

string $method

The JSON-RPC method name to call

any $args

An optional list of arguments (or single argument) for the method.


Table 4.493. Return Values for JsonRpcClient::callArgsWithInfo()

Return Type

Description

any

The information returned by the JSON-RPC method.


4.12.8. JsonRpcClient::setEventQueue()

Synopsis

Sets a Queue object to receive HTTPClient and Socket events. To remove the event queue and stop monitoring events, pass NOTHING to the method. See Event Handling for more information.

Prototype

JsonRpcClient::setEventQueue() returns nothing

JsonRpcClient::setEventQueue(Queue $queue) returns nothing

Example
$jrc.setEventQueue($queue);

Table 4.494. Arguments for JsonRpcClient::setEventQueue()

Argument

Description

[Queue $queue]

To set the event queue, pass a Queue object; to clear the event queue, pass no argument to the function.


4.13. SSLPrivateKey Class

SSLPrivateKey objects are containers for private key data.

Table 4.495. SSLPrivateKey Class Method Overview

Method

Except?

Description

SSLPrivateKey::constructor(string $key_pem, string $pass = "")

SSLPrivateKey::constructor(binary $key_der)

Y

Creates the SSLPrivateKey object from the data argument passed; as a deprecated, backwards-compatibilty extension, if the string variant is used and a string less then 120 bytes long is passed, it is taken as a filename to use to load the private key data from in PEM format. In this case PO_NO_FILESYSTEM is checked at run-time; if set, and exception is thrown.

SSLPrivateKey::destructor()

N

Destroys the SSLPrivateKey object.

SSLPrivateKey::copy()

Y

Copying objects of this class is not supported, an exception will be thrown.

SSLPrivateKey::getType() returns string

N

Returns the algorithm used for the private key.

SSLPrivateKey::getVersion() returns int

N

Returns the version of the private key.

SSLPrivateKey::getBitLength() returns int

N

Returns the bit length of the private key.

SSLPrivateKey::getInfo() returns hash

N

Returns a hash of all information for the private key.


4.13.1. SSLPrivateKey::constructor()

Synopsis

Creates the SSLPrivateKey object from the data argument passed.

As a deprecated, backwards-compatibilty extension, if the string variant is used and a string less then 120 bytes long is passed, it is taken as a filename to use to load the private key data from in PEM format. In this case PO_NO_FILESYSTEM is checked at run-time; if set, and exception is thrown. Do not use this feature; load the file first and pass the data to the constructor instead. This functionality will be removed in a future release of Qore.

Prototype

SSLPrivateKey::constructor(string $key_pem, string $pass = "")

SSLPrivateKey::constructor(binary $key_der)

Example
my SSLPrivateKey $pkey($data);

Table 4.496. Arguments for SSLPrivateKey::constructor()

Argument

Description

string $key_pem, string $pass = ""

The PEM-encoded text representation of the private key and optionally its passphrase.

binary $key_der

The DER-encoded binary representation of the private key.


Table 4.497. Exceptions thrown by SSLPrivateKey::constructor()

err

desc

SSLPRIVATEKEY-CONSTRUCTOR-ERROR

invalid format, invalid or missing password, etc


4.13.2. SSLPrivateKey::destructor()

Synopsis

Destroys the SSLPrivateKey object.

Example
delete $pkey;

4.13.3. SSLPrivateKey::copy()

Synopsis

Copying objects of this class is not supported, an exception will be thrown.

Table 4.498. Exceptions thrown by SSLPrivateKey::copy()

err

desc

SSLPRIVATEKEY-COPY-ERROR

objects of this class may not be copied


4.13.4. SSLPrivateKey::getType()

Synopsis

Returns a string giving the algorithm used for the private key.

Prototype

SSLPrivateKey::getType() returns string

Example
$str = $pkey.getType();

Table 4.499. Return Values for SSLPrivateKey::getType()

Return Type

Description

string

Returns values include: RSA, RSA2, DSA, DSA1, DSA2, DSA3, DSA4, DH, and unknown


4.13.5. SSLPrivateKey::getVersion()

Synopsis

Returns the version of the private key as an integer.

Prototype

SSLPrivateKey::getVersion() returns int

Example
$int = $pkey.getVersion();

Table 4.500. Return Values for SSLPrivateKey::getVersion()

Return Type

Description

int

The version of the private key.


4.13.6. SSLPrivateKey::getBitLength()

Synopsis

Returns the bit length of the private key.

Prototype

SSLPrivateKey::getBitLength() returns int

Example
$int = $pkey.getBitLength();

Table 4.501. Return Values for SSLPrivateKey::getBitLength()

Return Type

Description

int

The bit length of the private key.


4.13.7. SSLPrivateKey::getInfo()

Synopsis

SSLPrivateKey::getInfo() returns hash

Prototype
SSLPrivateKey::getInfo()
Example
$hash = $pkey.getInfo();

Table 4.502. Return Values for SSLPrivateKey::getInfo()

Return Type

Description

hash

Keys are 'type', 'version', and 'bitLength' corresponding to the algorithm type, the version, and the bit length of the key respectively.


4.14. SSLCertificate Class

SSLCertificate objects are designed to work with X.509 certificate data.

Table 4.503. SSLCertificate Class Method Overview

Method

Except?

Description

SSLCertificate::constructor(string $cert_pem)

SSLCertificate::constructor(binary $cert_der)

Y

Creates the SSLCertificate object from the filename argument passed; as a deprecated, backwards-compatibilty extension, if the string variant is used and a string less then 200 bytes long is passed, it is taken as a filename to use to load the private key data from in PEM format. In this case PO_NO_FILESYSTEM is checked at run-time; if set, and exception is thrown.

SSLCertificate::destructor()

N

Destroys the SSLCertificate object.

SSLCertificate::copy()

Y

Copying objects of this class is not supported, an exception will be thrown.

SSLCertificate::getPEM() returns string

N

Returns a string in PEM format representing the certificate.

SSLCertificate::getVersion() returns int

N

Returns the version of the certificate.

SSLCertificate::getSignatureType() returns string

N

Returns the signature type of the certificate.

SSLCertificate::getSignature() returns binary

N

Returns a binary object representing the signature of the certificate.

SSLCertificate::getPublicKeyAlgorithm() returns string

N

Returns name of the public key algorithm of the certificate.

SSLCertificate::getPublicKey() returns any

N

Returns a binary object representing the public key of the certificate in DER (Distinguished Encoding Rules) format or NOTHING if the public key cannot be retrieved.

SSLCertificate::getSubjectHash() returns hash

N

Returns a hash of strings representing the subject information of the certificate.

SSLCertificate::getIssuerHash() returns hash

N

Returns a hash of strings representing the issuer information of the certificate.

SSLCertificate::getSerialNumber() returns int

N

Returns the integer serial number of the certificate.

SSLCertificate::getPurposeHash() returns hash

N

Returns a hash of booleans representing the allowed purposes of the certificate.

SSLCertificate::getNotBeforeDate() returns date

N

Returns a date/time value representing the start date of the certificate.

SSLCertificate::getNotAfterDate() returns date

N

Returns a date/time value representing the end date of the certificate.

SSLCertificate::getInfo() returns hash

N

Returns a hash of all information for the certificate.


4.14.1. SSLCertificate::constructor()

Synopsis

Creates the SSLCertificate object from the argument passed. If a string is passed, the value is assumed to be the PEM representation of the certificate; if a binary is passed, the value is assumed to be the DER-encoded form of the certificate.

DEPRECATED: If a string is passed that is less than 200 bytes long, the string is assumed to be a file name; in which case the PO_NO_FILESYSTEM parse option is checked at run-time; if this restriction is not set, then the certificate is loaded from the filename (in this case, the certificate must be in PEM format). Do not use this feature; load the file first and pass the data to the constructor instead. This functionality will be removed in a future release of Qore.

Prototype

SSLCertificate::constructor(string $cert_pem)

SSLCertificate::constructor(binary $cert_der)

Example
my SSLCertificate $cert($pem_cert_string);

Table 4.504. Arguments for SSLCertificate::constructor()

Argument

Description

string $cert_pem, string $pass = ""

The PEM-encoded text representation of the X509 certificate.

binary $cert_der

The DER-encoded binary representation of the X509 certificate.


Table 4.505. Exceptions thrown by SSLCertificate::constructor()

err

desc

SSLCERTIFICATE-CONSTRUCTOR-ERROR

missing or invalid argument, unable to parse file, etc


4.14.2. SSLCertificate::destructor()

Synopsis

Destroys the SSLCertificate object.

Example
delete $cert;

4.14.3. SSLCertificate::copy()

Synopsis

Copying objects of this class is not supported, an exception will be thrown.

Table 4.506. Exceptions thrown by SSLCertificate::copy()

err

desc

SSLCERTIFICATE-COPY-ERROR

objects of this class may not be copied


4.14.4. SSLCertificate::getPEM()

Synopsis

Returns a string in PEM format representing the certificate.

Prototype

SSLCertificate::getPEM() returns string

Example
$pem_str = $cert.getPEM();

Table 4.507. Return Values for SSLCertificate::getPEM()

Return Type

Description

string

A string in PEM format representing the certificate.


4.14.5. SSLCertificate::getVersion()

Synopsis

Returns the version of the certificate as an integer.

Prototype

SSLCertificate::getVersion() returns int

Example
$int = $cert.getVersion();

Table 4.508. Return Values for SSLCertificate::getVersion()

Return Type

Description

int

The version of the certificate.


4.14.6. SSLCertificate::getSignatureType()

Synopsis

Returns the signature type of the certificate.

Prototype

SSLCertificate::getSignatureType() returns string

Example
$str = $cert.getSignatureType();

Table 4.509. Return Values for SSLCertificate::getSignatureType()

Return Type

Description

string

The signature type of the certificate.


4.14.7. SSLCertificate::getSignature()

Synopsis

Returns a binary object representing the signature of the certificate.

Prototype

SSLCertificate::getSignature() returns binary

Example
$bin = $cert.getSignature();

Table 4.510. Return Values for SSLCertificate::getSignature()

Return Type

Description

binary

The signature data for the certificate.


4.14.8. SSLCertificate::getPublicKeyAlgorithm()

Synopsis

Returns name of the public key algorithm of the certificate.

Prototype

SSLCertificate::getPublicKeyAlgorithm() returns string

Example
$str = $cert.getPublicKeyAlgorithm();

Table 4.511. Return Values for SSLCertificate::getPublicKeyAlgorithm()

Return Type

Description

string

The name of the public key algorithm of the certificate.


4.14.9. SSLCertificate::getPublicKey()

Synopsis

Returns a binary object representing the public key of the certificate in DER (Distinguished Encoding Rules) format.

Prototype

SSLCertificate::getPublicKey() returns any

Example
$bin = $cert.getPublicKey();

Table 4.512. Return Values for SSLCertificate::getPublicKey()

Return Type

Description

binary

The public key of the certificate in DER format.


4.14.10. SSLCertificate::getSubjectHash()

Synopsis

Returns a hash of strings representing the subject information of the certificate.

Prototype

SSLCertificate::getSubjectHash() returns hash

Example
$hash = $cert.getSubjectHash();

Table 4.513. Return Values for SSLCertificate::getSubjectHash()

Return Type

Description

hash

Key-value pairs representing the subject information of the certificate.


4.14.11. SSLCertificate::getIssuerHash()

Synopsis

Returns a hash of strings representing the issuer information of the certificate.

Prototype

SSLCertificate::getIssuerHash() returns hash

Example
$hash = $cert.getIssuerHash();

Table 4.514. Return Values for SSLCertificate::getIssuerHash()

Return Type

Description

hash

Key-value pairs representing the issuer information of the certificate.


4.14.12. SSLCertificate::getSerialNumber()

Synopsis

Returns the integer serial number of the certificate.

Prototype

SSLCertificate::getSerialNumber() returns int

Example
$hash = $cert.getIssuerHash();

Table 4.515. Return Values for SSLCertificate::getSerialNumber()

Return Type

Description

int

The serial number of the certificate.


4.14.13. SSLCertificate::getPurposeHash()

Synopsis

Returns a hash of booleans representing the allowed purposes of the certificate.

Prototype

SSLCertificate::getPurposeHash() returns hash

Example
$hash = $cert.getPurposeHash();

Table 4.516. Return Values for SSLCertificate::getPurposeHash()

Return Type

Description

hash

Key-value pairs representing the allowed purposes of the certificate.


4.14.14. SSLCertificate::getNotBeforeDate()

Synopsis

Returns a date/time value representing the start date of the certificate.

Prototype

SSLCertificate::getNotBeforeDate() returns date

Example
$date = $cert.getNotBeforeDate();

Table 4.517. Return Values for SSLCertificate::getNotBeforeDate()

Return Type

Description

date

The start date of the certificate.


4.14.15. SSLCertificate::getNotAfterDate()

Synopsis

Returns a date/time value representing the end date of the certificate.

Prototype

SSLCertificate::getNotAfterDate() returns date

Example
$date = $cert.getNotAfterDate();

Table 4.518. Return Values for SSLCertificate::getNotAfterDate()

Return Type

Description

date

The end date of the certificate.


4.14.16. SSLCertificate::getInfo()

Synopsis

Returns a hash of all information for the certificate.

Prototype

SSLCertificate::getInfo() returns hash

Example
$hash = $cert.getInfo();

Table 4.519. Return Values for SSLCertificate::getInfo()

Return Type

Description

hash

Keys are 'version', 'serialNumber', 'subject', 'issuer', 'purposes', 'notBefore', 'notAfter', 'signatureType', 'signature', and 'publicKey' corresponding to the respective attributes of the certificate.


4.15. TimeZone Class

The TimeZone class provides access to time zone functionality.

TimeZone objects based on zoneinfo region files can have daylight savings time information; those based on UTC offsets have none.

Table 4.520. TimeZone Method Overview

Method

Except?

Description

TimeZone::constructor(string $region)

TimeZone::constructor(softint $secs_east)

Y

Creates the TimeZone object based on the region name (ex: "America/Chicago") or the number of seconds east of UTC (3600 = UTC +01).

TimeZone::destructor()

N

Destroys the TimeZone object.

TimeZone::copy()

N

Creates a copy of the TimeZone object.

TimeZone::UTCOffset() returns int

N

Returns the number of seconds east of UTC for the zone; negative numbers indicate a zone west of UTC.

TimeZone::hasDST() returns bool

N

Returns True if the current zone has daylight saving's time rules, False if not. TimeZone objects based on zoneinfo region files can have (but do not necessarily have) daylight savings time information; those based on UTC offsets have none.

TimeZone::region() returns string

N

Returns the region name as a string; if the current zone is based on a UTC offset, then the UTC offset is returned as a string like "+01:00".

TimeZone::date(softint $secs, softint $us = 0) returns date

TimeZone::date(date $date) returns date

N

Returns the equivalent date in the current time zone; when using integer arguments, offsets are in seconds and microseconds from 1970-01-01Z.

TimeZone::dateMs(softint $ms) returns date

N

Returns a date in the object's zone based on an offset in milliseconds from 1970-01-01Z.

TimeZone::dateUs(softint $us) returns date

N

Returns a date in the object's zone based on an offset in microseconds from 1970-01-01Z.

static TimeZone::get() returns TimeZone

N

Returns the default time zone for the current execution context.

static TimeZone::set(TimeZone $zone) returns nothing

N

Sets the default time zone for the current execution context.

static TimeZone::setUTCOffset(softint $secs_east) returns nothing

N

Sets the default time zone for the current execution context based on the number of seconds east of UTC; for zones west of UTC, use negative numbers.

static TimeZone::setRegion(string $region) returns nothing

Y

Sets the default time zone for the current execution context from a zoneinfo region file; if there are errors reading or parsing the file, an exception is thrown.


4.15.1. TimeZone::constructor()

Synopsis

Creates the TimeZone object based on the region name (ex: "America/Chicago") or the UTC offset passed as the number of seconds east of UTC for the zone.

Prototype

TimeZone::constructor(string $region)

TimeZone::constructor(softint $secs_east)

Example
my TimeZone $tz("Europe/Prague");

Table 4.521. Arguments for TimeZone::constructor()

Argument

Description

string $region

The region name for the time zone (ex: "America/Chicago"); if the zoneinfo file for the region cannot be found or parsed, then an exception is thrown.

softint $secs_east

The number of seconds east of UTC for the time zone; for zones west of UTC, use negative numbers.


Table 4.522. Exceptions Thrown by TimeZone::constructor()

err

desc

TZINFO-ERROR

Unable to read zoneinfo file; invalid file magic; error parsing zoneinfo file, etc


4.15.2. TimeZone::destructor()

Synopsis

Destroys the TimeZone object.

Example
delete $tz;

4.15.3. TimeZone::copy()

Synopsis

Creates a copy of the TimeZone object.

Example
my TimeZone $newzone = $tz.copy();

4.15.4. TimeZone::UTCOffset()

Synopsis

Returns the number of seconds east of UTC for the zone; negative numbers indicate a zone west of UTC.

Prototype

TimeZone::UTCOffset() returns int

Example
my int $offset = $tz.UTCOffset();

Table 4.523. Return Values for TimeZone::UTCOffset()

Return Type

Description

int

Returns the number of seconds east of UTC for the zone; negative numbers indicate a zone west of UTC.


4.15.5. TimeZone::hasDST()

Synopsis

Returns True if the current zone has daylight saving's time rules, False if not. TimeZone objects based on zoneinfo region files can have (but do not necessarily have) daylight savings time information; those based on UTC offsets have none.

Prototype

TimeZone::hasDST() returns bool

Example
my bool $hasdst = $tz.hasDST();

Table 4.524. Return Values for TimeZone::hasDST()

Return Type

Description

bool

Returns True if the current zone has daylight saving's time rules, False if not. TimeZone objects based on zoneinfo region files can have (but do not necessarily have) daylight savings time information; those based on UTC offsets have none.


4.15.6. TimeZone::region()

Synopsis

Returns the region name as a string; if the current zone is based on a UTC offset, then the UTC offset is returned as a string like "+01:00".

Prototype

TimeZone::region() returns string

Example
my string $region = $tz.region();

Table 4.525. Return Values for TimeZone::region()

Return Type

Description

string

Returns the region name as a string; if the current zone is based on a UTC offset, then the UTC offset is returned as a string like "+01:00".


4.15.7. TimeZone::date()

Synopsis

Returns the equivalent date in the current time zone; when using integer arguments, offsets are in seconds and microseconds from 1970-01-01Z.

Prototype

TimeZone::date(softint $secs, softint $us = 0) returns date

TimeZone::date(date $date) returns date

Example
my date $dt = $tz.date($other);

Table 4.526. Arguments for TimeZone::set()

Argument

Description

softint $secs, softint $us = 0

Offset in seconds and microseconds from 1970-01-01Z.

date $date

A date that will be used to create the date in the time zone of the objects; the same point in time will be returned but in the time zone of the object.


Table 4.527. Return Values for TimeZone::date()

Return Type

Description

date

Returns the equivalent date in the current time zone; when using integer arguments, offsets are in seconds and microseconds from 1970-01-01Z.


4.15.8. TimeZone::dateMs()

Synopsis

Returns a date in the object's zone based on an offsets in milliseconds from 1970-01-01Z.

Prototype

TimeZone::dateMs(softint $ms) returns date

Example
my date $dt = $tz.dateMs($ms);

Table 4.528. Return Values for TimeZone::dateMs()

Return Type

Description

date

Returns a date in the object's zone based on an offsets in milliseconds from 1970-01-01Z.


4.15.9. TimeZone::dateUs()

Synopsis

Returns a date in the object's zone based on an offset in microseconds from 1970-01-01Z.

Prototype

TimeZone::dateUs(softint $us) returns date

Example
my date $dt = $tz.dateUs($us);

Table 4.529. Return Values for TimeZone::dateUs()

Return Type

Description

date

Returns a date in the object's zone based on an offset in microseconds from 1970-01-01Z.


4.15.10. TimeZone::get()

Synopsis

Returns the default time zone for the current execution context.

Prototype

static TimeZone::get() returns TimeZone

Example
my TimeZone $tz = TimeZone::get();

Table 4.530. Return Values for TimeZone::get()

Return Type

Description

TimeZone

Returns the default time zone for the current execution context.


4.15.11. TimeZone::set()

Synopsis

Sets the default time zone for the current execution context.

See also Program::setTimeZone().

Prototype

static TimeZone::set(TimeZone $zone) returns nothing

Example
TimeZone::set($zone);

Table 4.531. Arguments for TimeZone::set()

Argument

Description

TimeZone $zone

The default time zone to set for the current execution context.


4.15.12. TimeZone::setUTCOffset()

Synopsis

Sets the default time zone for the current execution context based on the number of seconds east of UTC; for zones west of UTC, use negative numbers.

Time zones set with this method cannot have any daylight savings time information; to set a zone with daylight savings time information, use TimeZone::setRegion() instead.

See also Program::setTimeZoneUTCOffset().

Prototype

static TimeZone::setUTCOffset(softint $secs_east) returns nothing

Example

The following examples are all equivalent, setting the time zone to +02 UTC:

TimeZone::setUTCOffset(7200);
TimeZone::setUTCOffset(2h);
TimeZone::setUTCOffset(PT2H);

Table 4.532. Arguments for TimeZone::setUTCOffset()

Argument

Description

softint $secs_east

The number of seconds east of UTC; for zones west of UTC, use negative numbers


4.15.13. static TimeZone::setRegion()

Synopsis

Sets the default time zone for the current execution context from a zoneinfo region file; if there are errors reading or parsing the file, an exception is thrown.

See also Program::setTimeZoneRegion().

Prototype

static TimeZone::setRegion(string $region) returns nothing

Example
TimeZone::setRegion("Europe/Prague");
Restrictions

Not available with PO_NO_LOCALE_CONTROL

Table 4.533. Arguments for TimeZone::setRegion()

Argument

Description

string $region

The region name for the time zone (ex: "America/Chicago"); if the zoneinfo file for the region cannot be found or parsed, then an exception is thrown.


Table 4.534. Exceptions Thrown by TimeZone::setRegion()

err

desc

TZINFO-ERROR

Unable to read zoneinfo file; invalid file magic; error parsing zoneinfo file, etc


4.16. SQL Constants

Table 4.535. Database Driver Constants in the SQL Namespace

Constant

Value

Description

SQL::DSOracle

"oracle"

Indicates that the oracle driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DSMySQL

"mysql"

Indicates that the mysql driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DSPGSQL

"pgsql"

Indicates that the pgsql driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DSSybase

"sybase"

Indicates that the sybase driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DSFreeTDS, SQL::MSSQL

"freetds"

Indicates that the freetds driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DB2

"db2"

Indicates that the db2 driver should be used by Datasource::constructor() and DatasourcePool::constructor()

SQL::DSSQLite3

"sqlite3"

Indicates that the sqlite3 driver should be used by Datasource::constructor() and DatasourcePool::constructor()


Table 4.536. Placeholder Bind Constants in the SQL Namespace

Constant

Description

SQL::VARCHAR

Indicates that the placeholder buffer should be a string buffer

SQL::CLOB

Indicates that the placeholder buffer should be a CLOB string buffer.

SQL::BLOB

Indicates that the placeholder buffer should be a binary buffer.

SQL::DATE

Indicates that the placeholder buffer should be a date-time buffer.


Table 4.537. DBI Capability Constant Codes in the SQL Namespace

Constant

Description

SQL::DBI_CAP_CHARSET_SUPPORT

Indicates that the DBI driver supports proper character encoding conversions.

SQL::DBI_CAP_TRANSACTION_MANAGEMENT

Indicates that the DBI driver supports transaction management.

SQL::DBI_CAP_STORED_PROCEDURES

Indicates that the DBI driver supports stored procedure execution.

SQL::DBI_CAP_LOB_SUPPORT

Indicates that the DBI driver supports *LOB columns.

SQL::DBI_CAP_BIND_BY_VALUE

Indicates that the DBI driver supports directly binding qore values into queries using the %v placeholder in the query string.

SQL::DBI_CAP_BIND_BY_PLACEHOLDER

Indicates that the DBI driver supports binding placeholder buffers when executing SQL to retrieve data from queries and procedures, etc.


4.17. SQL::Datasource Class

Note: This class is not available with the PO_NO_DATABASE parse option.

The Datasource class is the high-level Qore interface to Qore's DBI layer, and as such, Datasource objects allow Qore programs to access databases that have a Qore DBI driver. The Datasource class will attempt to load any DBI driver that is not currently loaded in the constructor. For connection pooling support, see the DatasourcePool class.

Datasource objects will implicitly call Datasource::open() if no connection has yet been established and a method is called requiring a connection to the database server. Therefore any method that requires communication with the database server can also throw any exception that the open method can throw.

Some Qore DBI drivers allow "select" queries to be executed through the Datasource::exec() method, and allow SQL commands (procedure calls, etc) to be executed through the Datasource::select() method, and some DBI drivers do not (depends on the underlying DB API). At any rate, the transaction lock is set when auto-commit is disabled and when the Datasource::exec() or Datasource::beginTransaction() methods are executed as documented above. Therefore executing a transaction relevant command through the Datasource::select() method while auto-commit mode is disabled and a transaction has not yet started will not result in the transaction lock being allocated to the current thread and therefore could cause transaction errors when sharing the Datasource object between multiple threads.

Only databases with an existing Qore DBI driver can be accessed through the Qore Datasource class.

All Qore DBI drivers set new connections to use transaction isolation level "read committed".

The Datasource class provides consistent, high-level, per-connection locking on requests at a level above the DBI drivers to ensure that the communication between clients and servers is properly serialized.

4.17.1. Datasource Binding By Value and By Placeholder

All Datasource methods accepting SQL strings to execute understand a special syntax used in the query string to bind Qore data by value and to specify placeholders for output variables (for example, when executing a stored procedure or database function). Placeholder binding is DBI driver specific, but binding by value is supported with the same syntax in all drivers. Additionally, the %d numeric specifier is supported equally in all Qore DBI drivers.

Table 4.538. Datasource Format Specifiers

Format Specification

Description

%d

If any value other than NOTHING or NULL is given, then the value is converted to an integer and this value is substituted in the string at this position; if the value is NOTHING or NULL, then a literal 'null' is substituted instead.

%s

The argument is converted to a string and the string is inserted literally without any conversion or escape sequences in the string; this is useful for table or schema prefixes, etc

%v

The argument is bound by value according to the DBI driver's implementation.


To bind qore data values directly in a binary format in an SQL command, use %v in the command string, and include the value as an argument after the string. Binding by value means that Qore's DBI driver will take care of formatting the data properly for use in the query with the database server. That means that strings do not need to be quoted, date/time values do not need special formatting, binary object (with BLOB columns, for example) can be used directly in queries, etc.

Here is an example:

$rows = $pool.exec("insert into table (varchar_col, timestamp_col, blob_col, numeric_col)
values (%v, %v, %v, %d)", $string, now(), $binary, 100);

To insert a numeric value or a literal 'null' in a query, use %d in the command string, and include the value as an argument after the string. If the value is NOTHING or NULL, a literal 'null' will be written to the string; otherwise the argument is converted to a floating-point value or integer if necessary and written to the string. This is useful for working with DECIMAL (NUMERIC, NUMBER) types in a database-independent way; for example PostgreSQL servers do not do type conversions to DECIMAL types when a string, integer, or float is bound by value, therefore to ensure that integral decimal values can be used in a database-independent way (with 'null' substitution when no value is bound), it's best to use the %d code in the command string instead of %v.

For binding placeholders for output variables, write a unique name in the string and prefix it with a colon (ex: :code). In this case the method will return a hash of the output variables using the placeholder names as keys, but without the colon prefix. By default, a string type will be bound to the position. To bind other variable types to placeholder positions, include the type constant (see Type Constants) as an argument after the command string. For BLOBs, use Binary, for CLOBs, use the string "clob" (constants will be provided in a future release). Not all DBI drivers require placeholder buffer specifications; see the documentation for the DBI driver in question for more information and examples regarding placeholder buffer specifications.

4.17.2. Datasource Transaction Locks

Datasource objects have an internal transaction lock which will be grabbed when the Datasource::exec(), Datasource::vexec() Datasource::execRaw(), or Datasource::beginTransaction() methods are executed and autocommit is not enabled. This enables a single datasource to be safely used for transaction management by several threads simultaneously. Note that an exception in a Datasource method that would acquire the lock (such as the Datasource::exec() method) when it's not already held, will have the effect that the transaction lock is not acquired.

Any thread attempting to do transaction-relevant actions on a Datasource with auto-commit disabled while a transaction is in progress by another thread will block until the thread currently executing a transaction executes the Datasource::commit() or Datasource::rollback() methods (or the Datasource is deleted, reset, or closed, in which case the lock is released and an exception is raised as well).

There is a timeout associated with the transaction lock; if a thread waits for the transaction lock for more than the timeout period, then an exception will be raised in the waiting thread. The timeout value can be read and changed with the Datasource::getTransactionLockTimeout() and Datasource::setTransactionLockTimeout() methods, respectively. The default transaction lock timeout value is 120 seconds.

Table 4.539. SQL::Datasource Method Overview

Method

Except?

Description

Datasource::constructor(string $driver, string $user = "", string $pass = "", string $dbname = "", string $encoding = "", string $host = "", softint $port = 0)

Datasource::constructor(hash $params)

Y

Creates the Datasource object; attempts to load a DBI driver if the driver is not already present in Qore.

Datasource::destructor()

Y

Destroys the object.

Datasource::copy()

N

Creates a new Datasource object with the same driver as the original and copies of all the connection parameters.

Datasource::open() returns nothing

Y

Opens a connection to a database; an exception is thrown if any errors occur.

Datasource::close() returns nothing

N

Closes the connection to the database; an exception is thrown if any errors occur.

Datasource::commit() returns nothing

Y

Commits the transaction and releases the transaction lock; an exception is thrown if any errors occur.

Datasource::rollback() returns nothing

Y

Rolls back the transaction and releases the transaction lock; an exception is thrown if any errors occur.

Datasource::setAutoCommit(softbool $b = True) returns nothing

N

Turns autocommit on or off for this object.

Datasource::exec(string $sql, ...) returns any

Datasource::exec() returns nothing (RT_NOOP)

Y

Executes SQL code on the DB connection.

Datasource::execRaw(string $sql) returns any

Y

Executes SQL code (like Datasource::exec()) on the DB connection without any variable binding.

Datasource::vexec(string $sql, list $args) returns any

Datasource::vexec(string $sql) returns any

Datasource::vexec() returns nothing (RT_NOOP)

Y

Executes SQL code on the DB connection, taking a list for all bind arguments.

Datasource::select(string $sql, ...) returns any

Datasource::select() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a hash (column names) of lists (rows).

Datasource::vselect(string $sql, list $args) returns any

Datasource::vselect(string $sql) returns any

Datasource::vselect() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a hash (column names) of lists (rows), taking a list for all bind arguments.

Datasource::selectRow(string $sql, ...) returns any

Datasource::selectRow() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the first row as a hash (column names and values).

Datasource::vselectRow(string $sql, list $args) returns any

Datasource::vselectRow(string $sql) returns any

Datasource::vselectRow() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the first row as a hash (column names and values), taking a list for all bind arguments.

Datasource::selectRows(string $sql, ...) returns any

Datasource::selectRows() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a list (rows) of hashes (column names and values).

Datasource::vselectRows(string $sql, list $args) returns any

Datasource::vselectRows(string $sql) returns any

Datasource::vselectRows() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a list (rows) of hashes (column names and values), taking a list for all bind arguments.

Datasource::beginTransaction() returns nothing

Y

Manually grabs the transaction lock

Datasource::setUserName(string $user) returns nothing

Datasource::setUserName() returns nothing (RT_NOOP)

N

Sets the username parameter for the next open.

Datasource::getUserName() returns any

N

Returns the username parameter as a string or NOTHING if none is set.

Datasource::setPassword(string $pass) returns nothing

Datasource::setPassword() returns nothing (RT_NOOP)

N

Sets the password parameter for the next open.

Datasource::getPassword() returns any

N

Returns the password parameter as a string or NOTHING if none is set.

Datasource::setDBName(string $db) returns nothing

Datasource::setDBName() returns nothing (RT_NOOP)

N

Sets the DB name parameter for the next open.

Datasource::getDBName() returns any

N

Returns the dbname parameter as a string or NOTHING if none is set.

Datasource::setDBCharset(string $encoding) returns nothing

Datasource::setDBCharset() returns nothing (RT_NOOP)

N

Sets the charset (encoding) parameter for the next open.

Datasource::getDBCharset() returns any

N

Returns the DBI driver specific charset name for the current connection as a string or NOTHING if none is set.

Datasource::getOSCharset() returns string

N

Returns the Qore charset name for the current connection as a string or "(unknown)" if none is set.

Datasource::setHostName(string $host) returns nothing

Datasource::setHostName() returns nothing (RT_NOOP)

N

Sets the hostname parameter for the next open.

Datasource::getHostName() returns any

N

Returns the hostname parameter as a string or NOTHING if none is set.

Datasource::setPort(softint $port = 0) returns nothing

N

Sets the port parameter for the next open.

Datasource::getPort() returns any

N

Returns the port parameter as an int or NOTHING if none is set.

Datasource::getDriverName() returns string

N

Returns the name of the driver used for the object.

Datasource::setTransactionLockTimeout(softint $timeout_ms = 0) returns nothing

Datasource::setTransactionLockTimeout(date $timeout) returns nothing

N

Sets the transaction lock timeout value in milliseconds. Set to 0 for no timeout.

Datasource::getTransactionLockTimeout() returns int

N

Retrieves the transaction lock timeout value as an integer in milliseconds.

Datasource::getServerVersion() returns any

Y

Returns the driver-specific server version data for the current connection.

Datasource::getClientVersion() returns any

Y

Returns the driver-specific client library version data. Not implemented by all drivers.

Datasource::inTransaction() returns bool

N

Returns True if a transaction is in progress, False if not.


4.17.3. Datasource::constructor()

Synopsis

Creates a Datasource object. The constructor variant taking separate arguments requires the datasource type as the first argument, while most other parameters are optional.

Prototype

Datasource::constructor(string $driver, string $user = "", string $pass = "", string $dbname = "", string $encoding = "", string $host = "", softint $port = 0)

Datasource::constructor(hash $params)

Example
my Datasource $db(DSPGSQL, "user", "pass", "database", "utf8", "localhost", 5432);

Table 4.540. Arguments for Datasource::constructor(string $driver, string $user = "", string $pass = "", $dbname = "", string $encoding = "", string $host = "", softint $port = 0) Variant

Argument

Description

string $driver

The name of the DBI driver for the Datasource. See SQL Constants for builtin constants for DBI drivers shipped with Qore, or see the DBI driver documentation to use an add-on driver.

string $user = ""

The user name for the new connection. Also see Datasource::setUserName() for a method that allows this parameter to be set after the constructor.

string $pass = ""

The password for the new connection. Also see Datasource::setPassword() for a method that allows this parameter to be set after the constructor.

string $dbname = ""

The database name for the new connection. Also see Datasource::setDBName() for a method that allows this parameter to be set after the constructor.

string $encoding = ""

The database-specific name of the character encoding to use for the new connection. Also see Datasource::setDBCharset() for a method that allows this parameter to be set after the constructor. If no value is passed for this parameter, then the database character encoding corresponding to the default character encoding for the Qore process will be used instead.

string $host = ""

The host name for the new connection. Also see Datasource::setHostName() for a method that allows this parameter to be set after the constructor.

softint $port = 0

The port number for the new connection. Also see Datasource::setPort() for a method that allows this parameter to be set after the constructor.


Table 4.541. Arguments for Datasource::constructor(hash $params) Variant

Argument

Description

hash params

A hash of parameters for the Datasource; see Datasource Constructor Hash for more information.


Table 4.542. Datasource Constructor Hash

Key

Type

Description

type

string

The name of the database driver to use; this key is mandatory; if not present, an exception will be raised. See SQL Constants for builtin constants for DBI drivers shipped with Qore, or see the DBI driver documentation to use an add-on driver.

user

string

The user name for the new connection. Also see Datasource::setUserName() for a method that allows this parameter to be set after the constructor.

pass

string

The password for the new connection. Also see Datasource::setPassword() for a method that allows this parameter to be set after the constructor.

db

string

The database name for the new connection. Also see Datasource::setDBName() for a method that allows this parameter to be set after the constructor.

charset

string

The database-specific name of the character encoding to use for the new connection. Also see Datasource::setDBCharset() for a method that allows this parameter to be set after the constructor. If no value is passed for this parameter, then the database character encoding corresponding to the default character encoding for the Qore process will be used instead.

host

string

The host name for the new connection. Also see Datasource::setHostName() for a method that allows this parameter to be set after the constructor.

port

softint

The port number for the new connection. Also see Datasource::setPort() for a method that allows this parameter to be set after the constructor. If this key is present and is 0 then an exception will be raised.


Table 4.543. Exceptions Thrown by Datasource::constructor()

err

desc

DATASOURCE-PARAMETER-EEROR

Missing DBI driver identifier as first argument.

DATASOURCE-UNSUPPORTED-DATABASE

Could not load a driver for the database identified.


4.17.4. Datasource::destructor()

Synopsis

Closes the datasource if it's open (if any operations are in progress, will block until the operations complete) and destroys the object.

Example
delete $db;

Table 4.544. Exceptions Thrown by Datasource::destructor()

err

desc

DATASOURCE-TRANSACTION-EXCEPTION

The Datasource was destroyed while a transaction was still in progress; the transaction will be automatically rolled back.


4.17.5. Datasource::copy()

Synopsis

Creates a new Datasource object with the same driver as the original and copies of all the connection parameters.

Example
my Datasource $new_ds = $ds.copy();

4.17.6. Datasource::beginTransaction()

Synopsis

Manually grabs the transaction lock. This method should be called when the Datasource object will be shared between more than 1 thread, and a transaction will be started with a Datasource::select() method.

Prototype

Datasource::beginTransaction() returns nothing

Example
$db.beginTransaction();

Table 4.545. Exceptions Thrown by Datasource::beginTransaction()

err

desc

AUTOCOMMIT-ERROR

Cannot start a transaction when autocommit is enabled.

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.


4.17.7. Datasource::open()

Synopsis

Opens a connection to the datasouce, using the connection parameters already set. If any errors are encountered, an exception is raised.

Prototype

Datasource::open() returns nothing

Example
$db.open();

Table 4.546. Exceptions Thrown by Datasource::open()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.8. Datasource::close()

Synopsis

Closes the connection to the database. If any actions are in progress on the database, the close call will block until the actions complete. If any errors are encountered, an exception is raised.

Prototype

Datasource::close() returns nothing

Example
$db.close();

4.17.9. Datasource::commit()

Synopsis

Commits the current transaction and releases the transaction lock.

Prototype

Datasource::commit() returns nothing

Example
$db.commit();

Table 4.547. Exceptions Thrown by Datasource::commit()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.10. Datasource::inTransaction()

Synopsis

Returns True if the Datasource is currently in a transaction (has the transaction lock allocated to the calling thread), False if not.

Prototype

Datasource::inTransaction() returns bool

Example
my bool $is_trans = $db.inTransaction();

Table 4.548. Return Value for Datasource::inTransaction()

Return Type

Description

bool

Returns True if the Datasource is currently in a transaction (has the transaction lock allocated to the calling thread), False if not.


4.17.11. Datasource::rollback()

Synopsis

Rolls back the current transaction and releases the transaction lock.

Prototype

Datasource::rollback() returns nothing

Example
$db.rollback();

Table 4.549. Exceptions Thrown by Datasource::rollback()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.12. Datasource::setAutoCommit()

Synopsis

Turns autocommit on or off for this object.

Prototype

Datasource::setAutoCommit(softbool $b = True) returns nothing

Example
$db.setAutoCommit(False);

Table 4.550. Arguments for Datasource::setAutoCommit()

Argument

Description

softbool $b = True

True to turn on autocommit (a commit will be executed after every Datasource::exec()), False to turn off autocommit (commits must be manually triggered).


4.17.13. Datasource::exec()

Synopsis

Grabs the transaction lock (if autocommit is disabled) and executes an SQL command on the server and returns either the row count (for example, for updates and inserts) or the data retrieved (for example, if a stored procedure is executed that returns values).

Prototype

Datasource::exec(string $sql, ...) returns any

Datasource::exec() returns nothing (RT_NOOP)

Example
$rows = $db.exec("insert into table (varchar_col, timestamp_col, blob_col, numeric_col)
values (%v, %v, %v, %d)", $string, now(), $binary, 100);

Table 4.551. Arguments for Datasource::exec()

Argument

Description

string $sql

The SQL command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.552. Return Values for Datasource::exec()

Return Type

Description

any

The return value depends on the DBI driver; normally, for commands with placeholders, a hash is returned holding the values acquired from executing the SQL statement. For all other commands, normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


Table 4.553. Exceptions Thrown by Datasource::exec()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.14. Datasource::execRaw()

Synopsis

Grabs the transaction lock (if autocommit is disabled) and executes an SQL command on the server and returns either the row count (for example, for updates and inserts) or the data retrieved (for example, if a stored procedure is executed that returns values).

This method does not do any variable binding, so it's useful for example for DDL statements etc.

Warning

Using this method for OLTP statements can affect the application performance. See used DB server documentation for variable binding.

Prototype

Datasource::execRaw(string $sql) returns any

Example
$rows = $db.exec("create table my_tab (id number, some_text varchar2(30))");

Table 4.554. Arguments for Datasource::execRaw()

Argument

Description

string $sql

The SQL command to execute on the server.


Table 4.555. Return Values for Datasource::execRaw()

Return Type

Description

any

The return value depends on the DBI driver; normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


Table 4.556. Exceptions Thrown by Datasource::execRaw()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.15. Datasource::vexec()

Synopsis

Same as the Datasource::exec() method, except this method takes a single argument after the SQL command giving the list of bind parameters.

Prototype

Datasource::vexec(string $sql, list $args) returns any

Datasource::vexec(string $sql) returns any

Datasource::vexec() returns nothing (RT_NOOP)

Example
$rows = $db.vexec("insert into example_table value (%v, %v, %v)", $arg_list);

Table 4.557. Arguments for Datasource::vexec()

Argument

Description

string $sql

The SQL command to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.558. Return Values for Datasource::vexec()

Return Type

Description

any

The return value depends on the DBI driver; normally, for commands with placeholders, a hash is returned holding the values acquired from executing the SQL statement. For all other commands, normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


Table 4.559. Exceptions Thrown by Datasource::vexec()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.16. Datasource::select()

Synopsis

Executes an SQL select statement on the server and returns the result as a hash (column names) of lists (rows). This format is suitable for use with context Statements, for easy iteration and processing of query results. Additionally, this format is more efficient format than that returned by the Datasource::selectRows() method, because the column names are not repeated for each row returned. Therefore, for retrieving anything greater than small amounts of data, it is recommended to use this method instead of Datasource::selectRows().

Prototype

Datasource::select(string $sql, ...) returns any

Datasource::select() returns nothing (RT_NOOP)

Example
# bind a string and a date/time value by value in a query
$query = $db.select("select * from table where varchar_column = %v and timestamp_column > %v", $string, 2007-10-11T15:31:26.289);

Table 4.560. Arguments for Datasource::select()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.561. Return Values for Datasource::select()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of list (each hash key's value is a list giving the row data), however some DBI drivers allow any SQL to be executed through this method, in which case also int.


Table 4.562. Exceptions Thrown by Datasource::select()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.17. Datasource::vselect()

Synopsis

Same as the Datasource::select() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Prototype

Datasource::vselect(string $sql, list $args) returns any

Datasource::vselect(string $sql) returns any

Datasource::vselect() returns nothing (RT_NOOP)

Example
$query = $db.vselect("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.563. Arguments for Datasource::vselect()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.564. Return Values for Datasource::vselect()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of list (each hash key's value is a list giving the row data), however some DBI drivers allow any SQL to be executed through this method, in which case also int.


Table 4.565. Exceptions Thrown by Datasource::vselect()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.18. Datasource::selectRow()

Synopsis

Executes an SQL select statement on the server and returns the first row as a hash (the column values). If more than one row is returned, then all but the first row are discarded. For a similar method taking a list for all bind arguments, see Datasource::vselectRow().

This method also accepts all bind parameters (%d, %v, etc) as documented in Datasource Binding.

Prototype

Datasource::selectRow(string $sql, ...) returns any

Datasource::selectRow() returns nothing (RT_NOOP)

Example
$list = $db.selectRow("select * from example_table");

Table 4.566. Arguments for Datasource::selectRow()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.567. Return Values for Datasource::selectRow()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of row data or nothing if no row is found for the query. However, DBI could return other types (all known drivers at the time of writing this documentation only return hash or nothing).


Table 4.568. Exceptions Thrown by Datasource::selectRow()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.19. Datasource::vselectRow()

Synopsis

Same as the Datasource::selectRow() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Prototype

Datasource::vselectRow(string $sql, list $args) returns any

Datasource::vselectRow(string $sql) returns any

Datasource::vselectRow() returns nothing (RT_NOOP)

Example
$list = $db.vselectRow("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.569. Arguments for Datasource::vselectRow()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.570. Return Values for Datasource::vselectRow()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of row data or nothing if no row is found for the query. However, DBI could return other types (all known drivers at the time of writing this documentation only return hash or nothing).


Table 4.571. Exceptions Thrown by Datasource::vselectRow()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.20. Datasource::selectRows()

Synopsis

Executes an SQL select statement on the server and returns the result as a list (rows) of hashes (the column values). This format is not as efficient as that returned by the Datasource::select() method, therefore for larger amounts of data, it is recommended to use Datasource::select().

This method also accepts all bind parameters (%d, %v, etc) as documented in Datasource Binding.

Prototype

Datasource::selectRows(string $sql, ...) returns any

Datasource::selectRows() returns nothing (RT_NOOP)

Example
$list = $db.selectRows("select * from example_table");

Table 4.572. Arguments for Datasource::selectRows()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.573. Return Values for Datasource::selectRows()

Return Type

Description

any

Normally returns a list (rows) of hash (where the keys are the column names of each row) or nothing if no rows are found for the query. However, DBI could return other types; for DBI drivers that allow executing generic SQL through this method, any result sets returns should also be in the format list (rows) of hash.


Table 4.574. Exceptions Thrown by Datasource::selectRows()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.21. Datasource::vselectRows()

Synopsis

Same as the Datasource::selectRows() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Prototype

Datasource::vselectRows(string $sql, list $args) returns any

Datasource::vselectRows(string $sql) returns any

Datasource::vselectRows() returns nothing (RT_NOOP)

Example
$list = $db.vselectRows("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.575. Arguments for Datasource::vselectRows()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.576. Return Values for Datasource::vselectRows()

Return Type

Description

any

Normally returns a list (rows) of hash (where the keys are the column names of each row) or nothing if no rows are found for the query. However, DBI could return other types; for DBI drivers that allow executing generic SQL through this method, any result sets returns should also be in the format list (rows) of hash.


Table 4.577. Exceptions Thrown by Datasource::vselectRows()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.17.22. Datasource::setTransactionLockTimeout()

Synopsis

Sets the transaction lock timeout value in milliseconds; set to 0 for no timeout. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds).

Prototype

Datasource::setTransactionLockTimeout(softint $timeout_ms = 0) returns nothing

Datasource::setTransactionLockTimeout(date $timeout) returns nothing

Example
$db.setTransactionLockTimeout(5m); # transaction lock timeout set to 5 minutes

Table 4.578. Arguments for Datasource::setTransactionLockTimeout()

Argument

Description

softint $timeout_ms = 0 or date $timeout

The timeout value to set in seconds. For no timeout, set to 0. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds).


4.17.23. Datasource::getTransactionLockTimeout()

Synopsis

Retrieves the transaction lock timeout value as an integer in milliseconds.

Prototype

Datasource::getTransactionLockTimeout() returns int

Example
$int = $db.getTransactionLockTimeout();

Table 4.579. Return Values for Datasource::getTransactionLockTimeout()

Return Type

Description

int

The transaction lock timeout value in milliseconds.


4.17.24. Datasource::setUserName()

Synopsis

Sets the username to use for the connection. Invalid usernames will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setUserName(string $user) returns nothing

Datasource::setUserName() returns nothing (RT_NOOP)

Example
$db.setUserName("user");

Table 4.580. Arguments for Datasource::setUserName()

Argument

Description

string $user

The username to be used for the connection.


4.17.25. Datasource::getUserName()

Synopsis

Retrieves the username parameter for connections to the database.

Prototype

Datasource::getUserName() returns any

Example
$str = $db.getUserName();

Table 4.581. Return Values for Datasource::getUserName()

Return Type

Description

string or nothing

The username connection parameter or NOTHING if no value is set.


4.17.26. Datasource::setPassword()

Synopsis

Sets the password to use for the connection. Invalid passwords will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setPassword(string $pass) returns nothing

Datasource::setPassword() returns nothing (RT_NOOP)

Example
$db.setPassword("pass");

Table 4.582. Arguments for Datasource::setPassword()

Argument

Description

string $pass

The password name to be used for the connection.


4.17.27. Datasource::getPassword()

Synopsis

Retrieves the password connection parameter.

Prototype

Datasource::getPassword() returns any

Example
$str = $db.getPassword();

Table 4.583. Return Values for Datasource::getPassword()

Return Type

Description

string or nothing

Retrieves the password connection parameter or NOTHING if none is set.


4.17.28. Datasource::setDBName()

Synopsis

Sets the database name to use for the connection. Invalid database names will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setDBName(string $db) returns nothing

Datasource::setDBName() returns nothing (RT_NOOP)

Example
$db.setDBName("database");

Table 4.584. Arguments for Datasource::setDBName()

Argument

Description

string $db

The database name to be used for the connection.


4.17.29. Datasource::getDBName()

Synopsis

Retrieves the dbname connection parameter.

Prototype

Datasource::getDBName() returns any

Example
$str = $db.getDBName();

Table 4.585. Return Values for Datasource::getDBName()

Return Type

Description

string or nothing

Retrieves the password connection parameter or NOTHING if none is set.


4.17.30. Datasource::setDBCharset()

Synopsis

Sets the database-specific character encoding to use for the connection. Invalid character encoding names will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setDBCharset(string $encoding) returns nothing

Datasource::setDBCharset() returns nothing (RT_NOOP)

Example
$db.setDBCharset("ALU32UTF8"); # Oracle UTF-8 encoding equivalent

Table 4.586. Arguments for Datasource::setDBCharset()

Argument

Description

string $encoding

The database-specific name for the encoding to be used for the connection.


4.17.31. Datasource::setHostName()

Synopsis

Sets the hostname to use for the connection (for DBI drivers that support this parameter, such as the mysql and pgsql, for example). Invalid hostnames will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setHostName(string $host) returns nothing

Datasource::setHostName() returns nothing (RT_NOOP)

Example
$db.setHostName("localhost");

Table 4.587. Arguments for Datasource::setHostName()

Argument

Description

string $host

The hostname to be used for the connection.


4.17.32. Datasource::setPort()

Synopsis

Sets the port number to use for the connection (for DBI drivers that support this parameter, such as the mysql, pgsql, and oracle drivers, for example). Invalid port numbers will cause an exception to be thrown when the connection is opened.

Prototype

Datasource::setPort(softint $port = 0) returns nothing

Example
$db.setPort(5432);

Table 4.588. Arguments for Datasource::setPort()

Argument

Description

softint $port = 0

The port number to be used for the connection.


4.17.33. Datasource::getDBCharset()

Synopsis

Retrieves the database-specific charset set encoding for the current connection.

Prototype

Datasource::getDBCharset() returns any

Example
$str = $db.getDBCharset();

Table 4.589. Return Values for Datasource::getDBCharset()

Return Type

Description

string or nothing

Retrieves the database-specific charset set encoding for the current connection or NOTHING if none is set.


4.17.34. Datasource::getOSCharset()

Synopsis

Retrieves the Qore charset set encoding for the current connection.

Prototype

Datasource::getOSCharset() returns string

Example
$str = $db.getOSCharset();

Table 4.590. Return Values for Datasource::getOSCharset()

Return Type

Description

string

Retrieves the Qore charset set encoding for the current connection or "unknown" if unknown.


4.17.35. Datasource::getHostName()

Synopsis

Retrieves the hostname connection parameter.

Prototype

Datasource::getHostName() returns any

Example
$str = $db.getHostName();

Table 4.591. Return Values for Datasource::getHostName()

Return Type

Description

string or nothing

Retrieves the hostname connection parameter or NOTHING if none is set.


4.17.36. Datasource::getPort()

Synopsis

Retrieves the port connection parameter or NOTHING if none is set.

Prototype

Datasource::getPort() returns any

Example
$port = $db.getPort();

Table 4.592. Return Values for Datasource::getPort()

Return Type

Description

int or nothing

Retrieves the port connection parameter or no value if no port is set.


4.17.37. Datasource::getDriverName()

Synopsis

Returns the name of the DBI driver used for this object.

Prototype

Datasource::getDriverName() returns string

Example
$name = $db.getDriverName();

Table 4.593. Return Values for Datasource::getDriverName()

Return Type

Description

string

The name of the database driver used for this object.


4.17.38. Datasource::getServerVersion()

Synopsis

Retrieves the driver-specific server version information for the current connection.

Prototype

Datasource::getServerVersion() returns any

Example
$data = $db.getServerVersion();

Table 4.594. Return Values for Datasource::getServerVersion()

Return Type

Description

any

The return type and value depends on the driver; see the documentation for the DBI driver used for the connection.


4.17.39. Datasource::getClientVersion()

Synopsis

Retrieves the driver-specific client library version information. Not implemented for all drivers.

Prototype

Datasource::getClientVersion() returns any

Example
$data = $db.getClientVersion();

Table 4.595. Return Values for Datasource::getClientVersion()

Return Type

Description

any

The return type and value depends on the driver; see the documentation for the DBI driver used for the connection.


4.18. SQL::DatasourcePool Class

Note: This class is not available with the PO_NO_DATABASE parse option.

The DatasourcePool class provides transparent per-thread, per-transaction Datasource connection pooling.

In most cases, the DatasourcePool class can be used as a drop-in replacement for the Datasource class with autocommit disabled; when a transaction begins, a datasource will be automatically assigned to the calling thread, and it will only be released when a commit or rollback is called on the object. If no Datasource is available, the calling thread will block until a Datasource comes available.

Note that the same principles apply to SQL and database driver usage as with the Datasource class, see the Datasource class documentation for more information.

The DatasourcePool class uses Qore's thread resource tracking infrastructure to raise an exception if a thread terminates while a connection is allocated to it. If Qore user code enters a transaction with a DatasourcePool object and the thread terminates without closing the transaction (via DatasourcePool::commit() or DatasourcePool::rollback()), an exception will automatically be raised, the transaction will be rolled back, and the Datasource connection will be freed to the pool.

4.18.1. DatasourcePool Connection Allocations

The following methods allocate a persistent connection to the calling thread: DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), and DatasourcePool::beginTransaction(). The connection is released to the pool when DatasourcePool::commit() or DatasourcePool::rollback() are called (or in the case the thread terminates, in which case an exception is raised as well).

To begin a transaction with one of the select methods (for example, with "select for update"), call DatasourcePool::beginTransaction() first to manually dedicate a Datasource to the thread before calling the select method. Otherwise statements that should be in the same transaction may be executed in different connections.

Executing a DatasourcePool method while not in a transaction is realized by allocating a temporary connection to the calling thread which is re-released when the method returns. No explicit commits are executed by the class, therefore it is an error to execute transaction-relevant commands without first calling DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Table 4.596. DatasourcePool Method Overview

Method

Except?

Description

DatasourcePool::constructor(string $driver, string $user = "", string $pass = "", string $dbname = "", string $encoding = "", string $host = "", softint $min = DP_MIN, softint $max = DP_MAX, softint $port = 0)

DatasourcePool::constructor()

Y

Creates the DatasourcePool object; attempts to load a DBI driver if the driver is not already present in Qore.

DatasourcePool::destructor()

Y

Destroys the object.

DatasourcePool::copy()

Y

Throws an exception; currently DatasourcePool objects may not be copied.

DatasourcePool::commit() returns nothing

Y

Commits the transaction and releases the connection to the pool.

DatasourcePool::rollback() returns nothing

Y

Rolls back the transaction and releases the connection to the pool.

DatasourcePool::exec(string $sql, ...) returns any

DatasourcePool::exec() returns nothing (RT_NOOP)

Y

Executes SQL code on the DB connection and dedicates a connection to the calling thread.

DatasourcePool::execRaw(string $sql) returns any

Y

Executes SQL code (like DatasourcePool::exec()) on the DB connection without any variable binding and dedicates a connection to the calling thread.

DatasourcePool::vexec(string $sql, list $args) returns any

DatasourcePool::vexec(string $sql) returns any

DatasourcePool::vexec() returns nothing (RT_NOOP)

Y

Executes SQL code on the DB connection, taking a list for all bind arguments. Dedicates a connection to the calling thread.

DatasourcePool::select(string $sql, ...) returns any

DatasourcePool::select() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a hash (column names) of lists (rows).

DatasourcePool::vselect(string $sql, list $args) returns any

DatasourcePool::vselect(string $sql) returns any

DatasourcePool::vselect() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a hash (column names) of lists (rows), taking a list for all bind arguments.

DatasourcePool::selectRow(string $sql, ...) returns any

DatasourcePool::selectRow() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the first row as a hash (column names and values).

DatasourcePool::vselectRow(string $sql, list $args) returns any

DatasourcePool::vselectRow(string $sql) returns any

DatasourcePool::vselectRow() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the first row as a hash (column names and values), taking a list for all bind arguments.

DatasourcePool::selectRows(string $sql, ...) returns any

DatasourcePool::selectRows() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a list (rows) of hashes (column names and values).

DatasourcePool::vselectRows(string $sql, list $args) returns any

DatasourcePool::vselectRows(string $sql) returns any

DatasourcePool::vselectRows() returns nothing (RT_NOOP)

Y

Executes a select statement on the server and returns the results in a list (rows) of hashes (column names and values), taking a list for all bind arguments.

DatasourcePool::beginTransaction() returns nothing

Y

Manually allocates a persistent connection to the calling thread.

DatasourcePool::getUserName() returns any

N

Returns the username parameter as a string or NOTHING if none is set.

DatasourcePool::getPassword() returns any

N

Returns the password parameter as a string or NOTHING if none is set.

DatasourcePool::getDBName() returns any

N

Returns the dbname parameter as a string or NOTHING if none is set.

DatasourcePool::getDBCharset() returns any

N

Returns the DBI driver specific charset name for the current connection as a string or NOTHING if none is set.

DatasourcePool::getOSCharset() returns any

N

Returns the Qore charset name for the current connection as a string or NOTHING if none is set.

DatasourcePool::getHostName() returns any

N

Returns the hostname parameter as a string or NOTHING if none is set.

DatasourcePool::getPort() returns any

N

Returns the port parameter as an integer or NOTHING if none is set.

DatasourcePool::getDriverName() returns string

N

Returns the name of the database driver used for this object as a string.

DatasourcePool::getServerVersion() returns any

Y

Returns the driver-specific server version data for the current connection.

DatasourcePool::getClientVersion() returns any

Y

Returns the driver-specific client library version data. Not implemented by all drivers.

DatasourcePool::inTransaction() returns bool

N

Returns True if a transaction is in progress (and therefore a Datasource form the pool is dedicated to the calling thread), False if not.


4.18.2. DatasourcePool::constructor()

Synopsis

Creates a DatasourcePool object. The constructor taking separate arguments requires the database driver name as the first argument, and normally the dbname; the port number is supplied as the final parameter because support for the port number as a connection parameter was added after this class was already present in Qore. The constructor variant taking a hash accepts a hash as produced from parseDatasource().

Prototype

DatasourcePool::constructor(string $driver, string $user = "", string $pass = "", string $dbname = "", string $encoding = "", string $host = "", softint $min = DP_MIN, softint $max = DP_MAX, softint $port = 0)

Example
# open a Datasource pool to a PostgreSQL database, username="user", password="pass", dbname="database"
# use "utf8" for the character encoding for the connection, hostname="localhost", port=5432
# minimum 5 connections (opened immediately), with a maximum of 20
my DatasourcePool $pool(DSPGSQL, "user", "pass", "database", "utf8", "localhost", 5, 20, 5432);
# same as above but using a hash argument with parseDatasource()
my DatasourcePool $pool(parseDatasource("pgsql:user/pass@database(utf8)%localhost:5432{min=5,max=20}"));

Table 4.597. Arguments for DatasourcePool::constructor(string $driver, string $user = "", string $pass = "", $dbname = "", string $encoding = "", string $host = "", softint $min = DP_MIN, softint $max = DP_MAX, softint $port = 0) Variant

Argument

Description

string $driver

The name of the DBI driver for the DatasourcePool. See SQL Constants for builtin constants for DBI drivers shipped with Qore, or see the DBI driver documentation to use an add-on driver.

string $user = ""

The user name for the new pool.

string $pass = ""

The password for the new pool.

string $dbname = ""

The database name for the new pool.

string $encoding = ""

The database-specific name of the character encoding to use for the new pool. If no value is passed for this parameter, then the database character encoding corresponding to the default character encoding for the Qore process will be used instead.

string $host = ""

The host name for the new pool.

softint $min = DP_MIN

The minimum number of connections for the new pool; this number of connections will be opened immediately when the pool is created.

softint $max = DP_MAX

The maximum number of connections for the new pool; must be greater than or equal to $min.

softint $port = 0

The port number for the new pool.


Table 4.598. Arguments for DatasourcePool::constructor(hash $params) Variant

Argument

Description

hash params

A hash of parameters for the DatasourcePool; see DatasourcePool Constructor Hash for more information.


Table 4.599. DatasourcePool Constructor Hash

Key

Type

Description

type

string

The name of the database driver to use; this key is mandatory; if not present, an exception will be raised. See SQL Constants for builtin constants for DBI drivers shipped with Qore, or see the DBI driver documentation to use an add-on driver.

user

string

The user name for the new connection. Also see Datasource::setUserName() for a method that allows this parameter to be set after the constructor.

pass

string

The password for the new connection. Also see Datasource::setPassword() for a method that allows this parameter to be set after the constructor.

db

string

The database name for the new connection. Also see Datasource::setDBName() for a method that allows this parameter to be set after the constructor.

charset

string

The database-specific name of the character encoding to use for the new connection. Also see Datasource::setDBCharset() for a method that allows this parameter to be set after the constructor. If no value is passed for this parameter, then the database character encoding corresponding to the default character encoding for the Qore process will be used instead.

host

string

The host name for the new connection. Also see Datasource::setHostName() for a method that allows this parameter to be set after the constructor.

port

softint

The port number for the new connection. Also see Datasource::setPort() for a method that allows this parameter to be set after the constructor. If this key is present and is 0 then an exception will be raised.

options

hash

A hash where the min and max options may be given, giving the minimum and maximum connections for the pool. min must be greater than zero, and max must be greater than or equal to min. If min is not present, DP_MIN is assumed; if max is not present, DP_MAX is assumed.


Table 4.600. Exceptions Thrown by DatasourcePool::constructor()

err

desc

DATASOURCEPOOL-PARAM-EEROR

Missing DBI driver, negative number of connections specified, or max < min.

DATASOURCEPOOL-UNSUPPORTED-DATABASE

Could not load a driver for the database identified.


4.18.3. DatasourcePool::destructor()

Synopsis

Throws an exception if any transactions are in progress and returns immediately. The object is destroyed after any in-progress requests are completed.

Example
delete $pool;

Table 4.601. Exceptions Thrown by DatasourcePool::destructor()

err

desc

DATASOURCEPOOL-ERROR

The destructor was called while a transaction was still in progress.


4.18.4. DatasourcePool::copy()

Synopsis

Thows an exception; DatasourcePool objects cannot be copied at the moment.

4.18.5. DatasourcePool::beginTransaction()

Synopsis

Manually allocates a persistent connection from the pool to the calling thread. This method should be called when a transaction will be started with a DatasourcePool::select() method (or vselect*, etc).

Prototype

DatasourcePool::beginTransaction() returns nothing

Example
$pool.beginTransaction();

4.18.6. DatasourcePool::commit()

Synopsis

Commits the current transaction and releases the connection to the pool.

Prototype

DatasourcePool::commit() returns nothing

Example
$pool.commit();

Table 4.602. Exceptions Thrown by DatasourcePool::commit()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.7. DatasourcePool::inTransaction()

Synopsis

Returns True if there is a Datasource from the pool currently allocated to the calling thread, False if not.

Prototype

DatasourcePool::inTransaction() returns bool

Example
my bool $in_trans = $pool.inTransaction();

Table 4.603. Return Value for DatasourcePool::inTransaction()

Return Type

Description

bool

Returns True if there is a Datasource from the pool currently allocated to the calling thread, False if not.


4.18.8. DatasourcePool::rollback()

Synopsis

Rolls back the current transaction and releases the connection to the pool.

Prototype

DatasourcePool::rollback() returns nothing

Example
$pool.rollback();

Table 4.604. Exceptions Thrown by DatasourcePool::rollback()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.9. DatasourcePool::exec()

Synopsis

Allocates a persistent connection to the calling thread, executes an SQL command on the server and returns either the row count (for example, for updates and inserts) or the data retrieved (for example, if a stored procedure is executed that returns values). This method takes a special syntax for binding values and placeholders; see the Datasource::exec() method for more information.

Prototype

DatasourcePool::exec(string $sql, ...) returns any

DatasourcePool::exec() returns nothing (RT_NOOP)

Example
$rows = $pool.exec("insert into table (varchar_col, timestamp_col, blob_col, numeric_col)
values (%v, %v, %v, %d)", $string, now(), $binary, 100);

Table 4.605. Arguments for DatasourcePool::exec()

Argument

Description

string $sql

The SQL command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.606. Return Values for DatasourcePool::exec()

Return Type

Description

any

The return value depends on the DBI driver; normally, for commands with placeholders, a hash is returned holding the values acquired from executing the SQL statement. For all other commands, normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


Table 4.607. Exceptions Thrown by DatasourcePool::exec()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.10. DatasourcePool::execRaw()

Synopsis

Grabs the transaction lock (if autocommit is disabled) and executes an SQL command on the server and returns either the row count (for example, for updates and inserts) or the data retrieved (for example, if a stored procedure is executed that returns values).

This method does not do any variable binding, so it's useful for example for DDL statements etc.

Warning

Using this method for OLTP statements can affect the application performance. See used DB server documentation for variable binding.

Prototype

DatasourcePool::execRaw(string $sql) returns any

Example
$rows = $pool.execRaw("create table my_tab (id number, some_text varchar2(30))");

Table 4.608. Arguments for DatasourcePool::execRaw()

Argument

Description

string $sql

The SQL command to execute on the server.


Table 4.609. Return Values for DatasourcePool::execRaw()

Return Type

Description

any

The return value depends on the DBI driver; normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


Table 4.610. Exceptions Thrown by DatasourcePool::execRaw()

err

desc

TRANSACTION-LOCK-TIMEOUT

Timeout trying to acquire the transaction lock.

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.11. DatasourcePool::vexec()

Synopsis

Same as the DatasourcePool::exec() method, except this method takes a single argument after the SQL command giving the list of bind parameters.

This method allocates a persistent connection from the pool to the calling thread.

Prototype

DatasourcePool::vexec(string $sql, list $args) returns any

DatasourcePool::vexec(string $sql) returns any

DatasourcePool::vexec() returns nothing (RT_NOOP)

Example
$rows = $pool.vexec("insert into example_table value (%v, %v, %v)", $arg_list);

Table 4.611. Arguments for DatasourcePool::vexec()

Argument

Description

string $sql

The SQL command to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.612. Return Values for DatasourcePool::vexec()

Return Type

Description

Integer or Hash

For commands with placeholders, a hash is returned holding the values acquired from executing the SQL statement. For all other commands, a row count is returned.


Table 4.613. Exceptions Thrown by DatasourcePool::vexec()

err

desc

any

The return value depends on the DBI driver; normally, for commands with placeholders, a hash is returned holding the values acquired from executing the SQL statement. For all other commands, normally an int row count is returned. However, some DBI drivers also allow select statements to be executed through this interface, which would also return a hash of list.


4.18.12. DatasourcePool::select()

Synopsis

Executes an SQL select statement on the server and returns the result as a hash (column names) of lists (rows). See Datasource::select() for more information.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::select(string $sql, ...) returns any

DatasourcePool::select() returns nothing (RT_NOOP)

Example
# bind a string and a date/time value by value in a query
$query = $pool.select("select * from table where varchar_column = %v and timestamp_column > %v",
$string, 2007-10-11T15:31:26.289);

Table 4.614. Arguments for DatasourcePool::select()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.615. Return Values for DatasourcePool::select()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of list (each hash key's value is a list giving the row data), however some DBI drivers allow any SQL to be executed through this method, in which case also int.


Table 4.616. Exceptions Thrown by DatasourcePool::select()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.13. DatasourcePool::vselect()

Synopsis

Same as the DatasourcePool::select() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::vselect(string $sql, list $args) returns any

DatasourcePool::vselect(string $sql) returns any

DatasourcePool::vselect() returns nothing (RT_NOOP)

Example
$query = $pool.vselect("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.617. Arguments for DatasourcePool::vselect()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.618. Return Values for DatasourcePool::vselect()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of list (each hash key's value is a list giving the row data), however some DBI drivers allow any SQL to be executed through this method, in which case also int.


Table 4.619. Exceptions Thrown by DatasourcePool::vselect()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.14. DatasourcePool::selectRow()

Synopsis

Executes an SQL select statement on the server and returns the first row as a hash (the column values). If more than one row is returned, then all but the first row are discarded. For a similar method taking a list for all bind arguments, see DatasourcePool::vselectRow().

This method also accepts all bind parameters (%d, %v, etc) as documented in Datasource Binding.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::selectRow(string $sql, ...) returns any

DatasourcePool::selectRow() returns nothing (RT_NOOP)

Example
$list = $pool.selectRow("select * from example_table");

Table 4.620. Arguments for DatasourcePool::selectRow()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.621. Return Values for DatasourcePool::selectRow()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of row data or nothing if no row is found for the query. However, DBI could return other types (all known drivers at the time of writing this documentation only return hash or nothing).


Table 4.622. Exceptions Thrown by DatasourcePool::selectRow()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.15. DatasourcePool::vselectRow()

Synopsis

Same as the DatasourcePool::selectRow() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::vselectRow(string $sql, list $args) returns any

DatasourcePool::vselectRow(string $sql) returns any

DatasourcePool::vselectRow() returns nothing (RT_NOOP)

Example
$list = $pool.vselectRow("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.623. Arguments for DatasourcePool::vselectRow()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.624. Return Values for DatasourcePool::vselectRow()

Return Type

Description

any

Normally returns a hash (the keys are the column names) of row data or nothing if no row is found for the query. However, DBI could return other types (all known drivers at the time of writing this documentation only return hash or nothing).


4.18.16. DatasourcePool::selectRows()

Synopsis

Executes an SQL select statement on the server and returns the result as a list (rows) of hashes (the column values). This format is not as efficient as that returned by the DatasourcePool::select() method, therefore for larger amounts of data, it is recommended to use DatasourcePool::select().

This method also accepts all bind parameters (%d, %v, etc) as documented in Datasource Binding.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::selectRows(string $sql, ...) returns any

DatasourcePool::selectRows() returns nothing (RT_NOOP)

Example
$list = $pool.selectRows("select * from example_table");

Table 4.625. Arguments for DatasourcePool::selectRows()

Argument

Description

string $sql

The SQL select command to execute on the server.

...

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in order after the command string.


Table 4.626. Return Values for DatasourcePool::selectRows()

Return Type

Description

any

Normally returns a list (rows) of hash (where the keys are the column names of each row) or nothing if no rows are found for the query. However, DBI could return other types; for DBI drivers that allow executing generic SQL through this method, any result sets returns should also be in the format list (rows) of hash.


Table 4.627. Exceptions Thrown by DatasourcePool::selectRows()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.17. DatasourcePool::vselectRows()

Synopsis

Same as the DatasourcePool::selectRows() method, except this method takes a single argument after the SQL command giving the list of bind value parameters.

Note that this method does not allocate a persistent connection to the calling thread; if the calling thread does not already have a connection allocated to it, a temporary connection will be allocated for executing the select query and returning the results; the temporary connection will be immediately returned to the pool when this method returns. It is an error to execute transaction relevant commands with this method without first allocating a persistent connection with DatasourcePool::exec(), DatasourcePool::vexec(), DatasourcePool::execRaw(), or DatasourcePool::beginTransaction().

Prototype

DatasourcePool::vselectRows(string $sql, list $args) returns any

DatasourcePool::vselectRows(string $sql) returns any

DatasourcePool::vselectRows() returns nothing (RT_NOOP)

Example
$list = $pool.vselectRows("select * from example_table where id = %v and name = %v", $arg_list);

Table 4.628. Arguments for DatasourcePool::vselectRows()

Argument

Description

string $sql

The SQL select statement to execute on the server.

[list $args]

Include any values to be bound (using %v in the command string) or placeholder specifications (using :<key_name> in the command string) in a single optional list in order after the command string.


Table 4.629. Return Values for DatasourcePool::vselectRows()

Return Type

Description

any

Normally returns a list (rows) of hash (where the keys are the column names of each row) or nothing if no rows are found for the query. However, DBI could return other types; for DBI drivers that allow executing generic SQL through this method, any result sets returns should also be in the format list (rows) of hash.


Table 4.630. Exceptions Thrown by DatasourcePool::vselectRows()

err

desc

depends on DBI driver

See documentation for the DBI driver for driver-specific exceptions.


4.18.18. DatasourcePool::getUserName()

Synopsis

Retrieves the username parameter for all connections in this pool.

Prototype

DatasourcePool::getUserName() returns any

Example
$str = $pool.getUserName();

Table 4.631. Return Values for DatasourcePool::getUserName()

Return Type

Description

string or nothing

The username connection parameter or NOTHING if no value is set.


4.18.19. DatasourcePool::getPassword()

Synopsis

Retrieves the password connection parameter.

Prototype

DatasourcePool::getPassword() returns any

Example
$str = $pool.getPassword();

Table 4.632. Return Values for DatasourcePool::getPassword()

Return Type

Description

string or nothing

Retrieves the password connection parameter or NOTHING if none is set.


4.18.20. DatasourcePool::getDBName()

Synopsis

DatasourcePool::getDBName() returns any

Prototype
DatasourcePool::getDBName()
Example
$str = $pool.getDBName();

Table 4.633. Return Values for DatasourcePool::getDBName()

Return Type

Description

string or nothing

Retrieves the password connection parameter or NOTHING if none is set.


4.18.21. DatasourcePool::getDBCharset()

Synopsis

Retrieves the database-specific charset set encoding for the current connection.

Prototype

DatasourcePool::getDBCharset() returns any

Example
$str = $pool.getDBCharset();

Table 4.634. Return Values for DatasourcePool::getDBCharset()

Return Type

Description

string or nothing

Retrieves the database-specific charset set encoding for the current connection or NOTHING if none is set.


4.18.22. DatasourcePool::getOSCharset()

Synopsis

Retrieves the Qore charset set encoding for the current connection.

Prototype

DatasourcePool::getOSCharset() returns any

Example
$str = $pool.getOSCharset();

Table 4.635. Return Values for DatasourcePool::getOSCharset()

Return Type

Description

string

Retrieves the Qore charset set encoding for the current connection or "unknown" if unknown.


4.18.23. DatasourcePool::getHostName()

Synopsis

Retrieves the hostname connection parameter.

Prototype

DatasourcePool::getHostName() returns any

Example
$str = $pool.getHostName();

Table 4.636. Return Values for DatasourcePool::getHostName()

Return Type

Description

string or nothing

Retrieves the hostname connection parameter or NOTHING if none is set.


4.18.24. DatasourcePool::getPort()

Synopsis

Retrieves the port connection parameter.

Prototype

DatasourcePool::getPort() returns any

Example
$port = $pool.getPort();

Table 4.637. Return Values for DatasourcePool::getPort()

Return Type

Description

int or nothing

Retrieves the port connection parameter or no value if no port is set.


4.18.25. DatasourcePool::getDriverName()

Synopsis

Returns the name of the DBI driver used for this object.

Prototype

DatasourcePool::getDriverName() returns string

Example
$name = $pool.getDriverName();

Table 4.638. Return Values for DatasourcePool::getDriverName()

Return Type

Description

string

The name of the database driver used for this object.


4.18.26. DatasourcePool::getServerVersion()

Synopsis

Retrieves the driver-specific server version information for the current connection.

Prototype

DatasourcePool::getServerVersion() returns any

Example
$data = $pool.getServerVersion();

Table 4.639. Return Values for DatasourcePool::getServerVersion()

Return Type

Description

any

The return type and value depends on the driver; see the documentation for the DBI driver used for the connection.


4.18.27. DatasourcePool::getClientVersion()

Synopsis

Retrieves the driver-specific client library version information. Not implemented for all drivers.

Prototype

DatasourcePool::getClientVersion() returns any

Example
$data = $pool.getClientVersion();

Table 4.640. Return Values for DatasourcePool::getClientVersion()

Return Type

Description

any

The return type and value depends on the driver; see the documentation for the DBI driver used for the connection.


4.19. Thread::AbstractSmartLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

This is an abstract class to be inherited by builtin classes that implement the internal Qore API that allows them to be used by the Condition class. Currently the RWLock and Mutex classes inherit this class.

This class cannot be instantiated directly and also cannot be directly inherited by user-defined classes.

Table 4.641. AbstractSmartLock Method Overview

Method

Except?

Description

AbstractSmartLock::constructor()

Y

Throws an exception if called directly; this class can only be instantiated by builtin subclasses.

::AbstractSmartLock::destructor()

N

Performs no action.

AbstractSmartLock::copy()

N

Performs no action.

AbstractSmartLock::getName() returns string

N

Returns the name of the threading class directly inheriting this class.


4.19.1. AbstractSmartLock::constructor()

Synopsis

Throws an exception if called directly or if inherited by a user-defined class; this class can only be instantiated by builtin subclasses.

Table 4.642. Exceptions Thrown by AbstractSmartLock::constructor()

err

desc

ABSTRACTSMARTLOCK-CONSTRUCTOR-ERROR

This class cannot be instantiated directly or inherited by user code.


4.19.2. AbstractSmartLock::destructor()

Synopsis

Performs no action.

4.19.3. AbstractSmartLock::copy()

Synopsis

Performs no action.

4.19.4. AbstractSmartLock::getName()

Synopsis

Returns the name of the threading class directly inheriting this class.

Prototype

AbstractSmartLock::getName() returns string

Example
my $name = $lock.getName();

Table 4.643. Return Values for AbstractSmartLock::getName()

Return Type

Description

string

Returns the name of the threading class directly inheriting this class.


4.20. Thread::AutoGate Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

AutoGate objects, when used along with a Gate object, allow Qore programmers to safely enter and exit a gate lock, even if exceptions are thrown or return statements are executed in the block where the AutoGate object is created. AutoGate objects enter the gate lock for the lifetime of the AutoGate object. For this reason, it is only appropriate to assign an AutoGate object to a local variable, so when the local variable goes out of scope, the AutoGate object will be deleted and the gate automatically exited.

For example:

our Gate $gate();

sub check_error($error) {
    # note that the Gate is entered in the AutoGate constructor, and
    # the Gate will be exited as soon as the block is exited below.
    # (with either the throw statement or the return statement)
    my AutoGate $ag($gate);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.644. AutoGate Method Overview

Method

Except?

Description

AutoGate::constructor(Gate $gate)

Y

Creates the AutoGate object based on the Gate argument passed and immediately calls Gate::enter().

AutoGate::destructor()

Y

Calls Gate::exit() and destroys the AutoGate object.

AutoGate::copy()

Y

Throws an exception; objects of this class cannot be copied.


4.20.1. AutoGate::constructor()

Synopsis

Creates the AutoGate object based on the Gate argument passed and immediately calls Gate::enter().

Prototype

AutoGate::constructor(Gate $gate)

Example
my AutoGate $gate($gate);

Table 4.645. Arguments for AutoGate::constructor()

Argument

Description

Gate $gate

The Gate object to enter for the lifetime of the AutoGate object.


4.20.2. AutoGate::destructor()

Synopsis

Calls Gate::exit() on the saved Gate object and destroys the AutoGate object.

Example
delete $ag;

4.20.3. AutoGate::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.646. Exceptions Thrown by AutoGate::copy()

err

desc

AUTOGATE-COPY-ERROR

Objects of this class cannot be copied.


4.21. Thread::AutoLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

AutoLock objects, when used along with a Mutex object, allow Qore programmers to safely acquire and release a Mutex lock, even if exceptions are thrown or return statements are executed in the block where the AutoLock object is created. AutoLock objects are helper objects that acquire a Mutex for the lifetime of the object. For this reason, it is only appropriate to assign an AutoLock object to a local variable, so when the local variable goes out of scope, the AutoLock object will be deleted and the Mutex will be automatically released.

For example:

our Mutex $mutex();

sub check_error($error) {
    # note that the Mutex is acquired in the AutoLock constructor, and
    # the Mutex will be released as soon as the block is exited below.
    # (with either the throw statement or the return statement)
    my AutoLock $al($mutex);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.647. AutoLock Method Overview

Method

Except?

Description

AutoLock::constructor(Mutex $mutex)

Y

Creates the AutoLock object based on the Mutex argument passed and immediately calls Mutex::lock().

AutoLock::destructor()

Y

Calls Mutex::unlock() on the saved Mutex and destroys the AutoLock object.

AutoLock::copy()

Y

Throws an exception; objects of this class cannot be copied.


4.21.1. AutoLock::constructor()

Synopsis

Creates the AutoLock object based on the Mutex argument passed. The AutoLock object immediately calls Mutex::lock() on the Mutex object passed, and saves it so it can be released when the AutoLock object is destroyed.

Prototype

AutoLock::constructor(Mutex $mutex)

Example
my AutoLock $al($mutex);

Table 4.648. Arguments for AutoLock::constructor()

Argument

Description

Mutex $mutex

The Mutex object to manage for the lifetime of this object.


4.21.2. AutoLock::destructor()

Synopsis

Calls Mutex::unlock() on the saved Mutex and destroys the AutoLock object.

Example
delete $al;

4.21.3. AutoLock::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.649. Exceptions Thrown by AutoLock::copy()

err

desc

AUTOLOCK-COPY-ERROR

Objects of this class cannot be copied.


4.22. Thread::AutoReadLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

AutoReadLock objects, when used along with a RWLock object, allow Qore programmers to safely acquire and release a read lock, even if exceptions are thrown or return statements are executed in the block where the AutoReadLock object is created. AutoReadLock objects are helper objects that acquire a read lock for the lifetime of the AutoReadLock object. For this reason, it is only appropriate to assign an AutoReadLock object to a local variable, so when the local variable goes out of scope, the AutoReadLock object will be deleted and the read lock will be automatically released.

For example:

our RWLock $rwl();

sub check_error($error) {
    # note that the read lock is acquired in the AutoReadLock constructor, and
    # the read lock will be released as soon as the block is exited below.
    # (with either the throw statement or the return statement)
    my AutoReadLock $arl($rwl);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.650. AutoReadLock Method Overview

Method

Except?

Description

AutoReadLock::constructor(RWLock $rwlock)

Y

Creates the AutoReadLock object based on the RWLock argument passed and immediately calls RWLock::readLock().

AutoReadLock::destructor()

Y

Calls RWLock::readUnlock() on the saved RWLock and destroys the AutoReadLock object.

AutoReadLock::copy()

Y

Throws an exception; objects of this class cannot be copied.


4.22.1. AutoReadLock::constructor()

Synopsis

Creates the AutoReadLock object based on the RWLock argument passed. The AutoReadLock object immediately calls RWLock::readLock() on the RWLock object passed, and saves it so it can be released when the AutoReadLock object is destroyed.

Prototype

AutoReadLock::constructor(RWLock $rwlock)

Example
my AutoReadLock $arl($rwlock);

Table 4.651. Arguments for AutoReadLock::constructor()

Argument

Description

RWLock $rwlock

The RWLock object to manage for the lifetime of this object.


4.22.2. AutoReadLock::destructor()

Synopsis

Calls RWLock::readUnlock() on the saved RWLock and destroys the AutoReadLock object.

Example
delete $arl;

4.22.3. AutoReadLock::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.652. Exceptions Thrown by AutoReadLock::copy()

err

desc

AUTOREADLOCK-COPY-ERROR

Objects of this class cannot be copied.


4.23. Thread::AutoWriteLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

AutoWriteLock objects, when used along with a RWLock object, allow Qore programmers to safely acquire and release a write lock, even if exceptions are thrown or return statements are executed in the block where the AutoWriteLock object is created. AutoWriteLock objects are helper objects that acquire a write lock for the lifetime of the AutoWriteLock object. For this reason, it is only appropriate to assign an AutoWriteLock object to a local variable, so when the local variable goes out of scope, the AutoWriteLock object will be deleted and the write lock will be automatically released.

For example:

our RWLock $rwl();

sub check_error($error) {
    # note that the write lock is acquired in the AutoWriteLock constructor, and
    # the write lock will be released as soon as the block is exited below.
    # (with either the throw statement or the return statement)
    my AutoWriteLock $arl($rwl);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.653. AutoWriteLock Method Overview

Method

Except?

Description

AutoWriteLock::constructor(RWLock $rwlock)

Y

Creates the AutoWriteLock object based on the RWLock argument passed and immediately calls RWLock::writeLock().

AutoWriteLock::destructor()

Y

Calls RWLock::writeUnlock() on the saved RWLock and destroys the AutoWriteLock object.

AutoWriteLock::copy()

Y

Throws an exception; objects of this class cannot be copied.


4.23.1. AutoWriteLock::constructor()

Synopsis

Creates the AutoWriteLock object based on the RWLock argument passed. The AutoWriteLock object immediately calls RWLock::writeLock() on the RWLock object passed, and saves it so it can be released when the AutoWriteLock object is destroyed.

Prototype

AutoWriteLock::constructor(RWLock $rwlock)

Example
my AutoWriteLock $awl($rwlock);

Table 4.654. Arguments for AutoWriteLock::constructor()

Argument

Description

RWLock $rwlock

The RWLock object to manage for the lifetime of this object.


4.23.2. AutoWriteLock::destructor()

Synopsis

Calls RWLock::writeUnlock() on the saved RWLock and destroys the AutoWriteLock object.

Example
delete $awl;

4.23.3. AutoWriteLock::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.655. Exceptions Thrown by AutoWriteLock::copy()

err

desc

AUTOWRITELOCK-COPY-ERROR

Objects of this class cannot be copied.


4.24. Thread::Condition Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

Condition objects, when used along with an AbstractSmartLock object (such as RWLock and Mutex objects), allow Qore threads to sleep until a certain condition becomes true.

Table 4.656. Condition Method Overview

Method

Except?

Description

Condition::constructor()

N

Creates the Condition object.

Condition::destructor()

N

Destroys the Condition object.

Condition::copy()

N

Creates a new Condition object, not based on the original.

Condition::signal() returns nothing

Y

Signals a single blocked thread to wake up.

Condition::broadcast() returns nothing

Y

Signals all threads blocked on this Condition object to wake up.

Condition::wait(AbstractSmartLock $lock) returns int

Condition::wait(AbstractSmartLock $lock, softint $timeout_ms) returns int

Condition::wait(AbstractSmartLock $lock, date $timeout) returns int

Y

Blocks a thread until signaled; accepts an optional timeout value.

Condition::wait_count(AbstractSmartLock $lock) returns int

N

Returns the number of threads currently blocked on this object.


4.24.1. Condition::constructor()

Synopsis

Creates the Condition object.

Prototype

Condition::constructor()

Example
my Condition $cond();

4.24.2. Condition::destructor()

Synopsis

Destroys the object.

Example
delete $cond;

4.24.3. Condition::copy()

Synopsis

Creates a new Condition object, not based on the original.

Example
my Condition $new_cond = $cond.copy();

4.24.4. Condition::signal()

Synopsis

Signals a single blocked thread to wake up. Normally this method call will be made while the same AbstractSmartLock object used for Condition::wait() calls is locked. Then, when the thread calling this method unlocks the AbstractSmartLock object, the thread(s) woken up by this call can continue executing.

Prototype

Condition::signal() returns nothing

Example
$cond.signal();

Table 4.657. Exceptions Thrown by Condition::signal()

err

desc

CONDITION-SIGNAL-ERROR

This exception should never be thrown - it indicates a low-level error in executing the method.


4.24.5. Condition::broadcast()

Synopsis

Wakes up all threads waiting on the Condition object. Normally this method call will be made while the same AbstractSmartLock object used for Condition::wait() calls is locked. Then, when the thread calling this method unlocks the AbstractSmartLock object, the thread(s) woken up by this call can continue executing.

Prototype

Condition::broadcast() returns nothing

Example
$cond.broadcast();

Table 4.658. Exceptions Thrown by Condition::broadcast()

err

desc

CONDITION-BROADCAST-ERROR

This exception should never be thrown - it indicates a low-level error in executing the method.


4.24.6. Condition::wait()

Synopsis

Blocks a thread on the Condition object. Must be called with an AbstractSmartLock argument, and the AbstractSmartLock must be locked before the call. This method will atomically unlock the AbstractSmartLock object and wait on this Condition object to be woken up with a Condition::signal() or Condition::broadcast() method call in another thread. At this point, the AbstractSmartLock will be reacquired with the same state as it was acquired previously before control returns to the blocked thread. The wait condition should always be tested again when the thread is unblocked.

Also accepts an optional timeout value in milliseconds. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds). Also if the call times out, the AbstractSmartLock will also be acquired when the Condition::wait() call returns and ETIMEDOUT will be returned.

Prototype

Condition::wait(AbstractSmartLock $lock) returns int

Condition::wait(AbstractSmartLock $lock, softint $timeout_ms) returns int

Condition::wait(AbstractSmartLock $lock, date $timeout) returns int

Example
{
    $mutex.lock();
    on_exit $mutex.unlock();
    while ($num > 0)
        $cond.wait($mutex);
    # ... do something
}

Table 4.659. Arguments for Condition::wait()

Argument

Description

AbstractSmartLock $lock

The AbstractSmartLock object to use for synchronization on this Condition object. The AbstractSmartLock must be locked before calling this method.

[softint $timeout_ms or date $timeout]

An optional timeout value; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.660. Return Values for Condition::wait()

Return Type

Description

int

0 for success, ETIMEDOUT if a timeout has occurred.


Table 4.661. Exceptions Thrown by Condition::wait()

err

desc

CONDITION-WAIT-ERROR

This exception should never be thrown - it indicates a low-level error in executing the method.


4.24.7. Condition::wait_count()

Synopsis

Returns the number of threads currently blocked on this object using the AbstractSmartLock passed; the AbstractSmartLock can be in any state (locked or unlocked) for this call (does not necessarily have to be locked).

Prototype

Condition::wait_count(AbstractSmartLock $lock) returns int

Example
$num_threads = $cond.wait_count();

Table 4.662. Arguments for Condition::wait()

Argument

Description

AbstractSmartLock $lock

The AbstractSmartLock to check for waiting threads. The AbstractSmartLock can be in any state (locked or unlocked) for this call (does not necessarily have to be locked).


Table 4.663. Return Values for Condition::wait_count()

Return Type

Description

int

The number of threads currently blocked on this object.


4.25. Thread::Counter Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

Counter objects allow Qore threads to sleep until a counter reaches zero.

Table 4.664. Counter Method Overview

Method

Except?

Description

Counter::constructor(softint $count = 0)

N

Creates the Counter object.

Counter::destructor()

Y

Destroys the Counter object.

Counter::copy()

N

Creates a new Counter object, not based on the original.

Counter::inc() returns nothing

N

Atomically increments the counter value.

Counter::dec() returns nothing

Y

Atomically decrements the counter value.

Counter::waitForZero() returns nothing

Counter::waitForZero(softint $timeout_ms) returns int

Counter::waitForZero(date $timeout) returns int

Y

Blocks a thread until the counter reaches zero; returns zero on sucess, or non-zero if a timeout occurred.

Counter::getCount() returns int

N

Returns the current counter value.

Counter::getWaiting() returns int

N

Returns the number of threads currently blocked on this object.


4.25.1. Counter::constructor()

Synopsis

Creates the Counter object; an optional integer argument may be given giving the intial value of the Counter. If no value is given, then the Counter is initialized with 0.

Prototype

Counter::constructor(softint $count = 0)

Example
my Counter $counter();

Table 4.665. Arguments for Counter::constructor()

Argument

Description

softint $count = 0

If an argument is supplied here, then the Counter will be initialized with this value, otherwise the Counter is initialized with 0.


4.25.2. Counter::destructor()

Synopsis

Destroys the object. Note that it is a programming error to delete this object while other threads are blocked on it; in this case an exception is thrown in the deleting thread, and in each thread blocked on this object when it is deleted.

Example
delete $counter;

Table 4.666. Exceptions Thrown by Counter::destructor()

err

desc

COUNTER-ERROR

Object deleted while other threads blocked on it.


4.25.3. Counter::copy()

Synopsis

Creates a new Counter object, not based on the original.

Example
my Counter $new_counter = $counter.copy();

4.25.4. Counter::inc()

Synopsis

Atomically increments the counter value.

Prototype

Counter::inc() returns nothing

Example
$counter.inc();

4.25.5. Counter::dec()

Synopsis

Atomically decrements the counter value. An exception can only be thrown if the object is deleted in another thread while this call is in progress; this is a race condition caused by a user programming error and should not occur in practise with correct code.

Prototype

Counter::dec() returns nothing

Example
$counter.dec();

Table 4.667. Exceptions Thrown by Counter::dec()

err

desc

COUNTER-ERROR

Object deleted in another thread.


4.25.6. Counter::waitForZero()

Synopsis

Blocks a thread until the counter reaches zero. Takes an optional timeout value in milliseconds. Like all Qore functions and methods taking timeout values, a relative date/time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds).

Returns -1 if the call times out (only if a timeout value is passed), 0 if the counter reached zero.

Prototype

Counter::waitForZero() returns nothing

Counter::waitForZero(softint $timeout_ms) returns int

Counter::waitForZero(date $timeout) returns int

Example
$counter.waitForZero();

Table 4.668. Arguments for Counter::waitForZero()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait for the Counter to reach zero; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.669. Return Values for Counter::waitForZero()

Return Type

Description

int

If a timeout value was passed, -1 means that the call timed out, 0 means that the counter reached zero.


Table 4.670. Exceptions Thrown by Counter::dec()

err

desc

COUNTER-ERROR

Object deleted in another thread.


4.25.7. Counter::getCount()

Synopsis

Returns the current counter value.

Prototype

Counter::getCount() returns int

Example
my int $count = $counter.getCount();

Table 4.671. Return Values for Counter::getCount()

Return Type

Description

int

The current counter value.


4.25.8. Counter::getWaiting()

Synopsis

Returns the number of threads currently blocked on this object.

Prototype

Counter::getWaiting() returns int

Example
my int $threads = $counter.getWaiting();

Table 4.672. Return Values for Counter::getWaiting()

Return Type

Description

int

The number of threads currently blocked on this object.


4.26. Thread::Queue Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

Queue objects provide a blocking, thread-safe message-passing object to Qore programs.

Table 4.673. Queue Method Overview

Method

Except?

Description

Queue::constructor()

N

Creates the Queue object.

Queue::destructor()

Y

Destroys the Queue object.

Queue::copy()

N

Creates a new Queue object with the same elements as the original.

Queue::get() returns any

Queue::get(softint $timeout_ms) returns any

Queue::get(date $timeout) returns any

Y

Blocks until at least one entry is available on the queue, then returns the first entry in the queue. If a timeout occurs, an exception is thrown.

Queue::pop() returns any

Queue::pop(softint $timeout_ms) returns any

Queue::pop(date $timeout) returns any

Y

Blocks until at least one entry is available on the queue, then returns the last entry in the queue. If a timeout occurs, an exception is thrown.

Queue::push(any $val) returns nothing

N

Puts a value on the end of the queue.

Queue::size() returns int

N

Returns the number of elements in the queue.

Queue::getWaiting() returns int

N

Returns the number of threads currently blocked on this queue.


4.26.1. Queue::constructor()

Synopsis

Creates the Queue object.

Prototype

Queue::constructor()

Example
my Queue $queue();

4.26.2. Queue::destructor()

Synopsis

Destroys the object. Note that it is a programming error to delete this object while other threads are blocked on it; in this case an exception is thrown in the deleting thread, and in each thread blocked on this object when it is deleted.

Example
delete $queue;

Table 4.674. Exceptions Thrown by Queue::destructor()

err

desc

QUEUE-ERROR

The queue was deleted while other threads were blocked on it.


4.26.3. Queue::copy()

Synopsis

Creates a new Queue object with the same elements as the original.

Example
my Queue $new_queue = $queue.copy();

4.26.4. Queue::get()

Synopsis

Blocks until at least one entry is available on the queue, then returns the first entry in the queue. Accepts an optional timeout value in milliseconds (1/1000 second). Like all Qore functions and methods taking timeout values, a relative date/time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds). If no value or a value that converts to integer 0 is passed as the argument, then the call does not timeout until data is available on the queue.

Note that this function will throw an exception on timeout, in order to enable the case where NOTHING was pushed on the queue to be differentiated from a timeout.

Prototype

Queue::get() returns any

Queue::get(softint $timeout_ms) returns any

Queue::get(date $timeout) returns any

Example
$data = $queue.get();

Table 4.675. Arguments for Queue::get()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait for data to become available on the queue; integers are interpreted as milliseconds; relative date/time values are interpreted literally. If no value or a value that converts to integer 0 is passed as the argument, then the call does not timeout until data is available on the queue. If a non-zero timeout argument is passed, and no data is available in the timeout period, a QUEUE-TIMEOUT exception is thrown.


Table 4.676. Return Values for Queue::get()

Return Type

Description

any

Depends on the value put on the queue; could also be NOTHING, because NOTHING can be pushed as a value on the queue.


Table 4.677. Exceptions Thrown by Queue::get()

err

desc

QUEUE-TIMEOUT

The timeout value was exceeded.

QUEUE-ERROR

The queue was deleted in another thread while this thread was blocked on it.


4.26.5. Queue::pop()

Synopsis

Blocks until at least one entry is available on the queue, then returns the last entry in the queue. Accepts an optional timeout value in ms (1/1000 second). Like all Qore functions and methods taking timeout values, a relative date/time value may be passed instead of an integer to make the timeout units clear (ex: 2500ms for 2.5 seconds). If no value or a value that converts to integer 0 is passed as the argument, then the call does not timeout until data is available on the queue.

Note that this function will throw an exception on timeout, in order to enable the case where NOTHING was pushed on the queue to be differentiated from a timeout.

Prototype

Queue::pop() returns any

Queue::pop(softint $timeout_ms) returns any

Queue::pop(date $timeout) returns any

Example
$data = $queue.pop();

Table 4.678. Arguments for Queue::pop()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait for data to become available on the queue; integers are interpreted as milliseconds; relative date/time values are interpreted literally. If no value or a value that converts to integer 0 is passed as the argument, then the call does not timeout until data is available on the queue. If a non-zero timeout argument is passed, and no data is available in the timeout period, a QUEUE-TIMEOUT exception is thrown.


Table 4.679. Return Values for Queue::pop()

Return Type

Description

any

Depends on the value put on the queue.


Table 4.680. Exceptions Thrown by Queue::pop()

err

desc

QUEUE-TIMEOUT

The timeout value was exceeded.

QUEUE-ERROR

The queue was deleted in another thread while this thread was blocked on it.


4.26.6. Queue::push()

Synopsis

Adds a value to the end of the queue.

Prototype

Queue::push(any $val) returns nothing

Example
$queue.push($value);

Table 4.681. Arguments for Queue::push()

Argument

Description

any $val

Value to be put on the queue.


4.26.7. Queue::size()

Synopsis

Returns the number of elements in the queue.

Prototype

Queue::size() returns int

Example
my int $size = $queue.size();

Table 4.682. Return Values for Queue::size()

Return Type

Description

int

The number of elements in the queue.


4.26.8. Queue::getWaiting()

Synopsis

Returns the number of threads currently blocked on this queue.

Prototype

Queue::getWaiting() returns int

Example
my int $num = $queue.getWaiting();

Table 4.683. Return Values for Queue::getWaiting()

Return Type

Description

int

The number of threads currently blocked on this queue.


4.27. Thread::RWLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

This class inherits AbstractSmartLock, so it can be used by Condition objects, while using either the read lock or the write lock.

The RWLock class implements a read-write lock for efficient thread locking when write actions must be atomic and reads can be made in parallel if no write is in progress. When a thread holds the write lock, no other thread can grab the read or write lock. Multiple threads can hold the read lock at one time.

As with all Qore threading primitives, this class supports deadlock detection and throws exceptions when threading errors are encountered (for example, trying to free the read lock while holding the write lock, etc).

This read-write lock favors readers, so the read lock can be safely acquired recursively.

See the AutoReadLock and the AutoWriteLock classes for classes that assist in exception-safe RWLock locking.

Additionally, the on_exit statement can provide exception-safe RWLock handling at the lexical block level as in the following example:

{
    $rwl.writeLock();
    on_exit
        $rwl.writeUnlock();

    # ... when this block exits the lock will be released, even in the
    #     case of return statements or exceptions
}

Table 4.684. RWLock Method Overview

Method

Except?

Description

RWLock::constructor()

N

Creates the RWLock object.

RWLock::destructor()

Y

Destroys the RWLock object.

RWLock::copy()

N

Creates a new RWLock object, not based on the original.

RWLock::readLock() returns nothing

RWLock::readLock(softint $timeout_ms) returns int

RWLock::readLock(date $timeout) returns int

Y

Acquires the read lock with an optional timeout value; blocks if the write lock is already acquired. Returns 0 for success, non-zero for timeout; exceptions are thrown for other errors.

RWLock::readUnlock() returns nothing

Y

Decrements the read lock counter and releases the read lock if the counter is zero. If at least one thread is blocked trying to acquire the write lock and the read counter reaches zero, then one thread waiting on the write lock is woken up.

RWLock::writeLock() returns nothing

RWLock::writeLock(softint $timeout_ms) returns int

RWLock::writeLock(date $timeout) returns int

Y

Acquires the write lock with an optional timeout; blocks if either the read lock or write lock is already acquired. Returns 0 for success, non-zero for timeout; exceptions are thrown for other errors.

RWLock::writeUnlock() returns nothing

Y

Releases the write lock, if any writers are waiting, then wakes one up, otherwise if any readers are waiting, wakes up all readers.

RWLock::tryReadLock() returns int

N

Acquires the read lock only if it can be acquired immediately. Returns 0 for success (read lock acquired, read lock count incremented) or -1 if the call would block.

RWLock::tryWriteLock() returns int

N

Acquires the write lock only if it can be acquired immediately. Returns 0 for success (write lock acquired) or -1 if the call would block.

RWLock::numReaders() returns int

N

Returns the read lock count.

RWLock::getReadWaiting() returns int

N

Returns the number of threads waiting on the read lock.

RWLock::getWriteWaiting() returns int

N

Returns the number of threads waiting on the write lock.


4.27.1. RWLock::constructor()

Synopsis

Creates the RWLock object.

Prototype

RWLock::constructor()

Example
my RWLock $rwl();

4.27.2. RWLock::destructor()

Synopsis

Destroys the object. Note that it is a programming error to delete this object while other threads are blocked on it; in this case an exception is thrown in the deleting thread, and in each thread blocked on this object when it is deleted.

Example
delete $rwl;

Table 4.685. Exceptions Thrown by RWLock::destructor()

err

desc

LOCK-ERROR

Object deleted while other threads blocked on it.


4.27.3. RWLock::copy()

Synopsis

Creates a new RWLock object, not based on the original.

Example
my RWLock $new_rwl = $rwl.copy();

4.27.4. RWLock::readLock()

Synopsis

Acquires the read lock with an optional timeout value; blocks if the write lock is already acquired. The read lock may be acquired recursively, however, each call to RWLock::readLock() requires a corresponding call to RWLock::readUnlock(). An optional timeout value may be passed to this method, giving a time in milliseconds to wait for the lock to become free. Like all Qore functions and methods taking timeout values, a relative date/time value may be passed instead of an integer to make the timeout units clear.

Prototype

RWLock::readLock() returns nothing

RWLock::readLock(softint $timeout_ms) returns int

RWLock::readLock(date $timeout) returns int

Example
$rwl.readLock();

Table 4.686. Arguments for RWLock::readLock()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait to acquire the read lock; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.687. Return Values for RWLock::readLock()

Return Type

Description

nothing or int

Only variants accepting a timeout return a value; they return 0 for success, -1 for timeout


Table 4.688. Exceptions Thrown by RWLock::readLock()

err

desc

THREAD-DEADLOCK

A deadlock was detected while trying to acquire the lock.

LOCK-ERROR

readLock() called while already holding the write lock, object deleted in another thread, etc.


4.27.5. RWLock::readUnlock()

Synopsis

Decrements the read lock counter and releases the read lock if the counter is zero. If at least one thread is blocked trying to acquire the write lock and the read counter reaches zero, then one thread waiting on the write lock is woken up.

Prototype

RWLock::readUnlock() returns nothing

Example
$rwl.readUnlock();

Table 4.689. Exceptions Thrown by RWLock::readUnlock()

err

desc

LOCK-ERROR

readUnlock() called while not holding the read lock, object deleted in another thread, etc.


4.27.6. RWLock::writeLock()

Synopsis

Acquires the write lock; blocks if either the read lock or write lock is already acquired. An optional timeout value may be passed to this method, giving a time in milliseconds to wait for the lock to become free. Like all Qore functions and methods taking timeout values, a relative date/time value may be passed instead of an integer to make the timeout units clear.

To release the write lock, use RWLock::readUnlock().

Prototype

RWLock::writeLock() returns nothing

RWLock::writeLock(softint $timeout_ms) returns int

RWLock::writeLock(date $timeout) returns int

Example
$rwl.writeLock();

Table 4.690. Arguments for RWLock::writeLock()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait to acquire the write lock; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.691. Return Values for RWLock::writeLock()

Return Type

Description

nothing or int

Only variants accepting a timeout return a value; they return 0 for success, -1 for timeout


Table 4.692. Exceptions Thrown by RWLock::writeLock()

err

desc

THREAD-DEADLOCK

A deadlock was detected while trying to acquire the lock.

LOCK-ERROR

writeLock() called while holding the read lock, writeLock() called while already holding the write lock in the same thread, object deleted in another thread, etc.


4.27.7. RWLock::writeUnlock()

Synopsis

Releases the write lock, if any writers are waiting, then wakes one up, otherwise if any readers are waiting, wakes up all readers.

Prototype

RWLock::writeUnlock() returns nothing

Example
$rwl.writeUnlock();

Table 4.693. Exceptions Thrown by RWLock::writeUnlock()

err

desc

LOCK-ERROR

writeUnlock() called while not holding the write lock, object deleted in another thread, etc.


4.27.8. RWLock::tryReadLock()

Synopsis

Acquires the read lock only if it can be acquired immediately, returns 0 for success, -1 if it would block.

Prototype

RWLock::tryReadLock() returns int

Example
my int $i = $rwl.tryReadLock();

Table 4.694. Return Values for RWLock::writeUnlock()

Return Type

Description

int

Returns 0 for success (read lock acquired, read lock count incremented) or -1 if the call would block.


4.27.9. RWLock::tryWriteLock()

Synopsis

Acquires the write lock only if it can be acquired immediately, returns 0 for success, -1 if it would block.

Prototype

RWLock::tryWriteLock() returns int

Example
my int $i = $rwl.tryWriteLock();

Table 4.695. Return Values for RWLock::tryWriteLock()

Return Type

Description

int

Returns 0 for success (write lock acquired) or -1 if the call would block.


4.27.10. RWLock::numReaders()

Synopsis

Returns the read lock count.

Prototype

RWLock::numReaders() returns int

Example
$num = $rwl.numReaders();

Table 4.696. Return Values for RWLock::numReaders()

Return Type

Description

int

The read lock count.


4.27.11. RWLock::getReadWaiting()

Synopsis

Returns the number of threads blocked on the read lock (only non-zero while the write lock is held).

Prototype

RWLock::getReadWaiting() returns int

Example
$num = $rwl.getReadWaiting();

Table 4.697. Return Values for RWLock::getReadWaiting()

Return Type

Description

int

The number of threads blocked on the read lock.


4.27.12. RWLock::getWriteWaiting()

Synopsis

Returns the number of threads blocked on the write lock.

Prototype

RWLock::getWriteWaiting() returns int

Example
$num = $rwl.getWriteWaiting();

Table 4.698. Return Values for RWLock::getWriteWaiting()

Return Type

Description

int

The number of threads blocked on the write lock.


4.28. Thread::Mutex Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

This class inherits AbstractSmartLock, so it can be used by Condition objects.

The Mutex class implements a mutual-exclusion lock for thread locking. Like all Qore thread primitives, objects of this class participate in deadlock detection and throw exceptions when threading errors occur (ex: unlocking a Mutex object locked by another thread, etc). See individual methods for more information on exceptions thrown.

See the AutoLock class for a class that assists in exception-safe Mutex locking.

Additionally, the on_exit statement can provide exception-safe unlocking at the lexical block level for Mutex objects as in the following example:

{
    $m.lock();
    on_exit
        $m.unlock();

    # ... when this block exits the lock will be released, even in the
    #     case of return statements or exceptions
}

Table 4.699. Mutex Method Overview

Method

Except?

Description

Mutex::constructor()

N

Creates the Mutex object.

Mutex::destructor()

Y

Destroys the Mutex object.

Mutex::copy()

N

Creates a new Mutex object, not based on the original.

Mutex::lock() returns nothing

Mutex::lock(softint $timeout_ms) returns int

Mutex::lock(date $timeout) returns int

Y

Locks the Mutex object. Blocks if the lock is already held.

Mutex::unlock() returns nothing

Y

Unlocks the Mutex object. Wakes up one thread if any threads are blocked on this lock.

Mutex::trylock() returns int

Y

Acquires the lock only if it is not already held. Returns 0 for success (lock acquired) or -1 if the call would block.


4.28.1. Mutex::constructor()

Synopsis

Creates the Mutex object.

Prototype

Mutex::constructor()

Example
my Mutex $mutex();

4.28.2. Mutex::destructor()

Synopsis

Destroys the object. Note that it is a programming error to delete this object while other threads are blocked on it; in this case an exception is thrown in the deleting thread, and in each thread blocked on this object when it is deleted.

Example
delete $mutex;

Table 4.700. Exceptions Thrown by Mutex::destructor()

err

desc

LOCK-ERROR

Object deleted while other threads blocked on it.


4.28.3. Mutex::copy()

Synopsis

Creates a new Mutex object, not based on the original.

Example
my Mutex $new_mutex = $mutex.copy();

4.28.4. Mutex::lock()

Synopsis

Locks the Mutex object. Blocks if the lock is already held. An optional timeout value may be passed to this method, giving a time in milliseconds to wait for the lock to become free. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear.

To release the Mutex, use Mutex::unlock().

Prototype

Mutex::lock() returns nothing

Mutex::lock(softint $timeout_ms) returns int

Mutex::lock(date $timeout) returns int

Example
$mutex.lock();

Table 4.701. Arguments for Mutex::lock()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait to acquire the lock; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.702. Return Values for Mutex::lock()

Return Type

Description

nothing or int

Only variants accepting a timeout return a value; they return 0 for success, -1 for timeout


Table 4.703. Exceptions Thrown by Mutex::lock()

err

desc

THREAD-DEADLOCK

A deadlock was detected while trying to acquire the lock.

LOCK-ERROR

lock called twice in the same thread, object deleted in another thread, etc.


4.28.5. Mutex::unlock()

Synopsis

Unlocks the Mutex object. Wakes up one thread if any threads are blocked on this lock.

Prototype

Mutex::unlock() returns nothing

Example
$mutex.unlock();

Table 4.704. Exceptions Thrown by Mutex::unlock()

err

desc

LOCK-ERROR

lock not held, lock held by another thread, object deleted in another thread, etc.


4.28.6. Mutex::trylock()

Synopsis

Acquires the lock only if it is not already held; the return value indicates success (0, lock acquired) or failure (-1, lock already held).

Prototype

Mutex::trylock() returns int

Example
my int $i = $mutex.trylock();

Table 4.705. Return Values for Mutex::trylock()

Return Type

Description

int

Returns 0 for success (lock acquired) or -1 if the call would block.


4.29. Thread::RMutex Class

DEPRECATED: use the Gate class instead.

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

4.30. Thread::Sequence Class

The Sequence class implements a thread-safe increment-only object.

Table 4.706. Sequence Method Overview

Method

Except?

Description

Sequence::constructor()

Sequence::constructor(softint $start)

N

Creates a new Sequence object.

Sequence::destructor()

N

Destroys the Sequence object.

Sequence::copy()

N

Creates a new Sequence object, not based on the original.

Sequence::next() returns int

N

Atomically increments the counter and returns the last value.

Sequence::getCurrent() returns int

N

Returns the current value of the counter.


4.30.1. Sequence::constructor()

Synopsis

Creates a new Sequence object.

Prototype

Sequence::constructor()

Sequence::constructor(softint $start)

Example
my Sequence $seq();

Table 4.707. Arguments for Sequence::constructor()

Argument

Description

[softint $start]

Optional start number for the sequence (default with no argument = 0).


4.30.2. Sequence::destructor()

Synopsis

Destroys the object.

Example
delete $seq;

4.30.3. Sequence::copy()

Synopsis

Creates a new Sequence object, not based on the original.

Example
my Sequence $new_seq = $seq.copy();

4.30.4. Sequence::next()

Synopsis

Atomically increments the counter and returns the last value.

Prototype

Sequence::next() returns int

Example
$seq.next();

Table 4.708. Return Values for Sequence::next()

Return Type

Description

int

The last value of the sequence.


4.30.5. Sequence::getCurrent()

Synopsis

Returns the current value of the counter.

Prototype

Sequence::getCurrent() returns int

Example
my int $num = $seq.getCurrent();

Table 4.709. Return Values for Sequence::getCurrent()

Return Type

Description

int

The current value of the counter.


4.31. Thread::Gate Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

The Gate class implements a reentrant thread lock. Once a thread grabs the lock, it can call the Gate::enter() method again without blocking. Other threads that try to enter the lock will block until the thread holding the lock calls Gate::exit() an equal number of times to Gate::enter() calls.

See the AutoGate class for a class that assists in exception-safe Gate locking.

Additionally, the on_exit statement can provide exception-safe Gate handling at the lexical block level as in the following example:

{
    $g.enter();
    on_exit
        $g.exit();

    # ... when this block exits the gate lock counter will be decremented,
    #     even in the case of return statements or exceptions
}

Table 4.710. Gate Method Overview

Method

Except?

Description

Gate::constructor()

N

Create a new Gate object.

Gate::destructor()

Y

Destroys the Gate object.

Gate::copy()

N

Creates a new Gate object, not based on the original.

Gate::enter() returns nothing

Gate::enter(softint $timeout_ms) returns int

Gate::enter(date $timeout) returns int

Y

Acquires the lock if it is unlocked or locked by the same thread, otherwise blocks until the lock counter reaches zero. For variants taking a timeout; returns 0 if no timeout occurred, non-zero if a timeout occurred.

Gate::tryEnter() return int

N

Acquires the lock if it is unlocked or locked by the same thread, otherwise returns immediately with -1.

Gate::exit() returns int

Y

Decrements the lock counter; if it reaches zero then the lock is unlocked and any blocked threads are awoken; in this case 0 is returns; in all other cases, non-zero is returned.

Gate::numInside() returns int

N

Returns the current lock count.

Gate::numWaiting() returns int

N

Returns the number of threads blocked on the Gate.


4.31.1. Gate::constructor()

Synopsis

Creates a new Gate object.

Prototype

Gate::constructor()

Example
my Gate $gate();

4.31.2. Gate::destructor()

Synopsis

Destroys the object. Note that it is a programming error to delete this object while other threads are blocked on it; in this case an exception is thrown in the deleting thread, and in each thread blocked on this object when it is deleted.

Example
delete $gate;

Table 4.711. Exceptions Thrown by Gate::destructor()

err

desc

LOCK-ERROR

Object deleted while other threads blocked on it.


4.31.3. Gate::copy()

Synopsis

Creates a new Gate object, not based on the original.

Example
my Gate $new_gate = $gate.copy();

4.31.4. Gate::enter()

Synopsis

Acquires the lock if it is unlocked or locked by the same thread, otherwise blocks until the lock counter reaches zero. An optional timeout value may be passed to this method, giving a time in milliseconds to wait for the lock to become free. Like all Qore functions and methods taking timeout values, a relative time value may be passed instead of an integer to make the timeout units clear.

Prototype

Gate::enter() returns nothing

Gate::enter(softint $timeout_ms) returns int

Gate::enter(date $timeout) returns int

Example
$gate.enter();

Table 4.712. Arguments for Gate::enter()

Argument

Description

[softint $timeout_ms or date $timeout]

An optional timeout value to wait to acquire the lock; integers are interpreted as milliseconds; relative date/time values are interpreted literally.


Table 4.713. Return Values for Gate::enter()

Return Type

Description

nothing or int

Only variants accepting a timeout return a value; they return 0 for success, -1 for timeout


Table 4.714. Exceptions Thrown by Gate::enter()

err

desc

THREAD-DEADLOCK

A deadlock was detected while trying to acquire the lock.

LOCK-ERROR

object deleted in another thread


4.31.5. Gate::tryEnter()

Synopsis

Acquires the lock if it is unlocked or locked by the same thread, otherwise returns immediately.

Prototype

Gate::tryEnter() return int

Example
$gate.tryEnter();

Table 4.715. Return Values for Gate::tryEnter()

Return Type

Description

int

Returns 0 for success (acquired the lock) or -1 for failure (would block).


4.31.6. Gate::exit()

Synopsis

Decrements the lock counter; if it reaches zero then the lock is unlocked and any blocked threads are awoken.

Prototype

Gate::exit() returns int

Example
$gate.exit();

Table 4.716. Exceptions Thrown by Gate::exit()

err

desc

LOCK-ERROR

lock not held by this thread, object deleted in another thread


4.31.7. Gate::numInside()

Synopsis

Returns the current lock count.

Prototype

Gate::numInside() returns int

Example
my int $num = $gate.numInside();

Table 4.717. Return Values for Gate::numInside()

Return Type

Description

int

Returns the current lock count.


4.31.8. Gate::numWaiting()

Synopsis

Returns the number of threads blocked on this object.

Prototype

Gate::numWaiting() returns int

Example
my int $num = $gate.numWaiting();

Table 4.718. Return Values for Gate::numWaiting()

Return Type

Description

int

Returns the number of threads blocked on this object.


4.32. Xml Namespace

The following constants are defined in the Qore namespace.

Table 4.719. XML Element Type Constants

Constant

Value

Description

XML_ELEMENT_NODE

1

Indicates an element

XML_ATTRIBUTE_NODE

2

Indicates an attribute

XML_TEXT_NODE

3

Indicates text

XML_CDATA_SECTION_NODE

4

Indicates CDATA: unparsed character data

XML_ENTITY_REF_NODE

5

Indicates an entity reference

XML_ENTITY_NODE

6

Indicates an entity

XML_PI_NODE

7

Indicates a processing instruction

XML_COMMENT_NODE

8

Indicates a comment

XML_DOCUMENT_NODE

9

Indicates a document

XML_DOCUMENT_TYPE_NODE

10

Indicates a document type

XML_DOCUMENT_FRAG_NODE

11

Indicates a document fragment

XML_NOTATION_NODE

12

Indicates a DTD notation

XML_HTML_DOCUMENT_NODE

13

Indicates an HTML document

XML_DTD_NODE

14

Indicates a DTD

XML_ELEMENT_DECL

15

Indicates an element declaration

XML_ATTRIBUTE_DECL

16

Indicates an attribute declaration

XML_ENTITY_DECL

17

Indicates an entity declaration

XML_NAMESPACE_DECL

18

Indicates a namespace declaration

XML_XINCLUDE_START

19

Indicates an XML xinlude start element

XML_XINCLUDE_END

20

Indicates an XML xinlude end element

XML_DOCB_DOCUMENT_NODE

21

Indicates a docbook document element


The ElementTypeMap constant in Xml namespace provides a mapping between element codes and the corresponding string code as defined in the following table.

Table 4.720. ElementTypeMap Constant Hash

Key

Value

"1"

XML_ELEMENT_NODE

"2"

XML_ATTRIBUTE_NODE

"3"

XML_TEXT_NODE

"4"

XML_CDATA_SECTION_NODE

"5"

XML_ENTITY_REF_NODE

"6"

XML_ENTITY_NODE

"7"

XML_PI_NODE

"8"

XML_COMMENT_NODE

"9"

XML_DOCUMENT_NODE

"10"

XML_DOCUMENT_TYPE_NODE

"11"

XML_DOCUMENT_FRAG_NODE

"12"

XML_NOTATION_NODE

"13"

XML_HTML_DOCUMENT_NODE

"14"

XML_DTD_NODE

"15"

XML_ELEMENT_DECL

"16"

XML_ATTRIBUTE_DECL

"17"

XML_ENTITY_DECL

"18"

XML_NAMESPACE_DECL

"19"

XML_XINCLUDE_START

"20"

XML_XINCLUDE_END

"21"

XML_DOCB_DOCUMENT_NODE


Table 4.721. XML Node Type Constants

Constant

Value

Description

XML_NODE_TYPE_NONE

0

Indicates no node is available

XML_NODE_TYPE_ELEMENT

1

Indicates an XML element

XML_NODE_TYPE_ATTRIBUTE

2

Indicates an attribute node

XML_NODE_TYPE_TEXT

3

Indicates a text node

XML_NODE_TYPE_CDATA

4

Indicates a CDATA node: unparsed character data

XML_NODE_TYPE_ENTITY_REFERENCE

5

Indicates an entity reference node

XML_NODE_TYPE_ENTITY

6

Indicates an entity node

XML_NODE_TYPE_PROCESSING_INSTRUCTION

7

Indicates an XML processing instruction

XML_NODE_TYPE_COMMENT

8

Indicates an XML comment

XML_NODE_TYPE_DOCUMENT

9

Indicates a document node

XML_NODE_TYPE_DOCUMENT_TYPE

10

Indicates a document type node

XML_NODE_TYPE_DOCUMENT_FRAGMENT

11

Indicates a document fragment node

XML_NODE_TYPE_NOTATION

12

Indicates a notation node

XML_NODE_TYPE_WHITESPACE

13

Indicates a whitespace node

XML_NODE_TYPE_SIGNIFICANT_WHITESPACE

14

Indicates a significant whitespace node

XML_NODE_TYPE_END_ELEMENT

15

Indicates an end element node

XML_NODE_TYPE_END_ENTITY

16

Indicates an end entity node

XML_NODE_TYPE_XML_DECLARATION

17

Indicates an XML declaration node


The NodeTypeMap constant in Xml namespace provides a mapping between node type codes and the corresponding string code as defined in the following table.

Table 4.722. NodeTypeMap Constant Hash

Key

Value

"0"

"XML_NODE_TYPE_NONE"

"1"

"XML_NODE_TYPE_ELEMENT"

"2"

"XML_NODE_TYPE_ATTRIBUTE"

"3"

"XML_NODE_TYPE_TEXT"

"4"

"XML_NODE_TYPE_CDATA"

"5"

"XML_NODE_TYPE_ENTITY_REFERENCE"

"6"

"XML_NODE_TYPE_ENTITY"

"7"

"XML_NODE_TYPE_PROCESSING_INSTRUCTION"

"8"

"XML_NODE_TYPE_COMMENT"

"9"

"XML_NODE_TYPE_DOCUMENT"

"10"

"XML_NODE_TYPE_DOCUMENT_TYPE"

"11"

"XML_NODE_TYPE_DOCUMENT_FRAGMENT"

"12"

"XML_NODE_TYPE_NOTATION"

"13"

"XML_NODE_TYPE_WHITESPACE"

"14"

"XML_NODE_TYPE_SIGNIFICANT_WHITESPACE"

"15"

"XML_NODE_TYPE_END_ELEMENT"

"16"

"XML_NODE_TYPE_END_ENTITY"

"17"

"XML_NODE_TYPE_XML_DECLARATION"


Additionally, the classes in the following table are included in the Xml namespace.

Table 4.723. Xml Class List

Name

Description

XmlDoc

For analyzing and manipulating XML documents.

XmlNode

Gives information about XML data in an XML document.

XmlReader

For parsing or iterating through the elements of an XML document.


4.33. Xml::XmlDoc Class

The XmlDoc class provides access to a parsed XML document by wrapping a C xmlDocPtr from libxml2. Currently this class provides read-only access to XML documents; it is possible that this restriction will be removed in future versions of Qore.

Table 4.724. XmlDoc Method Overview

Method

Except?

Description

XmlDoc::constructor(string $xml)

XmlDoc::constructor(hash $data)

Y

Creates a new XmlDoc object from an XML string or a Qore hash.

XmlDoc::destructor()

N

Destroys the XmlDoc object.

XmlDoc::copy()

N

Creates a copy of the XmlDoc object.

XmlDoc::evalXPath(string $xpath) returns list

Y

Evaluates an XPath expression and returns a list of matching XmlNode objects; an empty list is returned if there are no matches.

XmlDoc::getRootElement() returns any

N

Returns an XmlNode object representing the root element of the document, if any exists, otherwise returns NOTHING.

XmlDoc::getVersion() returns string

N

Returns the XML version of the document (normally 1.0).

XmlDoc::toQore() returns hash

N

Returns a Qore hash corresponding to the XML data; multiple out-of-order keys are created in order in the returned hash by appending a suffix to the key names.

XmlDoc::toQoreData() returns hash

N

Returns a Qore hash corresponding to the XML data; key order is not guaranteed to be maintained as multiple out-or-order keys are merged into the same Qore list.

XmlDoc::toString() returns string

N

Returns the XML string for the XML document.

XmlDoc::validateRelaxNG(string $relaxng) returns nothing

Y

Validates the XML document against a RelaxNG schema; if any errors occur, exceptions are thrown. Not available if HAVE_PARSEXMLWITHRELAXNG is False.

XmlDoc::validateSchema(string $xsd) returns nothing

Y

Validates the XML document against an XSD schema; if any errors occur, exceptions are thrown. Not available if HAVE_PARSEXMLWITHSCHEMA is False.


4.33.1. XmlDoc::constructor()

Synopsis

Creates a new XmlDoc object from the XML string or Qore hash valus passed. If a Qore hash value is passed, it must have only one top-level key, as the XML string will be created from the hash.

Prototype

XmlDoc::constructor(string $xml)

XmlDoc::constructor(hash $data)

Example
my XmlDoc $xd($xml);

Table 4.725. Arguments for XmlDoc::constructor()

Argument

Description

string $xml

The XML string to use to create the XmlDoc object.

hash $data

The Qore hash will be used to generate the XML string to use to create the XmlDoc object; the Qore hash must have only one top-level key. The XML will be generated according to the rules documented in XML Integration.


Table 4.726. Exceptions Thrown by XmlDoc::constructor()

err

desc

XMLDOC-CONSTRUCTOR-ERROR

Missing argument or invalid XML string passed.


Note that if a hash is passed as the argument to the constructor, then the method can throw any of the exceptions documented in makeXMLString().

4.33.2. XmlDoc::destructor()

Synopsis

Destroys the object.

Example
delete $xd;

This method does not throw any exceptions.

4.33.3. XmlDoc::copy()

Synopsis

Creates a new XmlDoc object, not based on the original.

Example
my XmlDoc $new_doc = $doc.copy();

4.33.4. XmlDoc::evalXPath()

Synopsis

Evaluates an XPath expression and returns a list of matching XmlNode objects.

Prototype

XmlDoc::evalXPath(string $xpath) returns list

Example
my $list = $xd.evalXPath("//list[2]");

Table 4.727. Arguments for XmlDoc::evalXPath()

Argument

Description

string $xpath

The XPath expression to evaluate on the XmlDoc object.


Table 4.728. Return Values for XmlDoc::evalXPath()

Return Type

Description

list

Returns a list of XmlNode objects that match the XPath expression.


Table 4.729. Exceptions Thrown by XmlDoc::evalXPath()

err

desc

XMLDOC-EVAL-XPATH-ERROR

Missing XPath expression.

XPATH-CONSTRUCTOR-ERROR

Cannot create XPath context from the XmlDoc object

XPATH-ERROR

An error occured evaluating the XPath expression


4.33.5. XmlDoc::getRootElement()

Synopsis

Returns an XmlNode object representing the root element of the document, if any exists, otherwise returns NOTHING.

Prototype

XmlDoc::getRootElement() returns any

Example
my any $node = $xd.getRootElement();

Table 4.730. Return Values for XmlDoc::getRootElement()

Return Type

Description

XmlNode or nothing

The XmlNode object for the root element of the XML document, or NOTHING if there is none.


This method does not throw any exceptions.

4.33.6. XmlDoc::getVersion()

Synopsis

Returns the XML version of the contained XML document.

Prototype

XmlDoc::getVersion() returns string

Example
my string $xmlver = $xd.getVersion();

Table 4.731. Return Values for XmlDoc::getVersion()

Return Type

Description

string

The XML version of the contained document (normally "1.0").


This method does not throw any exceptions.

4.33.7. XmlDoc::toQore()

Synopsis

Returns a Qore hash structure correponding to the XML data contained by the XmlDoc object. If duplicate, out-of-order XML elements are found in the input string, they are deserialized to Qore hash elements with the same name as the XML element but including a caret "^" and a numeric prefix to maintain the same key order in the Qore hash as in the input XML string.

For a similar method not preserving the order of keys in the XML in the resulting Qore hash by collapsing all elements at the same level with the same name to the same Qore list, see XmlDoc::toQoreData(). See also parseXMLAsData() and parseXML().

Prototype

XmlDoc::toQore() returns hash

Example
my hash $h = $xd.toQore();

Table 4.732. Return Values for XmlDoc::toQore()

Return Type

Description

hash

The Qore hash corresponding to the data contained in the XML document with out-of-order keys preserved by appending a suffix to hash keys.


This method does not throw any exceptions.

4.33.8. XmlDoc::toQoreData()

Synopsis

Returns a Qore hash structure corresponding to the XML data contained by the XmlDoc object; does not preserve hash order with out-of-order duplicate keys: collapses all to the same list.

Note that data deserialized with this function may not be reserialized to the same input XML string due to the fact that duplicate, out-of-order XML elements are collapsed into lists in the resulting Qore hash, thereby losing the order in the original XML string.

For a similar method preserving the order of keys in the XML in the resulting Qore hash by generating Qore hash element names with numeric suffixes, see XmlDoc::toQore(). See also parseXMLAsData() and parseXML().

Prototype

XmlDoc::toQoreData() returns hash

Example
my hash $h = $xd.toQoreData();

Table 4.733. Return Values for XmlDoc::toQoreData()

Return Type

Description

hash

The Qore hash corresponding to the data contained in the XML document; out-of-order keys are not preserved but are instead collapsed to the same Qore list.


This method does not throw any exceptions.

4.33.9. XmlDoc::toString()

Synopsis

Returns the XML string for the XML document

Prototype

XmlDoc::toString() returns string

Example
my string $xmlstr = $xd.toString();

Table 4.734. Return Values for XmlDoc::toString()

Return Type

Description

string

The XML string contained by the XmlDoc object.


This method does not throw any exceptions.

4.33.10. XmlDoc::validateRelaxNG()

Synopsis

Validates the XML document against a RelaxNG schema; if any errors occur, exceptions are thrown.

The availability of this function depends on the presence of libxml2's xmlTextReaderRelaxNGSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHRELAXNG before running this method. See Library Option Constants for a list of all option constants.

Prototype

XmlDoc::validateRelaxNG(string $relaxng) returns nothing

Example
$xd.validateRelaxNG($relaxng);

Table 4.735. Arguments for XmlDoc::validateRelaxNG()

Argument

Description

string $relaxng

The RelaxNG schema to use to validate the XmlDoc object.


Table 4.736. Exceptions Thrown by XmlDoc::validateRelaxNG()

err

desc

XMLDOC-VALIDATERELAXNG-ERROR

Missing RelaxNG schema string.

RELAXNG-ERROR

The RelaxNG schema could not be parsed.

XML-RELAXNG-PARSE-ERROR

The XML document failed RelaxNG validation.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHRELAXNG before calling this function.


4.33.11. XmlDoc::validateSchema()

Synopsis

Validates the XML document against an XSD schema; if any errors occur, exceptions are thrown.

The availability of this function depends on the presence of libxml2's xmlTextReaderSetSchema() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHSCHEMA before running this function. See Library Option Constants for a list of all option constants.

Prototype

XmlDoc::validateSchema(string $xsd) returns nothing

Example
$xd.validateSchema($xsd);

Table 4.737. Arguments for XmlDoc::validateSchema()

Argument

Description

string $xsd

The XSD schema to use to validate the XmlDoc object.


Table 4.738. Exceptions Thrown by XmlDoc::validateSchema()

err

desc

XMLDOC-VALIDATESCHEMA-ERROR

Missing XSD schema string.

SCHEMA-ERROR

The XSD schema could not be parsed.

XML-SCHEMA-PARSE-ERROR

The XML document failed XSD schema validation.

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHSCHEMA before calling this function.


4.34. Xml::XmlNode Class

The XmlNode class provides information about the components of an XML document. This class currently cannot be constructed manually, but rather can only be returned by the XmlDoc class. It is possible that future versions of Qore will remove this restriction.

Table 4.739. XmlNode Class Method Overview

Method

Except?

Description

XmlNode::constructor()

Y

Cannot be called manually; throws an exception.

XmlNode::destructor()

N

Destroys the XmlNode object.

XmlNode::copy()

N

Creates an independent copy of the XmlNode object.

XmlNode::childElementCount() returns int

N

Returns the number of child elements of the XmlNode.

XmlNode::getSpacePreserve() returns int

N

Returns the space-preserving behavior of the XmlNode object.

XmlNode::getElementType() returns int

N

Returns the type of the XmlNode object; for possible values see XML Element Type Constants.

XmlNode::getElementTypeName() returns any

N

Returns the name of the type of the XmlNode object if possible, NOTHING if not; for possible values see the ElementTypeMap constant.

XmlNode::firstElementChild() returns any

N

Returns an XmlNode object for the first child of the current XmlNode object that is an XML element, or NOTHING if there is none.

XmlNode::getLastChild() returns any

N

Returns an XmlNode object for the last child of the current XmlNode object, or NOTHING if there is none.

XmlNode::lastElementChild() returns any

N

Returns an XmlNode object for the last child of the current XmlNode object that is an XML element, or NOTHING if there is none.

XmlNode::nextElementSibling() returns any

N

Returns an XmlNode object for the next element at the same level of the current XmlNode object, or NOTHING if there is none.

XmlNode::previousElementSibling() returns any

N

Returns an XmlNode object for the previous element at the same level of the current XmlNode object, or NOTHING if there is none.

XmlNode::getPath() returns string

Y

Returns a string representing a structured path for the current node.

XmlNode::getNsProp(string $prop, string $ns) returns any

Y

Returns the value of the given property anchored in the given namespace as a string, or NOTHING if no such property exists in the current XmlNode.

XmlNode::getProp(string $prop) returns any

Y

Returns the value of the given property as a string, or NOTHING if no such property exists in the current XmlNode.

XmlNode::getContent() returns any

N

Returns a string of the content of the current node or NOTHING if no content is available.

XmlNode::getName() returns any

N

Returns the name of the current node or NOTHING if no name is available.

XmlNode::getLang() returns any

N

Returns the language of the current node, determined by the value of the xml:lang attribute of this node or of the nearest ancestor. If no such property is available, then NOTHING is returned.

XmlNode::isText() returns bool

N

Returns True if the node is a text node, False if not.

XmlNode::isBlank() returns bool

N

Returns True if the node is empty or whitespace only, False if not.

XmlNode::getXML() returns any

N

Returns XML corresponding to the current node and all its children or NOTHING if no data is available.


4.34.1. XmlNode::constructor()

Synopsis

Cannot be called manually; throws an exception.

Table 4.740. Exceptions thrown by XmlNode::constructor()

err

desc

XMLNODE-CONSTRUCTOR-ERROR

XmlNode objects cannot be constructed manually


4.34.2. XmlNode::destructor()

Synopsis

Destroys the XmlNode object.

Example
delete $xmlnode;

4.34.3. XmlNode::copy()

Synopsis

Creates an independent copy of the XmlNode object.

Example
my XmlNode $value = $xmlnode.copy();

4.34.4. XmlNode::childElementCount()

Synopsis

Returns the number of child elements of the XmlNode.

Prototype

XmlNode::childElementCount() returns int

Example
$value = $xmlnode.childElementCount();

Table 4.741. Return Values for XmlNode::childElementCount()

Return Type

Description

int

the number of child elements of the XmlNode


4.34.5. XmlNode::getSpacePreserve()

Synopsis

Returns the space-preserving behavior of the XmlNode object.

Prototype

XmlNode::getSpacePreserve() returns int

Example
$value = $xmlnode.getSpacePreserve();

Table 4.742. Return Values for XmlNode::getSpacePreserve()

Return Type

Description

int

The space-preserving behavior of the XmlNode: -1 = xml:space is not inherited, 0 = default, 1 = preserve


4.34.6. XmlNode::getElementType()

Synopsis

Returns the type of the XmlNode object; for possible values see XML Element Type Constants.

Prototype

XmlNode::getElementType() returns int

Example
$value = $xmlnode.getElementType();

Table 4.743. Return Values for XmlNode::getElementType()

Return Type

Description

int

the type of the XmlNode object; for possible values see XML Element Type Constants


4.34.7. XmlNode::getElementTypeName()

Synopsis

Returns the name of the type of the XmlNode object; for possible values see the ElementTypeMap constant.

Prototype

XmlNode::getElementTypeName() returns any

Example
$value = $xmlnode.getElementTypeName();

Table 4.744. Return Values for XmlNode::getElementTypeName()

Return Type

Description

string

the name of the type of the XmlNode object; for possible values see the ElementTypeMap constant


4.34.8. XmlNode::firstElementChild()

Synopsis

Returns an XmlNode object for the first child of the current XmlNode object that is an XML element, or NOTHING if there is none.

Prototype

XmlNode::firstElementChild() returns any

Example
$value = $xmlnode.firstElementChild();

Table 4.745. Return Values for XmlNode::firstElementChild()

Return Type

Description

XmlNode or nothing

returns an XmlNode object for the first element child of the current XmlNode object, or NOTHING if there is none


4.34.9. XmlNode::getLastChild()

Synopsis

Returns an XmlNode object for the last child of the current XmlNode object, or NOTHING if there is none.

Prototype

XmlNode::getLastChild() returns any

Example
$value = $xmlnode.getLastChild();

Table 4.746. Return Values for XmlNode::getLastChild()

Return Type

Description

XmlNode or nothing

returns an XmlNode object for the last child of the current XmlNode object, or NOTHING if there is none


4.34.10. XmlNode::lastElementChild()

Synopsis

Returns an XmlNode object for the last child of the current XmlNode object that is an XML element, or NOTHING if there is none.

Prototype

XmlNode::lastElementChild() returns any

Example
$value = $xmlnode.lastElementChild();

Table 4.747. Return Values for XmlNode::lastElementChild()

Return Type

Description

XmlNode or nothing

returns an XmlNode object for the last element child of the current XmlNode object, or NOTHING if there is none


4.34.11. XmlNode::nextElementSibling()

Synopsis

Returns an XmlNode object for the next element at the same level of the current XmlNode object, or NOTHING if there is none.

Prototype

XmlNode::nextElementSibling() returns any

Example
$value = $xmlnode.nextElementSibling();

Table 4.748. Return Values for XmlNode::nextElementSibling()

Return Type

Description

XmlNode or nothing

returns an XmlNode object for the next element sibling of the current XmlNode object, or NOTHING if there is none


4.34.12. XmlNode::previousElementSibling()

Synopsis

Returns an XmlNode object for the previous element at the same level of the current XmlNode object, or NOTHING if there is none.

Prototype

XmlNode::previousElementSibling() returns any

Example
$value = $xmlnode.previousElementSibling();

Table 4.749. Return Values for XmlNode::previousElementSibling()

Return Type

Description

XmlNode or nothing

returns an XmlNode object for the previous element sibling of the current XmlNode object, or NOTHING if there is none


4.34.13. XmlNode::getPath()

Synopsis

Returns a string representing a structured path for the current node.

Prototype

XmlNode::getPath() returns string

Example
$value = $xmlnode.getPath();

Table 4.750. Return Values for XmlNode::getPath()

Return Type

Description

string

a string representing a structured path for the current node


4.34.14. XmlNode::getNsProp()

Synopsis

Returns the value of the given property anchored in the given namespace, or NOTHING if no such property exists in the current XmlNode.

Prototype

XmlNode::getNsProp(string $prop, string $ns) returns any

Example
$value = $xmlnode.getNsProp($prop, $namespace);

Table 4.751. Arguments for XmlNode::getNsProp()

Argument

Description

string $prop

The name of the property to retrieve

string $ns

The name of the namespace of the property


Table 4.752. Return Values for XmlNode::getNsProp()

Return Type

Description

string or nothing

the value of the property or NOTHING if it does not exist


Table 4.753. Exceptions thrown by XmlNode::getNsProp()

err

desc

XMLNODE-GETNSPROP-ERROR

missing or invalid argument


4.34.15. XmlNode::getProp()

Synopsis

Returns the value of the given property, or NOTHING if no such property exists in the current XmlNode.

Prototype

XmlNode::getProp(string $prop) returns any

Example
$value = $xmlnode.getProp($prop);

Table 4.754. Arguments for XmlNode::getProp()

Argument

Description

string $prop

The name of the property to retrieve


Table 4.755. Return Values for XmlNode::getProp()

Return Type

Description

string or nothing

the value of the property or NOTHING if it does not exist


Table 4.756. Exceptions thrown by XmlNode::getProp()

err

desc

XMLNODE-GETPROP-ERROR

missing or invalid argument


4.34.16. XmlNode::getContent()

Synopsis

Returns a string of the content of the current node or NOTHING if there is none.

Prototype

XmlNode::getContent() returns any

Example
$value = $xmlnode.getContent();

Table 4.757. Return Values for XmlNode::getContent()

Return Type

Description

string or nothing

a string of the content of the current node or NOTHING if there is no content


4.34.17. XmlNode::getName()

Synopsis

Returns the name of the current node or NOTHING if no name is available.

Prototype

XmlNode::getName() returns any

Example
$value = $xmlnode.getName();

Table 4.758. Return Values for XmlNode::getName()

Return Type

Description

string or nothing

the name of the current node or NOTHING if no name is available


4.34.18. XmlNode::getLang()

Synopsis

Returns the language of the current node, determined by the value of the xml:lang attribute of this node or of the nearest ancestor. If no such property is available, then NOTHING is returned.

Prototype

XmlNode::getLang() returns any

Example
$value = $xmlnode.getLang();

Table 4.759. Return Values for XmlNode::getLang()

Return Type

Description

string or nothing

the language of the current node, determined by the value of the xml:lang attribute of this node or of the nearest ancestor. If no such property is available, then NOTHING is returned.


4.34.19. XmlNode::isText()

Synopsis

Returns True if the node is a text node, False if not.

Prototype

XmlNode::isText() returns bool

Example
$value = $xmlnode.isText();

Table 4.760. Return Values for XmlNode::isText()

Return Type

Description

bool

True if the node is a text node, False if not


4.34.20. XmlNode::isBlank()

Synopsis

Returns True if the node is empty or whitespace only, False if not.

Prototype

XmlNode::isBlank() returns bool

Example
$value = $xmlnode.isBlank();

Table 4.761. Return Values for XmlNode::isBlank()

Return Type

Description

bool

True if the node is empty or whitespace only, False if not


4.34.21. XmlNode::getXML()

Synopsis

Returns a string containing XML corresponding to the current node and all its children or NOTHING if no information is available.

Prototype

XmlNode::getXML() returns any

Example
$value = $xmlnode.getXML();

Table 4.762. Return Values for XmlNode::getXML()

Return Type

Description

string or nothing

XML corresponding to the current node and all its children or NOTHING if no information is available


4.35. Xml::XmlReader Class

The XmlReader class allows XML strings to be iterated and parsed piecewise.

Table 4.763. XmlReader Class Method Overview

Method

Except?

Description

XmlReader::constructor(XmlDoc $doc)

XmlReader::constructor(string $xml)

Y

Creates the XmlReader object based on the XmlDoc object or XML string passed.

XmlReader::destructor()

N

Destroys the XmlReader object.

XmlReader::copy()

N

Creates an independent copy of the XmlReader object.

XmlReader::read() returns bool

Y

Moves the position of the current instance to the next node in the stream.

XmlReader::readSkipWhitespace() returns bool

Y

Moves the position of the current instance to the next node in the stream, skipping any whitespace nodes.

XmlReader::nodeType() returns int

N

Returns the node type of the current node; for return values, see XML Node Type Constants.

XmlReader::nodeTypeName() returns any

N

Returns a string giving the node type of the current node or NOTHING if the node type name cannot be determined; for possible return values, see the values of the NodeTypeMap constant.

XmlReader::depth() returns int

N

Returns the depth of the node in the tree.

XmlReader::name() returns any

N

Returns the qualified name of the node (prefix:LocalName) or NOTHING if no name is available.

XmlReader::value() returns any

N

Returns the text value of the node or NOTHING if not available.

XmlReader::hasAttributes() returns bool

N

Returns True if the node has attributes or False if not.

XmlReader::hasValue() returns bool

N

Returns True if the node has a text value or False if not.

XmlReader::isDefault() returns bool

N

Returns True if an attribute node was generated from the default value defined in the DTD or schema, False if not.

XmlReader::isEmptyElement() returns bool

N

Returns True if the current node is empty or False if not.

XmlReader::isNamespaceDecl() returns bool

N

Returns True if the current node is a namespace declaration rather than a regular attribute or False if not.

XmlReader::isValid() returns bool

N

Returns True if the current reader parser context is valid, False if not

XmlReader::toQore() returns any

Y

Returns a hash corresponding to the XML string from the current node position, including all its children, or a string if the reader is on an element with no children, or NOTHING if there is no more data to read.

XmlReader::toQoreData() returns any

Y

Returns a hash corresponding to the XML string from the current node position, including all its children, or a string if the reader is on an element with no children, or NOTHING if there is no more data to read.

XmlReader::attributeCount() returns int

N

Returns the number of attributes of the current node

XmlReader::baseUri() returns any

N

Returns the base URI of the node if known, NOTHING if not.

XmlReader::encoding() returns any

N

Returns the encoding string given in the XML string or NOTHING if none is given.

XmlReader::localName() returns any

N

Returns the local name of the node or NOTHING if no name is available.

XmlReader::namespaceUri() returns any

N

Returns the URI defining the namespace associated with the node, or NOTHING if not available.

XmlReader::prefix() returns any

N

Returns the shorthand reference to the namespace associated with the node, or NOTHING if not available.

XmlReader::xmlLang() returns any

N

Returns the xml:lang scope within which the node resides or NOTHING if there is none.

XmlReader::xmlVersion() returns any

N

Returns a string giving the XML version of the source document (normally "1.0")

XmlReader::getAttribute(string $attr) returns any

Y

Returns the value of the attribute matching the qualified name passed, or NOTHING if no such attribute exists in the current XmlReader.

XmlReader::getAttributeNs(string $attr, string $ns) returns any

Y

Returns the value of the given attribute anchored in the given namespace, or NOTHING if no such attribute exists in the current XmlReader.

XmlReader::getAttributeOffset(softint $offset = 0) returns any

N

Returns the string value of the attribute with the specified index relative to the containing element, or NOTHING if no such attribute exists in the current XmlReader.

XmlReader::lookupNamespace() returns any

XmlReader::lookupNamespace(string $ns) returns any

N

Returns the namespace corresponding to the given prefix in the scope of the current element as a string or NOTHING if none is found. Called with no argument this function returns the default namespace.

XmlReader::moveToAttribute(string $attr) returns bool

Y

Moves the position of the current instance to the attribute with the specified qualified name.

XmlReader::moveToAttributeNs(string $attr, string $ns) returns bool

Y

Moves the position of the current instance to the attribute with the specified local name and namespace URI.

XmlReader::moveToAttributeOffset(int $offset) returns bool

Y

Moves the position of the current instance to the attribute with the specified index relative to the containing element.

XmlReader::moveToElement() returns bool

Y

Moves the position of the current instance to the element node containing the current attribute node.

XmlReader::moveToFirstAttribute() returns bool

Y

Moves the position of the current instance to the first attribute of the current node.

XmlReader::moveToNextAttribute() returns bool

Y

Moves the position of the current instance to the next attribute of the current node.

XmlReader::next() returns bool

Y

Moves the position of the current instance to the next node in the tree at the same level, skipping any subtree.

XmlReader::getInnerXml() returns any

N

Returns an XML string of the contents of the all current node's child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes.

XmlReader::getOuterXml() returns any

N

Returns an XML string of the contents of the current node and all child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes.

XmlReader::relaxNGValidate(string $relaxng) returns nothing

Y

Set a RelaxNG schema for schema validation while parsing the XML document. This method must be called before the first call to XmlReader::read(). Not available if HAVE_PARSEXMLWITHRELAXNG is False.

XmlReader::schemaValidate(string $xsd) returns nothing

Y

Set an XSD schema for schema validation while parsing the XML document. This method must be called before the first call to XmlReader::read(). Not available if HAVE_PARSEXMLWITHSCHEMA is False.


4.35.1. XmlReader::constructor()

Synopsis

Creates the XmlReader object based on the XmlDoc object or XML string passed.

Prototype

XmlReader::constructor(XmlDoc $doc)

XmlReader::constructor(string $xml)

Example
my XmlReader $xmlreader($xml);

Table 4.764. Arguments for XmlReader::constructor()

Argument

Description

XmlDoc $doc

The pre-parsed XML document object to iterate through.

string $xml

The XML string to parse.


Table 4.765. Exceptions thrown by XmlReader::constructor()

err

desc

XMLNODE-CONSTRUCTOR-ERROR

invalid argument, error in XML string, etc


4.35.2. XmlReader::destructor()

Synopsis

Destroys the XmlReader object.

Example
delete $xmlreader;

4.35.3. XmlReader::copy()

Synopsis

Creates an independent copy of the XmlReader object.

Example
my XmlReader $xr = $xmlreader.copy();

4.35.4. XmlReader::read()

Synopsis

Moves the position of the current instance to the next node in the stream. Returns True if the read was successful, False if there are no more nodes to read. If an error occurs parsing the XML string, an exception is raised (see below).

See also XmlReader::readSkipWhitespace().

Prototype

XmlReader::read() returns bool

Example
if (!$xmlreader.read())
    break;

Table 4.766. Return Values for XmlReader::read()

Return Type

Description

bool

True if the read was successful, False if there are no more nodes to read


Table 4.767. Exceptions thrown by XmlReader::read()

err

desc

PARSE-XML-EXCEPTION

cannot move to next node due to an error parsing the XML string (exception description string contains details about the error)


4.35.5. XmlReader::readSkipWhitespace()

Synopsis

Moves the position of the current instance to the next node in the stream, skipping any whitespace nodes. Returns True if the read was successful, False if there are no more nodes to read. If an error occurs parsing the XML string, an exception is raised (see below).

See also XmlReader::read().

Prototype

XmlReader::readSkipWhitespace() returns bool

Example
if (!$xmlreader.readSkipWhitespace())
    break;

Table 4.768. Return Values for XmlReader::readSkipWhitespace()

Return Type

Description

bool

True if the read was successful, False if there are no more nodes to read


Table 4.769. Exceptions thrown by XmlReader::readSkipWhitespace()

err

desc

PARSE-XML-EXCEPTION

cannot move to next node due to an error parsing the XML string (exception description string contains details about the error)


4.35.6. XmlReader::nodeType()

Synopsis

Returns the node type of the current node; for return values, see XML Node Type Constants.

See also NodeTypeMap.

See also XmlReader::nodeTypeName()

Prototype

XmlReader::nodeType() returns int

Example
$value = $xmlreader.nodeType();

Table 4.770. Return Values for XmlReader::nodeType()

Return Type

Description

int

the node type of the current node; for return values, see XML Node Type Constants


4.35.7. XmlReader::nodeTypeName()

Synopsis

Returns a string giving the node type of the current node or NOTHING if no current node is available; for possible return values, see the values of the NodeTypeMap constant.

See also XmlReader::nodeType()

Prototype

XmlReader::nodeTypeName() returns any

Example
$value = $xmlreader.nodeTypeName();

Table 4.771. Return Values for XmlReader::nodeTypeName()

Return Type

Description

string or nothing

a string giving the node type of the current node or NOTHING if no current node is available; for possible return values, see the values of the NodeTypeMap constant


4.35.8. XmlReader::depth()

Synopsis

Returns the depth of the node in the tree.

Prototype

XmlReader::depth() returns int

Example
$value = $xmlreader.depth();

Table 4.772. Return Values for XmlReader::depth()

Return Type

Description

int

the depth of the node in the tree


4.35.9. XmlReader::name()

Synopsis

Returns the qualified name of the node (prefix:LocalName) or NOTHING if no name is available.

See also XmlReader::localName().

Prototype

XmlReader::name() returns any

Example
$value = $xmlreader.name();

Table 4.773. Return Values for XmlReader::name()

Return Type

Description

string or nothing

the qualified name of the node (prefix:LocalName) or NOTHING if no name is available


4.35.10. XmlReader::value()

Synopsis

Returns the text value of the node or NOTHING if not available.

Prototype

XmlReader::value() returns any

Example
$value = $xmlreader.value();

Table 4.774. Return Values for XmlReader::value()

Return Type

Description

string or nothing

the text value of the node or NOTHING if not available


4.35.11. XmlReader::hasAttributes()

Synopsis

Returns True if the node has attributes or False if not.

Prototype

XmlReader::hasAttributes() returns bool

Example
$value = $xmlreader.hasAttributes();

Table 4.775. Return Values for XmlReader::hasAttributes()

Return Type

Description

bool

True if the node has attributes, False if not


4.35.12. XmlReader::hasValue()

Synopsis

Returns True if the node has a text value or False if not.

Prototype

XmlReader::hasValue() returns bool

Example
$value = $xmlreader.hasValue();

Table 4.776. Return Values for XmlReader::hasValue()

Return Type

Description

bool

True if the node has a text value, False if not


4.35.13. XmlReader::isDefault()

Synopsis

Returns True if an attribute node was generated from the default value defined in the DTD or schema, False if not.

Prototype

XmlReader::isDefault() returns bool

Example
$value = $xmlreader.isDefault();

Table 4.777. Return Values for XmlReader::isDefault()

Return Type

Description

bool

True if the node an attribute node was generated from the default value defined in the DTD or schema, False if not


4.35.14. XmlReader::isEmptyElement()

Synopsis

Returns True if the current node is empty or False if not.

Prototype

XmlReader::isEmptyElement() returns bool

Example
$value = $xmlreader.isEmptyElement();

Table 4.778. Return Values for XmlReader::isEmptyElement()

Return Type

Description

bool

True if the current node is empty, False if not


4.35.15. XmlReader::isNamespaceDecl()

Synopsis

Returns True if the current node is a namespace declaration rather than a regular attribute or False if not.

Prototype

XmlReader::isNamespaceDecl() returns bool

Example
$value = $xmlreader.isNamespaceDecl();

Table 4.779. Return Values for XmlReader::isNamespaceDecl()

Return Type

Description

bool

True if the current node is a namespace declaration rather than a regular attribute, False if not


4.35.16. XmlReader::isValid()

Synopsis

Returns True if the current reader parser context is valid, False if not

Prototype

XmlReader::isValid() returns bool

Example
$value = $xmlreader.isValid();

Table 4.780. Return Values for XmlReader::isValid()

Return Type

Description

bool

True if the current reader parser context is valid, False if not


4.35.17. XmlReader::toQore()

Synopsis

Returns Qore data corresponding to the XML starting at the current node position. If there are sub elements, a hash of the XML is returned, the sub elements representing the current node's children. If duplicate, out-of-order XML elements are found in the input string, they are deserialized to Qore hash elements with the same name as the XML element but including a caret "^" and a numeric prefix to maintain the same key order in the Qore hash as in the input XML string.

If only text is present at the current element, a string is returned. If no information is available, then NOTHING is returned.

See also XmlReader::toQoreData().

Functionally similar to parseXML()

Prototype

XmlReader::toQore() returns any

Example
$value = $xmlreader.toQore();

Table 4.781. Return Values for XmlReader::toQore()

Return Type

Description

hash, string, or nothing

Returns Qore data corresponding to the XML starting at the current node position. If there are sub elements, a hash of the XML is returned, the sub elements representing the current node's children; XML element order is maintained by appending a suffix to key names. If only text is present at the current element, a string is returned. If no information is available, then NOTHING is returned.


Table 4.782. Exceptions thrown by XmlReader::toQore()

err

desc

PARSE-XML-EXCEPTION

error parsing the XML string (exception description string contains details about the error)


4.35.18. XmlReader::toQoreData()

Synopsis

Returns Qore data corresponding to the XML starting at the current node position. If there are sub elements, a hash of the XML is returned, the sub elements representing the current node's children. Note that data deserialized with this method may not be reserialized to an identical XML string due to the fact that XML elements with the same name are collapsed into Qore lists in the resulting Qore hash irrespective of the order in the original XML string.

If only text is present at the current element, a string is returned. If no information is available, then NOTHING is returned.

See also XmlReader::toQore().

Functionally similar to parseXMLAsData()

Prototype

XmlReader::toQoreData() returns any

Example
$value = $xmlreader.toQoreData();

Table 4.783. Return Values for XmlReader::toQoreData()

Return Type

Description

hash, string, or nothing

Returns Qore data corresponding to the XML starting at the current node position. If there are sub elements, a hash of the XML is returned, the sub elements representing the current node's children; does not guarantee to maintain XML element order in the hash as elements at the same level with the same name are collapsed to a Qore list. If only text is present at the current element, a string is returned. If no information is available, then NOTHING is returned.


Table 4.784. Exceptions thrown by XmlReader::toQoreData()

err

desc

PARSE-XML-EXCEPTION

error parsing the XML string (exception description string contains details about the error)


4.35.19. XmlReader::attributeCount()

Synopsis

Returns the number of attributes of the current node

Prototype

XmlReader::attributeCount() returns int

Example
$value = $xmlreader.attributeCount();

Table 4.785. Return Values for XmlReader::attributeCount()

Return Type

Description

int

the number of attributes of the current node


4.35.20. XmlReader::baseUri()

Synopsis

Returns the base URI of the node if known, NOTHING if not.

Prototype

XmlReader::baseUri() returns any

Example
$value = $xmlreader.baseUri();

Table 4.786. Return Values for XmlReader::baseUri()

Return Type

Description

string or nothing

the base URI of the node if known, NOTHING if not


4.35.21. XmlReader::encoding()

Synopsis

Returns the encoding string given in the XML string or NOTHING if none is given.

Prototype

XmlReader::encoding() returns any

Example
$value = $xmlreader.encoding();

Table 4.787. Return Values for XmlReader::encoding()

Return Type

Description

string or nothing

Returns the encoding string given in the XML string or NOTHING if none is given.


4.35.22. XmlReader::localName()

Synopsis

Returns the local name of the node or NOTHING if no name is available.

Prototype

XmlReader::localName() returns any

Example
$value = $xmlreader.localName();

Table 4.788. Return Values for XmlReader::localName()

Return Type

Description

string or nothing

the local name of the node or NOTHING if no name is available


4.35.23. XmlReader::namespaceUri()

Synopsis

Returns the URI defining the namespace associated with the node, or NOTHING if not available.

Prototype

XmlReader::namespaceUri() returns any

Example
$value = $xmlreader.namespaceUri();

Table 4.789. Return Values for XmlReader::namespaceUri()

Return Type

Description

string or nothing

the URI defining the namespace associated with the node or NOTHING if not available


4.35.24. XmlReader::prefix()

Synopsis

Returns the shorthand reference to the namespace associated with the node, or NOTHING if not available.

Prototype

XmlReader::prefix() returns any

Example
$value = $xmlreader.prefix();

Table 4.790. Return Values for XmlReader::prefix()

Return Type

Description

string or nothing

the shorthand reference to the namespace associated with the node or NOTHING if not available


4.35.25. XmlReader::xmlLang()

Synopsis

Returns the xml:lang scope within which the node resides or NOTHING if there is none.

Prototype

XmlReader::xmlLang() returns any

Example
$value = $xmlreader.xmlLang();

Table 4.791. Return Values for XmlReader::xmlLang()

Return Type

Description

string or nothing

the xml:lang scope within which the node resides or NOTHING if there is none


4.35.26. XmlReader::xmlVersion()

Synopsis

Returns a string giving the XML version of the source document (normally "1.0") or NOTHING if none is present.

Prototype

XmlReader::xmlVersion() returns any

Example
$value = $xmlreader.xmlVersion();

Table 4.792. Return Values for XmlReader::xmlVersion()

Return Type

Description

string or nothing

a string giving the XML version of the source document (normally "1.0") or NOTHING if none is present


4.35.27. XmlReader::getAttribute()

Synopsis

Returns the value of the attribute matching the qualified name passed, or NOTHING if no such attribute exists in the current XmlReader.

See also XmlReader::getAttributeNs()

Prototype

XmlReader::getAttribute(string $attr) returns any

Example
$value = $xmlreader.getAttribute($name);

Table 4.793. Arguments for XmlReader::getAttribute()

Argument

Description

string $attr

The name of the attribute to retrieve


Table 4.794. Return Values for XmlReader::getAttribute()

Return Type

Description

string or nothing

the value of the attribute or NOTHING if it does not exist


Table 4.795. Exceptions thrown by XmlReader::getAttribute()

err

desc

XMLREADER-GETATTRIBUTE-ERROR

missing or invalid argument


4.35.28. XmlReader::getAttributeNs()

Synopsis

Returns the value of the given attribute anchored in the given namespace, or NOTHING if no such attribute exists in the current XmlReader.

See also XmlReader::getAttribute()

Prototype

XmlReader::getAttributeNs(string $attr, string $ns) returns any

Example
$value = $xmlreader.getAttributeNs($localname, $namespaceuri);

Table 4.796. Arguments for XmlReader::getAttributeNs()

Argument

Description

string $attr

The name of the attribute to retrieve

string $ns

The name of the namespace URI of the attribute


Table 4.797. Return Values for XmlReader::getAttributeNs()

Return Type

Description

string or nothing

the value of the attribute or NOTHING if it does not exist


Table 4.798. Exceptions thrown by XmlReader::getAttributeNs()

err

desc

XMLREADER-GETATTRIBUTENS-ERROR

missing or invalid argument


4.35.29. XmlReader::getAttributeOffset()

Synopsis

Returns the value of the attribute with the specified index relative to the containing element, or NOTHING if no such attribute exists in the current XmlReader.

See also XmlReader::getAttribute()

Prototype

XmlReader::getAttributeOffset(softint $offset = 0) returns any

Example
$value = $xmlreader.getAttributeOffset($offset);

Table 4.799. Arguments for XmlReader::getAttributeOffset()

Argument

Description

softint $offset = 0

the index of the attribute relative to the containing element


Table 4.800. Return Values for XmlReader::getAttributeOffset()

Return Type

Description

string or nothing

the value of the attribute or NOTHING if it does not exist


4.35.30. XmlReader::lookupNamespace()

Synopsis

returns the namespace corresponding to the given prefix in the scope of the current element. If no prefix is given, the default namespace is returned.

Prototype

XmlReader::lookupNamespace() returns any

XmlReader::lookupNamespace(string $ns) returns any

Example
$value = $xmlreader.lookupNamespace($prefix);

Table 4.801. Arguments for XmlReader::lookupNamespace()

Argument

Description

[string $ns]

The namespace prefix to resolve; if no value is sent for this argument, the default namespace is returned.


Table 4.802. Return Values for XmlReader::lookupNamespace()

Return Type

Description

string or nothing

The namespace corresponding to the given prefix in the scope of the current element or NOTHING if the prefix could not be resolved.


4.35.31. XmlReader::moveToAttribute()

Synopsis

Moves the position of the current instance to the attribute with the specified qualified name.

See also XmlReader::moveToAttributeNs()

Prototype

XmlReader::moveToAttribute(string $attr) returns bool

Example
$value = $xmlreader.moveToAttribute($name);

Table 4.803. Arguments for XmlReader::moveToAttribute()

Argument

Description

string $attr

The qualified name of the attribute to move to


Table 4.804. Return Values for XmlReader::moveToAttribute()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.805. Exceptions thrown by XmlReader::moveToAttribute()

err

desc

XMLREADER-MOVETOATTRIBUTE-ERROR

missing or invalid argument

PARSE-XML-EXCEPTION

error parsing XML


4.35.32. XmlReader::moveToAttributeNs()

Synopsis

Moves the position of the current instance to the attribute with the specified local name and namespace URI.

See also XmlReader::moveToAttribute()

Prototype

XmlReader::moveToAttributeNs(string $attr, string $ns) returns bool

Example
$value = $xmlreader.moveToAttributeNs($localname, $namespaceuri);

Table 4.806. Arguments for XmlReader::moveToAttributeNs()

Argument

Description

string $attr

The qualified name of the attribute to move to

string $ns

The namespace URI of the attribute


Table 4.807. Return Values for XmlReader::moveToAttributeNs()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.808. Exceptions thrown by XmlReader::moveToAttributeNs()

err

desc

XMLREADER-MOVETOATTRIBUTENS-ERROR

missing or invalid argument

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.33. XmlReader::moveToAttributeOffset()

Synopsis

Moves the position of the current instance to the attribute with the specified index relative to the containing element.

See also XmlReader::moveToAttribute()

Prototype

XmlReader::moveToAttributeOffset(softint $offset) returns bool

Example
$b = $xmlreader.moveToAttributeOffset($offset);

Table 4.809. Arguments for XmlReader::moveToAttributeOffset()

Argument

Description

softint $offset = 0

the index of the attribute relative to the containing element to move to


Table 4.810. Return Values for XmlReader::moveToAttributeOffset()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.811. Exceptions thrown by XmlReader::moveToAttributeOffset()

err

desc

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.34. XmlReader::moveToElement()

Synopsis

Moves the position of the current instance to the element node containing the current attribute node.

Prototype

XmlReader::moveToElement() returns bool

Example
$value = $xmlreader.moveToElement();

Table 4.812. Return Values for XmlReader::moveToElement()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.813. Exceptions thrown by XmlReader::moveToElement()

err

desc

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.35. XmlReader::moveToFirstAttribute()

Synopsis

Moves the position of the current instance to the first attribute of the current node.

Prototype

XmlReader::moveToFirstAttribute() returns bool

Example
$value = $xmlreader.moveToFirstAttribute();

Table 4.814. Return Values for XmlReader::moveToFirstAttribute()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.815. Exceptions thrown by XmlReader::moveToFirstAttribute()

err

desc

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.36. XmlReader::moveToNextAttribute()

Synopsis

Moves the position of the current instance to the next attribute of the current node.

Prototype

XmlReader::moveToNextAttribute() returns bool

Example
$value = $xmlreader.moveToNextAttribute();

Table 4.816. Return Values for XmlReader::moveToNextAttribute()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.817. Exceptions thrown by XmlReader::moveToNextAttribute()

err

desc

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.37. XmlReader::next()

Synopsis

Moves the position of the current instance to the next node in the tree at the same level, skipping any subtree. Returns True if the operation succeeded, False if there are no more nodes to read. If an error occurs parsing the XML string, an exception is raised.

Prototype

XmlReader::next() returns bool

Example
$value = $xmlreader.next();

Table 4.818. Return Values for XmlReader::next()

Return Type

Description

bool

True in case of success, False if not found; if an XML parsing error occurs, an exception is thrown.


Table 4.819. Exceptions thrown by XmlReader::next()

err

desc

PARSE-XML-EXCEPTION

an error occured parsing the XML string


4.35.38. XmlReader::getInnerXml()

Synopsis

Returns an XML string of the contents of the all current node's child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes.

See also XmlReader::getOuterXml().

Prototype

XmlReader::getInnerXml() returns any

Example
$value = $xmlreader.getInnerXml();

Table 4.820. Return Values for XmlReader::getInnerXml()

Return Type

Description

string or nothing

an XML string of the contents of all the current node's child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes


4.35.39. XmlReader::getOuterXml()

Synopsis

Returns an XML string of the contents of the current node and all child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes.

See also XmlReader::getInnerXml().

Prototype

XmlReader::getOuterXml() returns any

Example
$value = $xmlreader.getOuterXml();

Table 4.821. Return Values for XmlReader::getOuterXml()

Return Type

Description

string or nothing

an XML string of the contents of the current node and all child nodes and markup, or NOTHING if the current node is neither an element nor an attribute or has no child nodes


4.35.40. XmlReader::relaxNGValidate()

Synopsis

Set a RelaxNG schema for schema validation while parsing the XML document. This method must be called before the first call to XmlReader::read()

The availability of this function depends on the presence of libxml2's xmlTextReaderRelaxNGValidate() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHRELAXNG before calling this method. See Library Option Constants for a list of all option constants.

If any errors occur, an exception is thrown (see below).

Prototype

XmlReader::relaxNGValidate(string $relaxng) returns nothing

Example
$xmlreader.relaxNGValidate($rng);

Table 4.822. Arguments for XmlReader::relaxNGValidate()

Argument

Description

string $relaxng

The RelaxNG schema to use to validate the XML string while parsing.


Table 4.823. Exceptions thrown by XmlReader::relaxNGValidate()

err

desc

XMLREADER-RELAXNGVALIDATE-ERROR

missing or invalid argument

XMLREADER-RELAXNG-ERROR

invalid RelaxNG schema or method called after the first call to XmlReader::read()

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constant HAVE_PARSEXMLWITHRELAXNG before calling this function.


4.35.41. XmlReader::schemaValidate()

Synopsis

Set an XSD schema for schema validation while parsing the XML document. This method must be called before the first call to XmlReader::read()

The availability of this function depends on the presence of libxml2's xmlTextReaderSchemaValidate() function when Qore was compiled; for maximum portability check the constant HAVE_PARSEXMLWITHSCHEMA before calling this method. See Library Option Constants for a list of all option constants.

If any errors occur, an exception is thrown (see below).

Prototype

XmlReader::schemaValidate(string $xsd) returns nothing

Example
$xmlreader.schemaValidate($xsd);

Table 4.824. Arguments for XmlReader::schemaValidate()

Argument

Description

string xsd

The XSD schema to use to validate the XML string while parsing.


Table 4.825. Exceptions thrown by XmlReader::schemaValidate()

err

desc

XMLREADER-SCHEMAVALIDATE-ERROR

missing or invalid argument

XMLREADER-XSD-ERROR

invalid RelaxNG schema or method called after the first call to XmlReader::read()

MISSING-FEATURE-ERROR

This exception is thrown when the function is not available; for maximum portability, check the constan t HAVE_PARSEXMLWITHSCHEMA before calling this function.


Chapter 5. Command-Line Parsing

Qore will scan the command-line for the options in the following table. Arguments after the script name will be passed to the script in the global $ARGV variable as a list of options. $ARGV[0] will be the first option and will not be the script name. If no script name is given and the --exec option is not used, then Qore code is read from standard input.

qore [options] script.q

Table 5.1. Parse Option Command-Line Parameters

Long Param

Short

Description

--load=arg

-l

Loads a module immediately. The argument can be a module/feature name or an absolute path to the module.

--no-global-vars

-G

Disallows the use of global variables. Equivalent to parse option PO_NO_GLOBAL_VARS and the %no-global-vars directive.

--no-subroutine-defs

-S

Disallows subroutine (function) definitions. Equivalent to parse option PO_NO_SUBROUTINE_DEFS and the %no-subroutine-defs directive.

--no-thread-control

-R

Disallows any thread control operations (background operator and thread_exit statement, for example). Equivalent to parse option PO_NO_THREAD_CONTROL and the %no-thread-control directive.

--no-thread-classes

n/a

Disallows access to thread classes (for example, the Thread::Mutex Class, Thread::Gate Class, Thread::Queue Class, etc). Equivalent to parse option PO_NO_THREAD_CLASSES and the %no-thread-classes directive.

--no-threads

-T

Disallows access to both thread control and thread classes (equivalent to the --no-thread-control and --no-thread-classes options documented above). Equivalent to parse option PO_NO_THREADS and the %no-threads directive.

--no-top-level

-L

Disallows top level code. Equivalent to parse option PO_NO_TOP_LEVEL_STATEMENTS and the %no-top-level directive.

--no-class-defs

n/a

Disallows class definitions. Equivalent to PO_NO_CLASS_DEFS and the %no-class-defs directive.

--no-namespace-defs

-D

Disallows new namespace definitions. Equivalent to PO_NO_NAMESPACE_DEFS and the %no-namespace-defs directive.

--no-external-process

-E

Disallows any access to external processes (with system(), backquote(), exec(), the backquote operator, etc). Equivalent to parse option PO_NO_EXTERNAL_PROCESS and the %no-external-process directive.

--no-process-control

-P

Disallows access to functions that would affect the current process (exit(), fork(), etc). Equivalent to parse option PO_NO_PROCESS_CONTROL and the %no-process-control directive.

--no-filesystem

-F

Disallows access to the local filesystem; puts the no-filesystem parse option in effect. Equivalent to parse option code PO_NO_FILESYSTEM and the %no-filesystem parse directive.

--no-constant-defs

n/a

Disallows constant definitions. Equivalent to parse option PO_NO_CONSTANT_DEFS and the %no-constant-defs directive.

--no-network

-Y

Disallows access to the network; puts the no-network parse option in effect. Equivalent to parse option code PO_NO_NETWORK and the %no-network parse directive.

--no-new

-N

Disallows use of the new operator. Equivalent to parse option PO_NO_NEW and the %no-new directive.

--no-database

-D

Disallows use of database functionality. Equivalent to parse option PO_NO_DATABASE and the %no-database directive.

--no-child-restrictions

-I

Allows child program objects to have parse option restrictions that are not a strict subset of the parents. Equivalent to parse option PO_NO_CHILD_PO_RESTRICTIONS and the %no-child-restrictions directive.

--require-our

-O

Requires global variables to be declared with our prior to use (similar to perl's use strict vars pragma). Equivalent to parse option PO_REQUIRE_OUR and the %require-our directive.

--lock-options

-K

Prohibits further changes to parse options (equivalent to the %lock-options directive).

--lock-warnings

-A

Prohibits further changes to the warning mask. Equivalent to parse option PO_LOCK_WARNINGS and the %lock-warnings directive.

--enable-all-warnings

-W

Enables all warnings. Equivalent to the %enable-all-warnings directive.

--enable-warning=arg

-w

Enables the named warning. Equivalent to the %enable-warning directive.

--list-warnings

-i

Lists all valid warnings in Qore and exits immediately.


Table 5.2. Miscellaneous Command-Line Parameters

Long Param

Short

Description

--exec=ARG

-e

parses and executes the argument text as a Qore program. If this option is specified then any script given on the command-line will be ignored.

--exec-class[=ARG]

-x

parses and executes the argument text as a Qore program, instantiating the class with the same name as the program (with the directory path and extension stripped); also turns on --no-top-level. If the program is read from stdin or from the command-line, an argument must be given specifying the class name.

--show-module-errors

-m

Shows any errors loading Qore modules

--charset=ARG

-c

Sets the default character encoding for the program

--show-charset=ARG

Shows a list of all known character encodings

--show-aliases

Shows a list of all known character encoding aliases

--help

-h

Shows help text

--version

-v

Shows program version information and exits


There are two additional options available with debugging versions of Qore as follows:

Table 5.3. Description of Debugging Command-Line Parameters

Long Param

Short

Description

--debug=<arg>

-d<arg>

Turns on Qore debugging output. Higher arg numbers give more output. This option is only available with DEBUG builds.

--trace

-t

Turns on Qore tracing. This option is only available with DEBUG builds.


Chapter 6. Parse Directives

Qore supports the use of parse directives in order to set parsing options, load modules, control warnings, and include other files. Parse directives that set parsing options can be used any time parse options have not been locked on a Program object. They are used most often when it's not possible or desirable to set the parse options in the qore command-line.

Table 6.1. Parse Directives

Directive

Description

%disable-all-warnings

Turns off all warnings

%disable-warning warning-code

Disables the named warning until %enable-warning is encountered with the same code or %enable-all-warnings is encountered

%enable-all-warnings

Turns on all warnings

%enable-warning warning-code

Enables the named warning.

%exec-class class name

Instantiates the named class as the application class. Also turns on %no-top-level. If the program is read from stdin or from the command-line, an argument must be given specifying the class name.

%include file_name

Starts parsing file_name immediately. Parsing resumes with the current input after file_name has been completely parsed.

%lock-options

Prohibits further changes to parse options (equivalent to the --lock-options command-line option).

%lock-warnings

Prohibits further changes to the warning mask (equivalent to the --lock-warnings command-line option).

%no-class-defs

Disallows class definitions. Equivalent to PO_NO_CLASS_DEFS and the --no-class-defs command-line option.

%no-child-restrictions

Allows child program objects to have parse option restrictions that are not a strict subset of the parents'. Equivalent to parse option PO_NO_CHILD_PO_RESTRICTIONS and the --no-child-restrictions command-line option.

%no-constant-defs

Disallows constant definitions. Equivalent to parse option PO_NO_CONSTANT_DEFS and the --no-constant-defs command-line option.

%no-database

Disallows access to database functionality (for example the Datasource class. Equivalent to parse option PO_NO_DATABASE and the --no-database command-line option.

%no-external-info

Disallows any access to functionality that provides external information (see %no-external-info for a list of features not available with this parse option). Equivalent to parse option PO_NO_EXTERNAL_INFO and the --no-external-info command-line option.

%no-external-process

Disallows any access to external processes (see %no-external-process for a list of features not available with this parse option). Equivalent to parse option PO_NO_EXTERNAL_PROCESS and the --no-external-process command-line option.

%no-filesystem

Disallows access to the local filesystem. Equivalent to parse option PO_NO_FILESYSTEM and the --no-filesystem command-line option.

%no-global-vars

Disallows the use of global variables. Equivalent to parse option PO_NO_GLOBAL_VARS and the --no-global-vars command-line option.

%no-gui

Disallows functionality that draws graphics to the display. Equivalent to parse option PO_NO_GUI and the -pno-gui command-line option.

%no-locale-control

Disallows access to functionality that changes locale information (see %no-locale-control for a list of features not available with this parse option). Equivalent to parse option PO_NO_LOCALE_CONTROL and the --no-locale-control command-line option.

%no-namespace-defs

Disallows new namespace definitions. Equivalent to PO_NO_NAMESPACE_DEFS and the --no-namespace-defs command-line option.

%no-network

Disallows access to the network. Equivalent to parse option PO_NO_NETWORK and the --no-network command-line option.

%no-new

Disallows use of the new operator. Equivalent to parse option PO_NO_NEW and the --no-new command-line option.

%no-process-control

Disallows access to functions that would affect the current process (see %no-process-control for a list of features not available with this parse option). Equivalent to parse option PO_NO_PROCESS_CONTROL and the --no-process-control command-line option.

%no-subroutine-defs

Disallows subroutine (function) definitions. Equivalent to parse option PO_NO_SUBROUTINE_DEFS and the --no-subroutine-defs command-line option.

%no-terminal-io

Disallows access to terminal I/O (see %no-terminal-io for a list of features not available with this parse option). Equivalent to parse option PO_NO_TERMINAL_IO and the -pno-terminal-io command-line option.

%no-thread-classes

Disallows access to thread classes (see %no-thread-classes for a list of features not available with this parse option). Equivalent to parse option PO_NO_THREAD_CLASSES and the --no-thread-classes command-line option.

%no-thread-control

Disallows access to thread control operations (see %no-thread-control for a list of features not available with this parse option). Equivalent to parse option PO_NO_THREAD_CONTROL and the --no-thread-control command-line option.

%no-thread-info

Disallows any access to functionality that provides threading information (see %no-thread-info for a list of features not available with this parse option). Equivalent to parse option PO_NO_THREAD_INFO and the --no-thread-info command-line option.

%no-threads

Disallows access to all thread control operations and thread classes (equivalent to --no-thread-control and --no-thread-classes together). Equivalent to parse option PO_NO_THREADS and the --no-threads command-line option.

%no-top-level

Disallows top level code. Equivalent to parse option PO_NO_TOP_LEVEL_STATEMENTS and the --no-top-level command-line option.

%require-our

Requires global variables to be declared with our prior to use (like perl's use strict vars pragma). Equivalent to parse option PO_REQUIRE_OUR and the --require-our command-line option.

%require-prototypes

Requires type declarations for all function and method parameters and return types. Variables and object members do not need to have type declarations. Equivalent to parse option PO_REQUIRE_PROTOTYPES and the --require-prototypes command-line option.

%require-types

Requires type declarations for all function and method parameters, return types, variables, and object members. Equivalent to parse option PO_REQUIRE_TYPES and the --require-types command-line option. Implies also %strict-args.

%requires feature [<|<=|=|>=|> <version>]

If the named feature is not already present in Qore, then the QORE_MODULE_DIR environment variable is used to provide a list of directories to seach for a module with the same name (feature.qmod). If the module is not found, then the qore default module directory is checked. This directive must be used to load modules providing parse support (i.e. modules providing classes, constants, functions, etc that are resolved at parse time). If version information is provided, then it is compared with the module's version information, and if it does not match a parse exception is raised. See also load_module() for a run-time module loading.

%strict-args

Prohibits access to builtin functions and methods flagged with RT_NOOP and also causes errors to be raised if excess arguments are given to functions that do not access excess arguments.


6.1. disable-all-warnings

Parse Directive

%disable-all-warnings

Command-Line

none, warnings are disabled by default

Parse Option Constant

n/a

Description

Disables all warnings while parsing. See Warnings for more information.

6.2. disable-warning

Parse Directive

%disable-warning

Command-Line

none, warnings are disabled by default

Parse Option Constant

n/a

Description

Disables the named warning while parsing. See Warnings for more information.

6.3. enable-all-warnings

Parse Directive

%enable-all-warnings

Command-Line

--enable-all-warnings, -W

Parse Option Constant

n/a

Description

Enables all warnings while parsing. See Warnings for more information.

6.4. enable-warning

Parse Directive

%enable-warning

Command-Line

--enable-warning, -w

Parse Option Constant

n/a

Description

Enables the named warning while parsing. See Warnings for more information.

6.5. exec-class

Parse Directive

%exec-class

Command-Line

--exec-class, -x

Parse Option Constant

n/a

Description

Executes the named class as the application class and turns on no-top-level as well.

6.6. include

Parse Directive

%include

Command-Line

n/a from the command-line

Parse Option Constant

n/a

Description

Includes a file to be parsed. If the path is not absolute (i.e. starting with '/'), then files are searched first in the directory of the currently-executing script (if known), then in each path in the environment variable QORE_INCLUDE_DIR.

6.7. lock-options

Parse Directive

%lock-options

Command-Line

--lock-options, -K

Parse Option Constant

n/a

Description

Prohibits further changes to parse options.

6.8. lock-warnings

Parse Directive

%lock-warnings

Command-Line

--lock-warnings, -A

Parse Option Constant

PO_LOCK_WARNINGS

Description

Prohibits further changes to the warning mask.

6.9. no-child-restrictions

Parse Directive

%no-child-restrictions

Command-Line

--no-child-restrictions, -I

Parse Option Constant

PO_NO_CHILD_PO_RESTRICTIONS

Description

Allows child program objects to have parse option restrictions that are not a strict subset of the parents'.

6.10. no-class-defs

Parse Directive

%no-class-defs

Command-Line

--no-class-defs

Parse Option Constant

PO_NO_CLASS_DEFS

Description

Disallows new class definitions. Any use of the reserved word class will result in a parse exception.

6.11. no-constant-defs

Parse Directive

%no-constant-defs

Command-Line

--no-constant-defs

Parse Option Constant

PO_NO_CONSTANT_DEFS

Description

Disallows new constant definitions. Any use of the reserved word const will result in a parse exception.

6.12. no-database

Parse Directive

%no-database

Command-Line

--no-database, -D

Parse Option Constant

PO_NO_DATABASE

Description

Disallows access to database functionality. Currently this means that access to the Datasource and DatasourcePool classes is restricted.

6.13. no-external-info

Parse Directive

%no-external-info

Command-Line

--no-external-info

Parse Option Constant

PO_NO_EXTERNAL_INFO

Description

Disallows any access to functionality that provides external information.


6.14. no-external-process

Parse Directive

%no-external-process

Command-Line

--no-external-process, -E

Parse Option Constant

PO_NO_EXTERNAL_PROCESS

Description

Disallows any access to external processes.

Table 6.3. Unavailable Features with no-external-process


6.15. no-filesystem

Parse Directive

%no-filesystem

Command-Line

--no-filesystem, -F

Parse Option Constant

PO_NO_FILESYSTEM

Description

Disallows any access to the external filesystem.


6.16. no-global-vars

Parse Directive

%no-global-vars

Command-Line

--no-global-vars, -G

Parse Option Constant

PO_NO_GLOBAL_VARS

Description

Disallows the use of global variables.

6.17. no-gui

Parse Directive

%no-gui

Command-Line

--no-gui, --set-parse-option=no-gui, -pno-gui

Parse Option Constant

PO_NO_GUI

Description

Disallows the use of functionality that draws graphics to the display (this functionality is not implemented in the qore library; only implemented in modules).

6.18. no-locale-control

Parse Directive

%no-locale-control

Command-Line

--no-locale-control, -P

Parse Option Constant

PO_NO_LOCALE_CONTROL

Description

Disallows access to functions that would affect the current process.

Table 6.5. Unavailable Features with no-locale-control

Feature/Function

TimeZone::set() static method

TimeZone::setUTCOffset() static method

TimeZone::setRegion() static method


6.19. no-namespace-defs

Parse Directive

%no-namespace-defs

Command-Line

--no-namespace-defs, -M

Parse Option Constant

PO_NO_NAMESPACE_DEFS

Description

Disallows new namespace definitions.

6.20. no-network

Parse Directive

%no-network

Command-Line

--no-network, -Y

Parse Option Constant

PO_NO_NETWORK

Description

Disallows any access to the network.

Table 6.6. Unavailable Features with no-network

Feature/Function

FtpClient class

HTTPClient class

XmlRpcClient class

JsonRpcClient class

Socket class


6.21. no-new

Parse Directive

%no-new

Command-Line

--no-new, -N

Parse Option Constant

PO_NO_NEW

Description

Disallows use of the new operator.

6.22. no-process-control

Parse Directive

%no-process-control

Command-Line

--no-process-control, -P

Parse Option Constant

PO_NO_PROCESS_CONTROL

Description

Disallows access to functions that would affect the current process.


6.23. no-subroutine-defs

Parse Directive

%no-subroutine-defs

Command-Line

--no-subroutine-defs, -S

Parse Option Constant

PO_NO_SUBROUTINE_DEFS

Description

Disallows subroutine (function) definitions.

6.24. no-terminal-io

Parse Directive

%no-terminal-io

Command-Line

--no-terminal-io, --set-parse-option=no-terminal-io, -pno-terminal-io

Parse Option Constant

PO_NO_TERMINAL_IO

Description

Disallows access to terminal input and output.

Table 6.8. Unavailable Features with no-terminal-io


6.25. no-thread-classes

Parse Directive

%no-thread-classes

Command-Line

--no-thread-classes

Parse Option Constant

PO_NO_THREAD_CLASSES

Description

Disallows access to thread classes.

Table 6.9. Unavailable Features with no-thread-classes

Feature/Function

AutoGate class

AutoLock class

AutoReadLock class

AutoWriteLock class

Condition class

Counter class

Mutex class

Queue class

RWLock class


6.26. no-thread-control

Parse Directive

%no-thread-control

Command-Line

--no-thread-control, -R

Parse Option Constant

PO_NO_THREAD_CONTROL

Description

Disallows access to thread control operations.


6.27. no-thread-info

Parse Directive

%no-thread-info

Command-Line

--no-thread-info

Parse Option Constant

PO_NO_THREAD_INFO

Description

Disallows access to functionality that provides information about threading.

Table 6.11. Unavailable Features with no-thread-info

Feature/Function

gettid() function

num_threads() function

thread_list() function

get_thread_data() function

get_all_thread_data() function

getAllThreadCallStacks() function


6.28. no-threads

Parse Directive

%no-threads

Command-Line

--no-threads, -T

Parse Option Constant

PO_NO_THREADS

Description

Disallows access to all thread control operations and thread classes (equivalent to no-thread-control and no-thread-classes together).

6.29. no-top-level

Parse Directive

%no-top-level

Command-Line

--no-top-level, -L

Parse Option Constant

PO_NO_TOP_LEVEL_STATEMENTS

Description

Disallows top level code.

6.30. require-our

Parse Directive

%require-our

Command-Line

--require-our, -O

Parse Option Constant

PO_REQUIRE_OUR

Description

Requires global variables to be declared with our prior to use (recommended to use for all larger scripts/programs).

6.31. require-prototypes

Parse Directive

%require-prototypes

Command-Line

--require-prototypes

Parse Option Constant

PO_REQUIRE_PROTOTYPES

Description

Requires type declarations for all function and method parameters and return types. Variables and object members do not need to have type declarations with this option.

See also require-types, which is a superset of this option.

6.32. require-types

Parse Directive

%require-types

Command-Line

--require-types

Parse Option Constant

PO_REQUIRE_TYPES

Description

Requires type declarations for all function and method parameters, return types, variables, and object members.

See also require-prototypes, which is a subset of this option.

6.33. requires

Parse Directive

%requires

Command-Line

--load, -l

Parse Option Constant

n/a

Description

Loads a Qore module immediately. The parse directive can be used to load a module during parsing, and the command-line version can be used to load a module before parsing.

From Qore 0.7.1, you can specify a comparison operator (one of < <=, =, >=, or >) and version information after the module name as well. Version numbers are compared via integer comparisons of each element, where elements are separated by a '.'. If one of the versions does not have as many elements as another, the missing elements are assumed to be '0' (i.e. version "1.0" compared with version "1.0.1" will be exteneded to "1.0.0").

For example:

%requires oracle >= 1.0.1

This will load the oracle module if it is at least version 1.0.1.

Note that there is one special feature name: "qore". This pseudo-feature can be used to check the minimum qore version; if this feature is requested with version information, then the Qore library's version information is used for the version number comparison.

6.34. strict-args

Parse Directive

%strict-args

Command-Line

--strict-args

Parse Option Constant

PO_STRICT_ARGS

Description

Prohibits access to builtin functions and methods flagged with RT_NOOP and also causes errors to be raised if excess arguments are given to functions that do not access excess arguments.

Chapter 7. Warnings

Warnings give the programmer information about possible errors in qore code.

Warnings can be enabled using the -W command-line option (see Command-Line Parsing for more information) or by using the %enable-all-warnings or %enable-warning parse directives.

Note that parsing is done in two stages, so if a warning is enabled when the second stage of parsing begins, the warning can be generated anywhere in the source code. Parse directives are processed in the first stage of parsing. In other words, for warnings only raised in the second stage of parsing, it is not possible to turn on and turn off these warnings for specific code blocks within a section of text being parsed.

Table 7.1. Warnings

Warning Code

First In

Description

duplicate-local-vars

0.5.2

This warning is raised when the same local variable is declared more than once within the same lexical scope.

warning-mask-unchanged

0.5.2

This warning is raised when a program tries to change the warning mask with parse options, but the warnings are locked.

unknown-warning

0.5.2

This warning is raised when a program tries to enable or disable an unknown warning.

undeclared-var

0.5.2

This warning is raised when a program uses a variable that has not been declared with my or our.

duplicate-global-vars

0.5.2

Raised when a program declares a global variable more than once.

unreachable-code

0.5.2

Raised when code is defined that can never be executed (for example, code following a return or thread_exit statement).

non-existent-method-call

0.8.0

Warning is raised when the given method cannot be found in the class at parse time; this is a warning because the object could be a subclass that has the given method implemented, in which case the call will succeed at run time. Use the cast<>() operator to avoid this warning.

invalid-operation

0.8.0

Raised when the parser determins that the types of an operation are such that the operation is guaranteed to produce no value; this warning can only be raised when type information is available at parse time.

call-with-type-errors

0.8.0

Raised when the parser determines that the argument types of a function or method call are such that the operation is guaranteed to produce a constant value.

return-value-ignored

0.8.0

Raised when a function or method call is made with no side effects and the return value is ignored.

deprecated

0.8.0

Raised when deprecated functionality is accessed.

excess-args

0.8.0

Raised when a function or method call is made with more arguments than are used by the function or method.

duplicate-hash-key

0.8.0

Raised when an immediate hash is declared and at least one of the keys is repeated.


Chapter 8. Appendix A: List of Keywords

The following is a list of all keywords in the Qore language that may not be used as funciton or method names and also may not be used as unquoted hash or object member names with the "." operator:

by, break, catch, const, context, continue, do, else, for, foreach, if, in, inherits, instanceof, namespace, my, NOTHING, NULL, on_error, on_exit, on_success, our, rethrow, return, sortBy, sortDescendingBy, sub, subcontext, summarize, switch, synchronized, thread_exit, throw, try, where, while

The following are special keywords, in that a parser trick is used allowing them to be used as function or method names if they are followed immediately by an open parenthesis (with no whitespace between the keyword and the open parenthesis), and they may be referenced as unquoted object or hash member names if they are immediately preceded by the "." operator (again with no whitespace between the "." and the keyword):

background, case, chomp class, delete, exists, foldl, foldr, map, pop, private, push, new, select, shift, splice, trim, unshift

The following are special keywords, in that a parser trick is used allowing them to be used as function or method names if they are followed by an open parenthesis (in the case of these keywords, it is permissable to have whitespace between the keyword and the open parenthesis), and they may be referenced as unquoted object or hash member names if they are immediately preceded by the "." operator (again with no whitespace between the "." and the keyword):

default, static

The following are special keywords, in that they may be referenced as unquoted object or hash member names if preceded immediately by the "." operator, however they may not be used as function or class method names:

elements, find, keys,

Chapter 9. Appendix B: Known Bugs

Out of memory errors are not always captured. Internal support for trapping these conditions in the C++ new operator must be developed.

Chapter 10. Appendix D: Future Development

In general, Qore's main development target is to provide a stable, powerful, and efficient platform for developing complex programs. Backwards compatibility is a very high priority, even for versions before 1.0, and "unrestricted" code (code not subect to parse restrictions) should remain highly compatible until 1.0 and beyond.

There is no stable list of features that need to be there before the 1.0 release; Qore is getting better, cleaner, and more powerful with each release, so sooner or later 1.0 will happen.

Colophon

This document was first drafted with OpenOffice.org, then converted to docbook XML by Helmut Wollmersdorfer, then edited by hand with Emacs.