Deletion of a blank line in source code which causes unexpected functionality

38

6

Write a script that works fine when a blank line is present in the flow of program logic, but breaks or causes unexpected behaviour when that line is removed.

Avoid standard loopholes and stupid answers. Your program should do something "useful," even if all it does is add a few integers.

Removing an empty line from a multiline string doesn't count, unless the expected output from that multiline string shouldn't technically change (ie: if you're removing all blank lines matching ^$).

Whitespace foolery isn't allowed either; don't do weird things with carriage returns, tabs, spaces, etc.

Naftuli Kay

Posted 2014-06-12T18:34:53.503

Reputation: 489

Question was closed 2016-04-18T14:51:48.010

3

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

– cat – 2016-04-18T02:28:38.263

2Are empty lines inside multiline strings counted? – seequ – 2014-06-12T18:39:51.050

11I think you should exclude Whitespace. – nneonneo – 2014-06-12T18:40:23.283

17I think that Whitespace is a "standard loophole" – core1024 – 2014-06-12T18:42:25.383

Updated the question with qualifications. – Naftuli Kay – 2014-06-12T18:43:40.550

5

nneonneo is talking about Whitespace, which is a language that uses only spaces as its syntax.

– Kyle Kanos – 2014-06-12T18:48:43.287

Is there any blank line that doesn't match ^$ ?! – aditsu quit because SE is EVIL – 2014-06-12T19:03:37.417

@aditsu No there is not. – seequ – 2014-06-12T19:12:17.827

@TheRare so that means removing an empty line from a multiline string doesn't count... unless it's a blank line? o_O – aditsu quit because SE is EVIL – 2014-06-12T19:14:45.900

@aditsu My thought exactly. – seequ – 2014-06-12T19:16:02.420

1I'd love to see a solution using Brainfuck. – Nzall – 2014-06-13T09:44:47.003

4"unexpected functionality" is a very good phrase. – Kaz – 2014-06-13T19:16:52.190

"Whitespace foolery isn't allowed either; don't do weird things with carriage returns, tabs, spaces, etc." What's a blank line except but a newline character following another (or other character(s), depending on platform)? – Joshua Taylor – 2014-06-13T20:01:56.980

Acme::Bleach, anyone? – MarnixKlooster ReinstateMonica – 2014-06-15T20:20:20.470

@JoshuaTaylor, if you remove a line in your program that matches ^$ and observe different functionality, that's what we're looking for. A blank line is NOT ^\s+$. – Naftuli Kay – 2014-06-16T17:59:29.987

@NaftuliTzviKay It was tongue in cheek response, but the point was that a blank line is something that has to two with whitespace. If removing a blank line makes a difference, then just about by definition it's "whitespace foolery". The \<newline> behavior in C, for instance only works when \ is followed by a newline (which is a whitespace) character. It's whitespace foolery. :) – Joshua Taylor – 2014-06-16T18:08:31.427

Answers

62

Javascript

Opens an alert popup with "Hello, World!" if the blank line exists, otherwise alerts "0".

(function(){
    alert(~(arguments.callee+[]).indexOf('\n\n') && "Hello, World!");

})();

Demo

Explanation:

arguments.callee is a reference to the self-executing anonymous function.

Appending a blank array ([]) casts the function to a string, which gives you its source code.

indexOf returns -1 if the string is not found.

Performing a bitwise not operation (~) results in -1 being turned into 0, which is a falsey value.

nderscore

Posted 2014-06-12T18:34:53.503

Reputation: 4 912

2What trickery is this?! – Kroltan – 2014-06-13T01:10:07.497

1arguments.callee contains the source of the function. – Matthew – 2014-06-13T01:35:33.960

@Kroltan I've added an explanation to the answer :) – nderscore – 2014-06-13T02:34:49.597

@Matthew is that in the spec, or just something that most browsers happen to implement? – Michael – 2014-06-13T20:50:08.593

@Michael looks like it, according to the publicly accessible documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee

– Matthew – 2014-06-13T21:13:10.407

2Note that this no longer works in strict mode (which most modern code would be using). Strict mode forbids the use of arguments.callee. – Daniel Lo Nigro – 2014-06-15T04:18:11.913

