Qore v0.8.3

Programming Language Reference Manual

David Nichols

Helmut Wollmersdorfer

v. 0.8.3

Revision History
Revision 3.36 March 2011dn
Update to 0.8.3
Revision 3.226 December 2010dn
Update to 0.8.2
Revision 3.115 June 2010dn
Update to 0.8.1
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. Conditional Parsing and Parse Defines
2.4. Qore Modules
2.5. Include Files
2.6. Identifiers
2.7. Comments
2.8. Variables
2.9. Basic Data Types
2.10. Container Data Types
2.11. Data Type Declarations
2.12. Time Zone Handling in Qore
2.13. Qore Strings and Character Encoding
2.14. Expressions
2.15. Operators
2.16. Regular Expressions in Qore
2.17. Date/Time Arithmetic
2.18. Statements
2.19. Functions
2.20. Namespaces
2.21. Constants
2.22. Classes
2.23. Threading
2.24. Exception Handling
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. Debug Functions
3.15. 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. SSLPrivateKey Class
4.12. SSLCertificate Class
4.13. TimeZone Class
4.14. SQL Constants
4.15. SQL::Datasource Class
4.16. SQL::DatasourcePool Class
4.17. SQL::SQLStatement Class
4.18. Thread::AbstractSmartLock Class
4.19. Thread::AutoGate Class
4.20. Thread::AutoLock Class
4.21. Thread::AutoReadLock Class
4.22. Thread::AutoWriteLock Class
4.23. Thread::Condition Class
4.24. Thread::Counter Class
4.25. Thread::Queue Class
4.26. Thread::RWLock Class
4.27. Thread::Mutex Class
4.28. Thread::RMutex Class
4.29. Thread::Sequence Class
4.30. Thread::Gate Class
5. Command-Line Parsing
6. Parse Directives
6.1. allow-bare-refs
6.2. assume-local
6.3. define
6.4. disable-all-warnings
6.5. disable-warning
6.6. else
6.7. enable-all-warnings
6.8. enable-warning
6.9. endif
6.10. exec-class
6.11. ifdef
6.12. ifndef
6.13. include
6.14. lock-options
6.15. lock-warnings
6.16. new-style
6.17. no-child-restrictions
6.18. no-class-defs
6.19. no-constant-defs
6.20. no-database
6.21. no-external-info
6.22. no-external-process
6.23. no-filesystem
6.24. no-global-vars
6.25. no-gui
6.26. no-locale-control
6.27. no-namespace-defs
6.28. no-network
6.29. no-new
6.30. no-process-control
6.31. no-subroutine-defs
6.32. no-terminal-io
6.33. no-thread-classes
6.34. no-thread-control
6.35. no-thread-info
6.36. no-threads
6.37. no-top-level
6.38. require-our
6.39. require-prototypes
6.40. require-types
6.41. requires
6.42. set-time-zone
6.43. 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 home page.

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).

  • Function and Class Library

    Qore's basic functionality covers areas such as: POSIX-compliant command-line parsing (ex: GetOpt Class), 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, 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 function declarations.

Chapter 2. Qore Language Description

2.1. Language Overview

A Qore program is composed of a series of declarations, statements, function 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 created as a weakly typed language. That means that variables (without type restrictions) can hold values of any type and functions (without a return type restriction or parameter type descriptions) 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 also allows variable, parameter, class member, and return types to be declared, so that APIs can be formally defined or the programmer can decide to declare types to catch more errors at parse time (which is often preferable to discovering a type error at runtime).

Qore can be used a a traditional function-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 functions, Qore also supports nested namespaces, classes, multiple inheritance, overriding base class constructor arguments, public and private members and methods, static class methods, and static class variables.

All elements of Qore are designed to work together seamlessly: database access, 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 executing Qore-language signal handlers in special single-handling thread.

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. Conditional Parsing and Parse Defines

Qore supports conditional parsing with parse defines similar to the C/C++ preprocessor. In the current version of Qore, the implementation is very simple; only the following parse directives are supported: %define, %else, %endif, %ifdef, and %ifndef.

Basically, the above allow for the existence (or lack thereof) of a parse define to affect which code is parsed into the program at parse time.

Parse defines are defined on the command-line (or through the C++ API when executed in embedded code), as well as created automatically based on sytem options; all library options (if the option is True, then it is defined as True, if the option is False, then it is not defined at all).

Note that Unix is defined on all Unix platforms (also on Cygwin), while Windows is defined on native Windows ports (but not on Cygwin, as this is treated as Unix when compiling, as all Unix features are available).

Additionally, the following options are defined in every program (however they are not yet useful when parsing as the value of parse options cannot be used yet at parse time; only the existence or lack thereof can affect parsing in this version of Qore when parsing at least):

  • QoreVersionString: Version string for the Qore library
  • QoreVersionMajor: Major version for the Qore library
  • QoreVersionMinor: Minor version for the Qore library
  • QoreVersionSub: Sub version for the Qore library
  • QoreVersionBuild: Build version for the Qore library
  • QoreVersionBits: 32 or 64 depending on the library target
  • QorePlatformCPU: The CPU targeted by the library
  • QorePlatformOS: The OS targeted by the library

Additionally, only if the Qore library was compiled with debugging support, the following parse define is present (otherwise it is not defined):

  • QoreDebug: True

Here is an example of using parse defines in a program:

%ifndef HAVE_TERMIOS
printf("This program requires UNIX TermIOS features to be present; it does not run on platforms without this feature (current platform: %s); exiting...\n", Qore::PlatformOS);
exit(1);
%endif

Furthermore, parse defines can be manipulated in embedded code using the following functions:

2.4. 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 onwards, 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 onwards, 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

xml

Provides XML, XPath, etc functionality to Qore.

xmlsec

Provides xmldsig and xmlenc functionality to Qore.

json

Provides JSON 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.5. 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, function, 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.6. 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.7. 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.8. Variables

Unless parse option %allow-bare-refs is set, variables are Qore identifiers prefixed by a "$" sign, similar to Perl. If a variable is declared without any type restriction, then it is assumed to have type any. In this case, variables so declared can hold any data type.

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 function or method arguments that were not assigned to parameter variables (see Functions 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.8.1. Variable Declarations and Lexical Scope

Unless the %assume-local parse directive is used, 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 function, method, or catch block. Global variables can be explicitly declared with our. The our keyword is required if the parse option %require-our (-O or --require-our command-line option) is set for the parent program. See the section on Parse Options for more information.

When the %assume-local parse directive is used, variables without an explicit scope declaration (i.e. my or our) are assumed to be local variables.

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 %require-types parse option is set.

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

Note

If parse option %allow-bare-refs is set, then variable references must be made without the "$" character.

2.9. 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.9.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.9.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.9.3. Integer

Qore integers are 64-bit signed integers.

2.9.4. Float

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

2.9.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.9.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.9.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.9.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, Datasource, DatasourcePool, or SQLStatement 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, DatasourcePool, and SQLStatement 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.9.7. NULL

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

2.9.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.9.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.10. 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.10.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.10.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, 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.10.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();

If parse option %new-style is set, the above example declaring a local variable of class Mutex would look as follows:

Mutex m();

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

new class_identifier([argument list])

For example:

my $m = new Mutex();

Or, with parse option %new-style:

Mutex 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 Class 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])

Or, with parse option %new-style, the method call is made without the "$.":

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 function 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.11. 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 as well as any class name or '*classname', meaning either the given class or NOTHING:

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.

timeout

Integer, Date

Integer

Accepts Integer, Date and converts dates to an integer value representing milliseconds and returns the integer; incoming integers are assumed to represent milliseconds.

softint

Integer, Float, Boolean, String, NULL

Integer

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

softfloat

Integer, Float, Boolean, String, NULL

Float

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

softbool

Integer, Float, Boolean, String, NULL

Boolean

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

softstring

Integer, Float, Boolean, String, NULL

String

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

softdate

Integer, Float, Boolean, String, Date, NULL

Date

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

softlist

all types

List

Accepts all types; NOTHING is returned as an empty list; a list is returned unchanged, and any other type is returned as the first element of a new list.

*int

Integer or NOTHING

same as received

Restricts values to Qore's Integer or NOTHING types.

*float

Float or NOTHING

same as received

Restricts values to Qore's Float or NOTHING types.

*bool

Boolean or NOTHING

same as received

Restricts values to Qore's Boolean or NOTHING types.

*string

String or NOTHING

same as received

Restricts values to Qore's String or NOTHING types.

*date

Date or NOTHING

same as received

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

*binary

Binary or NOTHING

same as received

Restricts values to Qore's Binary or NOTHING types.

*hash

Hash or NOTHING

same as received

Restricts values to Qore's Hash or NOTHING types.

*list

List or NOTHING

same as received

Accepts either a List or NOTHING.

*data

String, Binary, or NOTHING

same as received

Restricts input to String, Binary, or NOTHING and returns the same type.

*code

Closure, Call Reference or NOTHING

same as received

Restricts values to closures, call references and NOTHING.

*timeout

Integer, Date or NOTHING

Integer or NOTHING

Accepts Integer, Date and converts dates to an integer value representing milliseconds and returns the integer; incoming integers are assumed to represent milliseconds. If no value is passed, then NOTHING is returned.

*softint

Integer, Float, Boolean, String, NULL or NOTHING

Integer or NOTHING

Accepts Integer, Float, Boolean, String, NULL and converts non-integer values to an integer and returns the integer. If no value is passed, then NOTHING is returned.

