7stud has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
Here's an example that uses the topic variable $_
use v6.d; sub go(Int $x where 1 < $_ < 9) { # $_ refers to $x say $x; } go(3); go(0); --output:-- 3 Constraint type check failed in binding to parameter '$x'; expected an +onymous constraint to be met but got Int (0) in sub go at b.raku line 4 in block <unit> at b.raku line 9
I've also seen examples that use a * instead of $_
sub go(Int $x where 1 < * < 9) { say $x; } go(3); go(0); --output:-- 3 Constraint type check failed in binding to parameter '$x'; expected an +onymous constraint to be met but got Int (0) in sub go at b.raku line 4 in block <unit> at b.raku line 9
But * and $_ do not appear to be synonyms because * doesn't work all the time:
for <a b c> {say $_}; # shorter version: for <a b c> {.say} for <a b c> {say *}; --output:-- a b c * * *
Here is another example in the docs that uses *:
sub MAIN( Str $file where *.IO.f = 'file.dat', Int :$length = 24, Bool :$verbose ) { say $length if $length.defined; say $file if $file.defined; say 'Verbosity ', ($verbose ?? 'on' !! 'off'); }
In that example, I can replace * with $_ or $file, and there is no error, and I get the same output. (I don't understand the where clause because $file.IO.f tests whether $file is a file and returns True or False, so the where clause evaluates to something like True = 'file.dat'. What does that do? Ahh, nevermind: 'file.dat' is the default value, and the parameter variable is $file where $file.IO.f. My tests show that the default value gets assigned to $file before the file test. It would be clearer if you could write Str $file = 'file.dat' where *.IO.f but that results in an error. )
Here's an example that calls first() on a list/array, which allows you to look for the first() thing that matches some condition:
class Foo { method bar( $self: ){ "baz" } }; say Foo.^methods.first(*.name eq 'bar').signature ~~ :($: *%) ; # OUTPUT: «True␤»
If I replace the * with $_, I get an error.
I can't find anything in the docs about the use of * in the examples I posted.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Raku: * v. $_ (asterisk v. the topic variable)
by Athanasius (Archbishop) on Feb 19, 2024 at 07:06 UTC | |
by 7stud (Deacon) on Feb 19, 2024 at 14:34 UTC | |
by raiph (Deacon) on Feb 20, 2024 at 02:18 UTC | |
by 7stud (Deacon) on Feb 20, 2024 at 21:54 UTC |