1

@Michael: No, spec says nothing about the exact format. In fact, there are engines running around that do not preserve whitespace.

– Bergi – 2014-06-15T04:59:14.223

2@DanielLoNigro You can just give the function expression a name and use that instead of arguments.callee. Even makes it shorter. – a cat – 2014-06-15T13:56:44.803

42

C

This magic 8-ball program will still work without the blank line, but it will be a bit more decisive — none of the neutral answers will ever appear in the output.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
  int x, t;
  char *quotes[] = {
        // Positive :-)
        "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it",
        "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes",
        // Indifferent :-\

        "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again",
        // Negative :-(
        "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" };
  srandom(time(NULL)); // Initialize random number generator
  x = random() % (sizeof(quotes) / sizeof(char*)); // Choose a random outcome
  printf("The Magic Eight Ball says...\n%s\n",quotes[x]);
  return 0;
}

Explanation

When the C parser sees a backslash followed by a newline character, it ignores both and treats the second line as a continuation of the first. Without the empty line, the "indifferent" answers will all be treated as part of the previous comment.

r3mainer

Posted 2014-06-12T18:34:53.503

Reputation: 19 135

51I +1'd, but seeing C comments ending with a backslash is starting to become a standard loophole, IMO. – Tim S. – 2014-06-12T22:27:12.133

1@TimS. Common I can see, but how on earth is it a loophole? – Kevin – 2014-06-13T01:12:18.863

2

It was a reference to this "standard loopholes" post, so maybe not literally a "loophole".

– Tim S. – 2014-06-13T01:14:33.660

Maybe add line breaks after Positive, before Indifferent, and before and after Negative to make it less obvious? – wchargin – 2014-06-13T05:07:22.383

5@TimS. if you are bored with this "solution", why did you upvote? – John Dvorak – 2014-06-13T05:21:51.827

8The backslash-the-next-line-into-a-comment answers (trigraph or no trigraph) are making me wish I had 125 reputation. I keep seeing them and they're starting to be awfully repetitive, totally see-through, and no longer clever or funny. (Which is unfortunate for those using them, like squeamish here, because they in no way deserve the ire and are sometimes totally unaware of this - but the trick is earning it.) – doppelgreener – 2014-06-13T07:11:57.890

1Sorry everybody. I didn't expect this to get many votes. Please vote for nderscore and aditsu instead. – r3mainer – 2014-06-13T07:31:52.027

4@Jan starting to become standard is not the same as long-standard/overdone...its use is fairly clever here, it doesn't look out of place (unlike some I've seen, which inexplicably have character(s) at the end of a comment, or end their comments with the comment-start character(s) in order to do something unusual). So: I upvote the solution, not the continued use of its trick. – Tim S. – 2014-06-13T16:31:07.813

1Related: Unicode escapes in Java outside of string literals. – Ming-Tang – 2014-06-13T22:58:12.240

37

Befunge-93

v
&
&
+
#

.
@

My first befunge program :)

It reads two numbers from the input and prints their sum. If you delete the empty line, it doesn't print anything.

Explanation:

v sets a downward direction for executing the code
& reads an integer
+ adds the numbers together
# skips the next command
. prints an integer from the stack
@ ends the program

As written, # skips over the empty line and contines with .. Buy when you delete the empty line, . is skipped.

There seems to be a nice interpreter at http://befunge.aurlien.net/

aditsu quit because SE is EVIL

Posted 2014-06-12T18:34:53.503

Reputation: 22 326

Ah, clever one. – seequ – 2014-06-12T19:55:30.563

1

Befunge 98 also does this. Good thinking. And this interpreter has some benefits (I haven't used yours much, so I don't know its benefits).

– Justin – 2014-06-12T20:31:11.650

32

Ruby/Shell

​​​​​​
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!   The Amazing Integer Adder             !
#! Adds 1 and 1, and displays the result   !
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

p 1+1

Works fine if a newline is at the top, otherwise the first comment line is interpreted by the shell as a malformed shebang.

histocrat

Posted 2014-06-12T18:34:53.503

Reputation: 20 600