*softfloat

Integer, Float, Boolean, String, NULL or NOTHING

Float or NOTHING

Accepts Integer, Float, Boolean, String, NULL and converts non-float values to a float and returns the new value. If no value is passed, then NOTHING is returned.

*softbool

Integer, Float, Boolean, String, NULL or NOTHING

Boolean or NOTHING

Accepts Integer, Float, Boolean, String, NULL and converts non-boolean values to a boolean and returns the new value. If no value is passed, then NOTHING is returned.

*softstring

Integer, Float, Boolean, String, NULL or NOTHING

String or NOTHING

Accepts Integer, Float, Boolean, String, NULL and converts non-string values to a string and returns the new value. If no value is passed, then NOTHING is returned.

*softdate

Integer, Float, Boolean, String, Date, NULL or NOTHING

Date or NOTHING

Accepts Integer, Float, Boolean, String, Date, and NULL and converts non-date values to a date and returns the new value. If no value is passed, then NOTHING is returned.

*softlist

all types

List or NOTHING

Accepts all types; NOTHING and list values are returned as the same value; any other type is returned as the first element of a new list.

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.11.1. Overloading

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

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

string sub example(string $str) {
    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.12. 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.13. Qore Strings and Character Encoding

2.13.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.13.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.13.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, DatasourcePool, and SQLStatement 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 class 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 of strings read from the server 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.

2.14. 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)

See also parse option %allow-bare-refs.

$var

A variable declaration

Qore variable declarations (see Variables for more information)

See also parse option %assume-local.

my int $var

An in-class object member reference

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

See also parse option %allow-bare-refs.

$.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 function call

Qore function calls (see Functions for more information)

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

A method call

Qore object method calls (see Object_Method_Calls for more information)

See also parse option %allow-bare-refs.

$object.method("argument")

An in-class method call

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

See also parse option %allow-bare-refs.

$.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() or SQLStatement::fetchColumns() 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.

string sub (string $a) { 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
$$

An implicit index reference

Gives the list index position when implicitly iterating a list.

$#

2.14.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.14.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() or SQLStatement::fetchColumns() methods). 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.14.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
my code $call_ref = \func_name();
$call_ref = \$object.method_name();

2.14.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

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

or the alternate syntax with the returns keyword after the parameters:

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 = int sub (int $a) { return $a + $b; };

2.14.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.6. Implicit Index

Synopsis

The current list index position when implicitly iterating through lists can be referenced using the implicit index reference characters: $#.

Syntax

$#

Description

The implicit index reference characters ($#) can be used whenever a list is iterated implicitly, such as with foreach statements and the map, foldl, foldr, and select operators.

Example
# create a list of indexes with negative values
my list $l = map $#, $list, ($1 < 0);

2.15. 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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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 element, the element is assigned NOTHING (i.e. the list size does not change).

The delete operator will delete multiple keys from a hash (i.e. delete a slice from a hash) when called on a hash dereferenced by a list of strings, giving the keys to delete (see example below).

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 a single key from a hash
delete $value;
# delete multiple values from a hash
delete $h.("a", "b", "c");

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

2.15.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, and the value returned is the value of the key removed from the hash; when called on a list element, the element is assigned NOTHING. (i.e. the list size does not change).

The remove operator will remove and return a slice from a hash when called on a hash dereferenced by a list of strings, giving the keys to remove (see example below).

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
# remove a single value from a hash
my any $var = remove $hash.value;
# remove a slice from a hash
my hash $nh = remove $h.("a", "b", "c");

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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.60. Extract Operator (extract)

Synopsis

Removes and optionally inserts elements in lists and strings. For a similar operator that only removes values 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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.15.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.16. 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.17. 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.17.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.17.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.17.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.17.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.17.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.18. 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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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.18.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() or SQLStatement::fetchColumns() methods), 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.18.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.18.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.18.16. return Statements

Synopsis

return statements causes the flow of execution of the function, 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 function, method, or program to cease and optionalls returns a value to the caller.

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

my string $name = getName();

2.18.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.18.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.18.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.19. Functions

A function is declared in Qore by using the key word sub (for subroutine) as follows:

[return_type] sub function_name([[type] variable1, ...]) {
    statements;
}
or the alternate syntax with the returns keyword:
sub function_name([[type] variable1, ...]) [returns type] {
    statements;
}

Variables listed in parentheses after the function name are the parameters to the function 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 function. Type declarations optionally precede the parameter variable and will restrict any arguments passed to the type declared. The same function can be declared multiple times if each declaration has different parameter types; this is called overloading the function.

Functions use the return statement to provide a return value. Function names must be valid Qore identifiers.

The return type of the function can be given by placing a type declaration before the sub keyword (the older syntax with the returns keyword after the parameter list is still accepted as well).

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 function 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.

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

return expression;

Here is an example function declaration returning a value:

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

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

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

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

