如何在perl中像C一样使用方括号?
昨天Computerphile上传了一段关于code golf和bitshift变体的视频,我对生成音乐的程序非常着迷。 这是我在视频中的格式化版本如何在perl中像C一样使用方括号?,perl,audio,literals,square-bracket,Perl,Audio,Literals,Square Bracket,昨天Computerphile上传了一段关于code golf和bitshift变体的视频,我对生成音乐的程序非常着迷。 这是我在视频中的格式化版本 int g(int sample, int x, int t, int overdrive) { return ( ( 3 & x & ( sample * ( ( 3 & sample >> 16 ? "BY}6YB6%" :
int g(int sample, int x, int t, int overdrive) {
return (
(
3 & x & (
sample *
(
(
3 & sample >> 16
?
"BY}6YB6%"
:
"Qj}6jQ6%"
)[t % 8]
+
51
) >> overdrive
)
) << 4
);
}
int main(int n, int s) {
for (int sample=0 ;; sample++)
putchar(
g(sample, 1, n=sample >> 14, 12)
+
g(sample, s=sample >> 17, n^sample >> 13, 10)
+
g(sample, s/3, n + ((sample >> 11) % 3), 10)
+
g(sample, s/5, 8 + n-((sample >> 10) % 3), 9)
);
}
我唯一的解释是,[$\u2]%8]
没有像我认为的那样在perl中工作
如何使程序在perl和C中产生相同的音乐?在windows上,您可以使用
perl theprogram.pl | sox-c 1-b 8-e unsigned-t raw-r 8k--t waveaudio 0
,如果您已经安装了该程序。字符串在perl中不是数组,您需要用调用substr()函数替换数组访问:
...
ord(substr((
3 & $_[0] >> 16
?
"BY}6YB6%"
:
"Qj}6jQ6%"
), $_[2] % 8, 1))
...
更有效率:
# Outside the sub.
my $a1 = [ unpack 'C*', "BY}6YB6%" ];
my $a2 = [ unpack 'C*', "Qj}6jQ6%" ];
...
${ 3 & $_[0] >> 16 ? $a1 : $a2 }[ $_[2] % 8 ]
...
字符串在perl中不是数组,您需要用调用substr()函数替换数组访问:
...
ord(substr((
3 & $_[0] >> 16
?
"BY}6YB6%"
:
"Qj}6jQ6%"
), $_[2] % 8, 1))
...
更有效率:
# Outside the sub.
my $a1 = [ unpack 'C*', "BY}6YB6%" ];
my $a2 = [ unpack 'C*', "Qj}6jQ6%" ];
...
${ 3 & $_[0] >> 16 ? $a1 : $a2 }[ $_[2] % 8 ]
...
我不知道标题是否正确,如果发现不正确,请更新。这不是关于C,而是关于Perl。
(LIST1)[LIST2]
返回由索引LIST2
指定的LIST1
的元素。C语言中没有与之等价的语言,所以是的,这确实是代码中的一个不同之处。@ikegami噢,我不明白括号运算符在perl中是如何工作的。perl中的正确方法是什么?答案中已经回答了这个问题。我只是提供了额外的信息。我不知道我的标题是否正确,如果发现不正确,请更新它。这不是关于C,而是关于Perl。(LIST1)[LIST2]
返回由索引LIST2
指定的LIST1
的元素。C语言中没有与之等价的语言,所以是的,这确实是代码中的一个不同之处。@ikegami噢,我不明白括号运算符在perl中是如何工作的。perl中的正确方法是什么?答案中已经回答了这个问题。我只是提供了额外的信息。@Linus,为什么不使用C中的数组呢?效率更高。@ikegami只是因为后一种解决方案更长。@Linus,为什么不使用C中的数组呢?更高效。@ikegami只是因为后者的解决方案更长。