Sidef

 view release on metacpan or  search on metacpan

TUTORIAL.md  view on Meta::CPAN

say quicksort(@("a".."z") -> shuffle)
```

Alternatively, Sidef provides the `Block.thr` method, which creates a deprecated Perl thread, or a system fork if [forks](https://metacpan.org/pod/forks) is installed.

# Interacting with Perl modules

Sidef can interact with Perl modules in a very easy way. There is the `require` keyword which will try to load an object-oriented Perl module.

```ruby
var lwp  = require('LWP::UserAgent')
var ua   = lwp.new(show_progress => 1)
var resp = ua.get('http://example.net')

if (resp.is_success) {
    say resp.decoded_content.length
}
```

For functional Perl modules, the `frequire` keyword should be used instead to denote that the module is function-oriented.

lib/Sidef.pm  view on Meta::CPAN


            $self->_init_code_db($lang)
              if not exists($self->{$lang}{_code_hash});

            if (time - $self->{$lang}{_time_hash}{$md5} >= UPDATE_SEC) {
                $self->{$lang}{_time_hash}{$md5} = time;
            }

            my $compressed_code = $self->{$lang}{_code_hash}{$md5};

            state $_x = require IO::Uncompress::RawInflate;
            IO::Uncompress::RawInflate::rawinflate(\$compressed_code => \my $decompressed_code)
              or die "rawinflate failed: $IO::Uncompress::RawInflate::RawInflateError";

            return Encode::decode_utf8($decompressed_code);
        }

        return;
    }

    sub dbm_store {

lib/Sidef.pm  view on Meta::CPAN

                    push @delete_keys, $key;
                }
            }

            if (@delete_keys) {
                delete @{$self->{$lang}{_time_hash}}{@delete_keys};
                delete @{$self->{$lang}{_code_hash}}{@delete_keys};
            }
        }

        state $_x = require IO::Compress::RawDeflate;
        IO::Compress::RawDeflate::rawdeflate(\$code => \my $compressed_code)
          or die "rawdeflate failed: $IO::Compress::RawDeflate::RawDeflateError";

        $self->{$lang}{_time_hash}{$md5} = time;
        $self->{$lang}{_code_hash}{$md5} = $compressed_code;
    }

    sub compile_code {
        my ($self, $code, $lang) = @_;

lib/Sidef/Parser.pm  view on Meta::CPAN

                return (bless {class => $class_obj, name => $var_name}, 'Sidef::Variable::ClassVar');
            }

            # Static object (like String or nil)
            if (/$self->{static_obj_re}/goc) {
                return $^R;
            }

            if (/\G__MAIN__\b/gc) {
                if (-e $self->{script_name}) {
                    state $x = require Cwd;
                    return Sidef::Types::String::String->new(Cwd::abs_path($self->{script_name}));
                }
                return Sidef::Types::String::String->new($self->{script_name});
            }

            if (/\G__FILE__\b/gc) {
                if (-e $self->{file_name}) {
                    state $x = require Cwd;
                    return Sidef::Types::String::String->new(Cwd::abs_path($self->{file_name}));
                }
                return Sidef::Types::String::String->new($self->{file_name});
            }

            if (/\G__DATE__\b/gc) {
                my (undef, undef, undef, $day, $mon, $year) = localtime;
                return Sidef::Types::String::String->new(join('-', $year + 1900, map { sprintf "%02d", $_ } $mon + 1, $day));
            }

lib/Sidef/Sys/Sys.pm  view on Meta::CPAN

    }

    sub fork {
        my ($self) = @_;
        Sidef::Types::Number::Number->new(CORE::fork() // return undef);
    }

    sub alarm {
        my ($self, $sec) = @_;

        state $x = require Time::HiRes;
        (Time::HiRes::alarm($sec)) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    sub ualarm {
        my ($self, $sec) = @_;

        state $x = require Time::HiRes;
        (Time::HiRes::ualarm($sec)) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    *micro_alarm = \&ualarm;

    sub sleep {
        my ($self, $sec) = @_;

        state $x = require Time::HiRes;
        (Time::HiRes::sleep($sec)) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    sub nanosleep {
        my ($self, $sec) = @_;

        state $x = require Time::HiRes;
        (Time::HiRes::nanosleep($sec)) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    *nano_sleep = \&nanosleep;

    sub usleep {
        my ($self, $sec) = @_;

        state $x = require Time::HiRes;
        (Time::HiRes::usleep($sec)) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    *micro_sleep = \&usleep;

    sub osname {
        my ($self) = @_;
        Sidef::Types::String::String->new($^O);
    }

lib/Sidef/Sys/Sys.pm  view on Meta::CPAN

        my ($self, $obj) = @_;
        my $ref = CORE::ref($obj);

        my $rindex = rindex($ref, '::');
        Sidef::Types::String::String->new($rindex == -1 ? $ref : substr($ref, $rindex + 2));
    }

    sub sidef {
        my ($self) = @_;

        state $x = require File::Spec;
        Sidef::Types::String::String->new(File::Spec->rel2abs($0));
    }

    sub die {
        my ($self, @args) = @_;
        CORE::die(@args, "\n");
    }

    *raise = \¨

lib/Sidef/Time/Time.pm  view on Meta::CPAN

    }

    *sec = \&time;

    sub now {
        Sidef::Types::Number::Number->new(CORE::time);
    }

    sub micro {
        my ($self) = @_;
        state $x = require Time::HiRes;
        Sidef::Types::Number::Number->new(scalar Time::HiRes::gettimeofday());
    }

    *micro_sec     = \µ
    *micro_seconds = \µ

    sub localtime {
        my ($self) = @_;
        Sidef::Time::Date->localtime($self->get_value);
    }

lib/Sidef/Types/Array/Array.pm  view on Meta::CPAN


        if (defined $block) {
            return Sidef::Types::String::String->new(CORE::join($delim, map { scalar $block->run($_) } @$self));
        }

        Sidef::Types::String::String->new(CORE::join($delim, @$self));
    }

    sub join_bytes {
        my ($self, $encoding) = @_;
        state $x = require Encode;
        $encoding = defined($encoding) ? "$encoding" : 'UTF-8';
        Sidef::Types::String::String->new(eval { Encode::decode($encoding, CORE::pack('C*', @$self)) } // return);
    }

    *chrs   = \&join_bytes;
    *decode = \&join_bytes;

    sub join_insert {
        my ($self, $obj) = @_;

lib/Sidef/Types/Array/Array.pm  view on Meta::CPAN

    *remove_last_by = \&delete_last_if;
    *delete_last_by = \&delete_last_if;

    sub to_list { @{$_[0]} }

    sub getopt {
        my ($self, %opts) = @_;

        @$self or return Sidef::Types::Array::Array->new;

        state $x = require Getopt::Long;
        Getopt::Long::Configure('no_ignore_case');

        my @argv = map { "$_" } @$self;
        my @opts = CORE::keys %opts;

        my %parsed;
        Getopt::Long::GetOptionsFromArray(\@argv, \%parsed, @opts);

        my %lookup = map {
            my ($name) = Getopt::Long::ParseOptionSpec($_, \my %info);

lib/Sidef/Types/Block/Block.pm  view on Meta::CPAN

        if ($ref eq 'Sidef::Types::Block::Block') {
            die "[ERROR] Blocks cannot be serialized!";
        }

        return;
    }

    sub ffork {
        my ($self, @args) = @_;

        state $x = require Data::Dump::Filtered;
        open(my $fh, '+>', undef);    # an anonymous temporary file
        my $fork = Sidef::Types::Block::Fork->new(fh => $fh);

        # Try to fork
        my $pid = fork() // die "[ERROR] Cannot fork";

        if ($pid == 0) {
            srand();
            my @objs = ($self->call(@args));
            print $fh scalar Data::Dump::Filtered::dump_filtered(@objs, \&__fdump);

lib/Sidef/Types/Block/Block.pm  view on Meta::CPAN

    sub prod {
        my ($self, $range) = @_;
        $range->prod_by($self);
    }

    *Π = \∏

    sub cache {
        my ($self) = @_;
        $self->{is_cached} && return $self;
        state $x = require Memoize;
        $self->{code}      = Memoize::memoize($self->{code});
        $self->{is_cached} = 1;
        $self;
    }

    sub uncache {
        my ($self) = @_;
        $self->{is_cached} || return $self;
        state $x = require Memoize;
        if (defined(my $uncached = eval { Memoize::unmemoize($self->{code}) })) {
            $self->{code}      = $uncached;
            $self->{is_cached} = 0;
        }
        $self;
    }

    sub flush_cache {
        my ($self) = @_;
        $self->{is_cached} || return $self;
        state $x = require Memoize;
        eval { Memoize::flush_cache($self->{code}) };
        $self;
    }

    sub dump {
        Sidef::Types::String::String->new("$_[0]");
    }

    *to_s   = \&dump;
    *to_str = \&dump;

lib/Sidef/Types/Glob/Dir.pm  view on Meta::CPAN

    sub home {
        my ($self) = @_;

        my $home = $ENV{HOME} || $ENV{LOGDIR};

        if (not $home and $^O ne 'MSWin32') {
            $home = (getpwuid($<))[7];
        }

        $home ? __PACKAGE__->new($home) : do {
            state $x = require File::HomeDir;
            __PACKAGE__->new(File::HomeDir->my_home);
        };
    }

    sub tmp {
        __PACKAGE__->new(File::Spec->tmpdir);
    }

    *temp = \&tmp;

    sub mktemp {
        my ($self, %opts) = @_;
        state $x = require File::Temp;
        __PACKAGE__->new(File::Temp::tempdir(CLEANUP => 1, %opts));
    }

    *make_tmp  = \&mktemp;
    *make_temp = \&mktemp;

    sub find {
        my ($self, $arg) = @_;
        state $x = require File::Find;

        my @files;
        my $ref      = ref($arg // '');
        my $is_block = $ref eq 'Sidef::Types::Block::Block';

        File::Find::find(
            sub {
                my $file = Encode::decode_utf8($File::Find::name);

                if (-d $file) {

lib/Sidef/Types/Glob/Dir.pm  view on Meta::CPAN

            },
            $$self
        );

        $is_block ? $self : Sidef::Types::Array::Array->new(\@files);
    }

    *browse = \&find;

    sub cwd {
        state $x = require Cwd;
        __PACKAGE__->new(Encode::decode_utf8(Cwd::getcwd()));
    }

    sub pwd {
        __PACKAGE__->new(File::Spec->curdir);
    }

    sub up {
        my ($self) = @_;
        __PACKAGE__->new(Encode::decode_utf8(File::Spec->catdir(ref($self) ? Encode::encode_utf8($$self) : (), File::Spec->updir)));

lib/Sidef/Types/Glob/Dir.pm  view on Meta::CPAN

    sub split {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        Sidef::Types::Array::Array->new([map { Sidef::Types::String::String->new($_) } File::Spec->splitdir("$self")]);
    }

    # Returns the parent of the directory
    sub parent {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        state $x = require File::Basename;
        __PACKAGE__->new(File::Basename::dirname("$self"));
    }

    # Remove the directory (works only on empty dirs)
    sub remove {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        CORE::rmdir("$self") ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    *delete = \&remove;
    *unlink = \&remove;

    # Remove the directory with all its content
    sub remove_tree {
        ref($_[0]) || shift(@_);
        my ($self) = @_;

        state $x = require File::Path;
        (File::Path::remove_tree("$self")) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    # Create directory without parents
    sub create {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        (CORE::mkdir("$self")) ? (Sidef::Types::Bool::Bool::TRUE) : (Sidef::Types::Bool::Bool::FALSE);
    }

    *make  = \&create;
    *mkdir = \&create;

    # Create the directory (with parents, if needed)
    sub create_tree {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        state $x = require File::Path;
        my $path = "$self";
        -d $path                           ? (Sidef::Types::Bool::Bool::TRUE)
          : (File::Path::make_path($path)) ? (Sidef::Types::Bool::Bool::TRUE)
          :                                  (Sidef::Types::Bool::Bool::FALSE);
    }

    *make_tree = \&create_tree;
    *mktree    = \&create_tree;
    *make_path = \&create_tree;
    *mkpath    = \&create_tree;

lib/Sidef/Types/Glob/File.pm  view on Meta::CPAN

    }

    sub size {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        Sidef::Types::Number::Number::_set_int(-s "$self");
    }

    sub md5 {
        ref($_[0]) || shift(@_);
        state $x = require Digest::MD5;
        open my $fh, '<:raw', "$_[0]" or return undef;
        my $o = Digest::MD5->new;
        $o->addfile($fh);
        Sidef::Types::String::String->new(scalar $o->hexdigest);
    }

    sub sha1 {
        ref($_[0]) || shift(@_);
        state $x = require Digest::SHA;
        open my $fh, '<:raw', "$_[0]" or return undef;
        my $o = Digest::SHA->new(1);
        $o->addfile($fh);
        Sidef::Types::String::String->new(scalar $o->hexdigest);
    }

    sub sha256 {
        ref($_[0]) || shift(@_);
        state $x = require Digest::SHA;
        open my $fh, '<:raw', "$_[0]" or return undef;
        my $o = Digest::SHA->new(256);
        $o->addfile($fh);
        Sidef::Types::String::String->new(scalar $o->hexdigest);
    }

    sub sha512 {
        ref($_[0]) || shift(@_);
        state $x = require Digest::SHA;
        open my $fh, '<:raw', "$_[0]" or return undef;
        my $o = Digest::SHA->new(512);
        $o->addfile($fh);
        Sidef::Types::String::String->new(scalar $o->hexdigest);
    }

    sub compare {
        ref($_[0]) || shift(@_);
        my ($self, $file) = @_;
        state $x = require File::Compare;
        my $cmp = File::Compare::compare("$self", "$file");

            $cmp < 0 ? Sidef::Types::Number::Number::MONE
          : $cmp > 0 ? Sidef::Types::Number::Number::ONE
          :            Sidef::Types::Number::Number::ZERO;
    }

    sub mktemp {
        my ($self, %opts) = @_;
        state $x = require File::Temp;
        my ($fh, $file) = File::Temp::tempfile(%opts);
        Sidef::Types::Glob::FileHandle->new($fh, __PACKAGE__->new($file));
    }

    *make_tmp  = \&mktemp;
    *make_temp = \&mktemp;

    sub exists {
        ref($_[0]) || shift(@_);
        my ($self) = @_;

lib/Sidef/Types/Glob/File.pm  view on Meta::CPAN

    sub name {
        ref($_[0]) || shift(@_);
        my ($self) = @_;
        Sidef::Types::String::String->new("$self");
    }

    sub basename {
        ref($_[0]) || shift(@_);
        my ($self) = @_;

        state $x = require File::Basename;
        Sidef::Types::String::String->new(File::Basename::basename("$self"));
    }

    *base      = \&basename;
    *base_name = \&basename;

    sub dirname {
        ref($_[0]) || shift(@_);
        my ($self) = @_;

        state $x = require File::Basename;
        Sidef::Types::Glob::Dir->new(File::Basename::dirname("$self"));
    }

    *dir      = \&dirname;
    *dir_name = \&dirname;

    sub is_absolute {
        ref($_[0]) || shift(@_);
        my ($self) = @_;

lib/Sidef/Types/Glob/File.pm  view on Meta::CPAN

    }

    *rel     = \&rel_name;
    *relname = \&rel_name;
    *abs2rel = \&rel_name;

    sub abs_path {
        my $class = ref($_[0]) || shift(@_);
        my ($self) = @_;

        state $x = require Cwd;
        $class->new(Encode::decode_utf8(Cwd::abs_path("$self")));
    }

    *realpath = \&abs_path;

    sub rename {
        ref($_[0]) || shift(@_);
        my ($self, $file) = @_;

        CORE::rename("$self", "$file")
          ? (Sidef::Types::Bool::Bool::TRUE)
          : (Sidef::Types::Bool::Bool::FALSE);
    }

    sub move {
        ref($_[0]) || shift(@_);
        my ($self, $file) = @_;

        state $x = require File::Copy;
        File::Copy::move("$self", "$file")
          ? (Sidef::Types::Bool::Bool::TRUE)
          : (Sidef::Types::Bool::Bool::FALSE);
    }

    *mv = \&move;

    sub copy {
        ref($_[0]) || shift(@_);
        my ($self, $file) = @_;

        state $x = require File::Copy;
        File::Copy::copy("$self", "$file")
          ? (Sidef::Types::Bool::Bool::TRUE)
          : (Sidef::Types::Bool::Bool::FALSE);
    }

    *cp = \&copy;

    sub edit {
        ref($_[0]) || shift(@_);
        my ($self, $code) = @_;

lib/Sidef/Types/Glob/FileHandle.pm  view on Meta::CPAN

    }

    sub fileno {
        my ($self) = @_;
        Sidef::Types::Number::Number::_set_int(CORE::fileno($self->{fh}));
    }

    sub lock {
        my ($self) = @_;

        state $x = require Fcntl;
        $self->flock(&Fcntl::LOCK_EX);
    }

    sub unlock {
        my ($self) = @_;

        state $x = require Fcntl;
        $self->flock(&Fcntl::LOCK_UN);
    }

    sub flock {
        my ($self, $mode) = @_;
        CORE::flock($self->{fh}, $mode)
          ? (Sidef::Types::Bool::Bool::TRUE)
          : (Sidef::Types::Bool::Bool::FALSE);
    }

lib/Sidef/Types/Glob/FileHandle.pm  view on Meta::CPAN

        $self;
    }

    sub copy {
        my ($self, $fh) = @_;

        if (ref($fh) ne __PACKAGE__) {
            return;
        }

        state $x = require File::Copy;
        File::Copy::copy($self->{fh}, $fh->{fh})
          ? (Sidef::Types::Bool::Bool::TRUE)
          : (Sidef::Types::Bool::Bool::FALSE);
    }

    *cp = \&copy;

    {
        no strict 'refs';
        *{__PACKAGE__ . '::' . '>>'} = \&read_to;

lib/Sidef/Types/Number/Number.pm  view on Meta::CPAN

            Math::GMPz::Rmpz_remove($r, $r, $g);
            Math::GMPz::Rmpz_gcd($g, $r, $g);
        }

        bless \$r;
    }

    sub useed {
        my ($n) = @_;

        state $_x = require Digest::SHA;

        my $z = _any2mpz($$n) // die "[ERROR] Number.useed(): invalid seed value <<$n>> (expected an integer)";

        my $hex = Math::GMPz::Rmpz_get_str($z, 16);
        $hex = substr($hex, 1) if (substr($hex, 0, 1) eq '-');

        my $bin  = CORE::pack('H*', $hex);
        my $seed = Digest::SHA::sha512($bin);

        while (CORE::length($seed) < 1024) {

lib/Sidef/Types/Perl/Perl.pm  view on Meta::CPAN

        ref($_[0]) || shift(@_);
        my ($self) = @_;
        __PACKAGE__->to_sidef(CORE::eval($$self));
    }

    *run  = \&execute;
    *eval = \&execute;

    sub tie {
        my ($self, $variable, $class_name, @args) = @_;
        state $x = require Scalar::Util;
        my $type = Scalar::Util::reftype($variable);
        __PACKAGE__->to_sidef(
                              CORE::tie(
                                        ($type eq 'ARRAY' ? (@$variable) : $type eq 'HASH' ? %$variable : $variable),
                                        "$class_name",
                                        map { defined($_) ? $_->get_value : $_ } @args
                                       )
                             );
    }

    sub untie {
        my ($self, $variable) = @_;
        state $x = require Scalar::Util;
        my $type = Scalar::Util::reftype($variable);
        __PACKAGE__->to_sidef(CORE::untie($type eq 'ARRAY' ? (@$variable) : $type eq 'HASH' ? %$variable : $variable));
    }

    sub dump {
        my ($self) = @_;
        Sidef::Types::String::String->new("$self");
    }

    *to_s   = \&dump;

lib/Sidef/Types/String/String.pm  view on Meta::CPAN

        bless \$r;
    }

    sub ascii2bits {
        my ($self) = @_;
        Sidef::Types::Array::Array->new(
                      [map { $_ ? Sidef::Types::Number::Number::ONE : Sidef::Types::Number::Number::ZERO } CORE::split(//, scalar CORE::unpack("B*", $$self))]);
    }

    sub decode_base64 {
        state $x = require MIME::Base64;
        bless \(my $value = MIME::Base64::decode_base64(${$_[0]}));
    }

    *base64_decode = \&decode_base64;

    sub encode_base64 {
        state $x = require MIME::Base64;
        bless \(my $value = MIME::Base64::encode_base64(${$_[0]}));
    }

    *base64_encode = \&encode_base64;

    sub md5 {
        state $x = require Digest::MD5;
        bless \(my $value = Digest::MD5::md5_hex(${$_[0]}));
    }

    sub sha1 {
        state $x = require Digest::SHA;
        bless \(my $value = Digest::SHA::sha1_hex(${$_[0]}));
    }

    sub sha256 {
        state $x = require Digest::SHA;
        bless \(my $value = Digest::SHA::sha256_hex(${$_[0]}));
    }

    sub sha512 {
        state $x = require Digest::SHA;
        bless \(my $value = Digest::SHA::sha512_hex(${$_[0]}));
    }

    sub parse_quotewords {
        my ($self, $delim, $keep) = @_;
        $delim //= ' ';
        state $x = require Text::ParseWords;
        my @words = map { bless \$_ } Text::ParseWords::parse_line("$delim", ($keep ? 1 : 0), $$self);
        Sidef::Types::Array::Array->new(\@words);
    }

    sub extract_bracketed {
        my ($self, $brackets) = @_;
        state $x = require Text::Balanced;
        my @results = Text::Balanced::extract_bracketed($$self, "$brackets");
        map { bless \$_ } @results;
    }

    sub extract_delimited {
        my ($self, $delim) = @_;
        state $x = require Text::Balanced;
        my @results = Text::Balanced::extract_delimited($$self, "$delim");
        map { bless \$_ } @results;
    }

    sub extract_codeblock {
        my ($self, $delim) = @_;
        state $x = require Text::Balanced;
        my @results = Text::Balanced::extract_codeblock($$self, "$delim");
        map { bless \$_ } @results;
    }

    sub extract_quotelike {
        my ($self) = @_;
        state $x = require Text::Balanced;
        my @results = Text::Balanced::extract_quotelike($$self);
        map { bless \$_ } @results;
    }

    sub extract_tagged {
        my ($self) = @_;
        state $x = require Text::Balanced;
        my @results = Text::Balanced::extract_tagged($$self);
        map { bless \$_ } @results;
    }

    sub substr {
        my ($self, $offs, $len) = @_;
        bless \(
                my $t = (
                         defined($len)
                         ? CORE::substr($$self, CORE::int($offs), CORE::int($len))

lib/Sidef/Types/String/String.pm  view on Meta::CPAN

            my $value = $$self;
            return $self->new($value =~ s{$search}{$block->run(_get_captures($value))}ger);
        }

        my $value = "$block";
        $self->new($$self =~ s{$search}{$value}geer);
    }

    sub glob {
        my ($self) = @_;
        state $x = require Encode;
        Sidef::Types::Array::Array->new([map { bless \(my $value = Encode::decode_utf8($_)) } CORE::glob($$self)]);
    }

    sub quotemeta {
        my ($self) = @_;
        $self->new(CORE::quotemeta($$self));
    }

    *escape = \&quotemeta;

lib/Sidef/Types/String/String.pm  view on Meta::CPAN

        warn $$self;
    }

    sub die {
        my ($self) = @_;
        die $$self;
    }

    sub encode {
        my ($self, $enc) = @_;
        state $x = require Encode;
        $self->new(Encode::encode("$enc", $$self));
    }

    sub decode {
        my ($self, $enc) = @_;
        state $x = require Encode;
        $self->new(Encode::decode("$enc", $$self));
    }

    sub encode_utf8 {
        my ($self) = @_;
        state $x = require Encode;
        $self->new(Encode::encode_utf8($$self));
    }

    sub decode_utf8 {
        my ($self) = @_;
        state $x = require Encode;
        $self->new(Encode::decode_utf8($$self));
    }

    sub deflate {
        my ($self) = @_;
        state $x = require IO::Compress::RawDeflate;
        my $input = $$self;
        IO::Compress::RawDeflate::rawdeflate(\$input => \my $output)
          or CORE::die("String.deflate failed: $IO::Compress::RawDeflate::RawDeflateError");
        bless \$output;
    }

    sub inflate {
        my ($self) = @_;
        state $x = require IO::Uncompress::RawInflate;
        my $input = $$self;
        IO::Uncompress::RawInflate::rawinflate(\$input => \my $output)
          or CORE::die("String.inflate failed: $IO::Uncompress::RawInflate::RawInflateError");
        bless \$output;
    }

    sub gzip {
        my ($self) = @_;
        state $x = require IO::Compress::Gzip;
        my $input = $$self;
        IO::Compress::Gzip::gzip(\$input => \my $output)
          or CORE::die("String.gzip failed: $IO::Compress::Gzip::GzipError");
        bless \$output;
    }

    sub gunzip {
        my ($self) = @_;
        state $x = require IO::Uncompress::Gunzip;
        my $input = $$self;
        IO::Uncompress::Gunzip::gunzip(\$input => \my $output)
          or CORE::die("String.gunzip failed: $IO::Uncompress::Gunzip::GunzipError");
        bless \$output;
    }

    sub _require {
        my ($self) = @_;

        my $name = $$self;

scripts/Graphical/hello_world_graphical.sf  view on Meta::CPAN

#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Hello_world/Graphical
#

var tk = require('Tk');
var main = 'MainWindow'.to_caller.new;
main.Button(
    '-text'    => 'Goodbye, World!',
    '-command' => 'exit',
).pack;
tk.MainLoop;

scripts/Graphical/sierpinski_triangle_graphical.sf  view on Meta::CPAN

    var sp = (' ' * pow(2, i));
    triangle = (triangle.map {|x| sp + x + sp} +
                triangle.map {|x| x + ' ' + x})
  } * n
  triangle
}

class Array {
  method to_png(scale=1, bgcolor='white', fgcolor='black') {

    static gd = require('GD::Simple')
    var width = self.max_by{.len}.len
    self.map!{|r| "%-#{width}s" % r}

    var img = gd.new(width * scale, self.len * scale)

    for i in ^self {
      for j in RangeNum(i*scale, i*scale + scale) {
        img.moveTo(0, j)
        for line in (self[i].scan(/(\s+|\S+)/)) {
          img.fgcolor(line.contains(/\S/) ? fgcolor : bgcolor)

scripts/Graphical/window_creation.sf  view on Meta::CPAN

#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Window_creation
#

var tk = require('Tk');
'MainWindow'.to_caller.new;
tk.MainLoop;

scripts/RosettaCode/md5_1.sf  view on Meta::CPAN

#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/MD5
#

var md5 = require('Digest::MD5').new;
md5.add("The quick brown fox jumped over the lazy dog's back");
say md5.hexdigest;

scripts/RosettaCode/secure_temporary_file.sf  view on Meta::CPAN

#!/usr/bin/ruby

#
## https://rosettacode.org/wiki/Secure_temporary_file
#

var tmpfile = require('File::Temp');
var fh = tmpfile.new(UNLINK => 1);
say fh.filename;
fh.print("Hello, World!\n");
fh.close;

scripts/Tests/scalar_context.sf  view on Meta::CPAN

#!/usr/bin/ruby

# Test scalar context (provided by the unary + operator).

var TimePiece = require('Time::Piece')

var d = TimePiece.strptime("2020-02-02", "%Y-%m-%d")
var a = [d.add(TimePiece.ONE_DAY)]
var b = +d.add(TimePiece.ONE_DAY)

assert_eq(a, [0, 0, 0, 3, 1, 120, 1, 33, 0])
assert_eq(b.strftime("%Y-%m-%d"), "2020-02-03")

var palindates = Enumerator({ |f|
    loop {

scripts/WWW/http_tiny.sf  view on Meta::CPAN

#!/usr/bin/ruby

var req = require('HTTP::Tiny');
var http = req.new;

var response = http.get('http://example.net');
if (!response{:success}) {
    "GET failed!\n".die;
}

say "#{response{:status}} #{response{:reason}}";

response{:headers}.each { |k,v|

scripts/WWW/socket_inet.sf  view on Meta::CPAN

#!/usr/bin/ruby

var inet = require('IO::Socket::INET');

var sock = inet.new(
                LocalAddr => "127.0.0.1:8080",
                Listen    => 1,
                Reuse     => 1,
        );

while (var client = sock.accept) {
    client.print ("HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/html; charset=UTF-8\r\n\r\n" +

scripts/json.sf  view on Meta::CPAN

#!/usr/bin/ruby

var json = require('JSON::PP').new;

# Parse JSON
var data = json.decode('{"blue": [1, 2], "ocean": "water"}');
say data;

# Change JSON
data{:ocean} = Hash.new(water => %w[fishy salty]);

# Encode JSON
say json.encode(data);



( run in 0.751 second using v1.01-cache-2.11-cpan-05444aca049 )