title: Execute prints backwards

text:
# Question
Title: Execute prints backwards
Your task is to reverse the order in which some `prints` get executed.

---

**Specs:**
Your code will be in this form:

```
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

```

You will have to `print` (or `echo`, or `write`, or equivalent) those strings **from the fourth to the first.**

* You decide which lines of your program must `print` the strings, but they must be **adjacent**;
* Every line can contain only one `print`, and cannot exceed *60 bytes* in length;
* Since this is , be creative and avoid to write just a `goto` or a simple `for(i){if(i=4)print"Line1";if(i=3)...}`
* The most upvoted answer in 2 weeks wins this.
* Your output **MUST** be `Line4 Line3 Line2 Line1` **OR** `Line4Line3Line2Line1` **OR** `Line4\nLine3\nLine2\nLine1`(where `\n` is a newline), and it must be generated only by executing those `prints` backwards.

Happy coding!

**UPDATE:** Contest is over! Thank you all :)

# Answer
## Commodore 64 BASIC

```
40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"

```
> 184 votes

# Answer
## PHP

Abusing precedence... :-)

```
!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";

```
> 108 votes

# Answer
## C

Undefined behavior is the most exciting kind of behavior!

```
f(){}
main()
{
   f(printf("Line 1\n"),
     printf("Line 2\n"),
     printf("Line 3\n"),
     printf("Line 4\n"));
}

```

Actual output may vary depending on your compiler, linker, operating system, and processor :)
> 77 votes

# Answer
# Java

Using reflection

```
public class ReversePrint {
    public static void main(String[]a) {
        System.out.println("Line1");
        System.out.println("Line2");
        System.out.println("Line3");
        System.out.println("Line4");
    }
    static {
        try{
            Field f=String.class.getDeclaredField("value");
            f.setAccessible(true);
            f.set("Line1","Line4".toCharArray());
            f.set("Line2","Line3".toCharArray());
            f.set("Line3","Line2 ".trim().toCharArray());
            f.set("Line4","Line1 ".trim().toCharArray());
        }catch(Exception e){}
    }
}

```

Output:

```
Line4
Line3
Line2
Line1

```

An explanation of why this works can be found here.
> 74 votes

# Answer
## C (and sort-of Python)

New version, using a macro to fit the question format perfectly. Following Quincunx's comment, I added `return` to make it nicer.

It also works in Python, but it prints in correct order.

```
#define print"\n",printf(
#define return"\n"))));}
#define def main(){0?

def main():
    print "Line 1"
    print "Line 2"
    print "Line 3"
    print "Line 4"
    return

main();

```

Original version - the two are practically the same, after macro substitution:

```
main(){
    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
    0))));
}

```
> 71 votes

# Answer
## ES6 (using backwards mode ;)

Wow, it looks like the designers of ECMAScript had some incredible foresight when they made backwards mode part of the spec:

```
// activate backwards mode:
'use backwardsˈ; \* mode backwards in now *\
code of lines some ⧵\
\*code*\ "Line1" print \*code*\
\*code*\ "Line2" print \*code*\
\*code*\ "Line3" print \*code*\
\*code*\ "Line4" print \*code*\
code of lines some ⧵\
⁏ˈforwards useˈ // back to ˈnormal'.

// So simple! No need to do anything this complicated:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')

```

Output (evaluation, really):

```
"Line4Line3Line2Line1"

```

Note that it's *exactly* of the form requested, with only slight backwardification to fit the syntax of the mode. Note also that this mode is only supported in recent versions of Firefox at the moment.

*Final note: Actually, there is no backwards mode. But this is still a valid script that runs in Firefox (copy the whole thing). :D*

---

### ES6 "lax mode"

**BONUS**: Here's an updated version that doesn't use backwards mode, but uses the newly-specified "lax mode" where the JS engine will just try to guess what the code is supposed to do, regardless of adherence to any specified JS syntax (basically the antithesis of strict mode):

```
// activate "lax" mode:
`use laxˋ; // also works: ˋuse relaxˋ, ˋuse guessingˋ, ˋuse whatevsˋ, etc.
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
ˋuse normalˋ; // same as ˋuse default`.

// Again, compare to inferior, illegible "traditional" ES6:
split('"').reduce((L,o,l)=>(l%2?o:'')+L,'')

```

Please note that "lax mode" is currently only available in Firefox \>= 34. ;P
> 62 votes

# Answer
# C

```
main()
{
  int i = 0;
  for(; i == 0; printf("Line 1\n"))
    for(; i == 0; printf("Line 2\n"))
      for(; i == 0; printf("Line 3\n"))
        for(; i == 0; printf("Line 4\n"))
          i = 1;
}

```
> 60 votes

# Answer
## Ruby

```
print 'Line1' unless
print 'Line2' unless
print 'Line3' unless
print 'Line4'

```

Edit: Alternatively,

```
def method_missing(meth,*)
  puts meth.to_s.sub('print'){}
end

printLine1(
printLine2(
printLine3(
printLine4)))

```
> 58 votes

# Answer
# PHP

I know, this is madness...

```
goto d;
a: print "Line1\n"; goto end;
b: print "Line2\n"; goto a;
c: print "Line3\n"; goto b;
d: print "Line4\n"; goto c;
end: exit;

```
> 51 votes

# Answer
## Haskell

This is almost idiomatic Haskell, as the program now looks like a right-to-left function composition. If the function wasn't print, but something that would return a (useful) value the operator declaration would be unnecessary and the code would be something you'd see in libraries.

```
a << b = (const a =<< b)

main = putStrLn "Line1"
    << putStrLn "Line2"
    << putStrLn "Line3"
    << putStrLn "Line4"

```
> 42 votes

# Answer
## Perl

```
use threads;

$a=threads->create(sub {sleep(5); print("Line1\n");});
$b=threads->create(sub {sleep(4); print("Line2\n");});
$c=threads->create(sub {sleep(3); print("Line3\n");});
$d=threads->create(sub {sleep(2); print("Line4\n");});

$a->join();
$b->join();
$c->join();
$d->join();

```
> 41 votes

# Answer
# HTML + CSS

```
<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
<p>Line 4</p>

```

CSS:

```
body {margin-top:7em}
p + p {margin-top:-4em}

```

See jsFiddle.

Edit:
To conform to the rules better, here is a variant in XML, that actually uses `print`.

```
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="style.css"?>
<root>
  <print>Line 1</print>
  <print>Line 2</print>
  <print>Line 3</print>
  <print>Line 4</print>
</root>

```

where style.css should be

```
* {display:block; margin-top:3em}
print + print {margin-top:-3em}

```

# HTML without CSS

And for the heck of it, here's one without CSS.

```
<table>
<tfoot><tr><td><table><tfoot><tr><td>Line 1</tr></tfoot>
<tbody><tr><td>                      Line 2</table></tfoot>
<tbody><tr><td><table><tfoot><tr><td>Line 3</tr></tfoot>
<tbody><tr><td>                      Line 4</table></tbody>
</table>

```

Fiddle.
> 38 votes

# Answer
# C++

```
#include <iostream>
#define Q(x,y) x ## y
#define P(x,y) Q(x, y)
#define print S P(s, __LINE__) =
struct S { const char *s; S(const char *s): s(s) {} ~S() { std::cout << s << std::endl; } };
int main() {
    print "Line1";
    print "Line2";
    print "Line3";
    print "Line4";
}

```

(Local variables are destroyed in reverse order of declaration.)

# C++11

```
#include <iostream>
int main() {
    struct S { void (*f)(); S(void (*f)()): f(f) {} ~S() { f(); } } s[] = {
        {[](){ std::cout << "Line1" << std::endl; }},
        {[](){ std::cout << "Line2" << std::endl; }},
        {[](){ std::cout << "Line3" << std::endl; }},
        {[](){ std::cout << "Line4" << std::endl; }},
    };
}

```

(Much the same, but using lambdas and an array data member instead.)
> 24 votes

# Answer
# Haskell

```
main = sequence_ $ reverse [
    putStr "Line1",
    putStr "Line2",
    putStr "Line3",
    putStr "Line4"]

```
> 22 votes

# Answer
# Javascript

```
setTimeout(function(){console.log("Line 1");},900);
setTimeout(function(){console.log("Line 2");},800);
setTimeout(function(){console.log("Line 3");},700);
setTimeout(function(){console.log("Line 4");},600);

```
> 21 votes

# Answer
# C

Trying to make defiance of the tips in the question as creative as possible:

```
#include <stdio.h>
#define print if (i == __LINE__) puts
static unsigned i;
int main(void) {
  while (--i) {
    print("Line 1");
    print("Line 2");
    print("Line 3");
    print("Line 4");
  }
  return 0;
}

```
> 21 votes

# Answer
# BF

Assumes cell-wrapping.

```
++++[->+
----[> (line 1) .[-]<]++++
---[> (line 2) .[-]<]+++
--[> (line 3) .[-]<]++
-[> (line 4) .[-]<]+
<]

```

**Why it works**

The first and last lines compose of a loop that repeats four times (counter = `cell0`).

Inside the loop, there is a counter variable (`cell1`) that is increased every run.

Each lines checks if decreasing by four, three, two, or one equals zero. Therefore, on the first run, the counter is one and the last line is executed, on the second run, the third line is executed, etc.

The `(line 1)` shows where you should make the text that is printed. The arrows in the loops allocate `cell2` for this purpose. The `[-]` cleans out `cell2` after you use it.
> 15 votes

# Answer
## Bash

In memory of the revered SleepSort and SleepAdd, I present to you... **SleepReverse**:

```
#!/bin/bash

function print(){(sleep $((4-$1));echo "Line $1";)&}

print 1
print 2
print 3
print 4

```
> 15 votes

# Answer
## Java

```
import java.io.PrintStream;
import java.util.concurrent.FutureTask;

public class Print {
  public static void main(String[] args) {
    new FutureTask<PrintStream>(new Runnable() {
      public void run() {
        new FutureTask<PrintStream>(new Runnable() {
          public void run() {
            new FutureTask<PrintStream>(new Runnable() {
              public void run() {
                System.out.append("Line1"); }
            }, System.out.append("Line2")).run(); }
        }, System.out.append("Line3")).run(); }
    }, System.out.append("Line4")).run();
  }
}

```

It's all in the right timing... ;-)
> 13 votes

# Answer
## Bash

Here comes the double-faced script:

```
#!/bin/bash
s=1
if [ $s -ne 0 ]; then tac $0 | bash; exit; fi
s=0
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"

```
> 13 votes

# Answer
# Python 3

```
import atexit

