单行小程序(One-liner program)是不多于一行的电脑程序表达式。它常被用来展示编程语言在不同范畴的表达能力。实际上,单行小程序常被直接地从命令线输入和执行。Perl是一种优秀的用来创造单行小程序的语言。许多单行小程序是实用的,例如以下perl单行小程序将反转文件中的所有字节:

perl -0777e 'print scalar reverse <>' filename

单行小程序经常用来展示编程的能力。经常有看谁能创造最好的单行小程序的比赛。

99瓶啤酒计算机程序单行小程序的例子:

   perl -e '$b="of beer";$w="on the wall";print "$_ ",b($_)," $b $w\n$_ ",b($_)," $b\ntake one down, pass it around, ",$_-1," ",b($_-1)," $b $w\n\n" foreach (reverse 1..99);sub b{$x="bottle";$_[0]==1?$x:$x."s";}'

一个剪刀石头布游戏单行小程序:

 perl -e '$c=(($r,$s,$p)=qw|rock scissors paper|)[(int rand 3)];$|=0;until($y=~/^($r|$s|$p)$/){print "$r, $s or $p? ";$y=<>;chop $y};%r=($s,{$p,1,$r,0},$p,{$r,1,$s,0},$r,{$s,1,$p,0});print "You: $y\nCom: $c\nYou ".((exists $r{$y}{$c}?($r{$y}{$c}?"Win":"Lose"):"Draw")."\n")'

Perl不是唯一一个能写出单行小程序的语言。以下是显示输入的内容的ASCII码的C程序:

   void main(void) {int c; while(c = getchar()) printf("%d %02X\n", c, c);}

Wikiwand in your browser!

Seamless Wikipedia browsing. On steroids.

Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.

Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.