One-liner program

Last updated

In computer programming, a one-liner program originally was textual input to the command line of an operating system shell that performed some function in just one line of input. In the present day, a one-liner can be

Contents

Certain dynamic languages for scripting, such as AWK, sed, and Perl, have traditionally been adept at expressing one-liners. Shell interpreters such as Unix shells or 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 [1] with the release of the APL 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 and BASIC. Computer magazines published type-in programs in many dialects of BASIC. Some magazines devoted regular columns solely to impressive short and one-line programs. [2]

The word One-liner also has two references in the index of the book The AWK Programming Language (the book is often referred to by the abbreviation TAPL). It explains the programming language AWK, which is part of the Unix operating system. The authors explain the birth of the one-liner paradigm with their daily work on early Unix machines:

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 introduced the category of Best One Liner for C, which is a compiled language.

Examples

One-liners are also used to show off the differential expressive power of programming languages. Frequently, one-liners are used to demonstrate programming ability. Contests are often held to see who can create the most exceptional one-liner.

BASIC

Simulated output of the 10PRINT one-liner BASIC program for the Commodore 64 10print.gif
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 [3] to graphical demos. One of the better-known demo one-liners is colloquially known as 10PRINT, written for the Commodore 64:

10PRINTCHR$(205.5+RND(1));:GOTO10

C

The following example is a C program (a winning entry in the "Best one-liner" category of the IOCCC).

main(intc,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);}

This one-liner program is a glob pattern matcher. It understands the glob characters *, meaning zero or more characters, and ?, meaning exactly one character, just like most Unix shells.

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:

$ ./a.outfoo'f??';echo$?$ ./a.out'best short program''??st*o**p?*';echo$?

AWK

The TAPL book contains 20 examples of one-liners at the end of the book's first chapter.

Here are the very first of them:

  1. Print the total number of input lines (like wc -l):
    END{printNR}
  2. Print the tenth input line:
    NR==10
  3. Print the last field of every input line:
    {print$NF}

J

Here are examples in J:

Perl

Here are examples in the Perl programming language:

perl -0777 -ne 'print"$.: doubled $_\n"while/\b(\w+)\b\s+\b\1\b/gi' 
perl -lne 'printif$_eqreverse' /usr/dict/words
perl -p -i.bak -e 's/\bfoo\b/bar/g' *.c

Many one-liners are practical. For example, the following Perl one-liner will reverse all the bytes in a file:

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

While most Perl one-liners are imperative, Perl's support for anonymous functions, closures, map, filter (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:

my$z=sub{grep{$a=$_;!grep{!($a%$_)}(2..$_-1)}(2..$_[0])}

It can be used on the command line, like this:

perl -e'$,=",";printsub{grep{$a=$_;!grep{!($a%$_)}(2..$_-1)}(2..$_[0])}->(shift)' number

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

Haskell

The following Haskell program is a one-liner: it sorts its input lines ASCIIbetically.

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.

An even shorter version:

main=interact(unlines.Data.List.sort.lines)-- Ditto.

Usable on the command line like:

catfilename|ghc-e"interact (unlines . Data.List.sort . lines)"

Racket

The following Racket program is equivalent to the above Haskell example:

#lang racket(for-eachdisplayln(sort(port->lines)string<?))

and this can be used on the command line as follows:

racket -e '(for-eachdisplayln(sort(port->lines)string<?))'

Python

Performing one-liners directly on the Unix command line can be accomplished by using Python'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 "importsys;[sys.stdout.write(' '.join([line.split(' ')[-1]]))forlineinsys.stdin]"

Python wrappers

Several open-source scripts have been developed to facilitate the construction of Python one-liners. Scripts such as pyp or 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):

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

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:

$ python-mCGIHTTPServer Serving HTTP on 0.0.0.0 port 8000 …

Tcl

