One-liner program


One-liner program

A one-liner is textual input to the command-line of an operating system shell that performs some function in just one line of input.

The one liner can be

  1. An expression written in the language of the shell.
  2. The invocation of an interpreter together with program source for the interpreter to run.
  3. The invocation of a compiler together with source to compile and instructions for executing the compiled program.

Certain dynamic scripting languages such as AWK, sed, and Perl have traditionally been adept at expressing one-liners. Specialist shell interpreters such as these Unix shells or the 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.

Contents

History

The word One-liner 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

The TAPL book contains 20 examples of One-liners (A Handful of Useful awk One-Liners[dead link]) at the end of the book's first chapter.

Here are the very first of them:

  1. Print the total number of input lines:
    END { print NR }
    
  2. Print the tenth input line:
    NR == 10
    
  3. Print the last field of every input line:
    { print $NF }
    

Here are examples in J:

  1. A function avg to return the average of a list of numbers:
    avg=: +/ % #
    
  2. Quicksort:
    quicksort=: (($:@(<#[) , (=#[) , $:@(>#[)) ({~ ?@#)) ^: (1<#)
    

Here are examples in Perl:

  • Look for duplicate words
    perl -0777 -ne 'print "$.: doubled $_\n" while /\b(\w+)\b\s+\b\1\b/gi'
    
  • Find Palindromes in /usr/dict/words
    perl -lne 'print if $_ eq reverse' /usr/dict/words
    
  • in-place edit of *.c files changing all foo to bar
    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

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.

The following example is a C program (a winning entry in the "Best one-liner" category of the IOCCC, here split to two lines for presentation).

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);}

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:

$ prog foo 'f??'; echo $?
$ prog 'best short program' '??st*o**p?*'; echo $?

One-liner in functional programming

Haskell

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

 main = (mapM_ putStrLn . List.sort . lines) =<< getContents -- In ghci a qualified name like List.sort will work, although as a standalone executable you'd need to import List.

An even shorter version:

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

Racket

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

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

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

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

Perl

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'$,=",";print sub { grep { $a=$_; !grep { !($a % $_) } (2..$_-1)} (2..$_[0]) }->(shift)' number

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

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 "import sys;[sys.stdout.write(' '.join([line.split(' ')[-1]])) for line in sys.stdin]"

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 -m CGIHTTPServer

It returns with:

Serving HTTP on 0.0.0.0 port 8000 ...

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:

ls -l | pyp "whitespace[-1]"                      #"whitespace" represents each line split on white space
ls -l | pyline "words[-1]"                        #"words"      represents each line split on white space

External links


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • One-liner — may refer to: one liner joke one liner program, textual input to the command line of an operating system shell that performs some function in just one line of input tagline, a variant of a branding slogan typically used in marketing materials and …   Wikipedia

  • One O'Clock Lab Band — Poster: 2009 Performance in New York Background information Genres Jazz, Big band …   Wikipedia

  • The One Wherein There Is a Big Twist, Part II — Infobox Television episode Title=The One Wherein There Is a Big Twist, Part II Series=Drawn Together Season=2 Episode=1 Airdate=October 19 2005 Writer= Matt Silverstein, Dave Jeser Caption = The new show introductory featuring Strawberry… …   Wikipedia

  • Tier One — is Scaled Composites program of suborbital human spaceflight using the reusable spacecraft SpaceShipOne and its launcher White Knight. The craft are designed by Burt Rutan, and the project is funded 20 million US Dollars by Paul Allen. In 2004 it …   Wikipedia

  • Scaled Composites Tier One — Tier One redirects here. For other uses, see Tier 1 (disambiguation). Tier One is Scaled Composites program of suborbital human spaceflight using the reusable spacecraft SpaceShipOne and its launcher White Knight. The craft was designed by Burt …   Wikipedia

  • Victory Liner — Infobox Bus transit name = Victory Liner logo size = 250 image size = company slogan = We Move People Better Safer founded = 1945 headquarters = Caloocan City, Philippines service area = Manila Northern Luzon, Philippines service type =… …   Wikipedia

  • Criticism of the APL programming language — The APL programming language has been used since the mid 1960s on mainframe computers and has itself evolved in step with computers and the computing market. APL is not widely used, but minimalistic and high level by design, at several points in… …   Wikipedia

  • Criticism of APL — APL has been used since the mid 1960s on mainframe computers and has itself evolved in step with computers and the computing market. APL is not widely used, but minimalistic and high level by design, at several points in its history it could have …   Wikipedia

  • Christmas in the post-War United States — New Orleans department store Santa Claus, 1954 Christmas in the United States during the post War years (1946–1964) reflected a period of peace, productivity, and prosperity. Americans staged sumptuous Christmases and enjoyed a variety of holiday …   Wikipedia

  • performing arts — arts or skills that require public performance, as acting, singing, or dancing. [1945 50] * * * ▪ 2009 Introduction Music Classical.       The last vestiges of the Cold War seemed to thaw for a moment on Feb. 26, 2008, when the unfamiliar strains …   Universalium


Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”

We are using cookies for the best presentation of our site. Continuing to use this site, you agree with this.