develooper Front page | perl.perl6.users | Postings from December 2022

Re: When to use .new?

Thread Previous | Thread Next
Ralph Mellor
December 5, 2022 19:08
Re: When to use .new?
Message ID:
On Thu, Dec 1, 2022 at 4:28 AM ToddAndMargo via perl6-users
<> wrote:
> Why can I get away with `my Str $x = "";`
> But I have to use .new here (an other places too) `my $ppSession =;`

There are ways to write the value of some data types with minimum fuss.

This is typically the case for oft used types like strings and numbers.

Many programming languages have "literals" as the ultimate no fuss way.

Raku has them for strings and numbers:

"this is a string"
42 # <-- `42` is a number, an integer

You create a string by just writing its value inside quote marks.

You create a number by just writing its value.

The `.new` is implicit, happening behind the scenes.


It's not practical to have "literal" short cuts for *all* data types.

While code corresponding to pointers (and dereferences of them)
is *explicitly* written a LOT in C, explicit pointer coding is almost
completely eliminated in Raku.

The only exception is in some NativeCall code that makes a lot of
use of its `Pointer` type for representing a Raku wrapped C Pointer.

Is that enough to justify introducing a "literal" form for `Pointer`s?

I doubt it. But if you wanted to explore that, Raku makes it possible.

> Is there some rule I can follow that let me know when I have to
> use `.new and when I do not?

About the only rule there can be for arbitrary Raku code is whether
you already know a way to create a value without using `.new`, or
have time available to investigate the two approaches. For builtin
types that means reading the official Raku doc. For user defined
types defined in modules you use that means reading the doc of
those modules.

But in general the vast majority of types require use of `.new`.

The main exceptions I can think of are strings, numbers, pairs,
and basic collections. (Untyped lists, captures, positional arrays,
and associative arrays -- hashes etc.)

> (I am getting tired of figuring it out the hard way.)

I found it easy because I didn't *try* to find out but was just
delighted each time I realized there was yet another nice and
even shorter way to create values.

One thing I note in this context here is that one doesn't have to
write out the fully qualified type name `NativeCall::Types::Pointer`.

One can just write `Pointer`.

(NativeCall introduces this short form by default if you write `use


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About