3Wouldn't this either always work or always not work? For example, if you ran it as ruby youranswer.rb, it wouldn't look for a shebang because it's being run in the ruby interpreter already, but if you ran it as ./youranswer.rb it wouldn't run at all because there's no shebang.. – Brendan Long – 2014-06-13T18:27:45.397

6At least with my ruby, the shebang is honored even if you run it as ruby youranswer.rb, which can be useful to set necessary command-line switches in the file. So without the newline I get ruby: no Ruby script found in input (LoadError) – histocrat – 2014-06-13T18:48:39.280

29

Scala

case class IntWrapper(i: Int)

{
  val answer = (IntWrapper(0) /: (1 to 100)){(x, y) => IntWrapper(x.i + y)} // Add up ints
  println(s"Sum of wrapped integers is $answer")
}

If you remove the blank line, no output will be printed. Which is for the best, as your stack would overflow if you actually called IntWrapper.

This is a corner case of Scala's semicolon inference. Normally newlines get a semicolon whenever the resulting code would be valid. However, the Scala devs didn't want to force people to use Egyptian brackets, so it's valid to put the brackets for a class definition on the line immediately after - no semicolon is added, even though one could be. However, a blank line divorces the brackets from the class definition. With the blank line removed, the code changes from being a class definition and a block, to a class definition with a constructor - and a recursive constructor at that!

James_pic

Posted 2014-06-12T18:34:53.503

Reputation: 3 988

6Very nice of them not to force Egyptian Brackets. But semicolon inferrence is a bad idea, in my opinion. – Almo – 2014-06-13T20:26:37.833

Semicolon inference gets a bad name, largely due to JavaScript. It's a bit less painful if you design the language with it in mind (no one complains about it in Python, for example). Unfortunately Scala included a couple of features that don't play nice with semicolon inference. There's this, and postfix operators (which I was tempted to use in my answer, but it's a bit passé). – James_pic – 2014-06-13T21:51:13.507

2@James_pic: AFAIK no one complains about it in Python because it doesn't exist in Python. In JS, semicolons are a necessary part of the syntax, and can be inserted (inferred) at certain points. In Python, semicolons are not a necessary part of the syntax, but can be used optionally. That's a big difference. – Mason Wheeler – 2014-06-16T21:42:43.860

It may seem like a big difference, but if Scala removed a few features, which currently make statement boundaries ambiguous, it would move from JavaScript's side of the fence to Python's. – James_pic – 2014-06-17T08:11:21.477

1@James_pic: What makes python different is that there newline terminates the statement unless escaped or inside any kind of bracket. That is there is no complete/incomplete rule. – Jan Hudec – 2014-06-17T08:21:43.600

@Jan Hydec I suppose that's true. I'd never really thought of it like that, as I always wrap multiline expressions in brackets, in both languages, but you're right. – James_pic – 2014-06-17T08:26:11.253

27

GolfScript

~{.@\%:

}do;

Calculates the GCD of two non-zero integers. Removing the blank line breaks the program.

Try it online.

How it works

This is a GolfScript implementation of the Euclidean algorithm:

      # STACK: "15 24"
~     # Interpret the input string.
{     # STACK: 15 24
  .@  # Duplicate the topmost integer and rotate the other on top of both copies.
      # STACK: 24 24 15
  \   # Swap the topmost integers.
      # STACK: 24 15 24
  %   # Calculate the modulus.
      # STACK: 24 15
}do   # If the modulus is non-zero, repeat the loop.
;     # Discard the last modulus.

There's just one tiny problem:

{}do pops the modulus from the stack to check if it's truthy, so it has to get duplicated at the end of the loop. This is normally accomplished by ., but :\n\n has the same effect: It stores the topmost stack item in the variable LF (:\n), then pushes the contents of that variable.

Dennis

Posted 2014-06-12T18:34:53.503

Reputation: 196 637

7Wow, even that's a variable? :O – aditsu quit because SE is EVIL – 2014-06-13T03:32:53.777

@aditsu: Only #, { and } cannot be used as variable names, as they're part of the syntax. Every other token is fine, including strings. – Dennis – 2014-06-13T03:53:28.187

@Dennis wow. TIL even strings can be used as variables. Is that useful for anything? – John Dvorak – 2014-06-13T05:24:24.857

