Sidef
view release on metacpan or search on metacpan
lib/Sidef.pod view on Meta::CPAN
=head2 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]
=head2 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
}
=head2 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
=head2 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
=head2 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
=head1 EMBEDDING SIDEF IN PERL
The Sidef module makes it easy to embed Sidef code within larger Perl applications:
=head2 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
=head2 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
=head2 Example: Code Generation and Metaprogramming
( run in 0.797 second using v1.01-cache-2.11-cpan-39bf76dae61 )