Can I choose between Perl 6 multis that have no parameters?

I can select multi based on some value other than the argument, but I must have at least one argument so that I can where :

 our $*DEBUG = 1; debug( 'This should print', 'Phrase 2' ); $*DEBUG = 0; debug( 'This should not print' ); multi debug ( *@a where ? $*DEBUG ) { put @a } multi debug ( *@a where ! $*DEBUG ) { True } 

It seems that I recall some kind of trick that someone used to send to multis, which did not take exactly any parameters. For example, I have a show-env routine that I would like to sprinkle, and that only does anything if I set some debugging conditions. I could achieve this, as I have shown, but it is not very satisfactory, and this is not what I think I saw elsewhere:

 our $*DEBUG = 1; debug( 'This should print', 'Phrase 2' ); show-env(); $*DEBUG = 0; debug( 'This should not print' ); show-env(); multi debug ( *@a where ? $*DEBUG ) { put @a } multi debug ( *@a where ! $*DEBUG ) { True } # use an unnamed capture | but insist it has 0 arguments multi show-env ( | where { $_.elems == 0 and ? $*DEBUG } ) { dd %*ENV } multi show-env ( | where { $_.elems == 0 and ! $*DEBUG } ) { True } 

I could do something similar with additional named parameters, but that was even less satisfying.

Of course, I could only do this with this simple example, but this is not fun:

 sub show-env () { return True unless $*DEBUG; dd %*ENV; } 
+6
source share
2 answers

You can destroy | using () .

 my $*DEBUG = 1; show-env(); $*DEBUG = 0; show-env(); # use an unnamed capture | but insist it has 0 arguments by destructuring multi show-env ( | () where ? $*DEBUG ) { dd %*ENV } multi show-env ( | () where ! $*DEBUG ) { True } show-env(42); # Cannot resolve caller show-env(42); … 

Or you can have a proto ad

 proto show-env (){*} multi show-env ( | where ? $*DEBUG ) { dd %*ENV } multi show-env ( | where ! $*DEBUG ) { True } show-env(42); # Calling show-env(Int) will never work with proto signature () … 
+7
source

A more elegant way to insist that the interception is empty by specifying it with an empty signature:

 multi show-env ( | () where ? $*DEBUG ) { dd %*ENV } multi show-env ( | () where ! $*DEBUG ) { True } 
+7
source

Source: https://habr.com/ru/post/1274431/


All Articles