Tcl (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. [4]

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:

setexample{foobargrill}

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 (braces won't do that). As Tcl commands are lists anyway, the following is a full substitute for the list command:

proclistargs{setargs}

Windows PowerShell

Finding palindromes in file words.txt

Get-Contentwords.txt|Where {$_-eq-join$_[($_.length-1)..0]}

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.

ipcsv .\fruit.txtH F,C|Group F|%{@{"$($_.Name)"=($_.Group|measure C-sum).Sum}}|sort value

See also

Related Research Articles

<span class="mw-page-title-main">AWK</span> Programming language

AWK is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.

<span class="mw-page-title-main">Regular expression</span> Sequence of characters that forms a search pattern

A regular expression is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. Regular expression techniques are developed in theoretical computer science and formal language theory.

sed Standard UNIX utility for editing streams of data

sed is a Unix utility that parses and transforms text, using a simple, compact programming language. It was developed from 1973 to 1974 by Lee E. McMahon of Bell Labs, and is available today for most operating systems. sed was based on the scripting features of the interactive editor ed and the earlier qed. It was one of the earliest tools to support regular expressions, and remains in use for text processing, most notably with the substitution command. Popular alternative tools for plaintext string manipulation and "stream editing" include AWK and Perl.

<span class="mw-page-title-main">Shell script</span> Script written for the shell, or command line interpreter, of an operating system

A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script which sets up the environment, runs the program, and does any necessary cleanup or logging, is called a wrapper.

A string literal or anonymous string is a literal for a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo", where "foo" is a string literal with value foo. Methods such as escape sequences can be used to avoid the problem of delimiter collision and allow the delimiters to be embedded in a string. There are many alternate notations for specifying string literals especially in complicated cases. The exact notation depends on the programming language in question. Nevertheless, there are general guidelines that most modern programming languages follow.

<span class="mw-page-title-main">Windows Script Host</span> Automation Technology for Windows

The Microsoft Windows Script Host (WSH) is an automation technology for Microsoft Windows operating systems that provides scripting abilities comparable to batch files, but with a wider range of supported features. This tool was first provided on Windows 95 after Build 950a on the installation discs as an optional installation configurable and installable by means of the Control Panel, and then a standard component of Windows 98 and subsequent and Windows NT 4.0 Build 1381 and by means of Service Pack 4. The WSH is also a means of automation for Internet Explorer via the installed WSH engines from IE Version 3.0 onwards; at this time VBScript became means of automation for Microsoft Outlook 97. The WSH is also an optional install provided with a VBScript and JScript engine for Windows CE 3.0 and following and some third-party engines including Rexx and other forms of Basic are also available.

xargs is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command.

Plain Old Documentation (pod) is a lightweight markup language used to document the Perl programming language as well as Perl modules and programs.

Expect is an extension to the Tcl scripting language written by Don Libes. The program automates interactions with programs that expose a text terminal interface. Expect, originally written in 1990 for the Unix platform, has since become available for Microsoft Windows and other systems.

<span class="mw-page-title-main">Pipeline (Unix)</span> Mechanism for inter-process communication using message passing

In Unix-like computer operating systems, a pipeline is a mechanism for inter-process communication using message passing. A pipeline is a set of processes chained together by their standard streams, so that the output text of each process (stdout) is passed directly as input (stdin) to the next one. The second process is started as the first process is still executing, and they are executed concurrently. The concept of pipelines was championed by Douglas McIlroy at Unix's ancestral home of Bell Labs, during the development of Unix, shaping its toolbox philosophy. It is named by analogy to a physical pipeline. A key feature of these pipelines is their "hiding of internals". This in turn allows for more clarity and simplicity in the system.

In computing, a here document is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace in the text.

A filter is a computer program or subroutine to process a stream, producing another stream. While a single filter can be used individually, they are frequently strung together to form a pipeline.

<span class="mw-page-title-main">Tk (software)</span> GUI toolkit or framework

Tk is a cross-platform widget toolkit that provides a library of basic elements of GUI widgets for building a graphical user interface (GUI) in many programming languages. It is free and open-source software released under a BSD-style software license.

<span class="mw-page-title-main">Scripting language</span> Programming language for run-time events

A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled.

<span class="mw-page-title-main">Command-line interface</span> Computer interface that uses text

A command-line interface (CLI) is a means of interacting with a computer program by inputting lines of text called command-lines. Command-line interfaces emerged in the mid-1960s, on computer terminals, as a user-friendly alternative to punched cards.

Strozzi NoSQL is a shell-based relational database management system initialized and developed by Carlo Strozzi that runs under Unix-like operating systems, or others with compatibility layers. Its file name NoSQL merely reflects the fact that it does not express its queries using Structured Query Language; the NoSQL RDBMS is distinct from the circa-2009 general concept of NoSQL databases, which are typically non-relational, unlike the NoSQL RDBMS. Strozzi NoSQL is released under the GNU GPL.

The following outline is provided as an overview of and topical guide to the Perl programming language:

Tcl is a high-level, general-purpose, interpreted, dynamic programming language. It was designed with the goal of being very simple but powerful. Tcl casts everything into the mold of a command, even programming constructs like variable assignment and procedure definition. Tcl supports multiple programming paradigms, including object-oriented, imperative, functional, and procedural styles.

References

  1. 10 PRINT CHR$ (205.5 + RND (1)); : GOTO 10 (PDF). Mit Press. 2014. p. 148. ISBN   9780262526746 . Retrieved 3 July 2018.
  2. "RUN magazine issue 35".
  3. "Acorn User One-Line Games (Escape From Voros, Lexxias, Race To Varpon, Storm Clouds Over Zaqqit, Zander (AKA Lurch))". bbcmicro.co.uk. Retrieved 3 July 2018.
  4. Following are direct quotes from Wikibooks-logo-en-noslogan.svg Tcl Programming at Wikibooks that are available under the Creative Commons Attribution-ShareAlike License.