@JanDvorak: Aside from some edges cases (palindromic code, underhanded code, probably not. I think this is just a (documented) side effect of how the GolfScript interpreter splits the code into tokens.

– Dennis – 2014-06-13T13:06:29.620

@Dennis does that mean that .:-1 stores the input into -1, not the minus sign itself? Hmm... – John Dvorak – 2014-06-13T13:58:03.343

@JanDvorak: It does. (Addendum to my first comment, : is also part of the syntax.) – Dennis – 2014-06-13T14:18:12.263

23

MediaWiki Template Syntax

Define Template:Foo as

{{{a

b|Uh-oh!}}}

In another page,

{{Foo|a

b=Works!}}  <!-- outputs "Works!" -->

{{Foo|a


b=Works!}}  <!-- outputs "Uh-oh!" -->

{{Foo|a
b=Works!}}  <!-- outputs "Uh-oh!" -->

In MediaWiki, parameter names can contain newlines.

Ypnypn

Posted 2014-06-12T18:34:53.503

Reputation: 10 485

1Nice, this is along the lines of what I was looking for, weird edge cases like this. – Naftuli Kay – 2014-06-12T19:26:29.767

16

LaTeX (backref)

The following LaTeX code uses a citation and the citation contains a list of pages, where the entry is citated. Here it is the first page. Package hyperref also adds PDF links, the page back reference is red, the citation link is green.

\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.

\end{thebibliography}
\end{document}

Result

But LaTeX does not require the empty line, the empty line looks superfluous and the example will still work without hyperref and the empty line:

\documentclass{article}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}

Result without hyperref

But the links and back reference are gone, thus we reinsert them:

\documentclass{article}
\usepackage[colorlinks,pagebackref]{hyperref}
\begin{document}
Donald E. Knuth is the inventor of \TeX~\cite{knuth}.
\begin{thebibliography}{9}
\bibitem{knuth}
Donald E. Knuth: \textit{The \TeX book}; Addison Wesley, 1984.
\end{thebibliography}
\end{document}

But now the example is broken and will not compile anymore:

Runaway argument?
 Donald E. Knuth: \textit {The \TeX book}; Addison Wesley, 1984. \end \ETC.
! File ended while scanning use of \BR@@bibitem.
<inserted text> 
                \par 
<*> knuth

?

What happened? Package hyperref (or more precise package backref, which is loaded by hyperref) wants to get at the end of the bibliography entry to add the back reference list. But the syntax in LaTeX only provides the beginning of the entry by \bibitem, the end can be anywhere. In this emergency package backref has added a restriction that \bibitem has to end the entry with an empty line. Then the package can redefine \bibitem to put the back references at the end of the entry.

Since the empty line is missing, TeX keeps looking for it, but found the end of file instead and issues the error message.

Heiko Oberdiek

Posted 2014-06-12T18:34:53.503

Reputation: 3 841

12

C (semi-obfuscated)

This little program takes a number on the command line and computes its factorial. However, it also contains cutting-edge AI functionality for runtime verification that the company's coding standards, including the correct use of whitespace and blank lines, are being followed. Removing a blank line will trigger the algorithm to reject the insufficiently maintainable program.

No line continuations or trigraphs anywhere. I believe it is valid ANSI C99.

Due to the advanced mathematics involved, if you compile with gcc, remember to use -lm.

#include <setjmp.h>
#include <stdio.h>
#define max(x,y) ((x<y?y:x))
#define swap(x,y) ((x^=y,y^=x,x^=y))
#include <stdlib.h>
#include <math.h>
#define vfry(x,p,z,y,i) (!!y&((z##z##L##I##p##x##z##z)))
#define NDEBUG

/* 
 * Proper use of whitespace is essential!
 * Please do not remove any blank lines.
 */

const double E = 2.71828182845904523536;

int vrfy(double epsilon, int magic, const char *key, long int L) {
  /* You are not expected to understand this */
  double x=284.2891,u=2.34e56;
  while (rand()+magic*pow(epsilon,sin(x-E))!=log(u*L))
    x*=vrfy(1.0/epsilon,(int)u,&key[swap(L,magic)],L++);
  return u/lgamma(x);
}

int main(int argc, char *argv[]) {
  int N_=831293812; /* do not change, see Knuth 1987 */
  if (!vfry(E, N,_, "M=&;VT=I!9", 0xfe86ddcaL)) {
    fprintf(stderr, "Code standards violation detected!\n");
    abort();
  }
  if (argc < 2) {
    fprintf(stderr, "Usage: %s n\nComputes n!\n", argv[0]);
    exit(1);
  }
  int m=1, n=atoi(argv[1]), i;
  for (i=1; i <= n; i++)
    m *= i;
  printf("%d! = %d\n", n, m);
  return 0;
}

Spoiler

The complicated vrfy function is never called, but rather the funny-looking vfry macro. The use of the preprocessor's string concatenation feature disguises the fact that we are really just checking the parity of __LINE__.

Nate Eldredge

Posted 2014-06-12T18:34:53.503

Reputation: 2 544

This is really neat. That vfry isn't expanded in the function definition really stumped me. – FUZxxl – 2015-03-18T20:41:49.947

Also works with tcc -run – Vi. – 2014-06-14T18:15:28.057

11

C

This program works as expected (as described in the comments) unless the blank line before foo = 5; is removed.

Sadly, I encountered an error almost exactly like this in production code once.

#include <stdio.h>

int main()
{
    int foo = 0;

    #define FROB(x) do {                                            \
        x++;                                                        \
        printf("%d\n", x);                                          \
    } while (0);                                                    \

    foo = 5;
    FROB(foo); /* prints 6 */
    FROB(foo); /* prints 7 */
    FROB(foo); /* prints 8 */

    return 0;
}

This example uses the do { ... } while (0) idiom for creating a multiline statement in a macro (see https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for). It also uses the backslash character to spread a #define over multiple lines, conveniently lined up well out of sight. However, it also does two things kind of wrong:

  • There is a semicolon after while (0), while the idiom usually omits this
  • There is a backslash after the final line of the #define

With this in place, removing the blank line before foo = 5; causes that assignment to be executed after the printf, but also after every invocation of the FROB macro. As a result, the output after removing the blank line is:

1
6
6

Greg Hewgill

Posted 2014-06-12T18:34:53.503

Reputation: 2 641

1

Basically a duplicate of http://codegolf.stackexchange.com/a/31662/20356

– seequ – 2014-06-12T21:43:36.897

@TheRare But it's less obvious. – Ypnypn – 2014-06-12T22:09:03.257

6It's only less obvious if you don't look at those backslashes floating very conspicuously over to the right. (But since they're floating there very conspicuously over to the right, they're going to get looked at.) – doppelgreener – 2014-06-13T07:17:03.590

3However, all but one of them are justified – QuadmasterXLII – 2014-06-14T18:10:07.180

6@QuadmasterXLII, technically speaking, they're all justified -- right-justified, to be precise. – Mark – 2014-06-17T09:05:44.230

9

C/C++

int main(){

    return __LINE__ - 3;
}

Returns success and can be used as an implementation for true. If the empty line is removed you can use it as an implementation for false instead.

nwp

Posted 2014-06-12T18:34:53.503

Reputation: 241

8

PowerShell

This function will add two numbers.

