# One-liner program

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/One-liner_program
> Markdown URL: https://mediated.wiki/source/One-liner_program.md
> Source: https://en.wikipedia.org/wiki/One-liner_program
> Source revision: 1333190349
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{Short description|Short command-line instruction}}
{{More citations needed|date=May 2019}}

In [computer programming](/source/computer_programming), a '''one-liner program''' originally was textual input to the [command line](/source/command_line) of an operating system [shell](/source/Shell_(computing)) that performed some function in just one line of input. In the present day, a one-liner can be
* an [expression](/source/Expression_(computer_science)) written in the language of the shell;
* the invocation of an [interpreter](/source/Interpreter_(computing)) together with program source for the interpreter to run;
* the invocation of a [compiler](/source/compiler) together with source to compile and instructions for [executing](/source/Execution_(computing)) the compiled program.
Certain [dynamic languages](/source/Dynamic_programming_language) for [scripting](/source/scripting_language), such as [AWK](/source/AWK_programming_language), [sed](/source/Sed_(programming_language)), and [Perl](/source/Perl), have traditionally been adept at expressing one-liners.
Shell interpreters such as [Unix shell](/source/Unix_shell)s or [Windows PowerShell](/source/Windows_PowerShell) allow for the construction of powerful one-liners.

The use of the phrase ''one-liner'' has been widened to also include program-source for any language that does something useful in one line.

