NAME
Sidef - The Sidef programming language
VERSION
This document describes Sidef version 26.04 and later.
DESCRIPTION
Sidef is a modern, expressive programming language that elegantly blends object-oriented and functional programming paradigms. Drawing inspiration from Ruby, Raku, Go, and Julia, Sidef provides a powerful and flexible environment for both scripting and complex application development.
Key Features
Multi-Paradigm Design
Seamlessly combines object-oriented and functional programming styles, allowing you to choose the best approach for each problem.
Rich Type System
Native support for arbitrary-precision integers, rationals, floating-point numbers, and complex numbers. All numeric types are first-class citizens.
Advanced OOP Support
Complete class system with inheritance, multiple dispatch, method overloading, and operator overloading.
Functional Programming
First-class functions, lexical closures, pattern matching, lazy evaluation, and higher-order functions.
Perl Interoperability
Direct access to the entire Perl ecosystem. Use any CPAN module without wrapper code.
Modern Language Features
Built-in regular expressions, Unicode support, optional type checking, keyword arguments, and destructuring.
Code Caching & Optimization
Intelligent compilation caching with DBM backend for faster repeated execution and multi-level optimization support.
Developer-Friendly
Clear syntax, expressive constructs, and helpful error messages with suggestions make development productive and enjoyable.
INSTALLATION
Prerequisites
Sidef requires the following C libraries to be installed before the Perl modules:
GMP - GNU Multiple Precision Arithmetic Library (https://gmplib.org/)
MPFR - Multiple Precision Floating-Point Reliable Library (http://www.mpfr.org/)
MPC - Multiple Precision Complex Library (http://www.multiprecision.org/)
Platform-Specific Instructions
Debian / Ubuntu / Linux Mint
sudo apt install libgmp-dev libmpfr-dev libmpc-dev libc-dev cpanminus
cpanm --sudo -n Sidef
Arch Linux
trizen -S sidef
Windows
Download the portable 32-bit executable from the GitHub releases page:
https://github.com/trizen/sidef/releases/download/26.04/sidef-26.04.exe.zip
Android (Termux)
pkg install perl make clang libgmp libmpfr libmpc
cpan -T Sidef
From CPAN (any platform with prerequisites installed)
cpan Sidef
# or (skip tests for faster install):
cpan -T Sidef
# or with cpanminus:
cpanm Sidef
From Source
wget 'https://github.com/trizen/sidef/archive/master.zip' -O master.zip
unzip master.zip
cd sidef-master
perl Build.PL
sudo ./Build installdeps
sudo ./Build install
Verification
sidef -v # print version
sidef -e 'say "Hello, World!"'
SYNOPSIS
Basic Usage
The Sidef module provides a programmatic interface to the Sidef language engine, allowing you to parse, compile, and execute Sidef code from Perl.
use Sidef;
# Create a Sidef engine instance
my $sidef = Sidef->new(
name => 'my_program', # Program name (for error messages)
opt => {}, # Command-line options
parser_opt => {}, # Parser-specific options
);
# Execute Sidef code directly
my $code = 'say "Hello, World!"';
$sidef->execute_code($code);
# Output: Hello, World!
Using Optimization and Caching
# Enable optimization and caching for better performance
my $sidef = Sidef->new(
name => 'calculator',
opt => {
O => 2, # Optimization level (0, 1, or 2)
s => 1, # Enable code caching with DBM
}
);
my $code = 'func fib(n) { (n < 2) ? n : (fib(n-1) + fib(n-2)) }; fib(20)';
# First run: compiles and caches
my $result = $sidef->execute_code($code);
# Second run: uses cached compiled code (much faster)
$result = $sidef->execute_code($code);
String Interpolation and Expressions
my $math_code = 'say "The answer is: #{6 * 7}"';
$sidef->execute_code($math_code);
# Output: The answer is: 42
Working with Return Values
my $result = $sidef->execute_code('2 + 2');
# $result is a Sidef::Types::Number::Number object
say $result; # Outputs: 4
Compiling to Perl
Transform Sidef code into Perl source code for inspection or optimization:
my $sidef_code = q{
func fibonacci(n) {
(n < 2) ? n : (fibonacci(n-1) + fibonacci(n-2))
}
fibonacci(10)
};
my $perl_code = $sidef->compile_code($sidef_code, 'Perl');
print $perl_code; # Shows generated Perl code
AST Manipulation
For advanced use cases, you can work directly with the Abstract Syntax Tree:
my $code = '2 + 3*4';
# Parse into AST
my $ast = $sidef->parse_code($code);
# Optimize (performs constant folding and other optimizations)
my $optimized_ast = $sidef->optimize_ast($ast);
# Compile back to Sidef (to see the optimized form)
my $optimized_code = $sidef->compile_ast($optimized_ast, 'Sidef');
print $optimized_code; # May show: 14
# Or compile to Perl
my $perl = $sidef->compile_ast($optimized_ast, 'Perl');
Direct Perl Execution
Execute pre-compiled Perl code directly:
my $perl_code = $sidef->compile_code('say "Fast execution"', 'Perl');
$sidef->execute_perl($perl_code);
Error Handling
my $invalid_code = 'say "missing quote';
eval {
$sidef->execute_code($invalid_code);
};
if ($@) {
warn "Sidef error: $@";
# Error messages include helpful suggestions for typos
}
COMMAND-LINE USAGE
The sidef command-line tool is the primary way to run Sidef programs. Run perldoc sidef for full option details.
Running a Script
sidef script.sf
By convention, Sidef scripts use the .sf file extension.
One-Liners
sidef -e 'say "Hello, World!"'
sidef -E '10.of { |i| say i**2 }'
Both -e and -E accept a code string and execute it directly.
Interactive REPL
Start the REPL by running sidef with no arguments (or sidef -i):
$ sidef
Sidef 26.04, running on Linux, using Perl v5.42.0.
Type "help", "copyright" or "license" for more information.
> say "Hello!"
Hello!
Special REPL commands: reset, quit/exit/q, # load file.sf, # save file.sf.
Compiling to Perl
sidef -c -o output.pl script.sf # compile to standalone Perl script
sidef -Rperl script.sf # print generated Perl code and exit
Optimization
sidef -O1 script.sf # standard optimization
sidef -O2 script.sf # aggressive optimization
Try It Online
Experiment with Sidef in your browser at https://tio.run/#sidef.
CONSTRUCTOR
new
my $sidef = Sidef->new(%options);
Creates and returns a new Sidef object representing a Sidef language engine instance.
Parameters:
name(optional)A string identifying the program name. Used in error messages and diagnostics. Defaults to
'-'.my $sidef = Sidef->new(name => 'calculator.sf');opt(optional)A hashref of command-line options that affect execution behavior. Defaults to
{}.Common options include:
O- Optimization level (0, 1, or 2)0- No optimization (default)1- Basic constant folding and dead code elimination2- Advanced optimization: deparse and re-parse for additional optimization passes
s- Enable compilation caching using DBMWhen enabled, compiled code is stored in a database for faster subsequent executions. Requires DB_File or GDBM_File.
warnings- Enable/disable warningsstrict- Enable strict mode
Example:
my $sidef = Sidef->new( opt => { O => 2, # Maximum optimization s => 1, # Enable caching warnings => 1, strict => 1, } );parser_opt(optional)A hashref of parser-specific options. Defaults to
{}.Example:
my $sidef = Sidef->new( parser_opt => { interactive => 1, } );
Returns: A new Sidef object.
call
my $sidef = Sidef->call(%options);
Alias for new(). Creates and returns a new Sidef object with the same parameters as new().
Example:
my $sidef = Sidef->call(name => 'test');
CORE METHODS
execute_code
my $result = $sidef->execute_code($code);
Parses, compiles, and executes the provided Sidef source code. This is the primary method for running Sidef code from Perl.
Parameters:
$codeA string containing Sidef source code to execute.
Returns: The result of the last expression evaluated in the Sidef code, as a Sidef object. For statements that don't produce a value, returns nil.
Example:
# Simple expression
my $result = $sidef->execute_code('10 + 20');
say $result; # 30
# Multiple statements (returns last value)
my $result = $sidef->execute_code(q{
var x = 10;
var y = 20;
x + y
});
say $result; # 30
execute_perl
my $result = $sidef->execute_perl($perl_code);
Executes pre-compiled Perl code that was generated from Sidef source. This is a lower-level method used internally by execute_code().
Parameters:
$perl_codeA string containing Perl source code (typically generated by
compile_code()orcompile_ast()).
Returns: The result of evaluating the Perl code.
Example:
# Compile once
my $perl_code = $sidef->compile_code('2 + 2', 'Perl');
# Execute multiple times without re-compilation
my $result1 = $sidef->execute_perl($perl_code);
my $result2 = $sidef->execute_perl($perl_code);
Use Case: Useful when you want to compile once and execute many times, or when you need fine-grained control over the compilation and execution phases.
compile_code
my $compiled = $sidef->compile_code($code, $backend);
Parses the source code and compiles it to the specified backend format without executing it. If caching is enabled (opt => {s => 1}), the compiled code may be retrieved from or stored to the DBM cache.
Parameters:
$codeA string containing Sidef source code to compile.
$backendThe target compilation backend. Valid options:
'Sidef'- Decompile back to Sidef source (useful for code formatting) (default)'Perl'- Compile to Perl source code
Returns: A string containing the compiled code in the target language.
Implementation Details:
When caching is enabled, the compiled code is stored with an MD5 hash as the key
Cached code is compressed using RawDeflate for storage efficiency
The cache sanitization runs every 3 days; during sanitization, entries not accessed for 2+ days are removed
Code containing
eval()is not cached to prevent security issuesEach compilation is wrapped in a unique package namespace (
Sidef::RuntimeXXXX) to avoid conflicts
Example:
my $sidef_code = 'func square(n) { n * n }; square(5)';
# Decompile to Sidef (useful for code formatting/normalization)
my $formatted = $sidef->compile_code($sidef_code, 'Sidef');
print $formatted;
# Compile to Perl
my $perl_code = $sidef->compile_code($sidef_code, 'Perl');
print $perl_code;
parse_code
my $ast = $sidef->parse_code($code);
Parses the provided Sidef source code and returns its Abstract Syntax Tree (AST) representation. The parser is lazily initialized on first use.
Parameters:
$codeA string containing Sidef source code to parse.
Returns: A Sidef AST object representing the parsed code structure.
Automatic Optimization:
If the O option is set to 1 or higher, the returned AST is automatically optimized:
Level 1: Calls
optimize_ast()on the parsed treeLevel 2: Performs level 1 optimization, then deparses to Sidef, and re-parses for additional optimization opportunities
Example:
my $ast = $sidef->parse_code('2 + 2*2');
# $ast contains the tree structure representing the expression
# You can now pass this to optimize_ast() or compile_ast()
Use Cases:
Building code analysis tools
Implementing custom optimizations
Creating code transformation utilities
Developing Sidef IDE features (syntax highlighting, autocomplete)
AST-based code metrics and complexity analysis
optimize_ast
my $optimized_ast = $sidef->optimize_ast($ast);
Performs optimization passes on an existing AST, including constant folding, dead code elimination, and other improvements.
Parameters:
$astAn AST object obtained from
parse_code().
Returns: A new, optimized AST object.
Optimizations Performed:
Constant folding (e.g.,
2 + 3becomes5)Dead code elimination
Expression simplification
Redundancy removal
Example:
my $ast = $sidef->parse_code('2 + 3*4 + 5');
my $optimized = $sidef->optimize_ast($ast);
# See what the optimizer did
my $result = $sidef->compile_ast($optimized, 'Sidef');
print $result; # Likely: 19 (constant folded at compile time)
Note: The original AST is not modified; a new optimized tree is returned.
compile_ast
my $code = $sidef->compile_ast($ast, $backend);
Compiles an existing AST to the specified backend format. The deparser is lazily initialized on first use.
Parameters:
$astAn AST object (from
parse_code()oroptimize_ast()).$backendThe target compilation backend:
'Sidef'or'Perl'.
Returns: A string containing the compiled code.
Example:
my $ast = $sidef->parse_code('func add(a, b) { a + b }');
my $optimized = $sidef->optimize_ast($ast);
# Compile to Perl for embedding
my $perl_code = $sidef->compile_ast($optimized, 'Perl');
# Or decompile to Sidef to see optimized form
my $sidef_code = $sidef->compile_ast($optimized, 'Sidef');
UTILITY METHODS
get_sidef_config_dir
my $config_dir = $sidef->get_sidef_config_dir();
Returns the path to the Sidef configuration directory. Creates the directory if it doesn't exist.
Directory Resolution Order:
- 1.
$ENV{SIDEF_CONFIG_DIR}if set - 2.
$ENV{XDG_CONFIG_DIR}/sidefif XDG_CONFIG_DIR is set - 3.
$HOME/.config/sidefon Unix-like systems - 4.
\Local Settings\Application Data\.config\sidefon Windows - 5. Current directory as fallback
Returns: A string containing the absolute path to the config directory.
Example:
my $config_dir = $sidef->get_sidef_config_dir();
print "Config directory: $config_dir\n";
# Output: Config directory: /home/user/.config/sidef
Use Case: Store user preferences, cached data, or custom modules.
get_sidef_vdir
my $version_dir = $sidef->get_sidef_vdir();
Returns the version-specific subdirectory within the Sidef config directory. This directory is used for version-specific cached compiled code.
Returns: A string containing the path to the version-specific directory (e.g., ~/.config/sidef/v26.04).
Example:
my $vdir = $sidef->get_sidef_vdir();
print "Version directory: $vdir\n";
# Output: Version directory: /home/user/.config/sidef/v26.04
Use Case: Allows different Sidef versions to maintain separate caches without conflicts.
has_dbm_driver
my $has_driver = $sidef->has_dbm_driver();
Checks for the availability of a supported DBM driver for code caching functionality.
Supported Drivers (in order of preference):
Returns:
The driver name string (
'bdbm'or'gdbm') if a driver is availableundefif no driver is found
Example:
if (my $driver = $sidef->has_dbm_driver()) {
print "Using DBM driver: $driver\n";
# Enable caching
$sidef->{opt}{s} = 1;
} else {
warn "No DBM driver available, caching disabled\n";
}
Note: A warning is issued if no driver is found, suggesting installation of DB_File or GDBM_File.
dbm_lookup
my $cached_code = $sidef->dbm_lookup($backend, $md5_hash);
Internal. Retrieves compiled code from the DBM cache by backend ('Perl' or 'Sidef') and MD5 hash of the source. Returns the decompressed code string, or undef if not found. Updates the access timestamp if older than 5 hours. Used internally by compile_code().
dbm_store
$sidef->dbm_store($backend, $md5_hash, $code);
Internal. Stores compiled code in the DBM cache, compressed with RawDeflate. Periodically removes entries not accessed for 2+ days. Used internally by compile_code().
CLASS METHODS
version
my $version = Sidef->version;
Returns the Sidef version as a Sidef String object.
Parameters: None.
Returns: A Sidef::Types::String::String object representing the version (e.g., 'v26.04').
Example:
my $v = Sidef->version;
say "Running Sidef version: $v";
# Output: Running Sidef version: v26.04
Note: Can be called as either a class method (Sidef->version) or an instance method ($sidef->version).
numeric_version
my $num_version = Sidef->numeric_version;
Returns the Sidef version as a Sidef Number object, suitable for numeric comparisons.
Parameters: None.
Returns: A Sidef::Types::Number::Number object representing the version (e.g., 26.04).
Example:
my $ver = Sidef->numeric_version;
if ($ver >= 25.0) {
say "Running modern Sidef version";
}
Note: Can be called as either a class method (Sidef->numeric_version) or an instance method ($sidef->numeric_version).
INTERNAL UTILITY FUNCTIONS
These functions are in the Sidef package namespace but are intended for internal use.
normalize_type
my $short_name = Sidef::normalize_type($full_type);
Converts a full Perl package name to a short type name (e.g. 'Sidef::Types::Number::Number' → 'Number').
normalize_method
my $short_sig = Sidef::normalize_method($full_method);
Converts a full method name to a short signature (e.g. 'Sidef::Types::Array::Array::length' → 'Array#length').
jaro
my $similarity = Sidef::jaro($string1, $string2);
Computes the Jaro similarity between two strings (0–1). Used internally for method-name suggestions.
jaro_winkler
my $similarity = Sidef::jaro_winkler($string1, $string2);
Computes the Jaro-Winkler similarity, giving extra weight to matching prefixes. Used internally for "Did you mean?" suggestions.
best_matches
my @suggestions = Sidef::best_matches($name, \@candidates);
Returns candidates from @candidates with Jaro-Winkler similarity ≥ 0.8 against $name, sorted by similarity. Powers the "Did you mean?" hints in error messages.
LANGUAGE OVERVIEW
Sidef is designed to be expressive and intuitive. Here is a tour of its key features:
Variables and Types
var name = "Alice" # String
var age = 30 # Integer
var pi = 3.14159f # Float
var ratio = 22/7 # Rational (exact fraction)
var items = [1, 2, 3, 4] # Array
var person = Hash( # Hash
name => "Bob",
age => 25,
)
Control Flow
# if / elsif / else
if (age < 13) {
say "Child"
}
elsif (age < 20) {
say "Teenager"
}
else {
say "Adult"
}
# Ternary operator
var label = (age >= 18 ? "Adult" : "Minor")
# given / when (pattern matching)
given (age) {
when (13) { say "Thirteen" }
when (/^\d+$/) { say "Some number" }
else { say "Something else" }
}
# for loop
for i in (1..5) { say i }
# while loop
var n = 0
while (n < 5) { say n; n++ }
Functions
# Named function with optional default
func power(base, exp=2) {
base ** exp
}
# Lambda / anonymous function
var square = { |n| n * n }
say square(5) # 25
# Arrow-style lambda
var double = ->(n) { n * 2 }
Error Handling
try {
die "Something went wrong!" if (condition)
}
catch { |msg|
say "Caught: #{msg}"
}
Closures
func make_counter(start = 0) {
var count = start
func { ++count }
}
var counter = make_counter(10)
say counter() # 11
say counter() # 12
Object-Oriented Programming
class Person (String name, Number age) {
method greet {
say "Hello, I'm #{name} and I'm #{age} years old."
}
}
var alice = Person(name: "Alice", age: 30)
alice.greet
Functional Programming
var numbers = [1..10]
var squares = numbers.map { |n| n**2 }
var evens = numbers.grep { |n| n.is_even }
var total = numbers.reduce { |a, b| a + b }
Multiple Dispatch and Pattern Matching
# Multiple dispatch on type
func process(String s) { say "String: #{s}" }
func process(Number n) { say "Number: #{n}" }
process("hi") # String: hi
process(42) # Number: 42
# Pattern matching on value
func fib ((0)) { 0 }
func fib ((1)) { 1 }
func fib (n) { fib(n-1) + fib(n-2) }
Method Caching
func fib(n) is cached {
n <= 1 ? n : fib(n-1) + fib(n-2)
}
say fib(50) # fast — results are memoized automatically
Lazy Evaluation and gather/take
# Lazy infinite sequence
var first_primes = (^Inf -> lazy).grep{.is_prime}.first(10)
say first_primes # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
# gather / take
var primes_under_20 = gather {
for i in (1..20) {
take(i) if i.is_prime
}
}
say primes_under_20 # [2, 3, 5, 7, 11, 13, 17, 19]
# Enumerator (lazy infinite iterator)
var primes = Enumerator({ |yield|
for n in (2..Inf) { yield(n) if n.is_prime }
})
say primes.first(5) # [2, 3, 5, 7, 11]
Regular Expressions
if ("hello@example.com" ~~ /^\w+@\w+\.\w+$/) {
say "Valid email!"
}
var text = "I have a cat and a dog"
while (var m = text.match(/\ba\h+(\w+)/g)) {
say m[0] # cat, dog
}
Ranges, Sets, and Bags
var r = 1..10 # Range (inclusive)
say r.sum # 55
var s = Set(1, 2, 3, 2) # Set — unique elements
say s # {1, 2, 3}
var b = Bag(1, 2, 2, 3) # Bag — counted multiset
say b.count(2) # 2
Structs, Subsets, and Enumerations
# Struct
struct Point { Number x, Number y }
var p = Point(x: 3, y: 4)
say p.x # 3
# Subset (refined type)
subset Positive < Number { |n| n.is_pos }
func sqrt_pos(Positive n) { n.sqrt }
# Enumeration
enum { Red, Green, Blue } # Red=0, Green=1, Blue=2
say Green # 1
Perl Module Integration
# Object-oriented module
var http = require('HTTP::Tiny').new
var resp = http.get('https://example.com')
say resp{:content} if resp{:success}
# Functional module
var posix = frequire('POSIX')
say posix.ceil(3.14) # 4
EMBEDDING SIDEF IN PERL
The Sidef module makes it easy to embed Sidef code within larger Perl applications:
Example: Using Sidef as a Configuration Language
use Sidef;
my $sidef = Sidef->new(name => 'config');
my $config_code = q{
Hash(
database => Hash(
host => "localhost",
port => 5432,
name => "myapp"
),
features => Hash(
caching => true,
debug => false
)
)
};
my $config = $sidef->execute_code($config_code);
# $config is now a Sidef Hash object
# Access values with Perl syntax:
say $config->{database}{host}; # localhost
Example: Using Sidef for Safe Expression Evaluation
use Sidef;
my $calculator = Sidef->new(
name => 'calc',
opt => { O => 2, s => 1 } # Optimize and cache
);
sub safe_eval {
my ($expr) = @_;
eval {
return $calculator->execute_code($expr);
} or do {
warn "Invalid expression: $@";
return undef;
};
}
my $result = safe_eval("2 + 2*10");
say $result; # 22
Example: Code Generation and Metaprogramming
use Sidef;
my $sidef = Sidef->new();
# Generate Sidef functions programmatically
my $func_name = 'calculate_total';
my @operations = ('sum', 'prod', 'avg');
for my $op (@operations) {
my $code = qq{
func ${func_name}_$op(numbers) {
numbers.$op
}
};
$sidef->execute_code($code);
}
Example: High-Performance Repeated Execution
use Sidef;
my $sidef = Sidef->new(
name => 'repeated',
opt => { O => 2, s => 1 }
);
my $complex_code = q{
func compute(n) {
(1..n).sum_by { |k| 1/k**2 }
}
compute(1000)
};
# First execution: parse, optimize, compile, cache, execute
my $start = time;
my $result1 = $sidef->execute_code($complex_code);
my $time1 = time - $start;
# Subsequent executions: retrieve from cache, execute
$start = time;
my $result2 = $sidef->execute_code($complex_code);
my $time2 = time - $start;
print "First run: ${time1}s, Cached run: ${time2}s\n";
# Cached run will be significantly faster
ADVANCED TOPICS
Performance Considerations
Enable caching for production:
opt => {s => 1}Speeds up repeated execution by caching compiled code.
Use optimization for CPU-intensive code:
opt => {O => 2}Level 2 optimization provides maximum performance but increases initial compilation time.
Compile to Perl for maximum performance
Generate Perl code once and execute it directly for the fastest runtime performance.
Cache Sidef instances to avoid repeated initialization
Creating a new
Sidefobject has overhead. Reuse instances when possible.Use lazy evaluation for large data sets
Sidef's lazy evaluation can significantly reduce memory usage.
Consider DBM driver choice
DB_File (Berkeley DB) generally performs better than GDBM_File for caching.
Cache Management
The compilation cache provides significant performance benefits but requires understanding:
Cache location:
~/.config/sidef/v26.04/(version-specific)Storage format: Two DBM databases (time and code)
Compression: RawDeflate compression for efficient storage
Automatic cleanup: Entries not accessed for 2+ days are removed every 3 days
MD5 hashing: Source code is hashed to create unique cache keys
Update interval: Access timestamps updated every 5 hours
To manually clear the cache:
rm -rf ~/.config/sidef/v26.04/
Thread Safety
Each Sidef instance maintains its own state, including parser and deparser objects. For multi-threaded applications:
Create separate instances per thread for true parallel execution
Use appropriate locking if sharing a single instance
The DBM cache is not thread-safe; use separate cache directories per thread if needed
Memory Management
Sidef objects are reference-counted through Perl's system
Circular references are handled by Perl's garbage collector
Large data structures are automatically freed when no longer referenced
The parser and deparser are lazily initialized and cached per instance
Use
undefto explicitly release large Sidef instances
Error Handling and Debugging
Sidef provides helpful error messages with suggestions:
# Typo in method name
my $result = $sidef->execute_code('[1,2,3].lnegth');
# Error: Undefined method 'Array#lnegth'
# [?] Did you mean: length
The AUTOLOAD mechanism:
Catches undefined method calls
Uses Jaro-Winkler similarity to suggest corrections
Shows context (calling method/function)
Provides similarity threshold of 0.8 for suggestions
Sidef also installs UNIVERSAL::get_value, which unwraps Sidef::Module::OO and Sidef::Module::Func objects to their underlying module value, and falls back to returning the object itself for all other types.
COMPARISON WITH OTHER LANGUAGES
Sidef vs Ruby
Sidef draws syntax inspiration from Ruby and adds:
Native arbitrary-precision integers, rationals, and complex numbers
Perl ecosystem access (any CPAN module available without wrapper code)
Built-in compilation caching and multi-level optimization
Multiple dispatch and value-level pattern matching
Sidef vs Raku
Raku and Sidef share some surface-level features (given/when, grammars, lazy lists). Key differences:
Sidef compiles to Perl and runs on standard Perl infrastructure
Sidef integrates directly with CPAN modules via
require/frequireRaku has a more elaborate type system and grammar engine; Sidef focuses on scripting ergonomics
Sidef vs Python
Objective feature differences:
Native exact rational arithmetic (
22/7is a fraction, not floating-point division)Arbitrary-precision integers by default
Multiple dispatch on types and on specific values
Lazy evaluation and infinite sequences built into the core
OPTIMIZATION LEVELS
Understanding the O option values:
Level 0 (No Optimization)
my $sidef = Sidef->new(opt => { O => 0 });
No optimization passes applied
Fastest compilation time
Suitable for development and debugging
AST used as-is for code generation
Level 1 (Standard Optimization)
my $sidef = Sidef->new(opt => { O => 1 });
Constant folding:
2 + 3becomes5Dead code elimination
Expression simplification
Recommended for most production use
Good balance of compilation time and runtime performance
Level 2 (Aggressive Optimization)
my $sidef = Sidef->new(opt => { O => 2 });
Performs level 1 optimizations
Deparses optimized AST back to Sidef source
Re-parses the deparsed code with level 1 optimization
Allows additional optimization opportunities
Longer compilation time but maximum runtime performance
Best for CPU-intensive production code
TROUBLESHOOTING
Common Issues
- "Undefined method" errors
-
Sidef uses
.for method calls. Check spelling and capitalization. The error message will suggest similar method names.Example error:
[AUTOLOAD] Undefined method 'Array#lnegth' called from main() [?] Did you mean: length - Type errors
-
Enable strict mode for better type checking:
my $sidef = Sidef->new(opt => { strict => 1 }); - Module not found
-
Sidef can use Perl modules via
require. Ensure the module is installed:cpan Module::Name # or cpanm Module::Name - Performance issues
-
Enable optimization:
opt => {O => 2}Enable caching:
opt => {s => 1}Install faster math libraries (Math::Prime::Util)
Compile to Perl for production use
- Cache not working
-
Check if a DBM driver is installed:
perl -e 'use DB_File; print "DB_File OK\n"' # or perl -e 'use GDBM_File; print "GDBM_File OK\n"'Install if missing:
cpan DB_File # or cpanm DB_File - Memory usage
-
For large data processing:
Use lazy evaluation where possible
Process data in chunks
Clear large structures when done
Consider streaming approaches for file processing
Debugging Tips
Use
warnstatements liberally for debuggingExamine compiled Perl code:
compile_code($code, 'Perl')Inspect optimized AST:
compile_ast(optimize_ast($ast), 'Sidef')Check parser state with
$sidef->{parser}Review cache entries in
~/.config/sidef/v26.04/
RESOURCES AND COMMUNITY
Official Resources
Try It Online: https://tio.run/#sidef
Run Sidef code in your browser without installing anything.
MetaCPAN: https://metacpan.org/pod/Sidef
CPAN module page with documentation and download links.
GitHub Repository: https://github.com/trizen/sidef
Main source code repository with issue tracking and discussions.
Language Documentation: https://trizen.gitbook.io/sidef-lang/
Comprehensive language reference and tutorial.
Wiki and Tutorial: https://codeberg.org/trizen/sidef/wiki
Community-maintained tutorials and guides.
RosettaCode Examples: https://rosettacode.org/wiki/Sidef
Hundreds of code examples showing Sidef solutions to common programming tasks.
Getting Help
Q&A Discussions: https://github.com/trizen/sidef/discussions/categories/q-a
Ask questions and get help from the community.
Issue Tracker: https://github.com/trizen/sidef/issues
Report bugs and request features.
IRC: Join
#sidefon Libera.Chat for real-time discussion.
Contributing
Contributions are welcome! See the GitHub repository for contribution guidelines. Areas where help is particularly appreciated:
Documentation improvements
Bug reports and fixes
Performance optimizations
New library modules
Example programs and tutorials
Porting RosettaCode examples
DEPENDENCIES
Required
Sidef requires:
Perl 5.16.0 or later
List::Util - Core utility functions
File::Spec - Portable file path operations
Encode - UTF-8 encoding/decoding (for caching)
Digest::MD5 - Hash generation (for caching)
IO::Compress::RawDeflate - Compression (for caching)
IO::Uncompress::RawInflate - Decompression (for caching)
Various Sidef type modules (automatically loaded)
Optional (for enhanced functionality)
DB_File or GDBM_File - For compilation caching
Without these, the
soption (caching) will not be available.Math::GMPz - Faster arbitrary-precision integer arithmetic
Math::GMPq - Faster arbitrary-precision rational arithmetic
Math::MPFR - Faster arbitrary-precision floating-point arithmetic
Math::MPC - Faster arbitrary-precision complex arithmetic
These optional math libraries can provide 10-100x speed improvement for mathematical operations.
INTERNALS
Constants and Package Variables
Cache timing constants:
UPDATE_SEC- 18000 s (5 h) — interval for updating cache access timestampsDELETE_SEC- 172800 s (2 days) — age threshold for cache entry deletionSANITIZE_SEC- 259200 s (3 days) — interval between cache sanitization runs
Package variables:
$Sidef::VERSION- Current version string$Sidef::SPACES/$Sidef::SPACES_INCR- Indentation state for the deparser%Sidef::INCLUDED- Tracks included source files%Sidef::EVALS- Metadata foreval()handling$Sidef::PARSER/$Sidef::DEPARSER- Current parser/deparser instances
SEE ALSO
Sidef::Parser - Sidef parser implementation
Sidef::Optimizer - AST optimization engine
Sidef::Deparse::Sidef - Sidef code generator
Sidef::Deparse::Perl - Perl code generator
Sidef::Types::Number::Number - Arbitrary-precision numbers
perl - The Perl programming language
perlapi - Perl API documentation
BUGS AND LIMITATIONS
Please report bugs via the GitHub issue tracker at https://github.com/trizen/sidef/issues.
Known limitations:
Unicode support depends on Perl's Unicode implementation
Performance for some operations may not match natively compiled languages
DBM cache is not thread-safe without external synchronization
Very large source files may exceed DBM record size limits
ACKNOWLEDGMENTS
Sidef builds upon decades of programming language research and draws inspiration from many sources:
Ruby for elegant syntax and object model
Raku for advanced language features and metaprogramming
Go for design simplicity
Julia for numerical computing and language design ideas
Perl for providing the robust foundation
Special thanks to the Perl community for providing the robust foundation upon which Sidef is built, and to all contributors who have helped improve the language.
AUTHORS
Daniel Șuteu (trizen) - Lead developer and maintainer
Primary developer responsible for language design, implementation, and maintenance.
Ioana Fălcușan - Core contributor
Contributions to language features and standard library in the early days of Sidef.
LICENSE AND COPYRIGHT
Copyright (C) 2013-2026 Daniel Șuteu, Ioana Fălcușan.
This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0. You may obtain a copy of the Artistic License 2.0 at:
http://www.perlfoundation.org/artistic_license_2_0
Disclaimer of Warranty
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.