bri*_*foy 7 multiple-dispatch perl6
我可以根据一些非参数值选择一个多,但我必须至少有一个参数,所以我可以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 }
Run Code Online (Sandbox Code Playgroud)
我似乎记得有人曾经在multis中发送一些没有参数的技巧.例如,我有一个show-env例程,我想在周围散布,如果我设置了一些调试条件,它只会做任何事情.我可以像我所展示的那样实现它,但这并不是很令人满意,而且我想象的其他地方并不聪明:
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 }
Run Code Online (Sandbox Code Playgroud)
我可以用可选的命名参数做类似的事情,但这更不令人满意.
当然,我可以在这个简单的例子中做到这一点,但这并不好玩:
sub show-env () {
return True unless $*DEBUG;
dd %*ENV;
}
Run Code Online (Sandbox Code Playgroud)
你可以解构的|用().
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); …
Run Code Online (Sandbox Code Playgroud)
或者你可以有一个proto声明
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 () …
Run Code Online (Sandbox Code Playgroud)