Re: MAIN(*magic)

[email protected] (Elizabeth Mattijsen)
Newsgroups perl.perl6.users
Message-ID <[email protected]>
> On 15 Mar 2024, at 03:57, Mark Devine <[email protected]> wrote:
> 
> Rakoons,
>  I keep running into a space with Raku where it would be nice to have some magic to reduce boilerplate.  I often make roles & classes with interface options that flow from a consuming script’s MAIN arguments, then the first bit of code at the top the MAIN block, then into instantiation.  If a person makes nice utility libraries with lots of options for the user & employs them a lot, the time consumed typing out the boilerplate adds up & bloats the code.  Is there any way to shorten this pattern?  I was thinking about a ‘switchable’ trait for attributes (with the naivety of a schoolboy).
>  my class Output {
>     has $.csv      is switchable;
>     has $.html     is switchable;
>       .
>       .
>       .
>     has $.xml     is switchable;
> }
>  my class Timer {
>     has $.count    is switchable;
>     has $.expire   is switchable;
>     has $.interval is switchable;
> }
>  sub MAIN (
>     Output.switchables,     #= switchables from Class 'Output'
>     Timer.switchables,      #= switchables from Class 'Timer'
> ) {
>     my Timer $t    .= new: :$expire, :$interval, :$count;   # variables magically appear in scope
>     my Output $o   .= new: :$csv, :$html, … , :$xml;        # variables magically appear in scope
> }
>  I estimate 10-50 lines of boilerplate could be removed from most of my Raku scripts with something like that.  Unfortunately, I don’t possess any dark magic for such things or I’d put forward an attempt.

An interesting idea!

Unfortunately I don't see this happening in the legacy grammar.  And it may still be pretty hard to do in RakuAST.

If you'd want to have a solution now, I'd look at *generating* the boilerplate code where appropriate.  This approach is used in the core in several locations, most notably recently in the localization modules.


Liz
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.