==History==
The concept of a one-liner program has been known since the 1960s<ref>{{cite book |title=10 PRINT CHR$ (205.5 + RND (1)); : GOTO 10 |date=2014 |publisher=Mit Press |isbn=9780262526746 |page=148 |url=http://nickm.com/trope_tank/10_PRINT_121114.pdf |accessdate=3 July 2018}}</ref> with the release of the [APL](/source/APL_(programming_language)) programming language. With its terse syntax and powerful mathematical operators, APL allowed useful programs to be represented in a few symbols.

In the 1970s, one-liners became associated with the rise of the [home computer](/source/home_computer) and [BASIC](/source/BASIC). Computer magazines published [type-in program](/source/type-in_program)s in many dialects of BASIC. Some magazines devoted regular columns solely to impressive short and one-line programs.<ref>{{cite web|url=https://archive.org/stream/run-magazine-35/Run_Issue_35_1986_Nov#page/n109/mode/2up|title=RUN magazine issue 35|date=November 1986 }}</ref>

The word ''One-liner'' also has two references in the index of the book ''[The AWK Programming Language](/source/The_AWK_Programming_Language)'' (the book is often referred to by the abbreviation ''TAPL''). It explains the programming language [AWK](/source/AWK_programming_language), which is part of the [Unix](/source/Unix) [operating system](/source/operating_system). The authors explain the birth of the ''one-liner'' paradigm with their daily work on early [Unix](/source/Unix) machines:
{{Quote|The 1977 version had only a few built-in variables and predefined functions. It was designed for writing short programs […] Our model was that an invocation would be one or two lines long, typed in and used immediately. Defaults were chosen to match this style […] We, being the authors, ''knew'' how the language was supposed to be used, and so we only wrote one-liners.}}

Notice that this original definition of a ''one-liner'' implies immediate execution of the program without any compilation. So, in a strict sense, only source code for interpreted languages qualifies as a ''one-liner''. But this strict understanding of a ''one-liner'' was broadened in 1985 when the [IOCCC](/source/IOCCC) introduced the category of ''Best One Liner'' for [C](/source/C_(programming_language)), which is a [compiled language](/source/compiled_language).

==Examples==
One-liners are also used to show off the differential expressive power of [programming language](/source/programming_language)s. Frequently, one-liners are used to demonstrate programming ability. Contests are often held to see who can create the most exceptional one-liner.

===BASIC===
thumb|Simulated output of the ''10PRINT'' one-liner BASIC program for the Commodore 64
A single line of BASIC can typically hold up to 255 characters, and one liners ranged from simple games<ref>{{cite web |title=Acorn User One-Line Games (Escape From Voros, Lexxias, Race To Varpon, Storm Clouds Over Zaqqit, Zander (AKA Lurch)) |url=http://bbcmicro.co.uk/game.php?id=2718 |website=bbcmicro.co.uk |accessdate=3 July 2018 |language=en}}</ref> to graphical demos. One of the better-known demo one-liners is colloquially known as ''10PRINT'', written for the [Commodore 64](/source/Commodore_64):
<syntaxhighlight lang="cbmbas">
10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</syntaxhighlight>

===C===
The following example is a [C](/source/C_(programming_language)) program (a winning entry in the "Best one-liner" category of the [IOCCC](/source/IOCCC)).
<syntaxhighlight lang="C">
main(int c,char**v){return!m(v[1],v[2]);}m(char*s,char*t){return*t-42?*s?63==*t|*s==*t&&m(s+1,t+1):!*t:m(s,t+1)||*s&&m(s+1,t);}
</syntaxhighlight>

This one-liner program is a glob pattern matcher. It understands the glob characters {{code|*}}, meaning zero or more characters, and {{code|?}}, meaning exactly one character, just like most [Unix shell](/source/Unix_shell)s.

Run it with two args, the string and the glob pattern. The exit status is 0 (shell true) when the pattern matches, 1 otherwise. The glob pattern must match the whole string, so you may want to use * at the beginning and end of the pattern if you are looking for something in the middle. Examples:
<syntaxhighlight lang="console">
$ ./a.out foo 'f??'; echo $?
$ ./a.out 'best short program' '??st*o**p?*'; echo $?
</syntaxhighlight>

===AWK===
The book ''[The AWK Programming Language](/source/The_AWK_Programming_Language)'' contains 20 examples of ''one-liners'' at the end of the book's first chapter.

Here are the very first of them:
# Print the total number of input lines (like [wc -l](/source/wc_(Unix))): <syntaxhighlight lang="awk">END { print NR }</syntaxhighlight>
# Print the tenth input line: <syntaxhighlight lang="awk">NR == 10</syntaxhighlight>
# Print the last field of every input line: <syntaxhighlight lang="awk">{ print $NF }</syntaxhighlight>

===J===
Here are examples in [J](/source/J_(programming_language)):
* A function avg to return the average of a list of numbers: <syntaxhighlight lang="j">avg=: +/ % #</syntaxhighlight>
* [Quicksort](/source/Quicksort): <syntaxhighlight lang="j">quicksort=: (($:@(<#[) , (=#[) , $:@(>#[)) ({~ ?@#)) ^: (1<#)</syntaxhighlight>

===Perl===
Here are examples in the [Perl](/source/Perl) [programming language](/source/programming_language):
* Look for duplicate words
 perl -0777 -ne '<syntaxhighlight lang="perl" inline>print "$.: doubled $_\n" while /\b(\w+)\b\s+\b\1\b/gi</syntaxhighlight>' 
* Find Palindromes in /usr/dict/words
 perl -lne '<syntaxhighlight lang="perl" inline>print if $_ eq reverse</syntaxhighlight>' /usr/dict/words
* in-place edit of *.c files changing all foo to bar
 perl -p -i.bak -e '<syntaxhighlight lang="perl" inline>s/\bfoo\b/bar/g</syntaxhighlight>' *.c

Many one-liners are practical. For example, the following [Perl](/source/Perl) one-liner will reverse all the bytes in a file:
<syntaxhighlight lang="bash">
perl -0777e 'print scalar reverse <>' filename
</syntaxhighlight>

While most [Perl](/source/Perl) one-liners are imperative, Perl's support for anonymous functions, closures, map, filter ([grep](/source/grep)) and fold (List::Util::reduce) allows the creation of 'functional' one-liners.

This one-liner creates a function that can be used to return a list of primes up to the value of the first parameter:
<syntaxhighlight lang="perl">
my $z = sub { grep { $a=$_; !grep { !($a % $_) } (2..$_-1)} (2..$_[0]) }
</syntaxhighlight>
It can be used on the command line, like this:

 perl -e'<syntaxhighlight lang="bash" inline>$,=",";print sub { grep { $a=$_; !grep { !($a % $_) } (2..$_-1)} (2..$_[0]) }->(shift)</syntaxhighlight>' number

to print out a comma-separated list of primes in the range 2 - number.

===Haskell===
The following [Haskell](/source/Haskell_(programming_language)) program is a one-liner: it sorts its input lines [ASCIIbetically](/source/ASCII).
<syntaxhighlight lang="haskell">
main = (mapM_ putStrLn . Data.List.sort . lines) =<< getContents -- In ghci a qualified name like Data.List.sort will work, although as a standalone executable you'd need to import Data.List.
</syntaxhighlight>

An even shorter version:
<syntaxhighlight lang="haskell">
main = interact (unlines . Data.List.sort . lines) -- Ditto.
</syntaxhighlight>

Usable on the command line like:
<syntaxhighlight lang="bash">
cat filename | ghc -e "interact (unlines . Data.List.sort . lines)"
</syntaxhighlight>

===Racket===
The following [Racket](/source/Racket_(programming_language)) program is equivalent to the above Haskell example:
<syntaxhighlight lang="racket">
#lang racket
(for-each displayln (sort (port->lines) string<?))
</syntaxhighlight>
and this can be used on the command line as follows:
 racket -e '<syntaxhighlight lang="racket" inline>(for-each displayln (sort (port->lines) string<?))</syntaxhighlight>'

===Python===
Performing one-liners directly on the Unix command line can be accomplished by using [Python](/source/Python_(programming_language))'s -cmd flag (-c for short), and typically requires the import of one or more modules. Statements are separated using ";" instead of newlines. For example, to print the last field of unix long listing:
 ls -l | python -c "<syntaxhighlight lang="python" inline>
import sys;[sys.stdout.write(' '.join([line.split(' ')[-1]])) for line in sys.stdin]</syntaxhighlight>"

====Python wrappers====
Several open-source scripts have been developed to facilitate the construction of Python one-liners. Scripts such as 
[http://code.google.com/p/pyp/ pyp] or [http://code.activestate.com/recipes/437932-pyline-a-grep-like-sed-like-command-line-tool/ Pyline] import commonly used modules and provide more human-readable variables in an attempt to make Python functionality more accessible on the command line. Here is a redo of the above example (printing the last field of a unix long listing):
<syntaxhighlight lang="bash">
ls -l | pyp "whitespace[-1]" # "whitespace" represents each line split on white space in pyp
ls -l | pyline "words[-1]"  # "words" represents each line split on white space in pyline
</syntaxhighlight>

====Executable libraries====
The Python CGIHTTPServer module for example is also an executable library that performs as a web server with CGI. To start the web server enter:
<syntaxhighlight lang="console">$ python -m CGIHTTPServer
Serving HTTP on 0.0.0.0 port 8000 …</syntaxhighlight>

===Tcl===
[Tcl](/source/Tcl_(programming_language)) (Tool Command Language) is a dynamic programming/scripting language based on concepts of Lisp, C, and Unix shells. It can be used interactively, or by running scripts (programs) which can use a package system for structuring.<ref>Following are direct quotes from {{Wikibooks-inline|Tcl Programming}} that are available under the [Creative Commons Attribution-ShareAlike License](/source/Creative_Commons_Attribution-ShareAlike_License).</ref>

Many strings are also well-formed lists. Every simple word is a list of length one, and elements of longer lists are separated by whitespace. For instance, a string that corresponds to a list of three elements:
<syntaxhighlight lang="TCL">
set example {foo bar grill}
</syntaxhighlight>

Strings with unbalanced quotes or braces, or non-space characters directly following closing braces, cannot be parsed as lists directly. You can explicitly split them to make a list.

The "constructor" for lists is of course called list. It's recommended to use when elements come from variable or [command substitution](/source/command_substitution) (braces won't do that). As Tcl commands are lists anyway, the following is a full substitute for the list command:
<syntaxhighlight lang="TCL">
proc list args {set args}
</syntaxhighlight>

===Windows PowerShell===
Finding palindromes in file words.txt
<syntaxhighlight lang="powershell">
Get-Content words.txt | Where { $_ -eq -join $_[($_.length-1)..0] }
</syntaxhighlight>

Piping semantics in PowerShell help enable complex scenarios with one-liner programs. This one-liner in PowerShell script takes a list of names and counts from a comma-separated value file, and returns the sum of the counts for each name.
<syntaxhighlight lang="powershell">
ipcsv .\fruit.txt –H F, C|Group F|%{@{"$($_.Name)"=($_.Group|measure C -sum).Sum}}|sort value
</syntaxhighlight>

==See also==
* [Bookmarklet](/source/Bookmarklet)
* [Tcl](/source/Tcl_(programming_language))

== References ==
{{Reflist}}

== External links ==
{{Sister project links|commons=Category:Perl (programming language)|v=Topic:Perl|n=no|q=Perl|s=no|b=Perl Programming}}
* Perl Programming links
* [Wikibooks](/source/Wikibooks) Free Tcl Programming introduction & download pdf
* [https://sourceforge.net/ SourceForge], download website and also Multiple computer languages 
* [http://core.tcl.tk/ Tcl Sources], main Tcl and Tk source code download website
* [http://wiki.tcl.tk/ Tcler's Wiki], Tcl/Tk scripts and reference clearing house
* [http://www.tkdocs.com/ TkDocs], Tcl/Tk Official documentation and archives

Category:Computer programming
Category:Articles with example Haskell code
Category:Articles with example C code
Category:Articles with example Perl code
Category:Articles with example Python (programming language) code
Category:Articles with example Racket code

---
Adapted from the Wikipedia article [One-liner program](https://en.wikipedia.org/wiki/One-liner_program) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/One-liner_program?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