atexit.register(print,"Line1")
atexit.register(print,"Line2")
atexit.register(print,"Line3")
atexit.register(print,"Line4")

```
> 12 votes

# Answer
## Common Lisp № 1

It's easy to write a `ngorp` macro that executes its forms in reverse order:

```
(macrolet ((ngorp (&body ydob) `(progn ,@(reverse ydob))))
  (ngorp
   (write-line "Line 1")
   (write-line "Line 2")
   (write-line "Line 3")
   (write-line "Line 4")))

```

```
Line 4
Line 3
Line 2
Line 1

```

## Common Lisp № 2

Here's one that takes the problem very literally; the code from the question appears in program without modification:

```
(macrolet ((execute-prints-backwards (&body body)
             `(progn
                ,@(nreverse (mapcar (lambda (string)
                                      (list 'write-line string))
                                    (remove-if-not 'stringp body))))))
  (execute-prints-backwards

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

  ))

```

```
Line4
Line3
Line2
Line1

```
> 11 votes

# Answer
# PHP

Another `eval` variant:

```
$lines=array_slice(file(__FILE__),-4); // get last 4 lines of current file
eval(implode('',array_reverse($lines)));exit; // eval lines reversed and exit
print "Line1\n";
print "Line2\n";
print "Line3\n";
print "Line4\n";

```
> 10 votes

# Answer
# F#

```
let inline (?) f g x = g x; f x

(printfn "Line1%s") ?
 (printfn "Line2%s") ?
  (printfn "Line3%s") ?
   (printfn "Line4%s") ""

```

Just created a custom operator that executes functions in reverse order.
> 9 votes

# Answer
# Go (Golang)

```
package main

import "fmt"

func main() {
    defer fmt.Println("Line 1")
    defer fmt.Println("Line 2")
    defer fmt.Println("Line 3")
    defer fmt.Println("Line 4")
}

```

Try it out: http://play.golang.org/p/fjsJLwOFn2
> 9 votes

# Answer
# Python3

```
print("Line1",
print("Line2",
print("Line3",
print("Line4") or '') or '') or '')

```

Can be 6 bytes shorter by removing all spaces in last line.
> 8 votes

# Answer
## Javascript

```
[
  "console.log('Line1')",
  "console.log('Line2')",
  "console.log('Line3')",
  "console.log('Line4')"
].reverse().forEach(function(e){eval(e)})

```

## C++11

```
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::function<void()>> functors;
    functors.push_back([] { std::cout << "Line1"; });
    functors.push_back([] { std::cout << "Line2"; });
    functors.push_back([] { std::cout << "Line3"; });
    functors.push_back([] { std::cout << "Line4"; });
    std::reverse(functors.begin(),functors.end());
    std::for_each (functors.begin(), functors.end(), [](std::function<void()> f) {f();});
    return 0;
}

```
> 7 votes

# Answer
**Batch**

```
echo off

call :revers ^
echo.line1 ^
echo.line2 ^
echo.line3 ^
echo.line4

:revers
if not "%2"=="" call :revers %2 %3 %4 %5 %6 %7 %8 %9
%1

```
> 7 votes

# Answer
# C#

Instead of directly calling the Run method, I'm creating a dynamic method that contains a copy of Run's IL bytecode, except that the load-string opcode operands are swapped. Which causes the new method to display the strings in reverse order.

```
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace TestApp
{
    class Program
    {
        public static void Run()
        {
            Console.WriteLine("Line 1");
            Console.WriteLine("Line 2");
            Console.WriteLine("Line 3");
            Console.WriteLine("Line 4");
        }

        static void Main(string[] args)
        {
            var method = typeof(Program).GetMethod("Run");
            var il = method.GetMethodBody().GetILAsByteArray();
            var loadStringOperands = new Stack<int>();
            for (int i = 0; i < il.Length; i++)
            {
                if (il[i] == OpCodes.Ldstr.Value)
                {
                    loadStringOperands.Push(BitConverter.ToInt32(il, i + 1));
                    i += 4;
                }
            }

            var run = new DynamicMethod("Run", typeof(void), null);
            var gen = run.GetILGenerator(il.Length);
            for (int i = 0; i < il.Length; i++)
            {
                if (il[i] == OpCodes.Ldstr.Value)
                {
                    var str = method.Module.ResolveString(loadStringOperands.Pop());
                    gen.Emit(OpCodes.Ldstr, str);
                    i += 4;
                }
                else if (il[i] == OpCodes.Call.Value)
                {
                    var mInfo = method.Module.ResolveMethod(BitConverter.ToInt32(il, i + 1)) as MethodInfo;
                    gen.Emit(OpCodes.Call, mInfo);
                    i += 4;
                }
                else if (il[i] == OpCodes.Ret.Value)
                {
                    gen.Emit(OpCodes.Ret);
                }
            }

            run.Invoke(null, null);
        }
    }
}

```
> 7 votes

# Answer
# Python

yet another solution using `eval()`

```
a = [
"print('Line1')",
"print('Line2')",
"print('Line3')",
"print('Line4')"]

for line in reversed(a):
    eval(line)

```

it's not very complex, but easy to understand.
> 6 votes

# Answer
# JavaScript

```
function golf() {
        /*
        console.log("Line1");
        console.log("Line2");
        console.log("Line3");
        console.log("Line4");
        */
        /\/\*(.+)\*\//.exec(golf.toString().replace(/\n/g,""))[1].split("; ").reverse().forEach(function(e){eval(e)});
    }

golf();

```

**Explanation:**
`golf.toString().replace(/\n/g,"")` returns the function's source on one line. The `/\/\*(.+)\*\//` regular expression matches the four `console.log` lines; it then separates them into an array, reverses the array, and uses `forEach` to `eval` each item in the array.

Edit: Removed the unnecessary `var r =`.
> 5 votes

# Answer
# Python 3

Misusing keyword arguments

```
print('Line1', end=
print('Line2', end=
print('Line3', end=
print('Line4'))))

```
> 5 votes

# Answer
# Rebol

```
do reverse [
    (print "Line1")
    (print "Line2")
    (print "Line3")
    (print "Line4")
]

```

An alternative option that doesn't use paren! blocks would be like this:

```
reverse2: func [
    "Reverse series/block in groups of 2 elements (modifies & returns)"
    s [block! series!]
  ][
    forskip s 2 [insert s take/last/part s 2]
    s
]

do reverse2 [
    print "Line1"
    print "Line2"
    print "Line3"
    print "Line4"
]

```

### A little explanation

In Rebol, code is data and data is code...

```
four-lines: [
    print "Line1"
    print "Line2"
    print "Line3"
    print "Line4"
]

```

At this point *four-lines* is just a variable pointing to data. But we can assign it to a function like so:

```
print-4-lines: does four-lines

; or exactly same is

print-4-lines: func [] four-lines

```

Now the *print-4-lines* function will print the 4 lines as is. However if we do this...

```
print-4-lines: does reverse2 four-lines

```

then *print-4-lines* now prints in reverse order.

If you go into Rebol console (REPL) you will see that *print-4-lines* function code is reversed.

```
>> source print-4-lines
print-4-lines: make function! [[][
    print "Line4"
    print "Line3"
    print "Line2"
    print "Line1"
]]

>> print-4-lines
Line4
Line3
Line2
Line1

```
> 4 votes

# Answer
### XQuery

As XQuery does not have any `print` statement (for those of you not familiar with XQuery, the result is simply outputted to the user) I defined a completely useless pseudo-print function, which does exactly nothing. This is just because you guys all have this nice and shiny `print` functions and I am trying to blend in.

```
declare function local:print($o) { $o };

fold-right((
  local:print("Line 1"),
  local:print("Line 2"),
  local:print("Line 3"),
  local:print("Line 4")
  ), (),
  function ($i, $r) { $r, $i }
)

```

You could also simply use `reverse()`, but how boring would that be? Instead it takes advantages of the powerful Higher-Order functions feature.
> 4 votes

# Answer
# C++

```
#include <iostream>
#include <functional>

int main()
{
    std::function<void ()> a = [](){};
    a = [=](){ std::cout << "Line 1"; a(); };
    a = [=](){ std::cout << "Line 2"; a(); };
    a = [=](){ std::cout << "Line 3"; a(); };
    a = [=](){ std::cout << "Line 4"; a(); };
    a();
}

```

Note that this would behave very differently if I used `[&]` instead.
> 4 votes

# Answer
Couldnt resist abusing overloaded System.out :P

```
import java.io.PrintStream;
import java.util.ArrayList;

class A
{
    public static void main(String[] arggxes)
    {
        CStream c = new CStream(System.out);
        System.setOut(c);
        System.out.println("Line 1");
        System.out.println("Line 2");
        System.out.println("Line 3");
        System.out.println("Line 4");
        c.done();
    }

}
class CStream extends PrintStream
    {
        ArrayList<String> bfr;
        public CStream(PrintStream ul)
        {
            super(ul);
            bfr=new ArrayList<>();
        }
        @Override
        public void println(String x)
        {
            bfr.add(x);
        }
        public void done()
        {
            for (int i = bfr.size(); i > 0; i--)
            {
                super.println(bfr.get(i-1));
            }
        }
    }

```

variable string amount print() with string as return works, too :P; inspired by the printf c one and the rebol one

```
class pr
{
    public static void main (String[] args)
    {
        print("Line1",
        print("Line2",
        print("Line3",
        print("Line4"
                ))));
    }
    public static String print(String... in)
    {
        System.out.println(in[0]);
        return "";
    }
}

```
> 4 votes

# Answer
**Pseudo Code** (will probably work in most languages with minor tweaks)

```
void printLine1() { print "Line 1"; }
void printLine2() { print "Line 2"; }
void printLine3() { print "Line 3"; }
void printLine4() { print "Line 4"; }

main
{
   printLine4();
   printLine3();
   printLine2();
   printLine1();
}

```
> 4 votes

# Answer
## Java

Using instance initializers:

```
class L1 {{new L2();System.out.println("Line 1");}}
class L2 {{new L3();System.out.println("Line 2");}}
class L3 {{new L4();System.out.println("Line 3");}}
class L4 {{System.out.println("Line 4");}}
public class S {
    public static void main(String[] args) {
        new L1();
    }
}

```
> 4 votes

# Answer
# Bash and coreutils

Not very creative, I'm afraid, but gets the job done with the `tac` tool, which is built for this job:

```
{
    echo "Line1"
    echo "Line2"
    echo "Line3"
    echo "Line4"
} | tac

```
> 4 votes

# Answer
# COBOL

The original of this I wrote some 30 years ago, so if the prize was for the oldest living, if brought-back-to-life, example of such a task... I re-wrote it about three years ago. After I had posted parts of it, parts appeared on some French web-site. This is the original and full working program, which I have posted some time last year on a LinkedIn group.

It still "works" today, and would have "worked" with the first COBOL compilers. GNU Cobol is readily available (SourgeForge) for anyone who would like to test the program...

The reason for writing it is mentioned in comments. Explanation follows the code. Enjoy :-)

```
   ID DIVISION.
   PROGRAM-ID. DEEPDOO.
  *REMARKS. THE PURPOSE OF THIS PROGRAM IS TO SHOW THAT, FAR
  *         FROM "THAT CAN'T BE THE PROBLEM, COBOL DOESN'T DO
  *         THAT", IT IS, AND IT DOES.
   DATA DIVISION.
   WORKING-STORAGE SECTION.
   01  A1-FG PIC X VALUE SPACE.
   01  B1-FG PIC X VALUE SPACE.
   01  C1-FG PIC X VALUE SPACE.
   PROCEDURE DIVISION.
   OBLIGATORY-SECTION SECTION.
   OB-PARA.
       PERFORM A
       IF A1-FG EQUAL TO "Y"
           DISPLAY "DO"
           GO TO G6
       END-IF
       .
   G1.
       PERFORM B
       IF B1-FG EQUAL TO "Y"
           DISPLAY "DOO"
           GO TO G5
       END-IF
       .
   G2.
       PERFORM C
       IF C1-FG EQUAL TO "Y"
           DISPLAY "IN DEEP"
           GO TO G4
       END-IF
       .
   G3.
       GO TO C5
       .
   G4.
       GO TO B5
       .
   G5.
       GO TO A5
       .
   G6.
       MOVE +11 TO RETURN-CODE
       GOBACK
       .
   A SECTION.
   A0-PARA.
       GO TO G1
       .
   A5.
       MOVE "Y" TO A1-FG
       .
   A9.
       EXIT.
   B SECTION.
   B0-PARA.
       GO TO G2
       .
   B5.
       MOVE "Y" TO B1-FG
       .
   B9.
       EXIT.
   0A SECTION.
   0-PARA.
       DISPLAY "I WAS GOING ALONG QUIETLY AND NOW I'M"
       .
   C SECTION.
   C0-PARA.
       IF C1-FG NOT EQUAL TO "Y"
           GO TO G3
       ELSE
           GO TO C9
       END-IF
       .
   C5.
       MOVE "Y" TO C1-FG
       GO TO 0-PARA
       .
   C9.
       EXIT.
   Z-OBFUSCATION SECTION.
   Z-OB.
       DISPLAY "IT DOESN'T GET HERE, NOT IN A MILLION YEARS"
       STOP RUN.

```

There, wasn't so bad, was it?

Output is:

```
I WAS GOING ALONG QUIETLY AND NOW I'M
IN DEEP
DOO
DO

```

Which is just a different way of spelling

```
Line4
Line3
Line2
Line1

```

When COBOL was designed, it was done such that a label (a paragraph or a SECTION) could be the target of a PERFORM or a GO TO or just "fallen into" sequentially, and even, though not explicitly stated, any combination for the same label.

The problem arises when the same label is already under the scope of a PERFORM, a GO TO (accidentally) comes out of the range of the PERFORM (leaving it still "active") and control later arrives at the same label. If progress is then smoothly to the end of the scope of the original PERFORM, then control will be returned to the statement ***after the original PERFORM***, no matter what else has happened since (as long as an infinite loop has not been created).

Very, very, bad practice to knowingly make use of that. Very. Can't stress that enough. Very, very, bad.

However, carelessness in whirling chunks of code about in an editor can cause this unintentionally. It can also be deliberately coded, without realising the consequences (example on SO recently, but without causing this type of problem).

However, when it does happen, the consequences evident seem so unlikely that people do not believe it. Parts of a program appear to, and actually do, run out of their expected sequence.

Of course, the "expected sequence" is just wrong, not the actual sequence, until you know what to expect, and then everything is OK (except the program doesn't work).

After two people came to me within a week with this type of problem, and didn't believe what I told them (although that bit of their code worked after my pointing out the errant GO TOs) I wrote the program to show these and any future Doubting Thomases.

For fun I compiled it using GNU COBOL with the -debug switch, which lists each verb and label as they are encountered. Here is the output:

```
Program-Id: DEEPDOO          Statement: PERFORM                Line: 15
Program-Id: DEEPDOO          Section:   A                      Line: 48
Program-Id: DEEPDOO          Paragraph: A0-PARA                Line: 49
Program-Id: DEEPDOO          Statement: GO TO                  Line: 50
Program-Id: DEEPDOO          Paragraph: G1                     Line: 21
Program-Id: DEEPDOO          Statement: PERFORM                Line: 22
Program-Id: DEEPDOO          Section:   B                      Line: 57
Program-Id: DEEPDOO          Paragraph: B0-PARA                Line: 58
Program-Id: DEEPDOO          Statement: GO TO                  Line: 59
Program-Id: DEEPDOO          Paragraph: G2                     Line: 28
Program-Id: DEEPDOO          Statement: PERFORM                Line: 29
Program-Id: DEEPDOO          Section:   C                      Line: 70
Program-Id: DEEPDOO          Paragraph: C0-PARA                Line: 71
Program-Id: DEEPDOO          Statement: IF                     Line: 72
Program-Id: DEEPDOO          Statement: GO TO                  Line: 73
Program-Id: DEEPDOO          Paragraph: G3                     Line: 35
Program-Id: DEEPDOO          Statement: GO TO                  Line: 36
Program-Id: DEEPDOO          Paragraph: C5                     Line: 78
Program-Id: DEEPDOO          Statement: MOVE                   Line: 79
Program-Id: DEEPDOO          Statement: GO TO                  Line: 80
Program-Id: DEEPDOO          Paragraph: 0-PARA                 Line: 67
Program-Id: DEEPDOO          Statement: DISPLAY                Line: 68
I WAS GOING ALONG QUIETLY AND NOW I'M
Program-Id: DEEPDOO          Section:   C                      Line: 70
Program-Id: DEEPDOO          Paragraph: C0-PARA                Line: 71
Program-Id: DEEPDOO          Statement: IF                     Line: 72
Program-Id: DEEPDOO          Statement: GO TO                  Line: 75
Program-Id: DEEPDOO          Paragraph: C9                     Line: 82
Program-Id: DEEPDOO          Statement: EXIT                   Line: 83
Program-Id: DEEPDOO          Statement: IF                     Line: 30
Program-Id: DEEPDOO          Statement: DISPLAY                Line: 31
IN DEEP
Program-Id: DEEPDOO          Statement: GO TO                  Line: 32
Program-Id: DEEPDOO          Paragraph: G4                     Line: 38
Program-Id: DEEPDOO          Statement: GO TO                  Line: 39
Program-Id: DEEPDOO          Paragraph: B5                     Line: 61
Program-Id: DEEPDOO          Statement: MOVE                   Line: 62
Program-Id: DEEPDOO          Paragraph: B9                     Line: 64
Program-Id: DEEPDOO          Statement: EXIT                   Line: 65
Program-Id: DEEPDOO          Statement: IF                     Line: 23
Program-Id: DEEPDOO          Statement: DISPLAY                Line: 24
DOO
Program-Id: DEEPDOO          Statement: GO TO                  Line: 25
Program-Id: DEEPDOO          Paragraph: G5                     Line: 41
Program-Id: DEEPDOO          Statement: GO TO                  Line: 42
Program-Id: DEEPDOO          Paragraph: A5                     Line: 52
Program-Id: DEEPDOO          Statement: MOVE                   Line: 53
Program-Id: DEEPDOO          Paragraph: A9                     Line: 55
Program-Id: DEEPDOO          Statement: EXIT                   Line: 56
Program-Id: DEEPDOO          Statement: IF                     Line: 16
Program-Id: DEEPDOO          Statement: DISPLAY                Line: 17
DO
Program-Id: DEEPDOO          Statement: GO TO                  Line: 18
Program-Id: DEEPDOO          Paragraph: G6                     Line: 44
Program-Id: DEEPDOO          Statement: MOVE                   Line: 45
Program-Id: DEEPDOO          Statement: GOBACK                 Line: 46
Program-Id: DEEPDOO          Exit:      DEEPDOO

```

Line: 80 is what causes the unwinding of the PERFORMs to start, as control will "fall through" from the target of that GO TO into the following SECTION.

This mimics the situation where a SECTION in the program has been copied, modified, but the "GO TO *the named paragraph which happens to be the end of the PERFORM range* has not been changed - so it GO TOs the end of the wrong SECTION, and "falls through" into the next SECTION and continues falling until it stumbles across a PERFORM-range which is still active, or it gets into a Big Fat Loop or the end of the program is reached.

There are COBOL programmers who feel it is OK to use `GO TO` to get to the last paragraph of a PERFORM-range (I'm not one). If doing this, and using SECTIONs, it is best to name the final paragraph in each SECTION identically. The compiler will then automatically "qualify" that paragraph-reference in the GO TO to being the one in the current SECTION.
> 4 votes

# Answer
# JavaScript

```
console.log("Line 1",
(console.log("Line 2",
(console.log("Line 3",
(console.log("Line 4"), "")), "")
  ), "")
)

```
> 4 votes

# Answer
## **Postscript**

```
{
    currentfile
    60 string readline
        { cvx }
        { pop count { exec } repeat exit }
    ifelse
} loop
(Line1\n) print
(Line2\n) print
(Line3\n) print
(Line4\n) print

```

and

```
gs -q -dBATCH print_backwards.ps
Line4
Line3
Line2
Line1

```

P.S. Oh, and if, I see, there should be some code *after* our `print "LineX"`, it can be modified easily:

```
4 {
    currentfile
    60 string readline pop cvx
} repeat
(Line1\n) print
(Line2\n) print
(Line3\n) print
(Line4\n) print
count { exec } repeat
(And that's all!\n) print

```

and

```
gs -q -dBATCH print_backwards.ps
Line4
Line3
Line2
Line1
And that's all!

```
> 3 votes

# Answer
Here is my attempt in **Befunge**:

```
"4"21p"3"22p"2"23p"1"24pv
" 1eniL",,,,,,   v      >
" 2eniL",,,,,,  v>
" 3eniL",,,,,, v>
" 4eniL",,,,,,@>

```

`" 1eniL",,,,,,` is a print statement; it prints `Line1`.

This works by modifying the code, overwriting the numbers in the print statements before they are executed.

Output:

```
Line4 Line3 Line2 Line1

```

However, since it unfortunately looks like that is not allowed (it is not executing the statements in reverse order, but modifying them), this works:

```
 v
" 1eniL",,,,,,@>
" 2eniL",,,,,, ^>
" 3eniL",,,,,,  ^>
" 4eniL",,,,,,   ^>
 >                ^

```
> 3 votes

# Answer
**C++11** using UDL and abusing RAII.

```
#include <iostream>

class wrapper
{
public:
  const char *s_;
  wrapper(const char *s) : s_(s) {}
  ~wrapper() { std::cout << s_ << std::endl;}

};

wrapper operator "" _print(const char *str, long unsigned int)
{
  return wrapper(str);
}

int     main()
{
  wrapper test[] = {
    "Line 1"_print,
    "Line 2"_print,
    "Line 3"_print,
    "Line 4"_print,
  };
}

```
> 3 votes

# Answer
# OCaml

Since lists are created starting from the tail prepending elements in front of it, these print statements end up executing backwards.

```
[print_string "Line1";
print_string "Line2";
print_string "Line3";
print_string "Line4"]

```

output is

```
Line4Line3Line2Line1

```

(you can try it here)
> 3 votes

# Answer
**Python**

After a little setup, you can get reversed printing from nearly unaltered Python code. (You do need parens around your print arguments).

```
from __future__ import print_function
import atexit
stack=[]
def done():
    stack.reverse()
    for a,k in stack: __builtins__.print(*a,**k)
atexit.register(done)
def print(*args,**kwargs):
    stack.append((args,kwargs))

#normal code from here down.

print('Line1')
print('Line2')
print('Line3')
print('Line4')

```
> 3 votes

# Answer
# Bash

This one abusing process substitution and redirects:

```
< <(< <(< <(< <(
1>&2 echo "Line1")
1>&2 echo "Line2")
1>&2 echo "Line3")
1>&2 echo "Line4")

```
> 3 votes

# Answer
# Perl 5

```
use 5.010;

!say "Line 1",
!say "Line 2",
!say "Line 3",
!say "Line 4";

```

This works basically the same way as bwoebi's PHP answer: the return value of each of the `say` commands is given as an argument to the previous one, so the interpreter must evaluate them from last to first. The negation operator `!` maps the return values from `1` to an empty string, keeping them from interfering with the output.
> 3 votes

# Answer
```
#include <stdio.h>
#include <stdlib.h>

void line1() { printf("line1\n"); }
void line2() { printf("line2\n"); }
void line3() { printf("line3\n"); }
void line4() { printf("line4\n"); }

int main() {
  atexit(line1);
  atexit(line2);
  atexit(line3);
  atexit(line4);
}

```
> 3 votes

# Answer
# Haskell

```
(<<)=flip(>>)
main=putStrLn "Line1" <<
     putStrLn "Line2" <<
     putStrLn "Line3" <<
     putStrLn "Line4"

```
> 3 votes

# Answer
## Coldfusion

---

anything not in a coldfusion tag is written to the output webpage, Coldfusion also lets you treat pretty much any string as a list and loop over a list in an output tag where things in #'s are evaluated

```
<cfsavecontent variable="output">
    Line 1
    Line 2
    Line 3
    Line 4
</cfsavecontent>

<cfset output = ListSort(output,'text','desc',chr(13))>

<cfloop index="i" list="#output#" delimiters="#chr(13)#">
    <cfoutput>#i#</cfoutput>
</cfloop>

```
> 3 votes

# Answer
# Python 2.7

The great thing about dynamic languages is that you can override anything. Also, finalizers are the future.

```
import sys
class StdOut(object):
    text = ""
    def __init__(self):
        self.stdout = sys.stdout
    def write(self, text):
        self.text = text + self.text
    def __del__(self):
        self.stdout.write(self.text)
sys.stdout = StdOut()

print "Line1"
print "Line2"
print "Line3"
print "Line4"

```

Note that we haven't overridden `print` \- we're using the stock `print` function that comes with Python.
> 3 votes

# Answer
# Thue

```
00::=~Line1
11::=~Line2
22::=~Line3
33::=~Line4
::=
01233210

```
> 3 votes

# Answer
# Tcl

Inspired by histocrat's Ruby solution.
Just demonstrates that any proc can be renamed and/or re-declared in Tcl.

```
rename puts stup

proc puts {{arg ""}} {
  global buffer
  if {$arg == ""} {
    stup [lreverse $buffer]
  } else {
    lappend buffer $arg
  }
}

puts Line1
puts Line2
puts Line3
puts Line4
puts

```

Sample run:

```
bash-4.2$ tclsh reverseputs.tcl
Line4 Line3 Line2 Line1

```

# Tcl

Inspired by all those looping solutions.
Just demonstrates that no `eval` is needed, as everything is a string.

```
foreach {line puts} [lreverse {
  puts Line1
  puts Line2
  puts Line3
  puts Line4
}] {
  $puts $line
}

```

Sample output:

```
bash-4.2$ tclsh reverseputs.tcl
Line4
Line3
Line2
Line1

```

# Tcl

Minimal version.

```
puts Line1[
puts Line2[
puts Line3[
puts Line4]]]

```

Sample output:

```
bash-4.2$ tclsh reverseputs.tcl
Line4
Line3
Line2
Line1

```
> 2 votes

# Answer
## PHP

Based on a sleepsort

```
<?php
if (!pcntl_fork()) { sleep(4); echo 'Line 1'; die;}
if (!pcntl_fork()) { sleep(3); echo 'Line 2'; die;}
if (!pcntl_fork()) { sleep(2); echo 'Line 3'; die;}
if (!pcntl_fork()) { sleep(1); echo 'Line 4'; die;}

```
> 2 votes

# Answer
# C#

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        new Action[] {
            () => Console.WriteLine("Line 1"),
            () => Console.WriteLine("Line 2"),
            () => Console.WriteLine("Line 3"),
            () => Console.WriteLine("Line 4"),
        }.Reverse().ToList().ForEach(a => a.Invoke());
    }
}

```

or:

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        foreach (var a in new Action[] {
                () => Console.WriteLine("Line 1"),
                () => Console.WriteLine("Line 2"),
                () => Console.WriteLine("Line 3"),
                () => Console.WriteLine("Line 4"),
            }.Reverse())
            a.Invoke();
    }
}

```

Or:

```
using System;
using System.Collections.Generic;

class P
{
    static void Main()
    {
        var t = new Stack<Action>(new Action[] {
                () => Console.WriteLine("Line 1"),
                () => Console.WriteLine("Line 2"),
                () => Console.WriteLine("Line 3"),
                () => Console.WriteLine("Line 4"),
            });
        while (t.Count > 0)
            t.Pop().Invoke();
    }
}

```
> 2 votes

# Answer
# F#

Pretty much like the Michael's JS and C++ entry.

```
[(fun () -> printfn "Line 1");
 (fun () -> printfn "Line 2");
 (fun () -> printfn "Line 3");
 (fun () -> printfn "Line 4")]
|> List.rev |> List.iter(fun u-> u())

```
> 2 votes

# Answer
## PHP

```
<?php
ob_start();print 'Line 1';$a=ob_get_clean();
ob_start();print 'Line 2';$a=ob_get_clean().$a;
ob_start();print 'Line 3';$a=ob_get_clean().$a;
ob_start();print 'Line 4';$a=ob_get_clean().$a;
fwrite(STDOUT, $a);

```

i'm not sure if it actually qualifies, as the prints are executed in order
> 2 votes

# Answer
# Perl

```
$_->() for reverse
  sub { print "Line1\n" },
  sub { print "Line2\n" },
  sub { print "Line3\n" },
  sub { print "Line4\n" };

```
> 2 votes

# Answer
# JavaScript

Kinda wanted to avoid using eval() or strings, so I gave each Line a separate function.

.reverse() makes it still too easy. :9

```
var cg = [
  function() {console.log('Line one')},
  function() {console.log('Line two')},
  function() {console.log('Line three')},
  function() {console.log('Line four')}
];
for(i in cg.reverse()) {cg[i]()}

```

Output:

```
Line four
Line three
Line two
Line one

```

---

Guess I could replace the loop with

```
for(i in cg) {cg[cg.length-++i]()}

```

to make it more interesting. Doesn't make it prettier, though.
> 2 votes

# Answer
# SQL

(mySQL 5.6)

```
SELECT 'Line1' UNION
SELECT 'Line2' UNION
SELECT 'Line3' UNION
SELECT 'Line4'
ORDER BY Line1 DESC;

```

If you count SELECTing a literal as equivalent to a print statement anyway.

mySQL defaults to including the column name and adding fancy table formatting, but if you're at the cli they can be turned off if you do something like:

```
mysql --skip-column-names -B -e "SELECT 'Line1' ... etc ...;"

```

Output:

```
Line4
Line3
Line2
Line1

```
> 2 votes

# Answer
# C#

Switching the console output to a `MemoryStream` and modifying that before dumping to screen

```
void Main()
{
    var stream = new MemoryStream();
    using (var writer = new StreamWriter(stream))
    {
        var defaultOut = Console.Out;

        // change the console output to the in-memory writer
        Console.SetOut(writer);

        Console.WriteLine("line1");
        Console.WriteLine("line2");
        Console.WriteLine("line3");
        Console.WriteLine("line4");

        // reset the console output to the default
        Console.SetOut(defaultOut);
    }

    // write the contents of the MemoryStream to screen whilst tweaking the output
    Console.Write(stream.ToArray().Select(SwitchChar).ToArray());
}

public char SwitchChar(byte b)
{
    var c = (char)b;
    switch (c)
    {
        case '1': return '4';
        case '2': return '3';
        case '3': return '2';
        case '4': return '1';
        default: return c;
    }
}

```
> 2 votes

# Answer
Kinda lame, but I think it works. C-like languages.

```
main()
{
    switch(4)
    {
    case 1: print(1); goto 5; break;
    case 2: print(2); goto 1; break;
    case 3: print(3); goto 2; break;
    case 4: print(4); goto 3; break;
    case 5: break;
    }
}

```
> 2 votes

# Answer
# Batch

```
@echo off
cls
goto d
:a
echo 'line1' & goto e
:b
echo 'line2' & goto a
:c
echo 'line3' & goto b
:d
echo 'line4' & goto c
:e
pause>nul

```

Quite frankly the best I could do...
> 2 votes

# Answer
# RProgN

```
1 print
2 print
3 print
4 print

```

# Output

```
4
3
2
1

```

> Print doesn't actually exist in RProgN, it's actually titled just 'p'. This just appends 1 through 4 to the stack, then RProgN implicitly prints the stack from top to bottom, which gives the desired result.
> 2 votes

# Answer
## Perl

At last a use for `eval`:

```
eval(join("", reverse <<"HERE"
print "Line 1\n";
print "Line 2\n";
print "Line 3\n";
print "Line 4\n";
HERE
))

```
> 1 votes

# Answer
## **Perl**

```
eval for reverse <DATA>
__DATA__
print "Line 1\n"
print "Line 2\n"
print "Line 3\n"
print "Line 4\n"

```

More or less an equivalent of my **Postscript** answer (though I like it less because of `reverse`. Stack-based Postscript is beautiful there, if you excuse me praising my own answer)
> 1 votes

# Answer
# Mathematica

```
Unprotect[Line];
Line = "Line4";
Line i_ ^:= "Line" <> ToString[5 - i]
Print[Line 1]
Print[Line 2]
Print[Line 3]
Print[Line 4]

```
> 1 votes

# Answer
# JavaScript

```
' \
    print "Line1" \
    print "Line2" \
    print "Line3" \
    print "Line4" \
'.replace(/["\s\\]/g,"").split("print").reverse().map(function(line){if(line)console.log(line)});

```

`Print()` means print(er) so outputs to console instead.
> 1 votes

# Answer
# Perl

Those pretty lines

```
map+$_->(),reverse
sub{print"Line1"},
sub{print"Line2"},
sub{print"Line3"},
sub{print"Line4"};

```
> 1 votes

# Answer
# Python 3

```
class Printer(object):
    def __init__(self):
        self.buffer = []

    def print(self, text):
        self.buffer.append(text)

        if len(self.buffer) == 4:
            while self.buffer:
                print(self.buffer.pop())

```

```
printer = Printer()

printer.print('Line 1')
printer.print('Line 2')
printer.print('Line 3')
printer.print('Line 4')

```
> 1 votes

# Answer
# K

K is evaluated right to left

```
(
  -1@"line 1";
  -1@"line 2";
  -1@"line 3";
  -1@"line 4"
  );

```

.

```
$ q a.k -q
line 4
line 3
line 2
line 1

```
> 1 votes

# Answer
# C#

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        Console.SetOut(new BackwardsWriter());

        Console.WriteLine("Line 1");
        Console.WriteLine("Line 2");
        Console.WriteLine("Line 3");
        Console.WriteLine("Line 4");
    }
}

class BackwardsWriter : TextWriter
{
    private readonly TextWriter console = Console.Out;
    private readonly IList<string> lines = new List<string>();

    public override void WriteLine(string value)
    {
        lines.Add(value);
    }

    public override Encoding Encoding
    {
        get { return console.Encoding; }
    }

    ~BackwardsWriter()
    {
        foreach (var line in lines.Reverse())
        {
            console.WriteLine(line);
        }
    }
}

```

Note that this may not actually work (objects are not required to be finalized in C#), but it does work for me in VS 2012.
> 1 votes

# Answer
## Perl

there is more than one way to do it!

```
package MagicHandle;
require Tie::Handle;
our @ISA = qw(Tie::Handle);
my @data = ();
sub TIEHANDLE { my $i; bless \$i, shift }
sub PRINT { shift @_; push @data, @_ }
sub UNTIE { print reverse @data }

package main;
tie *fh, 'MagicHandle';
select *fh;

print "one";
print "two";
print "three";
print "four";

select STDOUT;
untie *fh;

```
> 1 votes

# Answer
# PHP

Why use `eval` when you have data wrappers?

```
<?die(include('data:text/plaintext;base64,'.base64_encode(implode(PHP_EOL,array_slice(array_reverse(file(__FILE__)),0,4)))));?>
Line 1
Line 2
Line 3
Line 4

```

For this to work you must be running PHP 5.2 or greater and both `allow_url_fopen` and `allow_url_include` must be set to "On" in your php.ini file.
> 1 votes

# Answer
**Rebol**

```
do  sort/skip/reverse/compare [
  print "Line1"
  print "Line2"
  print "Line3"
  print "Line4"
] 2 2

```

and

```
cmd:  [
  [print "Line1"]
  [print "Line2"]
  [print "Line3"]
  [print "Line4"]
]
for i 4 1 -1 [do cmd/:i]

```

one more

```
until [
  do cmd: skip tail [
    print "Line1"
    print "Line2"
    print "Line3"
    print "Line4"
  ] -2
  empty? head clear cmd
]

```

Rebol allows so many variations on that

```
do reverse [
 ""
 print "Line1"
 print "Line2"
 print "Line3"
 print "Line4"
 print
]

```

.

```
print also "line 1" print also "line 2" print also "line 3" print "line 4"

```
> 1 votes

# Answer
## Python 3.3

```
print('Line 1') if not \
(print('Line 2') if not \
(print('Line 3') if not \
print('Line 4') else None) else None) else None

```
> 1 votes

# Answer
# JavaScript

Because of the nature of this problem; it is best that we use scalable asynchronous code.

```
var config = {
    maxLines: 4,
};

print.lines = 0;
function print() {
    // Error checking
    if (++print.lines > config.maxLines) throw new Error('T_PAAMAYIM_NEKUDOTAYIM');

    // TODO: Implement Promises
    window.setTimeout(
        console.log.apply.bind.apply(
            console.log.apply, [
                console.log,
                console,
                arguments
            ]
        ),
    config.maxLines + 4 - print.lines);
}

print('Line 1');
print('Line 2');
print('Line 3');
print('Line 4');

```
> 1 votes

# Answer
## Matlab: something different

```
s = {'print ' 'Line1'...
     'print ' 'Line2'...
     'print ' 'Line3'...
     'print ' 'Line4'};

[s{end:-2:2}]

```

Obfuscation attempted
> 1 votes

# Answer
# **SQL**

I felt a little left out no one tackled this with SQL.

```
declare @oldsql varchar(max)
declare @newSQL varchar(max)
declare @findvar varchar(7)
declare @replaceVar varchar(20)
declare @varLength int
declare @sqlLength int

set @findvar = '%print%'
set @varLength = len(@findvar) - 3

set @oldsql =
        ' print ''Line1''' +
        ' print ''Line2''' +
        ' print ''Line3''' +
        ' print ''Line4'''

set @sqlLength = len(@oldsql)

SET @newSQL = (
    SELECT SUBSTRING(@oldsql
            ,@sqlLength - PATINDEX(reverse(@findvar)
            ,REVERSE(@oldsql)) - @varLength
            ,LEN(@oldsql)))
SET @replaceVar =
    RIGHT(@oldsql
        ,PATINDEX(reverse(@findvar)
        ,REVERSE(@oldsql))+@varLength)
SET @oldSql =
    RTRIM(REPLACE(@oldSQL
        , REPLACE(@replaceVar,'','''')
        ,''))
SET @sqlLength = LEN(@oldsql)

SET @newSQL = @newSQL +  (
    SELECT SUBSTRING(@oldsql
            ,@sqlLength - PATINDEX(reverse(@findvar)
            ,REVERSE(@oldsql)) - @varLength
            ,LEN(@oldsql)))
SET @replaceVar =
    RIGHT(@oldsql
        ,PATINDEX(reverse(@findvar)
        ,REVERSE(@oldsql))+@varLength)
SET @oldSql =
    RTRIM(REPLACE(@oldSQL
        , REPLACE(@replaceVar,'','''')
        ,''))
SET @sqlLength = LEN(@oldsql)

SET @newSQL = @newSQL +  (
    SELECT SUBSTRING(@oldsql
            ,@sqlLength - PATINDEX(reverse(@findvar)
            ,REVERSE(@oldsql)) - @varLength
            ,LEN(@oldsql)))

SET @replaceVar =
    RIGHT(@oldsql
        ,PATINDEX(reverse(@findvar)
        ,REVERSE(@oldsql))+@varLength)
SET @oldSql =
    RTRIM(REPLACE(@oldSQL
        , REPLACE(@replaceVar,'','''')
        ,''))
SET @sqlLength = LEN(@oldsql)

SET @newSQL = @newSQL +  (
    SELECT SUBSTRING(@oldsql
            ,@sqlLength - PATINDEX(reverse(@findvar)
            ,REVERSE(@oldsql)) - @varLength
            ,LEN(@oldsql)))
exec (@newSQL)

```
> 1 votes

# Answer
## Rebol

```
use [p][p: :print  print: func [s n [any-type!]][p s]]
print {Line1}
print {Line2}
print {Line3}
print {Line4}

```

Normally 'print only takes 1 argument, but we're redefining it to take 2 - the second of which is the next call to \`print, which must be evaluated first to get a return value.

Except because it accepts \[any-type!\], the second argument is optional - hence not needing an extra arg for the last call.
> 1 votes

# Answer
# Coffeescript

This one is using coffeescript, by overriding the console.log function to skip the `undefined` second argument.

```
c = window.console
console =
  log: () ->
    c.log arguments[0]
    c.log arguments[1] if arguments[1]
console.log "Line1",
console.log "Line2",
console.log "Line3",
console.log "Line4"

```
> 1 votes

# Answer
**My version in batch - using "batch file reflection" ;)**

This one actually supports up to 9 statements to be executed backwards (but can easily be expanded to support more), and they could be almost any kind of commands - not just print statements!

The only rules are that the statements which you want to run reversed must appear in the file between the "rem BEGIN\_REV" and "rem END\_REV" comments, and that the file name you run it as must end in .BAT (not .CMD!).

```
@echo off
setlocal enabledelayedexpansion

set ffrag=FILEFRAG%random%

call :run %0
goto :eof

rem BEGIN_REV
echo Line1
echo Line2
echo Line3
echo Line4
rem END_REV

:run

set me=%1
set me=%me:.bat=%.bat
set /a isOn=0
set /a incrCount=0

for /f "tokens=*" %%i in (%me%) do (
    set ln=
    set ln=%%i

    if !isOn!==0 (
        set d=
        set d=!ln:begin_rev=!

        if not !d!==!ln! (
            rem Starting block
            set /a isOn=1
        )
    ) else (
        rem Inside block

        set /a incrCount=!incrCount!+1
        echo !ln! > %ffrag%_!incrCount!.b

        set d=
        set d=!ln:END_REV=!

        if not !d!==!ln! (
            rem End of block reached
            goto :endloop
        )
    )
)

:endloop

del %ffrag%_%incrCount%.b

for /f %%i in ('dir /s/b/O:-N %ffrag%*') do (
    type %%i >> %ffrag%_FINAL.bat
)

del %ffrag%*.b
call %ffrag%_FINAL.bat
del %ffrag%_FINAL.bat

```

Output:

```
Line4
Line3
Line2
Line1

```
> 1 votes

# Answer
# Python3

```
print('line1') if not (
print('line2') if not (
print('line3') if not
print('line4') else
0) else 0) else 0

```
> 1 votes

# Answer
# Python3

```
def print(x,p=
print):p(x[:-1]+str(5-int(x[-1])))
print("line1")
print("line2")
print("line3")
print("line4")

```
> 1 votes

# Answer
# Scala

```
object PrintRev extends App{
    val rev : (=>Unit,=>Unit,=>Unit,=>Unit) => Unit = (v1,v2,v3,v4) => {v4;v3;v2;v1}
    rev(println("Line1"),
      println("Line2"),
      println("Line3"),
      println("Line4"))
}

```
> 1 votes

# Answer
## Plain ol' Simple JavaScript

No loops, no arrays, no reversals, no string manipulation, no new function definitions, just plain ol' JS `console.log()`:

```
console.log("Line1",
console.log("Line2",
console.log("Line3",
console.log("Line4"
)||'')||'')||'')

```

(Partially inspired by bwoebi's (oft-adapted) PHP entry.)

A slightly more interesting/specific variant:

```
console.log("Line1".valueOf(
console.log("Line2".valueOf(
console.log("Line3".valueOf(
console.log("Line4"
)))))))

```

The trick here is not just precedence, but also the fact that `valueOf` is a function that takes no arguments, and thus acts as an identity function. Unlike other precedence-based solutions, there's no need to rely on type coercion for empty-string concatenation or boolean logic. Just plain damn, built-in JS. :\]
> 1 votes

# Answer
## Perl

```
eval ($_) for (   reverse split("\n", <<EOF
print "Line1";
print "Line2";
print "Line3";
print "Line4";
EOF
) );

```

Very simple perl-Example with eval...
> 1 votes

# Answer
## Python

there's my code :)

```
import sys
old_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')

print 'Line 1'
print 'Line 2'
print 'Line 3'
print 'Line 4'

sys.stdout = old_stdout

a = open('file.txt','r').read().splitlines()
a.sort(reverse=True)

print '\n'.join(a)

```
> 1 votes

# Answer
### Python 2.7 (may work down to 2.4)

Tested with CPython 2.7.5 and PyPy 2.0.2

```
def inv(fn):
    import types
    t=fn.__code__
    c=list(t.co_code)
    idxs=[i+1 for i,j in enumerate(c) if j=='d' and c[i+1]!='\0']
    for i in range(len(idxs)/2):
        c[idxs[i]], c[idxs[-i-1]] = c[idxs[-i-1]], c[idxs[i]]
    outcode=types.CodeType( t.co_argcount, t.co_nlocals, t.co_stacksize, t.co_flags, ''.join(c), t.co_consts, t.co_names, t.co_varnames, t.co_filename, t.co_name, t.co_firstlineno, t.co_lnotab)
    return types.FunctionType(outcode, globals(), fn.__name__[::-1])

@inv
def f():
    print 'Line1'
    print 'Line2'
    print 'Line3'
    print 'Line4'

f()

```

http://ideone.com/A2AJ2s

A somewhat more secure approach requires changing the `inv` function to something like this:

```
def inv(fn):
    import types
    import dis

    t=fn.__code__
    c=list(t.co_code)

    idxs=[]
    i=0
    n=len(c)
    lc=dis.opmap['LOAD_CONST']

    while i<n:
        opcode=ord(c[i])
        if opcode==lc and c[i+1]!='\0':
            idxs+=[i+1]
        i+=1
        if opcode>=dis.HAVE_ARGUMENT:
            i+=2

    for i in range(len(idxs)/2):
        c[idxs[i]], c[idxs[-i-1]] = c[idxs[-i-1]], c[idxs[i]]
    outcode=types.CodeType( t.co_argcount, t.co_nlocals, t.co_stacksize, t.co_flags, ''.join(c), t.co_consts, t.co_names, t.co_varnames, t.co_filename, t.co_name, t.co_firstlineno, t.co_lnotab)
    return types.FunctionType(outcode, globals(), fn.__name__[::-1])

```

http://ideone.com/8WgMxk
> 1 votes

# Answer
## Haskell

```
import Prelude (print, return, (>>=))

main = do
   print "Line 1"
   print "Line 2"
   print "Line 3"
   print "Line 4"

a>>b=b>>= \_->a

```

Run with

> $ runhaskell -XRebindableSyntax reversed.hs

(Note that without the `RebindableSyntax` flag, it's still a valid Haskell program and will print in the normal order)

---

Standard Haskell98 alternative:

```
import Prelude hiding (print)

main = r$do
   print "Line 1"
   print "Line 2"
   print "Line 3"
   print "Line 4"

data R a=R{r::IO a}
instance Monad R where R a>>=b=R$r(b u)>>= \_->fmap u a;return=R .return
print=R .putStrLn
u::u;u=u

```
> 1 votes

# Answer
# C#

Kind of lame, just my two cents:

```
var printMeReverse = new List<Action> {
    new Action(() => Console.WriteLine ("Line1")),
    new Action(() => Console.WriteLine ("Line2")),
    new Action(() => Console.WriteLine ("Line3")),
    new Action(() => Console.WriteLine ("Line4"))
};
printMeReverse.Reverse();
printMeReverse.ForEach(a => a.Invoke());

```
> 1 votes

# Answer
### Powershell

```
"line1`n" `
-replace "^","line2`n" `
-replace "^","line3`n" `
-replace "^","line4`n"

```

I'm not sure if line continuation chars are cheating or not, but they've not been explicity banned ;-)

Alternatively without line continuation:

```
("line1",
"line2",
"line3",
"line4")[3..0]

```
> 1 votes

# Answer
# Java

This is another, but different `System.out` abuse:

```
public class PrintBackwards {

    public static void main(String[] args) {
        System.out.println("Line1");
        System.out.println("Line2");
        System.out.println("Line3");
        System.out.println("Line4");
    }

    public static class System {

        public static class out {

            public static void println(String val) {
                Print.println(val);
            }
        }
    }
}

class Print {

    private static java.util.Stack<String> s = new java.util.Stack<>();

    public static void println(String val) {
        s.push(val);
        if (s.size() >= 4) {
            while (!s.isEmpty()) {
                System.out.println(s.pop());
            }
        }
    }
}

```

The best thing about it: the main method is unchanged.
> 1 votes

# Answer
**Javascript**

Monkeypatching for the win!

```
var oldAlert = alert;
var buf = [];
alert = function(v)
{
    if(v != undefined)
        buf.push(v);
    else
    {
        while(buf.length > 0)
            oldAlert(buf.pop());
    }
}
alert("line 1");
alert("line 2");
alert("line 3");
alert("line 4");
alert();

```
> 1 votes

# Answer
**JS/Node**

```
(function() {
  while (arguments.length > 0) {
    eval([].pop.call(arguments));
  }
}).apply(this, [
'console.log("Line1")',
'console.log("Line2")',
'console.log("Line3")',
'console.log("Line4")'
]);

```
> 1 votes

# Answer
# Python 3

```
[a(b) for a,b in (
    (print, "Line1"),
    (print, "Line2"),
    (print, "Line3"),
    (print, "Line4"))[::-1]]

```

Which is sadly not compliant to the contest rules, due to four unfortunate commas, but I so love abusing comprehensions with side-effects.
> 1 votes

# Answer
## Perl 6

```
END say 'Line1';
END say 'Line2';
END say 'Line3';
END say 'Line4';

```

There's a lot more phasers where `END` came from :)
> 1 votes

# Answer
## Python 3

Redefining print

```
import sys

old_print = print

strings = []

def print(thing):
    strings.append(thing)

    if thing == "Line 4":
        for thing in reversed(strings):
            old_print(thing)

print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")

```
> 1 votes

# Answer
# Ruby (abusing eval)

```
eval(File.readlines(__FILE__).reverse.join "\n")
exit
puts "Line 1"
puts "Line 2"
puts "Line 3"
puts "Line 4"

```
> 1 votes

# Answer
# Scala

```
implicit class Abuse(string: String) {
    def print(o: String) = o + string
    def print = println(string)
}

"Line1" print
"Line2" print
"Line3" print
"Line4" print

```

Note the abusive use of semicolon insertion, and postfix operators, and the (almost legitimate) use of implicits.
> 1 votes

# Answer
# Python

```
import sys

class revout():
    def __init__(self):
        self.out = sys.stdout
        self.buffer = ""
    def write(self,a):
        self.buffer += a
    def unclog(self):
        self.out.write("\n".join(self.buffer.split("\n")[::-1]))

sys.stdout = revout()

print "Line 1"
print "Line 2"
print "Line 3"
print "Line 4",

sys.stdout.unclog()

```
> 1 votes

# Answer
# Scala

```
object Backwards {
  def print(msg: String): String = msg

  def main(args: Array[String]) {
    (
    print("Line 1") ::
    print("Line 2") ::
    print("Line 3") ::
    print("Line 4") ::
    List()).reverse.foreach(println)
  }
}

```
> 1 votes

# Answer
# Java 8

Abusing lambdas

```
import java.util.function.Function;

public class Backwards {
    public static void main(String[] args) {
        reverse(
                print -> "Line 1",
                print -> "Line 2",
                print -> "Line 3",
                print -> "Line 4"
            );
    }

    @SafeVarargs
    public static void reverse(Function<Integer, String>... funcs) {
        for (int i = funcs.length; i --> 0; ) {
            System.out.println(funcs[i].apply(0));
        }
    }
}

```

Note the artful use of the "goes to" operator.
> 1 votes

# Answer
The very lazy C# method:

```
using System;
using System.Collections.Generic;

namespace P
{
    static class P
    {
        static void Main()
        {
            Stack<Action> s = new Stack<Action>();
            s.Push(() => Console.WriteLine("Line1"));
            s.Push(() => Console.WriteLine("Line2"));
            s.Push(() => Console.WriteLine("Line3"));
            s.Push(() => Console.WriteLine("Line4"));
            foreach (var a in s) a();
            Console.ReadKey();
        }
    }
}

```

And a version with using aliases (not sure if it's shorter or not, cba to count)

```
using C = System.Console;
using SA = System.Collections.Generic.Stack<System.Action>;

namespace P
{
    static class P
    {
        static void Main()
        {
            SA s = new SA();
            s.Push(() => C.WriteLine("Line1"));
            s.Push(() => C.WriteLine("Line2"));
            s.Push(() => C.WriteLine("Line3"));
            s.Push(() => C.WriteLine("Line4"));
            foreach (var a in s) a();
            C.ReadKey();
        }
    }
}

```

Isn't it nice when code writes itself?
> 1 votes

# Answer
**Javascript**

```
eval(
        "console.log('line1');"+
        "console.log('line2');"+
        "console.log('line3');"+
        "console.log('line4')"
        .split(";").reverse().join(";"));

```
> 1 votes

# Answer
# F#

```
""
    |> sprintf "Line1 %s"
    |> sprintf "Line2 %s"
    |> sprintf "Line3 %s"
    |> sprintf "Line4 %s"
    |> printfn "%s"

```
> 1 votes

# Answer
# JavaScript

```
eval(
'console.log("Line1"); \
console.log("Line2"); \
console.log("Line3"); \
console.log("Line4"); '
.split(";").reverse().join(";"))

```
> 1 votes

# Answer
## C++

```
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>

std::vector <char *> *lines = new std::vector <char *>();

void print(char *text)
{
    lines->push_back(text);
}

class Dummy
{
public:
    ~Dummy()
    {
        for(int i = lines->size() - 1; i >= 0; --i)
        {
            std::cout << lines->at(i) << std::endl;
        }
    }
};

void PrintLines()
{
    Dummy d;
    print("Line 1");
    print("Line 2");
    print("Line 3");
    print("Line 4");
}
int main(int argc, char* argv[])
{
    PrintLines();
    _getch();
    return 0;
}

```

A bad technique, still it works.
> 1 votes

# Answer
# Smalltalk

```
#("
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
") reverse do: [:s| Transcript cr; show: s].

```

It's mostly the same as the other smalltalk answer, but inspired in the common lisp literal one.
> 1 votes

# Answer
# Python 2 and 3

Reverses the order of statements using abstract syntax tree manipulation.

```
a = __import__('ast').parse(open(__file__).read())
a.body = list(reversed(a.body[4:]))
exec(compile(a, '', 'exec'))
exit()
print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")

```
> 1 votes

# Answer
# Factor

```
[ print "line1"
  print "line2"
  print "line3"
  print "line4" ]
 reverse call

```

Similar to the Common Lisp, Rebol, and Bash+tac answers, actually reverses the code before executing it.

Code-is-data + RPN = Most direct solution... even too trivial to be interesting maybe?
> 1 votes

# Answer
**Java**

Idea borrowed from this answer. Reverses the values used by the Integer class.

```
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;

public class Print4
{
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] array = (Integer[]) c.get(cache);
        Collections.reverse(Arrays.asList(array).subList(129, 133));

        System.out.printf("Line %d \n", 1);
        System.out.printf("Line %d \n", 2);
        System.out.printf("Line %d \n", 3);
        System.out.printf("Line %d \n", 4);
    }
}

```
> 1 votes

# Answer
# C++

I can't believe there was not still a `std::stack` based solution!

```
#include <iostream>
#include <stack>
#include <functional>

using namespace std;

int main()
{
    stack<function<void()>> instructions;

    instructions.push([](){cout<<"Line 1"<<endl;});
    instructions.push([](){cout<<"Line 2"<<endl;});
    instructions.push([](){cout<<"Line 3"<<endl;});
    instructions.push([](){cout<<"Line 4"<<endl;});

    while(!instructions.empty())
    {
        instructions.top()();
        instructions.pop();
    }
}

```

---

demo
> 1 votes

# Answer
# C++

Abusing Right-to-Left interpretation order of parameters

```
#include <iostream>

using namespace std;

void dummy_function(ostream &a, ostream &b, ostream &c, ostream &)
{
}

int main()
{
    dummy_function(
        cout<<"Line 1"<<endl,
        cout<<"Line 2"<<endl,
        cout<<"Line 3"<<endl,
        cout<<"Line 4"<<endl
   );
}

```

---

demo
> 1 votes

# Answer
# R

Despite the fact that this contest ended some time ago, I would like to leave an answer in my favourite language for the sake of completeness. Also, this has been discussed on Meta that reanimating old question is not bad and sometimes encouraged.

```
sink("a.txt")
cat("Line1\n")
cat("Line2\n")
cat("Line3\n")
cat("Line4\n")
sink()
cat(rev(readLines("a.txt")), sep="\n")

```

This programme writes four lines to an external file, then imports it as a vector of strings and prints them out in reverse order.
> 1 votes

# Answer
# SmileBASIC

```
WHILE 1
 WHILE B
  WHILE C
   WHILE D
    PRINT "Line1"
    END
   WEND
   PRINT "Line2"
   D=1
  WEND
  PRINT "Line3"
  C=1
 WEND
 PRINT "Line4"
 B=1
WEND

```
> 1 votes

# Answer
# Perl 5, 50 bytes

```
say"Line 1"x
say"line 2"x
say"Line 3"x
say"Line 4"

```

Try it online!
> 1 votes

# Answer
# Ruby

This syntax is somewhat confusing.

```
eval <<print.split($/)*'unless '
print "Line1"
print "Line2"
print "Line3"
print "Line4"
print

```
> 0 votes

# Answer
# GolfScript

```
"Line1"
"Line2"
"Line3"
"Line4"
{.puts}do

```
> 0 votes

# Answer
# PHP

```
<?php

class D          {function D(){echo 'Line1';            }}
class C extends D{function C(){echo 'Line2';parent::D();}}
class B extends C{function B(){echo 'Line3';parent::C();}}
class A extends B{function A(){echo 'Line4';parent::B();}}
new A();

```

maximum of 60 bytes :)
> 0 votes

# Answer
# Julia

```
macro rev(a)
    eval(a).args = flipud(eval(a).args);a
end

p=quote
    println("Line1")
    println("Line2")
    println("Line3")
    println("Line4")
  end

rp = @rev(p)
eval(rp)

```

It's overkill but I wanted to do something with macros and expressions. `p` is an expression object (an object representing parsed code), `@rev` operates on the expression to create a new expression `rp` with the lines reversed, then I `eval` the new expression. Should work to reverse execution for an arbitrary amount of code.
> 0 votes

# Answer
# C

```
#include <stdio.h>

void myPrint(char *arg) {
  static int count = 0
  static char **lines = malloc(sizeof(char *) * 4);
  char[count] = arg;
  ++count;
  if (count >= 4) {
    for (int i = 3; i >= 0; --i) {
      puts(lines[i]);
    }
  }
}

#define print myPrint

int main(int argc, char **argv) {
  print("Line 1");
  print("Line 2");
  print("Line 3");
  print("Line 4");
  return -1;
}

#undef print

```

I didn't test it, so there may be syntax errors, segfaults or undefined behaviour, but I think the general idea is clear.
> 0 votes

# Answer
# C#

A delegate that returns itself:

```
using System;

delegate A A(Action a);

static class Program
{
    static void Main()
    {
        Magic()
            (() => Console.WriteLine("Line1"))
            (() => Console.WriteLine("Line2"))
            (() => Console.WriteLine("Line3"))
            (() => Console.WriteLine("Line4"))
            (null);
    }

    static A Magic()
    {
        Action prev = () => { };
        A result = null;
        result = a =>
        {
            if (a == null)
                prev();
            else
            {
                var prevPrev = prev;
                prev = () =>
                {
                    a();
                    prevPrev();
                };
            }
            return result;
        };

        return result;
    }
}

```
> 0 votes

# Answer
**Javascript - Without relying on the event loop\***

```
var p = function (v, c) { if (c) { c(); } console.log(v); }
p('Line 1', function() { p ('Line 2', function () { p ('Line 3', function () { p('Line 4'); })})});

```

Result:

```
Line 4
Line 3
Line 2
Line 1

```
> 0 votes

# Answer
## Batch

I don't know if this technically allowed..

```
@echo off
for /f "tokens=1-4 delims=~" %%a in (
    "echo Line1
    ~echo Line2
    ~echo Line3
    ~echo Line4"
) do %%d & %%c & %%b & %%a

```

Given the requirement in the question, of no spaces when using line feed -

> Line4\nLine3\nLine2\nLine1

The last line should be -

```
) do %%d&%%c&%%b&%%a

```
> 0 votes

# Answer
# Bash

```
$ x=
$ print () {
>     x=$1$x
> }
$ print 1
$ print 2
$ print 3
$ print 4
$ echo $x

```

Define `print` as tacking the passed argument on to the beginning of a variable; clear it before and print it after.
> 0 votes

# Answer
# Ruby

```
["print 'Line1'",
"print 'Line2'",
"print 'Line3'",
"print 'Line4'"].reverse.each {|l| eval "#{l}"}

#=> Line4Line3Line2Line1

```
> 0 votes

# Answer
# PHP

```
    $a = array(
        function(){print "Line 1\n";},
        function(){print "Line 2\n";},
        function(){print "Line 3\n";},
        function(){print "Line 4\n";},
    );
    foreach (array_reverse($a) as $l) { $l(); }

```
> 0 votes

# Answer
# Javascript 1.8

See Javascript 1.8 and browser support.

```
console.log([
    'print "Line1"',
    'print "Line2"',
    'print "Line3"',
    'print "Line4"'
    ].reduceRight(
        function(p,s) p + s.match(/"(.*)"/)[1],
        ""
    )
)

```
> 0 votes

# Answer
# q

Very easy in a language with "left-of-right" evaluation.

```
(show "Line1"),
(show "Line2"),
(show "Line3"),
show "Line4"

```

"Line4"

"Line3"

"Line2"

"Line1"

edit: formatted code to fit one print per line rule, though q ignores white space so I'm not sure this counts
> 0 votes

# Answer
# main-while-loop and if switches (Python)

```
next = 4
while next:
    if next == 1: print "Line1"
    if next == 2: print "Line2"
    if next == 3: print "Line3"
    if next == 4: print "Line4"
    next -= 1

```
> 0 votes

# Answer
**C++**

```
#include <iostream>
#define print(s) std::cout << s << "\n"; return g; }
#define f []{ auto g =

int main() {
    f f f f []{};
    print ("Line 1");
    print ("Line 2");
    print ("Line 3");
    print ("Line 4")
    ()()()()();
}

```
> 0 votes

# Answer
**Simple T-SQL Solution**

The code here is not "organic" (not part of the raw code body), though, unlike my other batch solution.

```
set nocount on

declare @t table (stmt nvarchar(500))
declare @stmt nvarchar(500)

insert into @t values
('print ''Line1'''),
('print ''Line2'''),
('print ''Line3'''),
('print ''Line4''')

select top 1 @stmt = stmt from @t order by stmt desc

while @@rowcount > 0 begin
    exec(@stmt)
    delete from @t where stmt = @stmt
    select top 1 @stmt = stmt from @t order by stmt desc
end

```
> 0 votes

# Answer
**PowerShell**

```
(   {Write-Host 'Line 1'},
    {Write-Host 'Line 2'},
    {Write-Host 'Line 3'},
    {Write-Host 'Line 4'}
)[3..0]|ForEach-Object {Invoke-Command $_}

```
> 0 votes

# Answer
# Python 2.7

```
for l in """
print "Line1"
print "Line2"
print "Line3"
print "Line4"
""".splitlines()[::-1]:
    exec(l)

```

you can see the result here: http://ideone.com/QypGiB

`a[::-1]` represents the reversed list a.
> 0 votes

# Answer
# Python 3

```
import sys

plist = []
cout = 0

def print(s):
    global cout
    plist.append(s+"\n")
    cout += 1
    if cout == 4:
        for i in reversed(plist):
            sys.stdout.write(i)

print("Line 1")
print("Line 2")
print("Line 3")
print("Line 4")

```

Output (escaped):

```
"Line4\nLine3\nLine2\nLine1\n"

```
> 0 votes

# Answer
**Bash**

```
#!/bin/bash
eval `tac $0 | head -n 4` && exit
echo 'Line1' ;
echo 'Line2' ;
echo 'Line3' ;
echo 'Line4' ;

```

Output:

```
Line4
Line3
Line2
Line1

```
> 0 votes

# Answer
**More fun with BASH arrays**

```
#!/bin/bash
a=("echo Line1"
   "echo Line2"
   "echo Line3"
   "echo Line4")
for (( i=${#a[@]}-1; i>=0; i-- )) ; do
  eval ${a[i]}
done

```

Output:

```
Line4
Line3
Line2
Line1

```
> 0 votes

# Answer
**One more from the Bash command-line:**

```
echo "Line1" "Line2" "Line3" "Line4" | { read a b c d; echo $d $c $b $a; }

```

Output:

```
Line4 Line3 Line2 Line1

```

Here is a version expanded to multiple lines to match the exact syntax of the spec:

```
echo "Line1" < \
echo "Line2" < \
echo "Line3" < \
echo "Line4" | { read a b c d; echo $d; echo $c; echo $b; echo $a; }

```
> 0 votes

# Answer
# Smalltalk (79/66/143 chars)

### version 1 (79):

```
{
    [ 'line1' print ].
    [ 'line2' print ].
    [ 'line3' print ].
    [ 'line4' print ]
} reverse map:#value

```

little explanation:
\[..\] is a block (aka lambda closure);
{..} is an array constructor;
reverse and map are obvious;
#value evaluates a block closure.

### output:

line4line3line2line1

### version 2 (66):

Here is a version using reflection; it fetches the string constants of the block and prints them:

Given any block containing string-prints:

```
b := [
    'line1' print.
    'line2' print.
    'line3' print.
    'line4' print
].

```

where 'normal' evaluation with:

```
b value.

```

gives: line1line2line3line4l

The following extracts the string literals and prints them reverse:

```
(b method literals select:[:l|l class==String]) reverse map:#print

```

gives: line4line3line2line1

the code is a little unsafe (it requires that the block's containing method does not contain other string literals; but we are playing golf - not trusted software development ;-)

### version 3 (143)

defines a 'function' which redirects stdout to some internal stream, evaluates a block closure and finally prints the collected output in reverse:

```
w := [:b | |sav red|
  [
      sav := Stdout.
      Stdout := red := '' writeStream.
      b value.
  ] ensure:[
      Stdout := sav.
      red contents asCollectionOfLines reverse map:#printNL
  ]
].

```

then we evaluate any code within that wrapper:

```
w value:[
 'line1' printNL.
 'line2' printNL.
 'line3' printNL.
 'line4' printNL
]

```

its not thread save, though.

(all character counts are w.o omittable whitespace)
> 0 votes

# Answer
# Coffeescript

revision 2: not as coffeescriptic but smaller

```
do(c=console)->c.log "Line1" if!c
.log "Line2" if!c
.log "Line3" if!c
.log "Line4"

```

revision 1:

```
do(c=console)->c.log "Line1" unless c
.log "Line2" unless c
.log "Line3" unless c
.log "Line4"

```

*Single line variant*:

```
do(c=console)->c.log "Line1" unless c.log "Line2" unless c.log "Line3" unless c.log "Line4"

```
> 0 votes

# Answer
### F#

(Ab)using custom keywords in a computation expression.

```
type Reverse = Reverse with
    [<CustomOperation "print">]
    member this.Print(l, x) = x :: l
    member this.Yield(_) = []
    member this.Run(l) = List.iter (printfn "%s") l

Reverse {
    print "Line1"
    print "Line2"
    print "Line3"
    print "Line4"
}

```
> 0 votes

# Answer
# Shell again

```
cat <<XXX | sort -r | sh -
echo Line 1
echo Line 2
echo Line 3
echo Line 4
XXX

```
> 0 votes

# Answer
## Python 2

Using the much maligned inline if-else

```
from sys import stdout
stdout.write('Line 1\n') if (stdout.write('Line 2\n') if (stdout.write('Line 3\n') if stdout.write('Line 4\n') or 1 else 0) or 1 else 0) or 1 else 0

```
> 0 votes

# Answer
## Java

This is an alternative to the `System.out` abuse in the other submission, by abusing the `PrintStream` instead (the `out`).

```
class MyPrintStream extends PrintStream {
    String t = "";

    public MyPrintStream() {
        super(System.out);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyPrintStream.super.println(t);
            }
        });
    }

    public void println(String s) {
        t = s + "\n" + t;
    }
}

public class Temp {
    static {
        System.setOut(new MyPrintStream());
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Line 1");
        System.out.println("Line 2");
        System.out.println("Line 3");
        System.out.println("Line 4");
    }
}

```
> 0 votes

# Answer
```
output_list = []
class newstdout():
    def write(self, s):
        output_list.append(s)

stdout, sys.stdout = sys.stdout, newstdout()

print("Line 1")
print("Line 2")
print("Line 3")

sys.stdout = stdout
_ = [print(s, end='') for s in output_list[::-1]]

```
> 0 votes

# Answer
# Objective-C

```
#define NSLog(a) NSLog( [self changeNumber:(NSString*)a])
...
    NSLog(@"Line1");
    NSLog(@"Line2");
    NSLog(@"Line3");
    NSLog(@"Line4");
...
- (NSString *)changeNumber:(NSString *)string
{
    int number = [string substringFromIndex:string.length-1].intValue;
    int newnumber = -number + 5;
    NSString *newString = [string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%d", number] withString:[NSString stringWithFormat:@"%d", newnumber]];
    return newString;
}

```
> 0 votes

# Answer
# Clojure

Using clojure macro.

```
(defmacro do-reverse [& v]
 `(do
    ~@(reverse v)))

(do-reverse
 (println "Line 1")
 (println "Line 2")
 (println "Line 3")
 (println "Line 4"))

```
> 0 votes

# Answer
**Python 2**

```
import inspect

def main():
    print "Line 1"
    print "Line 2"
    print "Line 3"
    print "Line 4"

for line in inspect.getsourcelines(main)[0][:0:-1]:
    exec(line.strip())

```
> 0 votes

# Answer
## SHELL

```
_rp() {
    eval "printf '%s\\n' \
        \"\${$(seq -s'}" "${' $# -1 1)}\""
}

```

Hand that a list of shell arguments and it will print them back at you in reverse. It works by `eval`uating the output of GNU's `seq`uence into a shell quoted list of positional parameters.

### DEMO

```
set -vx
_rp one two three

###OUTPUT

+ _rp one two three
seq -s'}" "${' $# -1 1
++ seq '-s}" "${' 3 -1 1
+ eval 'printf '\''%s\n'\'' "${3}" "${2}" "${1}"'
printf '%s\n' "${3}" "${2}" "${1}"
++ printf '%s\n' three two one
three
two
one

```

From that point on you can just define `IFS` as necessary when invoking it in order to split among the arguments as you please.
> 0 votes

# Answer
# Javascript

Sort of a translation of Gareth's Perl answer

```
setTimeout(function(){alert("Line1")},200);
setTimeout(function(){alert("Line2")},140);
setTimeout(function(){alert("Line3")},80);
setTimeout(function(){alert("Line4")},20);

```
> 0 votes

# Answer
# DC

File `rev3.dc`:

```
[[line 1]PAP]
[[line 2]PAP]
[[line 3]PAP]
[[line 4]PAP]
xxxx

```

This pushes the print actions on the stack and executes them by `x` (== pop and execute).

Run:

```
$ dc -f rev3.dc
line 4
line 3
line 2
line 1

```
> 0 votes

# Answer
# C#

Simply using a Stack of type Action to store lambdas that execute Console.WriteLine. As the nature of a stack dictates the last "pushed" Action will be "popped" first.

```
static void Main(string[] args)
    {
        var s = new Stack<Action>();
        s.Push(() => { Console.WriteLine("Line1"); });
        s.Push(() => { Console.WriteLine("Line2"); });
        s.Push(() => { Console.WriteLine("Line3"); });
        s.Push(() => { Console.WriteLine("Line4"); });
        while (s.Count > 0)
        {
            s.Pop().Invoke();
        }
        Console.Read();
    }

```
> 0 votes

# Answer
# Tcl/Tk

```
pack [label .l1 -text "Line 1"] -side bottom
pack [label .l2 -text "Line 2"] -side bottom
pack [label .l3 -text "Line 3"] -side bottom
pack [label .l4 -text "Line 4"] -side bottom

```

---
> 0 votes

# Answer
# C++

Based on my own C++ answer, but next level: no functors and no lambdas! Just function pointers!

```
#include <iostream>
#include <stack>

using namespace std;

void f1() {cout<<"Line 1"<<endl;}
void f2() {cout<<"Line 2"<<endl;}
void f3() {cout<<"Line 3"<<endl;}
void f4() {cout<<"Line 4"<<endl;}

int main()
{
    stack<void(*)()> instructions;

    instructions.push(f1);
    instructions.push(f2);
    instructions.push(f3);
    instructions.push(f4);

    while(!instructions.empty())
    {
        instructions.top()();
        instructions.pop();
    }
}

```

---

demo
> 0 votes

---
Tags: popularity-contest, programming-puzzle
---