int sub fibonacci(int $num) {
    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.20. 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.20.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.20.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.20.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.21. 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

As of Qore 0.8.1 and onwards, the expression used to initialize a constant can be any valid Qore expression as long as no variables are referenced. Note that the order that constants are initialized and assigned does not necessarily correspond to the declaration order, and it is bad programming practice to assign a constant with an expression that has side effects. Furthermore if an expression used to initialize a constant throws an exception, that exception cannot be caught.

Classes can also declare constants; see class constants for more information.

2.22. 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];
	[static [type] var_name [ = expr];
	[const const_name = expr;
	...
    }]

    [public {
        [type] $.member_name [ = expr];
	[static [type] var_name [ = expr];
	[const const_name = expr;
	...
    }]

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

Alternatively class declarations and method declarations 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;
}

Note that when parse option %allow-bare-refs is enabled, no "$" or "$." prefixes can be used with variable or method or member names as in the specifications above.

Class members, class constants, and static class variables 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.22.1. Class Methods

2.22.1.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.22.1.2. Static Methods

Methods declared with the static keyword are like regular functions 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 methods may be declared private or public like non-static methods.

Static method calls take a special syntax as documented here.

2.22.1.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 constructors 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.

any memberGate(string $name)

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.

any methodGate(string $name)

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.22.2. Class Constants

Class constants, like non-class constants, allow programmers to refer to values with Qore identifiers rather than using the value or the expression that generates the value.

See Class Definition Syntax for a description of the syntax required to declare a class constant.

Like other attributes of classes, class constants may be declared private or public. The following is an example of a class constant definition:

class Test {
    public {
        const Version = "1.0";
    }

    private {
        const Limit = 100;
    }
}

Note

Note that a class constant cannot have the same same as a static class variable.

2.22.3. Static Class Variables

Static class variables are like global variables that belong to a class. They are not associated with any particular object.

See Class Definition Syntax for a description of the syntax required to declare a static class variable.

Like other attributes of classes, static class variables may be declared private or public. The following is an example of a static class variable definition:

class Test {
    public {
        static string lastFile = "none";
    }

    private {
        static int numProcessed = 0;
    }
}

Note

Static class variables cannot have the same same as a class constant.

2.22.4. Class Members

When defining a class, members of instantiated objects are 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.22.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 made 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();

When the %allow-bare-refs parse directive is set, then object methods are called without the '$.' prefix as in the following example:

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

Calls to object methods can be made outside the class by using the above syntax as well. If the object's class is not known at parse time, then the call is resolved at run-time, and if a call is attempted 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 is raised.

2.22.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.22.7. Object References

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 (similar to Java's handling of objects). 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");
}

Note that when parse option %allow-bare-refs is set, then variable references as in the above examples are made without the "$" character.

2.22.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.22.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.23. 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.23.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 functions 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.23.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.23.3. Thread Synchronization and Inter-Thread Communication

The synchronized keyword can be used before function 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.23.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 functions, 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.24. 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 function 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.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.98. 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, FtpClient, and File 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.99. 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.100. 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.101. 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.102. 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.103. 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.104. 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.105. 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.106. 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.107. 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.108. 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.109. 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.110. 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.111. 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.112. 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.113. 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.114. 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.115. 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.116. 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.117. 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.118. 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.119. 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.120. 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.121. 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.122. 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.123. 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.124. 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

This flag indicates that the function or method has no side effects and does not throw any exceptions (see also RET_VALUE_ONLY).

RET_VALUE_ONLY

This flag indicates that the function or method has no side effects but could throw an exception (see also CONST).

DEPRECATED

Code with this flag is deprecated and may 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

nothing abort()

N

aborts the process

float abs(softfloat)

int abs(int)

float abs() (RT_NOOP)

N

Returns the absolute value of the argument passed

float acos(any)

N

Returns the arc cosine of the number passed in radians

float asin(softfloat)

float asin() (RT_NOOP)

N

Returns the arc sine of the number passed in radians.

float atan(softfloat)

float atan() (RT_NOOP)

N

Returns the arc tangent of the number passed in radians.

string backquote(string)

nothing backquote() (RT_NOOP)

Y

Executes a process and returns a string of the output (stdout only)

string basename(string)

nothing basename() (RT_NOOP)

N

Returns a string giving the last element of a file path.

binary binary(softstring) (CONST)

binary binary(binary) (CONST)

binary binary(null) (CONST)

binary binary() (CONST)

N

Returns a binary data type of the data passed.

string binary_to_string(binary)

string binary_to_string(binary, string)

Y

Returns a string created from the binary data passed.

int bindex(softstring, softstring, softint = 0)

int bindex() (RT_NOOP)

N

Returns the byte position of a substring within a string and takes an optional starting offset

binary blowfish_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for the blowfish algorithm.

binary blowfish_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the blowfish algorithm.

string blowfish_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for the blowfish algorithm.

bool boolean(softbool) (CONST)

bool boolean(null) (CONST)

bool boolean() (CONST)

N

Converts the argument to a boolean value.

int brindex(softstring, softstring, softint = -1)

int brindex() (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

binary bunzip2_to_binary(binary)

nothing bunzip2_to_binary() (RT_NOOP)

Y

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary.

string bunzip2_to_string(binary, string = defaultEncoding)

nothing bunzip2_to_string() (RT_NOOP)

Y

Uncompresses the given data with the bzip2 algorithm and returns the uncompressed data as a string.

binary bzip2(data, softint = 9)

nothing bzip2() (RT_NOOP)

Y

Compresses the given data with the bzip2 algorithm and returns the uncompressed data as a binary.

any call_builtin_function(string, ...)

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

any call_builtin_function_args(string, list)

any call_builtin_function_args(string, 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.

any call_function(string, ...)

any call_function(code, ...)

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).

any call_function_args(string, list)

any call_function_args(string, any)

any call_function_args(code, list)

any call_function_args(code, 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.

any callObjectMethod(object, string)

nothing callObjectMethod() (RT_NOOP)

Y

calls a method given by a string of the object passed, passing the remaining arguments to the method as arguments

any callObjectMethodArgs(object, string, list)

any callObjectMethodArgs(object, string, any)

nothing callObjectMethodArgs() (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

binary cast5_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for the CAST5 algorithm.

binary cast5_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the CAST5 algorithm.

string cast5_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for the CAST5 algorithm.

float cbrt(softfloat)

float cbrt() (RT_NOOP)

N

Returns the cube root of the number passed.

float ceil(softfloat)

float ceil() (RT_NOOP)

N

Returns a value rounded up to the next highest integer

int chdir(string)

Y

Changes the current working directory.

int chmod(string, int)

Y

Changes the mode of a file.

string chomp(string)

any chomp(reference)

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.

int chown(string, softint = -1, softint = -1)

Y

Changes the user and group owners of a file (if the current user has permission to do so), follows symbolic links.

string chr(softint)

string chr(any) (NOOP)

nothing chr() (RT_NOOP)

N

Returns a string containing a single ASCII character represented by the numeric value passed.

int clock_getmicros() (CONST)

N

Returns the system time in microseconds (1/1000000 second intervals) since Jan 1, 1970 00:00:00Z.

int clock_getmillis() (CONST)

N

Returns the system time in milliseconds (1/1000 second intervals) since Jan 1, 1970 00:00:00Z.

int clock_getnanos() (CONST)

N

Returns the system time in nanoseconds (1/1000000000 second intervals) since Jan 1, 1970 00:00:00.

binary compress(data, softint = -1)

nothing compress() (RT_NOOP)

Y

Performs zlib-based "deflate" data compression (RFC 1951) and returns a binary object of the compressed data.

string convert_encoding(string, string) (CONST)

nothing convert_encoding() (RT_NOOP)

Y

Performs explicit string character encoding conversions.

float cos(softfloat) (CONST)

float cos() (RT_NOOP)

N

Returns the cosine of the number in radians passed.

float cosh(softfloat) (CONST)

float cosh() (RT_NOOP)

N

Returns the hyperbolic cosine of the number passed.

date date(string) (CONST)

date date(string, string) (CONST)

date date(softint) (CONST)

date date(null) (CONST)

date date() (CONST)

N

Converts the argument passed to a date.

hash date_info(date $date) (CONST)

hash date_info() (CONST)

N

Returns a hash of broken-down date/time information for the given date argument; if the variant with no argument is used, then the current date/time is assumed.

date date_ms(softint) (CONST)

date date_ms() (RT_NOOP)

N

Converts an integer argument as a millisecond offset from January 1, 1970Z to a date.

date date_us(softint) (CONST)

date date_us() (RT_NOOP)

N

Converts an integer argument as a microsecond offset from January 1, 1970Z to a date.

date days(softint) (CONST)

date days() (RT_NOOP)

N

Returns a relative date in days for date arithmetic.

string decode_url(string) (CONST)

nothing decode_url() (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.

nothing delete_thread_data(list)

nothing delete_thread_data(...)

N

Deletes the data associated to one or more keys in the thread-local data hash (destroys any objects as well).

binary des_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for the DES algorithm.

binary des_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the DES algorithm.

string des_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the DES algorithm.

binary des_ede_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm.

binary des_ede_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the two-key triple DES algorithm.

string des_ede_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for the two-key triple DES algorithm.

binary des_ede3_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm.

binary des_ede3_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for the three-key triple DES algorithm.

string des_ede3_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for the three-key triple DES algorithm.

binary desx_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm.

binary desx_decrypt_cbc(binary, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for RSA's DESX algorithm.

string desx_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Encrypts data to a string using the Cipher Block Chaining function for RSA's DESX algorithm.

string DSS(data)

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)

binary DSS_bin(data)

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)

string DSS1(data)

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)

binary DSS1_bin(data)

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)

int errno()

N

Returns the value of the system "errno" variable, holding the last error code generated by a system call

nothing exec(string)

nothing exec() (RT_NOOP)

N

Replaces the current process image with another.

bool existsFunction(string) (CONST)

bool existsFunction(code) (NOOP)

nothing existsFunction() (RT_NOOP)

N

Returns True if the function exists in the current program's function name space.

nothing exit(any = 0)

N

Exits the program

float exp(softfloat) (CONST)

float exp() (RT_NOOP)

N

Returns the value of e raised to the power of the argument passed

float exp2(softfloat) (CONST)

float exp2() (RT_NOOP)

N

Returns the value of 2 raised to the power of the argument passed

float expm1(softfloat) (CONST)

float expm1() (RT_NOOP)

N

Returns an equivalent of exp(x) - 1

string f_printf(string, ...)

string f_printf() (RT_NOOP)

Y

"field" printf, field width specifiers are respected. Returns string printed.

string f_sprintf(string, ...) (CONST)

string f_sprintf() (RT_NOOP)

Y

"field" sprintf(), field width specifiers are respected

float float(softfloat) (CONST)

float float(null) (CONST)

float float() (CONST)

N

Returns the argument converted to a floating-point number

float floor(softfloat) (CONST)

float floor() (RT_NOOP)

N

Returns a value rounded down to the nearest integer

nothing flush()

N

Flushes output to the console output with print(), printf(), etc

string force_encoding(string, string) (CONST)

nothing force_encoding() (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.

int fork()

Y

Creates a duplicate of the current process

string format_date(string, date) (CONST)

nothing format_date() (RT_NOOP)

N

Allows dates to be formatted

string format_number(string, any) (CONST)

nothing format_number() (RT_NOOP)

N

Allows numbers to be formatted with more options than sprintf()

*string functionType(string) (CONST)

nothing functionType() (RT_NOOP)

N

Returns "builtin", "user", or NOTHING according to the function name passed

hash get_all_thread_data() (CONST)

N

Returns the entire thread data hash.

*int get_byte(data, int = 0) (CONST)

N

Returns the byte value at the given byte offset or NOTHING if the offset is not legal for the given data.

int get_days(date) (CONST)

nothing get_days() (RT_NOOP)

N

Returns an integer value representing the days value of the date passed (can be either a relative or absolute date).

string get_default_encoding() (CONST)

N

Returns the name of the default character encoding for the Qore library.

int get_duration_microseconds(date) (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.

int get_duration_milliseconds(date) (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.

int get_duration_seconds(date) (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.

string get_encoding(string) (CONST)

nothing get_encoding() (RT_NOOP)

N

Returns a string describing the character encoding of the string passed.

int get_epoch_seconds(date) (CONST)

nothing get_epoch_seconds() (RT_NOOP)

N

Returns the number of seconds after Jan 1, 1970, 00:00:00Z for the date/time value passed.

int get_hours(date) (CONST)

nothing get_hours() (RT_NOOP)

N

Returns an integer value representing the hours value of the date passed (can be either a relative or absolute date).

int get_microseconds(date) (CONST)

N

Returns an integer value representing the microseconds value of the date passed (can be either a relative or absolute date).

date get_midnight(date) (CONST)

nothing get_midnight() (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)

int get_milliseconds(date) (CONST)

nothing get_milliseconds() (RT_NOOP)

N

Returns an integer value representing the milliseconds value of the date passed (can be either a relative or absolute date).

int get_minutes(date) (CONST)

nothing get_minutes() (RT_NOOP)

N

Returns an integer value representing the minutes value of the date passed (can be either a relative or absolute date).

int get_months(date) (CONST)

nothing get_months() (RT_NOOP)

N

Returns an integer value representing the months value of the date passed (can be either a relative or absolute date).

hash get_qore_library_info() (CONST)

N

Returns a hash of build and version information for the qore library.

list get_qore_option_list() (CONST)

N

Returns a list of hashes giving information about qore library options.

int get_seconds(date) (CONST)

nothing get_seconds() (RT_NOOP)

N

Returns an integer value representing the seconds value of the date passed (can be either a relative or absolute date).

*string get_script_path() (CONST)

N

Returns a string giving the path (directory and filename) from which the current script was executed (if known).

*string get_script_dir() (CONST)

N

Returns a string giving the directory from which the current script was executed (if known).

*string get_script_name() (CONST)

N

Returns a string giving the filename of the current script (if known).

any get_thread_data(string) (CONST)

nothing get_thread_data() (RT_NOOP)

N

Returns the value of the thread-local data attached to the key passed

*int get_word_16(data, softint = 0) (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.

*int get_word_16_lsb(data, softint = 0) (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.

*int get_word_32_lsb(data, softint = 0) (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..

*int get_word_64_lsb(data, softint = 0) (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..

int get_years(date) (CONST)

nothing get_years() (RT_NOOP)

N

Returns an integer value representing the years value of the date passed (can be either a relative or absolute date).

softint $family = AF_UNSPEC, softint $flags = 0

list getaddrinfo(*string $node, *softstring $service, softint $family = AF_UNSPEC, softint $flags = 0) (CONST)

Y

Returns a list of address information hashes for the given node name or string address.

hash getAllThreadCallStacks()

N

Returns a hash of call stacks keyed by each TID (thread ID).

*int getByte(data, softint = 0) (CONST)

nothing getByte() (RT_NOOP)

N

Returns the byte value withing the string or binary object passed, or if the offset is out of range, returns NOTHING.

string getClassName(object) (CONST)

nothing getClassName() (RT_NOOP)

N

Returns the class name of the object passed.

*string getcwd()

N

Returns the name of the current working directory or NOTHING if an error occurs.

string getcwd2()

Y

Returns the name of the current working directory and throws an exception if an error occurs.

date getDateFromISOWeek(softint, softint, softint = 1)

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.

int getDayOfWeek(date) (CONST)

nothing getDayOfWeek() (RT_NOOP)

N

Returns an integer representing the day of the week for the absolute date passed (0=Sunday, 6=Saturday)

int getDayNumber(date) (CONST)

nothing getDayNumber() (RT_NOOP)

N

Returns an integer representing the ordinal day number in the year for the absolute date passed

*list getDBIDriverCapabilities(string)

nothing getDBIDriverCapabilities() (RT_NOOP)

N

Returns an integer representing the capabilities of a DBI driver or NOTHING if the driver cannot be loaded.

*list getDBIDriverCapabilityList(string)

nothing getDBIDriverCapabilityList() (RT_NOOP)

N

Returns a list of codes representing the capabilities of a DBI driver of NOTHING if the driver cannot be loaded.

*list getDBIDriverList()

N

Returns a list of strings of DBI drivers currently loaded or NOTHING if no drivers have been loaded.

int getegid() (CONST)

Y

Returns the effective group ID of the current process.

int geteuid() (CONST)

Y

Returns the effective user ID of the current process.

list getFeatureList() (CONST)

N

Returns a list of strings of the builtin and module-supplied features of Qore.

*string getenv(string) (CONST)

nothing getenv() (RT_NOOP)

N

Retrieves the value of an environment variable or NOTHING if the variable is not set

int getgid(CONST)

Y

Returns the real group ID of the current process.

*hash getgrnam(string) (CONST)

Y

Returns a hash representing the group information of the group name passed or NOTHING if the group name is not found.

hash getgrnam2(string)

Y

Returns a hash representing the group information of the group name passed; throws an exception if the group name is not found.

*hash getgrgid(softint) (CONST)

Y

Returns a hash representing the group information of the group ID passed or NOTHING if the group ID is not found.

hash getgrgid2(softint)

Y

Returns a hash representing the group information of the group ID passed; throws an exception if the group ID is not found.

*string gethostbyaddr(string, softint = AF_INET) (CONST)

nothing gethostbyaddr() (RT_NOOP)

N

Returns the official hostname corresponding to the network addressed passed or NOTHING if the address cannot be resolved.

*hash gethostbyaddr_long(string, softint = AF_INET) (CONST)

nothing gethostbyaddr_long() (RT_NOOP)

N

Returns all host information corresponding to the network address as a hash or NOTHING if the address cannot be resolved.

*string gethostbyname(string) (CONST)

nothing gethostbyname() (RT_NOOP)

N

Returns the first network address corresponding to the hostname as a string or NOTHING if the name cannot be resolved.

*hash gethostbyname_long(string) (CONST)

N

Returns all host information corresponding to the hostname as a hash or NOTHING if the name cannot be resolved.

string gethostname()

Y

Returns the hostname of the system; throws an exception if an error occurs.

int getISODayOfWeek(date) (CONST)

nothing getISODayOfWeek() (RT_NOOP)

N

Returns an integer representing the ISO-8601 day of the week for the absolute date passed (1=Monday, 7=Sunday)

hash getISOWeekHash(date) (CONST)

nothing getISOWeekHash() (RT_NOOP)

N

Returns a hash representing the ISO-8601 calendar week information for the absolute date passed (hash keys: year, week, day)

string getISOWeekString(date) (CONST)

nothing getISOWeekString() (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")

list getMethodList(object) (CONST)

nothing getMethodList() (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).

hash getModuleHash() (CONST)

N

Returns a hash of hashes describing the currently-loaded Qore modules; the top-level hash keys are the module names.

list getModuleList() (CONST)

N

Returns a list of hashes describing the currently-loaded Qore modules.

int getpid() (CONST)

N

Returns the PID (process ID) of the current process.

int getppid() (CONST)

Y

Returns the parent PID of the current process.

*hash getpwnam(string) (CONST)

Y

Returns a hash representing the user information of the username passed or NOTHING if the username is not found.

hash getpwnam2(string)

Y

Returns a hash representing the user information of the username passed; throws an exception if the username is not found.

*hash getpwuid(softint) (CONST)

Y

Returns a hash representing the user information of the user ID passed or NOTHING if the user ID is not found.

hash getpwuid2(softint)

N

Returns a hash representing the user information of the user ID passed; throws an exception if the user ID is not found.

int gettid() (CONST)

N

Returns the Qore thread ID (TID) of the current thread.

int getuid() (CONST)

Y

Returns the real user ID of the current process.

any getWord32(string, int = 0) (CONST)

any getWord32(binary, int = 0) (CONST)

nothing getWord32() (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.

*list glob(string)

nothing glob() (RT_NOOP)

N

Returns a list of files matching the string argument or NOTHING if the call to glob() fails.

date gmtime(date) (CONST)

date gmtime(softint, softint = 0) (CONST)

date gmtime() (CONST)

N

Returns a date/time value in UTC (GMT).

binary gunzip_to_binary(binary)

nothing gunzip_to_binary() (RT_NOOP)

Y

Uncompresses data compressed with the "gzip" algorithm (RFC 1952) using zlib functions and returns a binary object.

string gunzip_to_string(binary)

string gunzip_to_string(binary, string)

nothing gunzip_to_string() (RT_NOOP)

Y

Uncompresses data compressed with the "gzip" algorithm (RFC 1952) using zlib functions and returns a string.

binary gzip(string, softint = -1)

binary gzip(binary, softint = -1)

nothing gzip() (RT_NOOP)

Y

Performs zlib-based "gzip" data compression (RFC 1952) and returns a binary object of the compressed data.

bool has_key(hash $hash, string $key) (RET_VALUE_ONLY)

bool has_key(object $obj, string $key) (RET_VALUE_ONLY)

Y

Returns True if the given key exists in the hash or object (does not necessarily have to have a value assigned); exceptions are only raised if string encoding errors are encountered or in case of object access errors.

hash hash(list $list)

hash hash(list $keys, list $values)

hash hash(hash $hash) (CONST)

hash hash(object $obj)

hash hash() (CONST)

N

Converts an object or a list to a hash; otherwise returns an empty hash.

list hash_values(hash) (CONST)

nothing hash_values() (RT_NOOP)

N

Returns a list of all the values in the hash argument passed.

int hextoint(string)

Y

Returns an integer for a hexadecimal string value; throws an exception if non-hex digits are found.

*hash hlstat(string)

nothing hlstat() (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.

date hours(softint) (CONST)

date hours() (RT_NOOP)

N

Returns a relative date in hours to be used in date arithmetic.

*hash hstat(string)

nothing hstat() (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.

string html_decode(string) (CONST)

nothing html_decode() (RT_NOOP)

N

Returns a string with any HTML escape codes translated to the original characters

string html_encode(string) (CONST)

nothing html_encode() (RT_NOOP)

N

Returns a string with any characters that can be escaped translated to HTML escape codes.

float hypot(any, softfloat) (CONST)

float hypot(softfloat, any) (CONST)

float hypot() (RT_NOOP)

N

Returns the length of the hypotenuse of a right-angle triangle with sides given as the two arguments.

int index(softstring, softstring, softint = 0) (CONST)

int index() (RT_NOOP)

N

Returns the character position of a substring within a string and takes an optional starting offset

bool inlist(any, list)

bool inlist(any, any)

bool inlist() (RT_NOOP)

N

Returns True if the first argument is a member of the second argument list using comparisons with type conversions.

bool inlist_hard(any, list)

bool inlist_hard(any, any)

N

Returns True if the first argument is a member of the second argument list using comparisons without type conversions.

int int(softint) (CONST)

int int(null) (CONST)

int int() (CONST)

N

Returns the argument converted to an integer

bool is_bdev(string) (CONST)

N

Returns True if the string passed identifies a block device file on the filesystem.

bool is_cdev(string) (CONST)

N

Returns True if the string passed identifies a character device file on the filesystem.

bool is_date_absolute(date) (CONST)

bool is_date_absolute(any) (RT_NOOP)

N

Returns True if an absolute date is passed as an argument, False if not.

bool is_date_relative(date) (CONST)

bool is_date_relative(any) (RT_NOOP)

N

Returns True if a relative date is passed as an argument, False if not.

bool is_dev(string) (CONST)

N

Returns True if the string passed identifies a device file (either block or character) on the filesystem.

bool is_dir(string) (CONST)

N

Returns True if the string passed identifies a directory on the filesystem.

bool is_executable(string) (CONST)

Y

Returns True if the string passed identifies an executable file.

bool is_file(string) (CONST)

N

Returns True if the string passed identifies a regular file on the filesystem.

bool is_link(string) (CONST)

Y

Returns True if the string passed identifies a symbolic link on the filesystem.

bool is_pipe(string) (CONST)

N

Returns True if the string passed identifies a pipe (FIFO) on the filesystem.

bool is_readable(string) (CONST)

N

Returns True if the string passed identifies a file readable by the current user.

bool is_socket(string) (CONST)

Y

Returns True if the string passed identifies a socket on the filesystem.

bool is_writeable(string) (CONST)

N

Returns True if the string passed identifies a file writable by the current user.

string join(string, list) (CONST)

string join(string, ...) (CONST)

nothing join() (RT_NOOP)

N

Creates a string from a list and separator character

int kill(softint, softint = SIGHUP)

nothing kill() (RT_NOOP)

Y

Sends a signal to a process (default: SIGHUP)

int lchown(string, softint = -1, softint = -1)

Y

Changes the user and group owners of a file (if the current user has permission to do so), does not follow symbolic links.

int length(softstring) (CONST)

int length(binary) (CONST)

int length(any) (NOOP)

nothing length() (RT_NOOP)

N

Returns the length in characters for the string passed.

list list(...) (CONST)

N

Returns a list with the argument passed as the first element (or an empty list if no argument is passed)

nothing load_module(string)

nothing load_module() (RT_NOOP)

Y

Loads a Qore module at run-time if the feature name is not already present in the current Program object.

date localtime(date) (CONST)

date localtime(softint, softint = 0) (CONST)

date localtime() (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).

float log10(softfloat) (CONST)

float log10() (RT_NOOP)

N

Returns the base 10 logarithm of the value passed

float log1p(softfloat) (CONST)

float log1p() (RT_NOOP)

N

Returns the natural logarithm of the value passed plus 1

float logb(softfloat) (CONST)

float logb() (RT_NOOP)

N

Returns the exponent of a number.

*list lstat(string)

nothing lstat() (RT_NOOP)

N

Returns a list of file status values for the file or symbolic link passed or NOTHING if the call to stat() fails.

string makeBase64String(data) (CONST)

nothing makeBase64String() (RT_NOOP)

N

Returns a base64-encoded representation of a binary object or a string.

string makeHexString(data) (CONST)

nothing makeHexString() (RT_NOOP)

N

Returns a hex-encoded representation of a binary object or a string.

any max(...) (CONST)

any max(list) (CONST)

any max(list, string)

any max(list, code)

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.

string MD2(data)

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)

binary MD2_bin(data)

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)

string MD4(data)

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)

binary MD4_bin(data)

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)

string MD5(data)

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)

binary MD5_bin(data)

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)

string MDC2(data)

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)

binary MDC2_bin(data)

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)

date microseconds(softint) (CONST)

date microseconds() (RT_NOOP)

N

Returns a relative date in microseconds to be used in date arithmetic.

date milliseconds(softint) (CONST)

date milliseconds() (RT_NOOP)

N

Returns a relative date in milliseconds to be used in date arithmetic.

any min(...) (CONST)

any min(list) (CONST)

any min(list, string)

any min(list, code)

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.

date minutes(softint) (CONST)

date minutes() (RT_NOOP)

N

Returns a relative date in minutes to be used in date arithmetic.

int mkdir(string, softint = 0777)

Y

Creates a directory with the given mode/permissions.

int mkfifo(string, softint = 0600)

Y

Creates a named pipe with the given mode/permissions.

int mktime(date) (CONST)

nothing mktime() (RT_NOOP)

N

Returns the number of seconds after Jan 1, 1970, 00:00:00Z for the date/time value passed.

date months(softint) (CONST)

date months() (RT_NOOP)

N

Returns a relative date in months to be used in date arithmetic.

float nlog(softfloat) (CONST)

float nlog() (RT_NOOP)

N

Returns the natural logarithm of the value passed

date now() (CONST)

N

Returns current date and time with resolution to the second

date now_ms() (CONST)

N

Returns current date and time with resolution to the millisecond

date now_us() (CONST)

N

Returns current date and time with resolution to the microsecond

date now_utc() (CONST)

N

Returns current UTC date and time with resolution to the microsecond.

int num_threads() (CONST)

N

Returns the current number of threads in the process

int ord(softstring, softint = 0) (CONST)

nothing ord() (RT_NOOP)

N

Gives the numeric value of the character passed

nothing parse(string, string)

nothing parse() (RT_NOOP)

Y

Adds the text passed to the current program's code

hash parse_url(string)

Y

Parses a URL string and returns a hash of the components; throws an exception if the string cannot be parsed as URL.

binary parseBase64String(string)

nothing parseBase64String() (RT_NOOP)

Y

Parses a base64 encoded string and returns the binary object

hash parseDatasource(string)

nothing parseDatasource() (RT_NOOP)

N

Returns a hash of the components of a datasource string (ex: "user/pass@db(encoding)%host:port{min=2,max=4}").

binary parseHexString(string)

nothing parseHexString() (RT_NOOP)

Y

Parses a hex-encoded string and returns the binary object; if invalid hex digits are found an exception is thrown.

*hash parseURL(string)

nothing parseURL() (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.

float pow(softfloat = 0.0, softfloat = 0.0)

Y

Returns the value of the first argument raised to the power of the second

nothing print(...)

N

Prints the string passed without any formatting.

string printf(string, ...)

string printf() (RT_NOOP)

Y

Prints a formatted string and returns string printed.

int rand()

N

Returns a random integer number.

binary rc2_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

binary rc2_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

string rc2_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC2(tm) algorithm.

binary rc4_encrypt(data, data, data = defaultIV)

Y

Encrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

binary rc4_decrypt(binary, data, data = defaultIV)

Y

Decrypts data using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

string rc4_decrypt_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Alleged RC4 cipher algorithm, which should be compatible with RSA's RC4(tm) algorithm.

binary rc5_encrypt_cbc(data, data, data = defaultIV)

Y

Encrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

binary rc5_decrypt_cbc(binary, data, data = defaultIV)

Y

Decrypts data using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

string rc5_decrypt_cbc_to_string(binary, data, data = defaultIV)

Y

Decrypts data to a string using the Cipher Block Chaining function for RSA's RC5(tm) algorithm.

string readlink(string)

N

Returns the target of a symbolic link; throws an exception if an error occurs.

bool regex(string, string, int = 0)

nothing regex() (RT_NOOP)

Y

Returns true if the regular expression matches the string passed

*list regex_extract(string, string, int = 0)

nothing regex_extract() (RT_NOOP)

Y

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

string regex_subst(string, string, string, int = 0)

nothing regex_subst() (RT_NOOP)

Y

Returns a string with patterns substituted according to the arguments passed.

nothing remove_signal_handler(softint)

N

Removes an installed signal handler and returns the signal handling state to the default.

nothing remove_thread_data(list)

nothing remove_thread_data(...)

N

Removes the listed keys from the thread-local data hash.

nothing rename(string, string)

Y

Renames (or moves) a file or directory.

string replace(string, string, string)

nothing replace() (RT_NOOP)

N

Replaces all occurrances of a substring in a string with another string and returns the new string.

string reverse(string) (CONST)

list reverse(list) (CONST)

nothing reverse() (RT_NOOP)

N

Reverses the order of a string or a list and returns the new string or list.

string RIPEMD160(data)

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)

binary RIPEMD160_bin(data)

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)

int rindex(softstring, softstring, softint = -1) (CONST)

int rindex() (RT_NOOP)

N

Returns the starting character position of a string in another string as searched from the end of the string.

int rmdir(string)

N

Removes a directory.

float round(softfloat) (CONST)

float round() (RT_NOOP)

N

Returns a value rounded up to the nearest integer.

nothing save_thread_data(hash)

nothing save_thread_data(string, any)

nothing save_thread_data() (RT_NOOP)

Y

Saves the data passed against the key passed in thread-local storage.

date seconds(softint) (CONST)

date seconds() (RT_NOOP)

N

Returns a relative date/time value in seconds to be used in date arithmetic.

nothing set_signal_handler(softint, code)

N

Installs or replaces a signal handler.

int setegid(softint)

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())

int seteuid(softint)

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())

int setenv(string, softstring)

nothing setenv() (RT_NOOP)

N

Sets the value of an environment variable

int setgid(softint)

Y

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())

int setsid()

Y

Creates a new session lead by the current process.

int setuid(softint)

Y

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())

string SHA(data)

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)

