【发布时间】:2017-01-19 23:39:34
【问题描述】:
我认为对于函数名称,%of 比 percent-of 更具可读性和简洁性。这是使用较长名称的工作代码。
#!/bin/env perl6
# Quick stats from gene_exp.diff file
sub percent-of
{
return sprintf('%.1f', (100 * $^a/ $^b).round(0.1));
}
my $total = first-word-from("wc -l gene_exp.diff ") -1; # subtract one for the header
my $ok = first-word-from "grep -c OK gene_exp.diff";
my $yes = first-word-from "grep -c yes gene_exp.diff";
put '| total | OK | OK % | yes | yes % | yes / OK |';
put "| $total | $ok | { percent-of $ok, $total } | $yes | { percent-of $yes,$total } | { percent-of $yes, $ok } |";
sub first-word-from ( $command )
{
return ( qqx{ $command } ).words[0];
}
由于我将子例程名称放在其参数之前,我认为这将是一个前缀运算符。所以这是我认为可以使较短的名称起作用的方法(即使用sub prefix:<%of> 来声明函数):
#!/bin/env perl6
# Quick stats from gene_exp.diff file
sub prefix:<%of>
{
return sprintf('%.1f', (100 * $^a/ $^b).round(0.1));
}
my $total = first-word-from("wc -l gene_exp.diff ") -1; # subtract one for the header
my $ok = first-word-from "grep -c OK gene_exp.diff";
my $yes = first-word-from "grep -c yes gene_exp.diff";
put '| total | OK | OK % | yes | yes % | yes / OK |';
put "| $total | $ok | { %of($ok, $total) } | $yes | { %of($yes,$total) } | { %of($yes,$ok) } |";
sub first-word-from ( $command )
{
return ( qqx{ $command } ).words[0];
}
但我收到以下错误:
| total | OK | OK % | yes | yes % | yes / OK |
Too few positionals passed; expected 2 arguments but got 1
in sub prefix:<%of> at /home/bottomsc/bin/gene_exp_stats line 6
in block <unit> at /home/bottomsc/bin/gene_exp_stats line 15
我确信我正在尝试的事情是可能的。我见过比这更疯狂的函数,比如中缀I don't care operator ¯\(°_o)/¯。我究竟做错了什么?在尝试使用和不使用括号调用 %of 时,我得到完全相同的错误,所以这不是问题。
当我输入这个问题时,我刚刚意识到我应该尝试遵循example just cited 并将其作为中缀运算符进行操作,并且它有效。但是,我仍然很好奇为什么我的前缀运算符代码不起作用。这可能是我忽略的一些非常基本的东西。
更新:
这是作为中缀运算符完成时的工作代码。但是我仍然很好奇我在前缀版本上做错了什么:
#!/bin/env perl6
# Quick stats from gene_exp.diff file
sub infix:<%of>
{
return sprintf('%.1f', (100 * $^a/ $^b).round(0.1));
}
my $total = first-word-from("wc -l gene_exp.diff ") -1; # subtract one for the header
my $ok = first-word-from "grep -c OK gene_exp.diff";
my $yes = first-word-from "grep -c yes gene_exp.diff";
put '| total | OK | OK % | yes | yes % | yes / OK |';
put "| $total | $ok | { $ok %of $total } | $yes | { $yes %of $total } | { $yes %of $ok } |";
sub first-word-from ( $command )
{
return ( qqx{ $command } ).words[0];
}
【问题讨论】: