I thought that %of would be more readable and concise than percent-of for the function name. Here is the working code using a longer name.
#!/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]; }
Since I put the name of the subroutine before its arguments, I would think that it would be a prefix operator. So here is what I would think in order to work with a shorter name (i.e. Using sub prefix:<%of> to declare a function):
#!/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]; }
But I get the following error:
| 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'm sure something like what I'm trying is possible. I saw much more crazy functions than this, for example infix. I do not need the operator Β―\(Β°_o)/Β― . What am I doing wrong? I get the same error when trying to call %of with and without parentheses, so this is not a problem.
As I typed this question, I just realized that I should try to follow the example and do it as an infix operator, and it worked. However, I'm still curious why my prefix code code is not working. This is probably something very basic that I am missing.
UPDATE:
Here is the working code made as an infix operator. But I'm still wondering what I'm doing wrong with the prefix version:
#!/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]; }