binary SHA_bin(data)

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)

string SHA1(data)

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)

binary SHA1_bin(data)

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)

string SHA224(data)

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)

binary SHA224_bin(data)

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)

string SHA256(data)

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)

binary SHA256_bin(data)

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)

string SHA384(data)

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)

binary SHA384_bin(data)

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)

string SHA512(data)

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)

binary SHA512_bin(data)

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)

int sleep(softint)

int sleep(date)

nothing sleep() (RT_NOOP)

N

Causes the current thread to sleep for a certain number of seconds.

list sort(list) (CONST)

list sort(list, code)

list sort(list, string)

nothing sort() (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.

list sortDescending(list) (CONST)

list sortDescending(list, code)

list sortDescending(list, string)

nothing sortDescending() (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.

list sortDescendingStable(list) (CONST)

list sortDescendingStable(list, code)

list sortDescendingStable(list, string)

nothing sortDescendingStable() (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.

list sortStable(list) (CONST)

list sortStable(list, code)

list sortStable(list, string)

nothing sortStable() (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.

list split(string $pattern, string $string, bool $with_pattern = False) (CONST)

list split(string $pattern, string $string, string $quote) (RET_VALUE_ONLY)

list split(binary $pattern, binary $bin) (CONST)

list split() (RT_NOOP)

Y

Splits a string into a list of components based on a separator string and an optional quote.

string sprintf(string, ...) (CONST)

string sprintf() (RT_NOOP)

Y

Creates a string from the format argument passed and the other arguments.

float sin(softfloat) (CONST)

float sin() (RT_NOOP)

N

Returns the sine of the number in radians passed.

float sinh(softfloat) (CONST)

float sinh() (RT_NOOP)

N

Returns the hyperbolic sine of the number passed.

float sqrt(softfloat) (CONST)

float sqrt() (RT_NOOP)

N

Returns the square root of the number passed.

nothing srand(softint)

nothing srand() (RT_NOOP)

N

Seeds the random number generator with the integer passed.

*list stat(string)

nothing stat() (RT_NOOP)

N

Returns a list of file status information for the filename passed or NOTHING if the stat() call fails.

*hash statvfs(string)

Y

Returns a list of filesystem status information for the filename passed or NOTHING if the statvfs() call fails.

string strerror(softint) (CONST)

nothing strerror() (RT_NOOP)

N

Returns the description of the error number passed

string string(softstring) (CONST)

string string(null) (CONST)

string string() (CONST)

N

Returns the argument converted to a string

int strlen(softstring) (CONST)

int strlen(any) (NOOP)

nothing strlen() (RT_NOOP)

N

Returns the number of characters in a string.

string strmul(softstring, int)

string strmul(softstring, int, int)

Y

"Multiplies" the string.

int strtoint(softstring, int = 10) (CONST)

nothing strtoint() (RT_NOOP)

N

Returns an integer corresponding to the string passed with the possibility to specify the base (default base 10).

string substr(softstring, softint, softint) (CONST)

string substr(softstring, softint) (CONST)

nothing substr() (RT_NOOP)

N

Returns a substring of a string

int system(string)

nothing system() (RT_NOOP)

Y

Executes a process and returns the return code

float tan(softfloat) (CONST)

float tan() (RT_NOOP)

N

Returns the tangent of the number in radians passed.

float tanh(softfloat) (CONST)

float tanh() (RT_NOOP)

N

Returns the hyperbolic tangent of the number passed.

list thread_list() (CONST)

N

Returns a list of all current thread IDs

nothing throwThreadResourceExceptions()

Y

Immediately runs all thread resource cleanup routines for the current thread and throws all associated exceptions.

int timegm(date) (CONST)

nothing timegm() (RT_NOOP)

N

Returns the number of seconds since January 1, 1970 00:00:00 in the local time zone for a given date.

string tolower(string) (CONST)

nothing tolower() (RT_NOOP)

N

Converts a string to all lowercase

string toupper(string) (CONST)

nothing toupper() (RT_NOOP)

N

Converts a string to all uppercase

string trim(string, string = "") (CONST)

any trim(reference, string = "")

nothing trim() (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.

string type(any) (CONST)

N

Returns the data type of the argument passed (see Type_Constants)

string typename(any) (CONST, DEPRECATED)

N

deprecated: use type() instead

int umask(softint)

nothing umask() (RT_NOOP)

N

Sets the file creation mask for the process

binary uncompress_to_binary(binary)

nothing uncompress_to_binary() (RT_NOOP)

Y

Uncompresses (inflates) data compressed with the "deflate" algorithm (RFC 1951) using zlib functions and returns a binary object.

string uncompress_to_string(binary)

string uncompress_to_string(binary, string)

nothing uncompress_to_string() (RT_NOOP)

Y

Uncompresses (inflates) data compressed with the "deflate" algorithm (RFC 1951) using zlib functions and returns a string.

int unlink(string)

nothing unlink() (RT_NOOP)

N

Deletes a file and returns 0 for success.

int unsetenv(string)

nothing unsetenv() (RT_NOOP)

N

Unsets an environment variable

int usleep(date)

int usleep(softint)

nothing usleep() (RT_NOOP)

N

Causes the current thread to sleep for a certain number of microseconds

string vprintf(string, any)

string vprintf() (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.

string vsprintf(string, any)

string vsprintf() (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.

date years(softint) (CONST)

date years() (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

float abs(softfloat)

int abs(int)

float abs() (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

float acos(any)

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

float asin(softfloat)

float asin() (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

float atan(softfloat)

float atan() (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

float cbrt(softfloat)

float cbrt() (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

float ceil(softfloat)

float ceil() (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

float cos(softfloat) (CONST)

float cos() (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

float cosh(softfloat) (CONST)

float cosh() (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

float exp(softfloat) (CONST)

float exp() (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

float exp2(softfloat) (CONST)

float exp2() (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

float expm1(softfloat) (CONST)

float expm1() (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

float floor(softfloat) (CONST)

float floor() (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

string format_number(string, any) (CONST)

nothing format_number() (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

float hypot(any $x, softfloat $y) (CONST)

float hypot(softfloat $x, any $y) (CONST)

float hypot() (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

float log10(softfloat) (CONST)

float log10() (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

float log1p(softfloat) (CONST)

float log1p() (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

float logb(softfloat) (CONST)

float logb() (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

float nlog(softfloat) (CONST)

float nlog() (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

float pow(softfloat $x = 0.0, softfloat $y = 0.0)

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. Numbers halfway between two integers are arounded away from zero.

Prototype

float round(softfloat) (CONST)

float round() (RT_NOOP)

Example
$x = round(3.2); # returns 3.0 
Platform Availability

HAVE_ROUND

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

float sin(softfloat) (CONST)

float sin() (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

float sinh(softfloat) (CONST)

float sinh() (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

float sqrt(softfloat) (CONST)

float sqrt() (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

float tan(softfloat) (CONST)

float tan() (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

float tanh(softfloat) (CONST)

float tanh() (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

string f_printf(string $fmt, ...)

string f_printf() (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

string f_sprintf(string $fmt, ...) (CONST)

string f_sprintf() (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

nothing flush()

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

nothing print(...)

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

string printf(string $fmt, ...)

string printf() (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

string sprintf(string $fmt, ...) (CONST)

string sprintf() (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

string vprintf(string $fmt, any $arg_or_list)

string vprintf() (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

string vsprintf(string $fmt, any $arg_or_list)

string vsprintf() (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

int clock_getmicros() (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

int clock_getmillis() (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

int clock_getnanos() (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_info()

Synopsis

Returns a hash of broken-down date/time information for the given date argument; if the variant with no argument is used, then the current date/time is assumed.

Prototype

hash date_info(date $date) (CONST)

hash date_info() (CONST)

Example
my hash $h = date_info($date);

Table 3.42. Arguments and Return Values for date_info()

Argument Type

Return Type

Description

[date $date]

hash

Returns a hash of broken-down date/time information for the given date argument; if the variant with no argument is used, then the current date/time is assumed.


This function does not throw any exceptions.

Table 3.43. Date Info Hash Description

Key

Type

Absolute/Relative

Description

relative

bool

Both

True if the date is a relative date, False if it is absolute

year

int

Both

The year value of the date

month

int

Both

The month value of the date

day

int

Both

The day value of the date (day of the month for absolute dates)

hour

int

Both

The hour value of the date

minute

int

Both

The minute value of the date

second

int

Both

The second value of the date

microsecond

int

Both

The microsecond value of the date

dow

int

Absolute Only

The day of the week, where 0=Sunday, 1=Monday, ... 6=Saturday

doy

int

Absolute Only

The ordinal day number in the year.

utc_secs_east

int

Absolute Only

Offset from UTC in seconds east; if the time zone is west of UTC then the value will be negative.

dst

bool

Absolute Only

A flag if daylight savings time is in effect

zone

TimeZone

Absolute Only

The time zone for the time.

zone_name

string

Absolute Only

The name of the time zone for the given time (ex: "CEST" for Central European Summer Time for a time during summer time or "CET" for Central European Time for the same time zone while daylight savings time is not active).


3.3.5. 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 date_ms(softint) (CONST)

date date_ms() (RT_NOOP)

Example
my date $date = date_ms(1); # returns 1970-01-01T00:00:00.001

Table 3.44. 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.6. 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 date_us(softint) (CONST)

date date_us() (RT_NOOP)

Example
my date $date = date_us(1); # returns 1970-01-01T00:00:00.000001

Table 3.45. 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.7. days

Synopsis

Returns a relative date/time value in days for date arithmetic.

Prototype

date days(softint) (CONST)

date days() (RT_NOOP)

Example
$days = days(5 * 5); # returns 25D

Table 3.46. 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.8. format_date()

Synopsis

Returns a formatting string for a date argument passed. See Date Formatting for information about the formatting string.

Prototype

string format_date(string, date) (CONST)

nothing format_date() (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.47. 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.48. 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.9. get_days()

Synopsis

Returns an integer value representing the days value of the date passed (can be either a relative or absolute date).

Prototype

int get_days(date) (CONST)

nothing get_days() (RT_NOOP)

Example
$days = get_days(2007-01-23); # returns 23

Table 3.49. 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.10. 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

int get_duration_microseconds(date) (CONST)

Example
my int $us = get_duration_microseconds(PT2M15S3u); # returns 135000003

Table 3.50. 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.11. 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

int get_duration_milliseconds(date) (CONST)

Example
my int $us = get_duration_milliseconds(PT2M15S3u); # returns 135000

Table 3.51. 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.12. 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

int get_duration_seconds(date) (CONST)

Example
my int $us = get_duration_seconds(PT2M15S3u); # returns 135

Table 3.52. 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.13. 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

int get_epoch_seconds(date) (CONST)

nothing get_epoch_seconds() (RT_NOOP)

Example
$secs = get_epoch_seconds(2007-09-23T00:00:01);

Table 3.53. 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.14. get_hours()

Synopsis

Returns an integer value representing the hours value of the date passed (can be either a relative or absolute date).

Prototype

int get_hours(date) (CONST)

nothing get_hours() (RT_NOOP)

Example
$hours = get_hours(2007-01-23T11:24:03); # returns 11

Table 3.54. 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.15. get_microseconds()

Synopsis

Returns an integer value representing the microseconds value of the date passed (can be either a relative or absolute date).

Prototype

int get_microseconds(date) (CONST)

nothing get_microseconds() (RT_NOOP)

Example
$ms = get_microseconds(2007-01-23T11:24:03.250); # returns 250

Table 3.55. 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.16. 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

date get_midnight(date) (CONST)

nothing get_midnight() (RT_NOOP)

Example
$date = get_midnight(2007-01-23T11:24:03.250); # returns 2007-01-23T00:00:00.000

Table 3.56. 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.17. get_milliseconds()

Synopsis

Returns an integer value representing the milliseconds value of the date passed (can be either a relative or absolute date).

Prototype

int get_milliseconds(date) (CONST)

nothing get_milliseconds() (RT_NOOP)

Example
$ms = get_milliseconds(2007-01-23T11:24:03.250); # returns 250

Table 3.57. 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.18. get_minutes()

Synopsis

Returns an integer value representing the minutes value of the date passed (can be either a relative or absolute date).

Prototype

int get_minutes(date) (CONST)

nothing get_minutes() (RT_NOOP)

Examples
$minutes = get_minutes(2007-01-23T11:24:03); # returns 24

Table 3.58. 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.19. get_months()

Synopsis

Returns an integer value representing the months value of the date passed (can be either a relative or absolute date).

Prototype

int get_months(date) (CONST)

nothing get_months() (RT_NOOP)

Example
$months = get_months(2007-01-23); # returns 1

Table 3.59. 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.20. get_seconds()

Synopsis

Returns an integer value representing the seconds value of the date passed (can be either a relative or absolute date).

Prototype

int get_seconds(date) (CONST)

nothing get_seconds() (RT_NOOP)

Example
$secs = get_seconds(2007-01-23T11:24:03); # returns 3

Table 3.60. 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.21. get_years()

Synopsis

Returns an integer value representing the years value of the date passed (can be either a relative or absolute date).

Prototype

int get_years(date) (CONST)

nothing get_years() (RT_NOOP)

Example
$years = get_years(2007-01-23); # returns 2007

Table 3.61. 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.22. 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

date getDateFromISOWeek(softint $year, softint $month, softint $wday = 1)

Example
$date = getDateFromISOWeek(2007, 3); # returns 2007-01-15T00:00:00

Table 3.62. 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.63. 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.23. getDayOfWeek()

Synopsis

Returns an integer representing the day of the week for the absolute date passed (0=Sunday, 6=Saturday)

Prototype

int getDayOfWeek(date) (CONST)

nothing getDayOfWeek() (RT_NOOP)

Prototype
$dow = getDayOfWeek(2007-05-15); # returns 2

Table 3.64. 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.24. getDayNumber()

Synopsis

Returns an integer representing the ordinal day number in the year for the absolute date passed

Prototype

int getDayNumber(date) (CONST)

nothing getDayNumber() (RT_NOOP)

Example
$dn = getDayNumber(2007-05-15); # returns 135

Table 3.65. 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.25. getISODayOfWeek()

Synopsis

Returns an integer representing the ISO-8601 day of the week for the absolute date passed (1=Monday, 7=Sunday)

Prototype

int getISODayOfWeek(date) (CONST)

nothing getISODayOfWeek() (RT_NOOP)

Example
$dow = getISODayOfWeek(2007-05-15); # returns 2 for Tuesday

Table 3.66. 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.26. 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

hash getISOWeekHash(date) (CONST)

nothing getISOWeekHash() (RT_NOOP)

Example
$h = getISOWeekHash(2007-05-15); # returns year=2007, week=20, day=2

Table 3.67. 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.27. 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

string getISOWeekString(date) (CONST)

nothing getISOWeekString() (RT_NOOP)

Example
$str = getISOWeekString(2007-05-15); # returns "2007-W20-2"

Table 3.68. 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.28. 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

date gmtime(date $date) (CONST)

date gmtime(softint $epoch_seconds, softint $microseconds = 0) (CONST)

date gmtime() (CONST)

Example
$date = gmtime(now_us());  # equivalent to now_utc()
$date = gmtime();          # also returns current UTC (GMT)

Table 3.69. 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.29. hours()

Synopsis

Returns a relative date/time value in hours to be used in date arithmetic.

Prototype

date hours(softint) (CONST)

date hours() (RT_NOOP)

Example
$h = hours(5 * 5); # returns 25h

Table 3.70. 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.30. is_date_absolute()

Synopsis

Returns True if the argument is an absolute date/time value, False if not.

Prototype

bool is_date_absolute(date) (CONST)

bool is_date_absolute(any) (RT_NOOP)

Example
my bool $b = is_date_absolute($date);

Table 3.71. 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.31. is_date_relative()

Synopsis

Returns True if the argument is an relative date/time value, False if not.

Prototype

bool is_date_relative(date) (CONST)

bool is_date_relative(any) (RT_NOOP)

Example
my bool $b = is_date_relative($date);

Table 3.72. 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.32. 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

date localtime(date $date) (CONST)

date localtime(softint $epoch_seconds, softint $microseconds = 0) (CONST)

date localtime() (CONST)

Example
$time = localtime(10);

Table 3.73. 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.33. microseconds()

Synopsis

Returns a relative date/time value in microseconds to be used in date arithmetic.

Prototype

date microseconds(softint) (CONST)

date microseconds() (RT_NOOP)

Example
$ms = millseconds(5 * 5); # returns 25ms

Table 3.74. 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.34. milliseconds()

Synopsis

Returns a relative date/time value in milliseconds to be used in date arithmetic.

Prototype

date milliseconds(softint) (CONST)

date milliseconds() (RT_NOOP)

Example
$ms = millseconds(5 * 5); # returns 25ms

Table 3.75. 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.35. minutes()

Synopsis

Returns a relative date/time value in minutes to be used in date arithmetic.

Prototype

date minutes(softint) (CONST)

date minutes() (RT_NOOP)

Example
$m = minutes(5 * 5); # returns 25m

Table 3.76. 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.36. 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

int mktime(date) (CONST)

nothing mktime() (RT_NOOP)

Example
$secs = mktime(2007-09-23T00:00:01);

Table 3.77. 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.37. months()

Synopsis

Returns a relative date/time value in months to be used in date arithmetic.

Prototype

date months(softint) (CONST)

date months() (RT_NOOP)

Example
$m = months(5 * 5); # returns 25M

Table 3.78. 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.38. 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

date now() (CONST)

Example
my date $now = now();

Table 3.79. 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.39. 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

date now_ms() (CONST)

Example
my date $now_ms = now_ms();

Table 3.80. 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.40. 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

date now_us() (CONST)

Example
my date $now_us = now_us();

Table 3.81. 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.41. 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

date now_utc() (CONST)

Example
my date $now_utc = now_utc();

Table 3.82. 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.42. seconds()

Synopsis

Returns a relative date/time value in seconds to be used in date arithmetic.

Prototype

date seconds(softint) (CONST)

date seconds() (RT_NOOP)

Example
$time = now() + seconds(5 * 5); # 25 seconds from now

Table 3.83. 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.43. timegm()

Synopsis

Returns the number of seconds since January 1, 1970 00:00:00 in the local time zone for the given date.

Prototype

int timegm(date) (CONST)

nothing timegm() (RT_NOOP)

Example
$secs = timegm(2007-05-01T11:34:01);

Table 3.84. 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.44. years()

Synopsis

Returns a relative date/time value in years to be used in date arithmetic.

Prototype

date years(softint) (CONST)

date years() (RT_NOOP)

Example
$years = years(5 * 5); # returns 25Y

Table 3.85. 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 binary(string) (CONST)

binary binary(binary) (CONST)

binary binary(null) (CONST)

binary binary() (CONST)

Example
$bin = binary("hello");

Table 3.86. 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

string binary_to_string(binary $bin)

string binary_to_string(binary $bin, string $encoding)

Example
$str = binary_to_string($bin, "utf8");

Table 3.87. 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

bool boolean(softbool) (CONST)

bool boolean(null) (CONST)

bool boolean() (CONST)

Example
$bool = boolean(1); # returns True

Table 3.88. 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.89. 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 date(string) (CONST)

date date(string, string) (CONST)

date date(softint) (CONST)

date date(null) (CONST)

date date() (CONST)

Example
$date = date(1); # return 1970-01-01T00:00:01

Table 3.90. Arguments and Return Values for date()

Argument Type

Return Type

Description

string

date

Converts the argument to a date and returns the date.

string, string

date

Converts the 1st argument to a date by the given conversion mask (2nd arg) and returns the date. Example: date("20100401 234520", "YYYYMMDD HHmmSS")

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.


Table 3.91. String to Date conversion masks

Symbol

Description

YY

Year's last two digits. The the current year's century is used for new date

YYYY

Year with the all digits (length 4) like 1956, 0870, or ' 546' with space as the placeholder

MM

Month number (length 2) like 11, 04, or ' 1' with space as the placeholder

Mon

Month name abbrevation (length 3) with the first letter uppercased. Example: Apr for April

MON

Month name abbrevation (length 3) with all letters uppercased. Example: APR for April

DD

Date number (length 2) like 29, 04, or ' 1' with space as the placeholder

mm

Minute number (length 2) like 11, 04, or ' 1' with space as the placeholder

SS

Second number (length 2) like 11, 04, or ' 1' with space as the placeholder

ss

Millisecond number (length 2) like 11, 04, or ' 1' with space as the placeholder


This function does not throw any exceptions - except for date(string, string). It can throw DATE-CONVERT-ERROR exception.

3.4.5. float()

Synopsis

Converts the argument passed to a floating-point value.

Prototype

float float(softfloat) (CONST)

float float(null) (CONST)

float float() (CONST)

Example
$float = float("1.435"); # returns 1.435

Table 3.92. 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 hash(list $list)

hash hash(list $keys, list $values)

hash hash(hash $hash) (CONST)

hash hash(object $obj)

hash hash() (CONST)

Example
$h = hash($object); # creates a hash of the object's members

Table 3.93. 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 int(softint) (CONST)

int int(null) (CONST)

int int() (CONST)

Example
$int = int("200"); # returns 200

Table 3.94. 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 list(...) (CONST)

Example
$l = list(200);

Table 3.95. 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 string(softstring) (CONST)

string string() (CONST)

Example
$str = string(200); # returns "200"

Table 3.96. 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

string type(any) (CONST)

Example
$type = type("hello"); # returns Type::String ("string")

Table 3.97. 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.98. 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

*string getenv(string) (CONST)

nothing getenv() (RT_NOOP)

Example
my *string $v = getenv("PATH");

Table 3.99. Arguments and Return Values for getenv()

Argument Type

Return Type

Description

string

*string

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

int setenv(string $var, softstring $value)

nothing setenv() (RT_NOOP)

Example
setenv("PATH", "/bin:/usr/bin");

Table 3.100. 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

int unsetenv(string)

nothing unsetenv() (RT_NOOP)

Example
unsetenv("PATH");

Table 3.101. 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

int bindex(softstring $string, softstring $substring, softint $offset = 0)

int bindex() (RT_NOOP)

Example
$i = bindex("hello there", "the");

Table 3.102. 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

int brindex(softstring $string, softstring $substring, softint $offset = -1)

int brindex() (RT_NOOP)

Example
$i = brindex("hello there", "the");

Table 3.103. 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

string chomp(string)

any chomp(reference)

Example
$line = chomp("hello\n"); # returns "hello"

Table 3.104. 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

string chr(softint)

string chr(any) (NOOP)

nothing chr() (RT_NOOP)

Example
$i = chr(65); # returns "A"

Table 3.105. 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

string convert_encoding(string, string) (CONST)

nothing convert_encoding() (RT_NOOP)

Example
$utf8_str = convert_encoding($iso_8859_1_str, "utf-8");

Table 3.106. 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.107. 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

string decode_url(string) (CONST)

nothing decode_url() (RT_NOOP)

Example
$decoded_url = decode_url($encoded_url);

Table 3.108. 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

string force_encoding(string, string) (CONST)

nothing force_encoding() (RT_NOOP)

Example
$utf8_str = force_encoding($bad_str, "utf-8");

Table 3.109. 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

string get_encoding(string) (CONST)

nothing get_encoding() (RT_NOOP)

Example
$enc = get_encoding($string);

Table 3.110. 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

int index(softstring $string, softstring $substring, softint $offset = 0) (CONST)

int index() (RT_NOOP)

Example
$i = index("hello there", "the");

Table 3.111. 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

string join(string, list) (CONST)

string join(string, ...) (CONST)

nothing join() (RT_NOOP)

Example
$str = join(":", ("a", "b", "c")); # returns "a:b:c"

Table 3.112. 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

int length(softstring) (CONST)

int length(binary) (CONST)

int length(any) (NOOP)

nothing length() (RT_NOOP)

Example
$len = length("hello"); # returns 5

Table 3.113. 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

int ord(softstring $string, softint $offset = 0) (CONST)

nothing ord() (RT_NOOP)

Example
$i = ord("A"); # returns 65

Table 3.114. 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

bool regex(string $string, string $pattern, int $options = 0)

nothing regex() (RT_NOOP)

Example
$bool = regex("hello", "^hel"); # returns True

Table 3.115. 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.116. 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

*list regex_extract(string $string, string $pattern, int $options = 0)

nothing regex_extract() (RT_NOOP)

Example
my *list $rv = regex_extract("hello:there", "(\\w+):(\\w+)");

Table 3.117. 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.118. 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

string regex_subst(string $string, string $pattern, string $new_string, int $options = 0)

nothing regex_subst() (RT_NOOP)

Example
$str = regex_subst("hello there", "^there$", "you"); # returns "hello you"

Table 3.119. 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.120. 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

string replace(string $string, string $old, string $new)

nothing replace() (RT_NOOP)

Example
$str = replace("hello there", "there", "you"); # returns "hello you"

Table 3.121. 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

int rindex(softstring $string, softstring $substring, softint $offset = -1) (CONST)

int rindex() (RT_NOOP)

Example
$i = rindex("hello there", "the");

Table 3.122. 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. If the separator string is not found in the string to split, then a list with only one element containing the entire string argument is returned.

Only the version that takes the third argument as a quote string can throw exceptions.

Prototype

list split(string $pattern, string $string, bool $with_pattern = False) (CONST)

list split(string $separator, string $string, string $quote) (RET_VALUE_ONLY)

list split(binary $separator, binary $bin) (CONST)

list split() (RT_NOOP)

Example
my list $list = split(":", "some:text:here"); # returns ("some", "text", "here")

Table 3.123. Arguments and Return Values for split()

Argument Type

Return Type

Description

string $separator, string $string, bool $with_pattern = False

list of string

Returns a list of each component of a string separated by a separator string, with the separator removed; the separator pattern will not be included in the elements of the list returned unless the third argument is True.

string $separator, string $string, string $quote

list of string

Returns a list of each component of a string separated by a separator string, with the separator removed; the quote character can appear as the first part of a field, in which case it is assumed to designate the entire field. If instances of the quote character are found in the field preceded by a backquote character (\), then these quote characters are ignored. Note that this variant of the function can throw exceptions if the quote character is found and not terminated, or if text other than the separator string follows an end quote. This is the only variant of split() that can throw exceptions.

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.


Table 3.124. Exceptions Thrown by split()

err

desc

SPLIT-ERROR

End quote character not found or excess text found following separator string.


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

int strlen(softstring) (CONST)

int strlen(any) (NOOP)

nothing strlen() (RT_NOOP)

Example
$len = strlen("hello"); # returns 5

Table 3.125. 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. strmul()

Synopsis

Returns new string with repeated original content with optionaly removed trailing characters.

Prototype

string strmul(softstring, int)

string strmul(softstring, int, int)

Example
my string $ret = strmul("hello", 2); # returns "hellohello"
my string $ret = strmul("%s,", 3, 1); # returns "%s,%s". See missing last ','
    

Table 3.126. Arguments and Return Values for strmul()

Argument Type

Return Type

Description

softstring $original, int $multiplicator, [int $offset]

string

Returns the $multiplicator times copied $original. If there $offset given the offset length is removed from end of the new string.


Table 3.127. Exceptions Thrown by strmul()

err

desc

STRMUL-ERROR

Offset argument has to be 0 or greater than 0.

STRMUL-ERROR

Multiple argument has to be greater than 0.


3.6.21. 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

string substr(softstring $string, softint $offset, softint $len) (CONST)

string substr(softstring $string, softint $offset) (CONST)

nothing substr() (RT_NOOP)

Example
$str = substr("hello there", 6); # returns "there"

Table 3.128. 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.22. tolower()

Synopsis

Converts the argument passed to a string value all in lower case.

Prototype

string tolower(string) (CONST)

nothing tolower() (RT_NOOP)

Example
$str = tolower("HELLO"); # returns "hello"

Table 3.129. 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.23. toupper()

Synopsis

Converts the argument passed to a string value all in upper case.

Prototype

string toupper(string) (CONST)

nothing toupper() (RT_NOOP)

Example
$str = toupper("hello"); # returns "HELLO"

Table 3.130. 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.24. 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

string trim(string $string, string $chars = "") (CONST)

any trim(reference $string_ref, string $chars = "")

nothing trim() (RT_NOOP)

Example
$line = trim("   hello  \n"); # returns "hello"

Table 3.131. 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 (