function add ($a, $b) {
    $numbers = @($a `

            $b)
        $numbers| measure -sum| select -expand sum
}

Removing the blank line will cause the function to fail with: Unexpected token '$b' in expression or statement.

Explanation

Array elements can be separated by newlines and/or commas. Placing the line continuation character (`) after $a requires an extra newline to separate $a and $b. Otherwise, the interpreter views the code as $numbers = @($a $b) (no element separator).

Rynant

Posted 2014-06-12T18:34:53.503

Reputation: 2 353

7

TeX

\noindent\everypar{$\bullet$ hello }

world
\bye

Without the empty line, "hello" is not printed.

Explanation

TeX treats the empty line as a paragraph break, and \everypar is executed at the start of a new paragraph.

Stephan Lehmke

Posted 2014-06-12T18:34:53.503

Reputation: 171

6

Java

import java.util.Scanner;

public class BlankLine
{
    public static void main( String[] args )
    {
        //This calculates 2^ given number
        //if you remove blank line after the next line it will always print 1
        int x = new Throwable().getStackTrace()[0].getLineNumber();

        int y = new Throwable().getStackTrace()[0].getLineNumber() - x;
        System.out.println("Number:");
        Scanner scanner = new Scanner(System.in);
        int r = 1;
        int n = scanner.nextInt();

        for(int i = 0; i < n; i++){
            r *= y;
        }
        System.out.println("2^number: "+r);
    }
}

x is current line number, y is current line number - x. If there is blank line between them the result is 2. So the code calculates 2 ^ number.

barteks2x

Posted 2014-06-12T18:34:53.503

Reputation: 281

1

+1 simply because it's Java, although as a frequent visitor of Code Review I wonder why you're not using Math.pow?

– Simon Forsberg – 2014-06-17T11:09:09.530

Because my code has to do something. Adding 2 numbers is a bit too simple. – barteks2x – 2014-06-17T18:28:57.890

Using Math.pow and print out the result is also doing something is it not? – Simon Forsberg – 2014-06-17T19:21:05.253

And now I realized I really could use .Math.pow I don't know why I thought I need to do it that way... Matbe I wanted to do it in mor "sneaky" way. – barteks2x – 2014-06-17T19:22:22.030

7

You've been golfing too much. You should visit Code Review instead where we do things right!

– Simon Forsberg – 2014-06-17T19:29:59.133

6

Perl 5

print(<<""
Hello, World!

);

This code prints Hello, World!. Removing the blank line gives a syntax error instead.

Explanation:

Perl's here-doc syntax for multi-line strings allows an empty terminator string. It's even explicitly documented. Removing the blank line causes the closing parenthesis (and everything else up to the next blank line, if there is one) to be interpreted as part of the string, causing a syntax error.

The error messages you get are actually pretty decent, for such an oddball syntax feature. If there are no blank lines at all in the program after the print(<<"" line, Perl simply says:

Can't find string terminator "" anywhere before EOF at foo.pl line 1.

If there is an empty line at the end of the program, you get something like this instead:

syntax error at foo.pl line 4, at EOF
  (Might be a runaway multi-line << string starting on line 1)
Execution of foo.pl aborted due to compilation errors.

Ilmari Karonen

Posted 2014-06-12T18:34:53.503

Reputation: 19 513

5

Batch

@echo off
setLocal enableDelayedExpansion
set NL=^


echo Hello!NL!World

This code will output Hello and on the next line World. When either or both of the blank lines are removed, it outputs nothing at all.

There is an explanation here.

unclemeat

Posted 2014-06-12T18:34:53.503

Reputation: 2 302

4

Ruby

Deletion of the first line will cause error:

line = IO.readlines($0).first.chomp if line.empty? puts 34+4 else raise "Please add a newline at the beginning of the program." end

Mhmd

Posted 2014-06-12T18:34:53.503

Reputation: 2 019

2I love the error message. Would like to see the reaction of someone that tries to run the program and gets that response. – tomsmeding – 2014-11-21T11:54:30.153

4

Python

Don't know if this falls under the standard loopholes, I looked at the list and didn't see this.

src = open(__file__, 'r')
code = src.readlines()
src.close()

if code[3] == '\n':
    print 'Hello World!'

Running this regularly returns

Hello World!

Running it without the blank line on line 4, ie like below:

src = open(
__file__, 'r')
code = src.readlines()
src.close()
if code[3] == '\n':
    print 'Hello World!'

returns nothing.

Zaxvo

Posted 2014-06-12T18:34:53.503

Reputation: 51

3

Python 2.x

This program outputs the fifth character of the inputted string.

import inspect

text = raw_input()
print 'Fifth character of the string:', text[inspect.getlineno(inspect.currentframe())]

This isn't in any way hidden. If you remove the empty line, it gives the fourth character and the sixth if you add one.

seequ

Posted 2014-06-12T18:34:53.503

Reputation: 1 714

3

Tcl

A function that adds two numbers (and checks if the newline have been deleted):

proc add {a b} {
    if {[llength [split [info body add] \n]] < 5} {error "function has been modified"}

    return [expr $a+$b]
}

There's nothing to hide here, it does what it says, so I'm not spoilerizing the explanation. The function info is a swiss army knife of introspection (what other languages call reflection). info body returns the source code of a function (if not written in C or assembly).

I have to admit that this had me stumped until I saw the javascript solution.

slebetman

Posted 2014-06-12T18:34:53.503

Reputation: 629

3

C

#include <stdio.h>


int main() {
    const char* a = "You love blank lines.";
    #define print_out(a) \

    printf("%s\n", a);
    a = "You don't seem to love blank lines";
    print_out(a);
    return 0;
}

With the blank line, a is the local variable a and without it's the macro parameter...

urzeit

Posted 2014-06-12T18:34:53.503

Reputation: 1 297

3

Technically not a "code" issue, but a server one. If this is sent to Apache from a CGI script (which can be generated with any language you please), it will send an HTTP response to the client:

HTTP/1.x 200 OK 
Content-Type: text/html; charset=UTF-8

Hello world!

On the other hand, this will fail as it is missing the blank space after the header.

HTTP/1.x 200 OK 
Content-Type: text/html; charset=UTF-8
Hello world!

cwallenpoole

Posted 2014-06-12T18:34:53.503

Reputation: 141

2

JavaScript

The function whereami responds with the position of the calling line, relative to its own position in the source code.

console.log (whereami ()) //3 line(s)  before me 


function whereami () {
    var a=function a(e){try{to}catch(c){for(var d=c.stack.split("\n"),b=0;b<d.length&&!~d[b].indexOf("a");b++);return c.stack.split("\n")[b+~~e].match(/:(\d+)/)[1]-~~window.hasOwnProperty("__commandLineAPI")}},a1=a(1),i


    i= a(2)>a(1)+4?a(1):a(1)>a1+2?a1-1:a/a1



    return ((i=(a(2)<i?i-1:a(1)>i+3?a(2)-a(1)-1:a/1)) + " line(s) "   ) + (i<a(2)?" after":(i>=a(2)?" before":"confusing")) + " me";
}


console.log (whereami ()) //3 line(s)  after me

If any blank line in the whereami function is removed. The output is NaN line(s) confusing me. (Adding lines doesn't break it)

It actually only counts how many lines are between i and the first and last line respectively. If they fall under a given value. The reference line is set to NaN which neither satisfies NaN<callingLine nor NaN>=callingLine. I tried to hide it a bit in unreadable ternary expressions.

C5H8NNaO4

Posted 2014-06-12T18:34:53.503

Reputation: 1 340

1Cool. I hadn't thought of using the exceptions stack like that. – nderscore – 2014-06-13T18:31:16.300

2

Perl

#!/usr/bin/perl

use strict;
use warnings;

open IN, "<".$0 or die "Did not find input files!";
while (<IN>) {
        m/blabla/ && ((<IN> =~ /\}/ && print "tra-la-la...\n") || print "ti-ri-li\n");

}
close IN;

This perl script will read the script file and check if after the line containing "blabla" there is a closing bracket.

urzeit

Posted 2014-06-12T18:34:53.503

Reputation: 1 297

2

Escript

Due to bug in escript implementation valid escript has to be at least three lines long and first line hast to be shebang line or empty line. So following script hast to have two empty lines where first one has to be first one:

main(_) -> io:format("Hello world!~n", []), halt().

Or it hast to be broken in two lines but still has to have first empty line.

main(_) ->
    io:format("Hello world!~n", []), halt().

Otherwise you will get

escript: Premature end of file reached

Hynek -Pichi- Vychodil

Posted 2014-06-12T18:34:53.503

Reputation: 350

2

Ruby

print %q
2+2=

p(2+2)

Prints 2+2=4, but gives a syntax error without the blank third line. %q allows any non-word character to serve as a string delimiter, even the newline character. So the first three lines of code are actually equivalent to print %q"2+2=", or just print "2+2=". Since the newline after 2+2= is being used as a quote delimiter, it's not also parsed as a line delimiter, so you need another one immediately after.

histocrat

Posted 2014-06-12T18:34:53.503

Reputation: 20 600

1

Insomnia (both versions)!

Þyoo

â

This code prints a ~ (don't ask why, insomnia is weird). If you remove the blank line, it prints a ÿ instead.

By the way that first letter is a thorn.

pppery

Posted 2014-06-12T18:34:53.503

Reputation: 3 987

1Hooray, thorns! Haven't seen that character in ages, +1. – Addison Crump – 2015-10-17T00:50:29.683

0

C++

This is a classic and rather dumb trick. You will know what it is when you see it, this is just here for completion's sake. As such, I'm marking this as a community wiki answer.

int main() {
    //This program won't work without the next line, why??/

    return 1;
}

Why this works

Aearnus

Posted 2014-06-12T18:34:53.503

Reputation: 251

13This is actually one of the loopholes. – Mhmd – 2014-06-13T02:41:15.513

@Mhmd I wasn't aware. Either way, I know people always use this in these kinds of question, and I just wanted to leave this here just so someone doesn't find it clever to do this. – Aearnus – 2014-06-13T23:51:21.070

1This answer is wrong for two reasons. The first is that ??/ means \​, so ??// means \/, and as the line doesn't end in \​, there is no line continuation. The second is that the behaviour is exactly the same regardless of whether return 0; is executed, because that is the standard behaviour when the execution of main reaches the closing }. – hvd – 2014-06-14T11:17:05.493

@hvd There. I fixed it. – Aearnus – 2014-06-14T11:23:28.727

3@cra I know people always use this in these kinds of question that's why we made it a standard loophole – undergroundmonorail – 2014-06-16T12:45:07.947

@undergroundmonorail I wasn't aware of that, like I said. I made it a community wiki answer for a reason. – Aearnus – 2014-06-17T06:53:41.790

0

Paste this into a html file, and open it in your browser. It's pretty simple, but a little tricky because it takes the number of blank lines in the document and indexes an array to call a function which shows an alert.

<body>
<script>
[null, function(){alert("GIVE ME MY LINE BACK")}, function(){alert("2 + 2 = " + (2+2))}][document.body.innerHTML.split("\n\n").length]()

</script>
</body>

This one is borderline rule breaking. Technically JavaScript doesn't have multiline strings, which is the only reason this works.

Because you can have a syntax error in one script tag without interfering with the other script tags this shows a positive result only if there's an error on the page. The error prevents the second alert from firing because it's in the same script tag.

<body>
<script>
window.onerror=function(){
  alert("2 + 2 = " + (2+2));
}
</script>
<script>
var a = "\

";
alert("GIVE ME MY LINE BACK!");
</script>
</body>

Brigand

Posted 2014-06-12T18:34:53.503

Reputation: 1 137

0

Ruby

puts (% #{ARGV[0].to_i + ARGV[1].to_i}

)

The secret is that the newline, is really a tab, then a new line. I don't know if this counts but I thought it was cleaver. The character after the % is also a tab, but for some reason it doesn't show up like one. I'm using Ruby's percent notation to make a string, that adds the first 2 arguments passed to the script. There's more on that here: http://teohm.com/blog/2012/10/15/start-using-ruby-percent-notation/

addison

Posted 2014-06-12T18:34:53.503

Reputation: 993

It actually doesn't count, read the instructions: "No whitespace foolery." Exactly one \n should be present and should be crucial to having the program work as expected. – Naftuli Kay – 2014-08-12T23:08:02.773

Ah ok :( well I tried – addison – 2014-08-12T23:32:30.647

1I think you can fix this, though: a newline can itself be a percent delimiter. – histocrat – 2014-11-21T17:16:46.787

0

AppleScript

say¬

quit

This code is absolutely meant to throw an error, as it matches (in compiler speak) to this:

¬
   say
quit

Which throws the error "Can’t make current application into type text."

However, if you delete the second line, you get the equivalent of this code:

say ¬
   (quit)

Which says nothing and attempts to close the current application (Script Editor or Terminal).

Addison Crump

Posted 2014-06-12T18:34:53.503

Reputation: 10 763

0

><>

This program

02.

v"?"o
;"!"o

outputs

?

and exits.

Removing the blank line cause it to output

!

Fongoid

Posted 2014-06-12T18:34:53.503

Reputation: 971