Questions tagged [raku]
For questions relating to the Raku programming language (formerly known as Perl 6).
1,997
questions
7
votes
1
answer
100
views
How can this Raku comparison be improved performance-wise?
I wanted to do some comparison between Python and Raku while also learning Raku.
Originally I wanted a much bigger script, but since the difference is already huge, I'll ask for guidance now.
I tried ...
8
votes
2
answers
166
views
Exit the function without aborting the script
I have a function that accepts an array of positive values only. Dies when any negative value is given.
# Consider edge cases
# First check if all elements are > 0, if not throw informative error
# ...
6
votes
2
answers
131
views
Is it possible to predefine the initial size of a Str?
In some languages it is possible for the developer to specify an initial size for a string. Has Raku something similar? I have a string where I'll be concatenating text a few thousand times. The final ...
8
votes
1
answer
119
views
When is "use lib PATH" evaluated?
I would like to set the library load paths for Raku and Inline::Perl5 modules from within my script while minimizing the runtime impact.
I tried to replace
use lib $*PROGRAM.resolve.parent(2) ~ '/lib';...
6
votes
1
answer
154
views
Why am I receiving a warning about deprecated code after installing Rakudo™ v2023.08?
After installing Rakudo™ v2023.08, I get the following error every time I run a raku command, either a script or a one-liner.
Saw 1 occurrence of deprecated code.
=====================================...
11
votes
3
answers
272
views
Avoid repeating the same variable in a chain of conditions
I have a script with a conditional and a pile of checks using the same variable. Something similar to this:
my $size = "123B";
say "OK" if $size ~~ Str && $size.ends-with(&...
10
votes
2
answers
132
views
Why can I not migrate a supply in a whenever block of a unix socket?
server
#!/usr/bin/env raku
unlink "/run/user/1000/sock";
my $socket = IO::Socket::Async.listen-path("/run/user/1000/sock");
react {
my $timerSupplier = Supplier.new;
...
10
votes
0
answers
89
views
How to read the docs with rakudoc?
I just installed rakudoc with zef. But it doesn't seem to find any
doc.
$ rakudoc --version
/home/user/.raku/bin/rakudoc :auth<zef:coke>:api<1>:ver<0.2.6>
$ rakudoc -b
$ rakudoc Map
...
5
votes
3
answers
127
views
Creating a raku module for zef upload
I've created a new Raku module and uploaded with fez, all working fine.
dist.ini file in the top directory. There are directives such as ReadmeFromPOD which don't seem to do anything. Is this file ...
8
votes
1
answer
104
views
How to pin a Raku Grammar token to only match when at the end of a string
I have written this - it works fine:
use Grammar::Tracer;
my grammar Lambda {
token TOP { <signature> <body> ' as ' <r-type> }
rule signature { '|' <a-sig> [','...
11
votes
1
answer
88
views
Strange behavior when changing $*SCHEDULER after execution of external program
Description
There is an example:
#!/bin/env raku
run 'raku', '-e', 'say "ok"';
exit 0;
my $*SCHEDULER = ThreadPoolScheduler.new(max_threads => 128);
On linux output is:
ok
Unhandled ...
9
votes
1
answer
84
views
How to add an attribute and its accessors in Raku using add_attribute()?
I have this program:
class Foo {
has $.first;
}
my $a = Attribute.new(
:name('$!second'),
:type(Int),
:package('Foo'),
:has_accessor(True)
);
Foo.^...
8
votes
1
answer
227
views
Where is Peterson's algorithm used in the real world?
I'm reading Operating Systems: Three Easy Pieces and I understand Peterson's algorithm is a synchronization mechanism that provides mutual exclusion among processes/threads, however it's unclear to me ...
8
votes
1
answer
129
views
Simple, stoppable Timer using Raku concurrency
I have been wrestling with Promises, Supplies and other concurrency features, but I can't get find a straightforward way to do what I want.
My goal is to do something like this:
class Timer {
has $...
5
votes
1
answer
161
views
How to debug a Raku program
I looked at the documentation, but I didn't quite understand how to debug. I use the raku-debug command, but it reports an error:
Could not find Debugger::UI::CommandLine.
When I tried to search on ...
10
votes
1
answer
91
views
Role-constrained variable does not accept derived role defined inline
role R { }
role S does R { }
role T does S { }
my R $r0 = T; # compiles
my R $r1 = role U does R { }; # compiles
my R $r2 = role V does S { }; # compile error:
# Type check failed in assignment to $...
8
votes
1
answer
90
views
How do I create a class with the same name as a built-in one without overshadowing it in Raku?
This is quite silly and I know the obvious thing to do is simply naming the class differently but I'm still curious. In the class ColumnType::Date, I'd like typecast to return a Raku's Date object, ...
9
votes
1
answer
141
views
How to convert Hex string to IEEE754 Float number with Raku?
In Python, unpack can convert Hex string to IEEE754 Float number:
import struct
print(struct.unpack('<f', bytes.fromhex("00000042"))[0]) # 32.0
< represents LITTLE ENDIAN byte order, ...
9
votes
1
answer
126
views
Can I check the type of the keys/values of an Array of Pairs?
I need to create a data structure with keys/values which maintains the order. The hashes don't keep the order, so I'm using an array of pairs. All is working as expected. However, I would like to ...
7
votes
1
answer
70
views
How can I reference an existing method in Raku?
As explained in the docs, you can reference an existing function by prepending the & sigil:
&say # reference to the `say` function
&infix:<+> # reference to the infix `+` ...
10
votes
2
answers
339
views
What's the Raku equivalent of the super keyword as used in JavaScript and Python?
Whenever you extend a class in JavaScript or Python, the derived class must use the super keyword in order to set attributes and/or invoke methods and constructor in the base class. For example:
class ...
6
votes
1
answer
73
views
How do I create a multiline string in Raku?
In JavaScript (ES6), you can use template literals (``) to create multiline strings as shown in the following example:
const html = `
<div>
<p>Raku is <b>ofun</b>.</p&...
5
votes
1
answer
57
views
What's the difference between $.attribute and self.attribute inside a class in Raku?
For example, in this class Foo both methods b and c return the same value:
class Foo {
method a { 42 }
method b { $.a }
method c { self.a }
}
my $foo = Foo.new;
say $foo.a; #=> ...
9
votes
1
answer
95
views
How does the scope effect EVAL of an infix:<> sub?
This code works as expected:
sub infix:<mean>(*@a) {
@a.sum / @a.elems
}
sub Mean (*@a) {
@a.sum / @a.elems
}
say EVAL 'Mean 2, 6, 4'; # Output: 4
say EVAL '2 mean 6 mean 4'; # ...
10
votes
2
answers
117
views
Raku NativeCall to SOD Segmentation fault
I am trying to use sod in Raku using NativeCall but I keep getting a segmentation fault error.
#!/usr/bin/env raku
use v6.d;
use NativeCall;
class Image is repr('CStruct') {
has int32 $.h;
...
7
votes
1
answer
153
views
CALL-ME with gather/take used in a hyper method chain doesn't work
Been playing with method chaining and CALL-ME
Below is a toy class I'm using to play with. The CALL-ME just invokes the double method for the Seq of values it gets given.
class Math does Callable
{
...
9
votes
2
answers
204
views
Safely escaping Raku regex metacharacters
I want to convert a glob-style pattern into a Raku regex. This is how I'm doing it now:
s :global {
|| $<question-mark> = '?'
|| $<asterisk> = '*'
|| $<non-word> ...
9
votes
2
answers
567
views
How are Junctions evaluated?
The idea of Junctions were originally introduced by Damian Conway in order to mimick Quantum superposition and express Quantum Computing algorithms.
As cute at this may be, the concepts of ...
13
votes
3
answers
1k
views
Is there a way to get all files in a directory recursively in a concise manner?
I mean usable in one-liners. For example this:
raku -e 'dir(".")==>say()'
prints all files and directories in the current directory. How do I update it so it works recursively (without ...
8
votes
2
answers
145
views
How to introspect a Raku operator?
I can introspect routines in Raku, for example the say
routine:
[5] > &say.WHAT ...
8
votes
2
answers
160
views
Why the pointy block with Match in for loop output Nil?
A valid Match object is not empty or undefined in my opinion:
say Match.new(:orig("20230213112803"), :from(4), :pos(6)).elems; # 0
say Match.new(:orig("20230213112803"), :from(4),...
7
votes
2
answers
195
views
How do I smartmatch against a list of values with when inside a given block in Raku?
I came across this JS code snippet:
function append(demo = "", file = "") {
const extra = "ctl=1&embed=1";
if (demo && file) return `/${demo}/?file=${...
9
votes
1
answer
178
views
Is there a way to consume request.body multiple times in Cro?
I'm writing a middleware that consumes request.body and does some validation like so:
before-matched {
request-body -> (:$email, :$captcha-token, :$captcha-solution, *%_) {
# Validate ...
7
votes
1
answer
97
views
How do I conceal RakuDoc (POD6) contents in vim?
I would like to use vim's conceal command to hide all my POD6. I've tried
syntax match rakuPodPrefix /^=begin/ conceal cchar=>
without success.
Alternatively, what is a good foldexpr to fold away ...
5
votes
1
answer
249
views
Foldcase conversion between (German) lower ß (U+00DF) and upper ẞ (U+1E9E)?
According to Wikipedia, in 2017 using an uppercase ẞ (Unicode U+1E9E) was officially adopted--at least as an option--for what may in fact be a subset of fully-capitalized words in German:
In June of ...
17
votes
1
answer
436
views
How do I register different events in a supply in Raku?
Hopefully "events" isn't a misnomer in Rakuland. As far as I understand, Supplies are the Raku equivalent for "events" in other programming languages such as NodeJS. In NodeJS, you ...
11
votes
1
answer
490
views
Too few positionals passed, why?
sub hanoi(Int:D $n, Str:D $start, Str:D $end, Str:D $extra,
&move_disk:(Int:D, Str:D, Str:D --> Nil)
--> Nil)
{
if $n == 1 {
move_disk(1, $start, $end); ...
10
votes
2
answers
186
views
definedness constraint on parametrized roles
Should it be possible to add a definedness constraint on parameterized roles? The following attempt:
role R[::T] { }
class C {
method m ( R[Str]:D $a ) { }
}
results in:
Invalid typename 'D' in ...
8
votes
1
answer
190
views
How can a Raku UDP server know where to send a response to?
I can write a UDP server that will receive messages from a client using IO::Socket::Async
my $socket = IO::Socket::Async.bind-udp: 'localhost', 3333;
react whenever $socket.Supply: :bin {
say &...
4
votes
3
answers
502
views
Processing POST request of an audio file
What is the equivalent POST request using:
Cro
"HTTP::Tiny"
Other libraries
for this curl shell command:
curl --request POST \
--url https://api.someservice.com/v1/ \
--header '...
2
votes
0
answers
65
views
is zef supposed to update the repository when the version of the module changed in a git? [duplicate]
WHen you have a module in Raku... there is a json file in which the version number is specified of the module.. Is zef supposed to update the repository by checking the given git repository regularly ...
5
votes
1
answer
129
views
How to use LibXML::Reader?
raku freezes when trying to use LibXML::Reader.
use v6;
use LibXML::Reader;
sub dump-node($reader)
{
printf "%d %d %s %d\n",
$reader.depth,
$reader.nodeType,
$reader.name,
...
10
votes
1
answer
74
views
In Raku, how can I get Pod::To modules to recognize a Pod::Block::Declarator POD element?
#!/usr/bin/env raku
use v6.d;
sub MAIN (
:$foo = 42, #= A test
) {
run $*EXECUTABLE, '--doc', $*PROGRAM;
}
=begin pod
=head1 Bar
blah, blah, blah
=head2 Baz
yadda, yadda, yadda
=end pod
...
9
votes
2
answers
155
views
Why is this Raku program producing a Seq of Array rather than a simple Array?
my %f;
for $*HOME.dir() -> $file {
my $filename = $file.basename;
%f{$filename}.push: $file, rand;
}
my $p = %f.pick; # just need any old random element
say $p.^name;
say "{$p.values.^...
10
votes
1
answer
172
views
is Date.new() ... DateTime.new() a valid syntax?
When I use two DateTime objects on both sides of the sequence operator (...), Raku reports that No such method 'succ' for invocant of type 'DateTime'. Did you mean any of these: 'sum', 'utc'?
DateTime....
9
votes
2
answers
407
views
How reliable is Raku's is-prime function?
The documentation for Raku's is-prime function says the following:
Returns True if this Int is known to be a prime, or is likely to be a
prime based on a probabilistic Miller-Rabin test.
Returns ...
10
votes
1
answer
200
views
why use double semicolon in Raku function signature?
In Raku functions documentation, there is an example as follows:
enum DebugType <LOG WARNING ERROR>;
#|[ Prints a message to stderr with a color-coded key. ]
proto debug(DebugType:D $type, ...
6
votes
0
answers
125
views
Is it possible to use Smart::Comments:from<Perl5> in a raku program?
#!/usr/bin/env raku
use Inline::Perl5;
use Smart::Comments:from<Perl5>;
my $foo = 42;
### $foo
say "Done";
Expected output:
### $foo: 42
Done
Actual output:
Done
zsh: ...
8
votes
1
answer
185
views
How to update Raku documentations which p6doc will read?
On mac, I have installed rakudo-star 2023.02 from Homebrew. Then I tried to zef install rakudoc, but it aborted installing due to test failures. It seems that the development of rakudoc had stalled ...
9
votes
1
answer
227
views
Using "is default" with Hash of Arrays
Here is the working example:
my %hash;
for 1..4 -> $i {
%hash{$i} = Array.new without %hash{$i};
%hash{$i}.push: $_ for ^$i;
}
say %hash; # OUTPUT: {1 => [0], 2 => [0 1], 3 => [0 1 ...