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

Re: When to use .new?

Thread Previous | Thread Next
From:
Ralph Mellor
Date:
December 5, 2022 19:20
Subject:
Re: When to use .new?
Message ID:
CAPLR5SfpSbcNJYDx79bJTd7wrSmBuOpWuJeCmcam6g_pu18wAA@mail.gmail.com
I forgot to mention one other shortcut that is always available
if you do have to use `.new` (which is the case for most types).

You can write:
```
my $foo = 42;
```
The `42` on the RHS of the `=` is the shortest way to create
an integer value corresponding to `42`.

But you could also write:
```
my $foo = Int.new: 42;
```
It's odd, but you could that. You could also write:

```
my Int $foo .= new: 42;
```
Note the `.=` instead of `=` and the `new` instead of `Int.new`.

That is, if you constrain a variable's type, and want to initialize
that variable to a value of exactly that type, you don't have to
repeat the type name on the RHS of the `=` if you write it as above.

For types that have literal forms it's not helpful. And for short type
names it's helpful, but only a little. But let's say you really wanted
to write out the full `NativeCall::Types::Pointer` and you wanted a
variable constrained to that type and initialized to have a value of
that type. Now it's a big deal:

```
my NativeCall::Types::Pointer $foo .= new: 42;
```

--
raiph

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About