in reply to Raku: * v. $_ (asterisk v. the topic variable)

Hello 7stud,

Consider the following:

16:46 >raku -e "for 1 .. * { qq[$_ is { $_.^name }].put; last if $_ >= + 3; }" 1 is Int 2 is Int 3 is Int 16:46 >

$_ is the topic variable which, as in Perl, acts like a pronoun: we can read the code as “for each value from 1 to infinity, print it and its type, ...” The topic variable $_ is documented in https://docs.raku.org/language/variables#The_$__variable.

The star, on the other hand, is not a variable, but rather an object — specifically, an instance of Raku’s built-in Whatever class. Its meaning depends on the context in which it is used. In this case it is being used as the end-point of a range, so its meaning is defined by the Range class, which interprets it as Inf (infinity). This use of the star in Raku is documented in https://docs.raku.org/type/Whatever.

So although $_ and * can sometimes be used interchangeably, they are in fact quite different things.

Hope that helps,

Athanasius <°(((><contra mundum סתם עוד האקר של פרל,

Replies are listed 'Best First'.
Re^2: Raku: * v. $_ (asterisk v. the topic variable)
by 7stud (Deacon) on Feb 19, 2024 at 14:34 UTC

    Thanks! I do think the * is prettier than $_. :)

    According to the Whatever docs, if you call a method on * then that creates a lambda (anonymous function):

    <a b c>.map: *.uc; # same as <a b c>.map: -> $char { $char.uc }

    Let's test that out on one of the examples in my question. I'll test whether:

    Str $file where *.IO.f = 'file.dat',

    ...is the same as:

    Str $file where -> $x {$x.IO.f} = 'file.dat',

    Here's the full code with a file name, a.txt, that exists in the current directory:

    #b.raku sub MAIN( Str $file where -> $x {$x.IO.f} = 'a.txt', Int :$length = 24, Bool :$verbose ) { say $length if $length.defined; say $file if $file.defined; say 'Verbosity ', ($verbose ?? 'on' !! 'off'); } --output:-- $ raku b.raku 24 a.txt Verbosity off $ raku b.raku --verbose --length=7 a.raku 7 a.raku Verbosity on

    It looks to me like when you specify a code block on the right of where, the code block is called with the term to the left of where as the argument.

    I don't think the if statements on the end of $length and $file actually do anything: with those default values both variables will be defined.

        That's some comment! Thanks!