[Question]
  [
## The Challenge
Write a program that outputs `Hello World, from line X!`, where `X` is the line number, in the source code, of the actual print statement itself.
## The Rules
* In this context, we want **the *first* line number of the statement which outputs the string** to be displayed to `stdout`
* You should **avoid simply searching through your source code as a string** (either file or quine) to find the line number
* If any **additional whitespace or statements** (which do not interrupt the flow of the code) is added to the source code, it should be **reflected at run-time** (after compiling if applicable)
## Recommendations
If provided by the language, you **may** use exceptions/stack traces to accomplish this goal. Try your best to use code that is **portable** across different systems/implementations, but note that this is **not** a requirement. Using defined variables like `__LINE__`, although allowed by the rules, are discouraged.
## The Winner
* This is a **popularity contest** (ended on June 10, 2014), where the **answer voted highest by the community** will be declared the winner based on the current votes at the time
* When voting, please consider the creativity of someone's answer, how elaborate or **interesting** it is. and the difficulties/constraints of the programming language being used
  
[Answer]
# Sinclair Basic
```
10 PRINT "Hello world, from line ";PEEK 23621;"!"
```
> 
> Hello world, from line 10!
> 
> 
> 
This will work for any line by `PEEK`ing at the address storing the current line number, so the following will work as well:
```
341 PRINT "Hello world, from line ";PEEK 23621;"!"
```
> 
> Hello world, from line 341!
> 
> 
> 
[Answer]
# BASIC
I think this does everything that was asked for:
```
10 PRINT "Hello World, from line 10!"
```
[Answer]
# Java
```
public class Hello{
    public static void main(String[] args) {
        System.out.println("Hello World, from line "+new Exception().getStackTrace()[0].getLineNumber()+"!");
    }
}
```
[Answer]
## Perl
```
close STDERR;
open FOOBAR,">",\$_;
print!warn,'Hello World, from line ',/(\d+)\.$/,'!';
```
Not quite as short as using `__LINE__`, but perhaps more interesting.
> 
>  `warn` is a debugging tool, which issues a statement to `STDERR`, indicating in which file, and on which line the warning was issued... *unless* `STDERR` has been previously closed or is otherwise inaccessible, in which case the warning is issued to the most recently opened file handle - this is undocumented behavior. I'm not sure if it would be better classified as a feature or a bug.  
> 
>   
> 
>  Here, `STDERR` is closed, and a new file handle identified as `FOOBAR` is opened, and routed to the variable `$_`. This is then parsed to retrieve the line number of the warning, which is embedded in the print statement.
> 
> 
> 
[Answer]
## C++
```
#include <iostream>
#include <utility>
#include <type_traits>
#define __(A,B,C,...) B##C##A
#define _(A,...) __(__VA_ARGS__, A)
template<unsigned...Is> struct v;
template<unsigned I0, unsigned... Is> struct v<I0, Is...>:v<I0-1,I0-1, Is...> {};
template<unsigned...Is> struct v<0,Is...>:std::integral_constant<unsigned, sizeof...(Is)> {};
int main() {
  std::cout << "Hello world from line " << v<_(EXTRACT,_(Q,_,E,_,$$main$$,),_(@22,,_,_),_(Z,N,L,I,_,,L),__STACK_TRACE__)>::value << "\n";
}
```
[live example](http://ideone.com/8uQ6Cv)
[Answer]
# Lua
```
print("Hello world, from line "..debug.getinfo(1).currentline.."!")
```
[Answer]
# C
```
#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}
```
[Answer]
## C#
C# 5.0's `[CallerLineNumber]` does the trick:
```
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace LineNumberConsole
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Hello World, from line {0}!", ToRoman(GetLineNumber()));
            Console.ReadLine();
        }
        private static int GetLineNumber([CallerLineNumber] int sourceLineNumber = 0)
        {
            return sourceLineNumber;
        }
        private static string ToRoman(int number)
        {
            // TODO: Copy some source code from http://pastebin.com/w0hm9n5W
            // Skipped here for brevity
            return number.ToString();
        }
    }
}
```
## Output
```
Hello World, from line X!
```
[Answer]
## Python
Example (10 lines, 213 characters):
```
import sys
import traceback
lineno = None
while True:
    try:
        print 'Hello World, from line %d!' % lineno
        break
    except:
        lineno = traceback.tb_lineno(sys.exc_info()[2])
        continue
```
[Try online here](http://ideone.com/iX6b2g). Non-flow altering code and whitespace can be added and the program will display the updated line count, and likewise, this code snippet can also be used anywhere in an existing program. Expected output:
```
Hello World, from line 6!
```
---
[Another example (try online here)](http://ideone.com/PzzxVn) to show that it works when code/whitespace is added. Expected output:
```
Down we go...
Gotta catch 'em all.
Down we go...
Hello World, from line 11!
Awesome!
```
[Answer]
**Javascript**
```
function getLine(n) {
   try {
      to
   } catch (dat) {
      var stack = dat.stack.split('\n');
       for (var i = 0; i < stack.length; i++) {
           if (~stack[i].indexOf ('getLine')) break;          
       }
      return dat.stack.split ('\n')[i + ~~n].match (/:(\d+)/)[1] - ~~window.hasOwnProperty ('__commandLineAPI')
   }
}
//Line 12
console.log ('Hello World, from line ' + getLine(1) + ' !')
```
*Note: Expressions, evaluated from within the chrome dev console will be wrapped in a `with` statement. Thus we need to decrement the line by one if that's the case*
[Answer]
## Python 3
```
import hashlib
with open(__file__) as f:
    line_num = 0
    for line in f.readlines():
        line = line.rstrip() # make it work with or without newline at the end
        line_num += 1
        if hashlib.sha256(bytes(line, "UTF-8")).hexdigest()[0:6] == 'cc46f7':
            print('Hello world, from line {}!'.format(line_num)) # cc46f7
```
> 
> Hello world, from line 8!
> 
> 
> 
This self-reading code contains a self-referencing hash. The SHA256 sum of the last line (with the beginning whitespace and without trailing whitespace) [begins with](http://www.convertstring.com/Hash/SHA256) `cc46f7...`. When it hashes the `print` line, it finds that the hash matches the magic value it's searching for.
[Answer]
GNU COBOL
Well, they said it couldn't be done. Actually, it was I who said it couldn't be done. Now it's done, and an obsolete language feature re-implemented using the method applied.
The question states:
> 
> If any additional whitespace or statements (which do not interrupt the
>  flow of the code) is added to the source code, it should be reflected
>  at run-time (after compiling if applicable).
> 
> 
> 
Any amount of stuff can be inserted prior to the three `DISPLAY`s which cause the start of the output, and anything *after* the `DISPLAY`s would "interrupt the flow of the code", so that's OK.
COBOL used to have a `TRACE` verb (statement) which simply listed source line-numbers as they were executed (no access to the line number in the program). Although of limited use, I've included an implementation of TRACE.
```
   ID Division.
   Program-ID. HIWHERE.
   ENVIRONMENT DIVISION.
   configuration section.
          source-computer. TinkerToy with debugging mode.
   Procedure Division.
   Declaratives.
   Debug-Declaratives Section.
       Use For Debugging on a b
       .
   Debug-Declaratives-Paragraph.
       Display Debug-Line "!"
       .
   End Declaratives
       .
   Main-Program Section.
       DISPLAY "Perform"
       Display "Hello World, from line " no advancing Perform b
       display "GO TO"
       Display "Hello World, from line " no advancing GO TO a
       .
   a.
       dISPLay "Fall through"
       Display "Hello World, from line " no advancing. b.
   The-Last-bit-OF-the-PROGRAM.
       GOBACK
       .
```
The output is
```
Perform
Hello World, from line     18!
GO TO
Hello World, from line     20!
Fall through
Hello World, from line     23!
```
As an exhibition of the power and flexibility of writing the language, this example uses mixed-case, entirely lowercase, and entirely uppercase, all at the same time. It does not matter, as when processed, everything is "folded" to UPPERCASE.
The only standard COBOL way to get at a source line-number in the running program, from the running program, is with a `DEBUGGING` `DECLARATIVE`. Within a `SECTION`, strictly within a paragraph within a `SECTION`, of a such a declarative you have access to the special-register `DEBUG-LINE`. This contains the source line-number of the verb (statement) which caused transfer of control to a particular procedure-name (paragraph or `SECTION`). 
So, with `PERFORM`, or `GO TO`, or "fall through" the paragraph in the debugging declaratives `SECTION` is executed.
OK, but `DISPLAY` does not cause transfer of control. 
No problem. Put it on the *same line* as the transfer of control. 
Problem, since if "any additional whitespace or statements (which do not interrupt the flow of the code) is added to the source code, it should be reflected at run-time (after compiling if applicable)". 
So, put it on the same line *but in front of* a transfer of control, split the content of the `DISPLAY` into two pieces (remember, "In this context, we want the first line number of the statement which outputs the string to be displayed") and output the first part prior to the transfer of control, and the second part, from the `DEBUG-LINE`, once inside the debugging procedure.
The final tricky bit is for the "fall through" ("procedures" can be `PERFORM`ed, can be the target of a `GO TO`, or can be entered simply by being the next line along). In this instance, put the `DISPLAY` *on the line which defines the procedure, but in front of the definition*.
The names of the "procedures" (`a` and `b`) have been severely shortened to allow them to fit on the same source-line as the `DISPLAY`. Strictly a COBOL procedure-name should start somewhere from column eight to column 11. However, the syntax is, these days, much more relaxed about that. To the extent that I can define a procedure name on the same line as some code. Even embedded in code. Care, and an occasional full-stop, is required.
In the `PROCEDURE DIVISION` each full-stop shown is required, and no more are.
To compile:
```
cobc -x -g hiwhere.cbl
```
To execute (linux):
```
COB_SET_DEBUG=Y ./hiwhere
```
Finally, the return of TRACE (without READY/RESET).
```
   ID Division.
   Program-ID. tRacE.
   ENVIRONMENT DIVISION.
   configuration section.
          source-computer. TinkerToy with debugging mode.
   Procedure Division.
   Declaratives.
   Debug-Declaratives Section.
       Use For Debugging on a
       .
   Debug-Declaratives-Paragraph.
       Display Debug-Line
       .
   End Declaratives
       .
   Main-Program Section.
  *    Just append "perform a" to a single-line statement.
       DISPLAY "1" . perform a
       Display "2" . perform a
       display "3" . perform a
  *    Or prepend "perform a." for a multi-line statement, or a
  *    statement which won't "come back". 
       perform a. GOBACK
       .
   a.
       CONTINUE
       .
```
Output is:
```
1
    17
2
    18
3
    19
    20
```
Where 1, 2 and 3 are output from the three DISPLAY statements, and 17, 18, 19 and 20 are the line numbers of the "executable" (non-debugging) lines.
[Answer]
# Java
Using the behavior of Exception's stack trace to get current line. as long as Printstatement isn't mangled into multiple lines or classfile gets mangled it should work
```
public class PrittLnbr
{
    public static void main(String[] args)
    {
        System.out.println("Hello World, from line "+new Error().getStackTrace()[0].toString().split(":")[1]+"!");
    }
}
```
[Answer]
**Python**
```
import traceback, inspect
frame = inspect.currentframe()
print("Hello World, from line "+traceback.format_stack(frame)[0].split()[3][:-1]+"!")  
```
[Answer]
**Befunge**
Done just for fun.
```
>00g1+:00p"v"\10v  
    v-*45g00p\g <  
#v+1_$10g1vv,,,,<  
^<p000p01+<#>,,,^  
>" enil morf ,oll"v
@.,,,,,,,,,<^,"He"<
```
Conditional: top left of the code has to be 0 < x < 20 and 0 <= y < 62; and the two first cells have to be empty.
example:
```
                         v                  
                         0                  
                         0                  
                         0                  
                         p                  
                         0                  
                         1                  
                         0                  
                         p                  
                         >00g1+:00p"v"\10v  
                             v-*45g00p\g <  
                         #v+1_$10g1vv,,,,<  
                         ^<p000p01+<#>,,,^  
                         >" enil morf ,oll"v
                         @.,,,,,,,,,<^,"He"<
```
Would output:
Hello, from line 10
[Answer]
# Perl
```
print 'Hello World, from line '.__LINE__.'!';
```
[Answer]
**Java**
```
public class HelloFrom {
    public static void main(String[] args) {
        System.out.println("Hello World, from line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + "!");
    }
}
```
[Answer]
**Python**
```
import inspect
print ("Hello world from line %d!" % (inspect.getlineno(inspect.currentframe())))
```
**Output**
```
Hello World from line 2!
```
[Answer]
# C
By using a variadic macro, we can make a print function which automatically adds the line number to the end of an arbitrary printf statement, and always prints to stdout.
test.c:
```
#include <stdio.h>
#define printfl(format, ...) fprintf(stdout, format " From line %d\n", ##__VA_ARGS__, __LINE__)
int main() {
    printfl("Hello World! I have %d argument(s).", 1);
    return 0;
}
```
outputs:
```
% ./test
Hello World! I have 1 argument(s). From line 6
```
Note: I deviated from the pattern to demonstrate that printfl is still a valid variadic function; if you *really* care about the format of the output, you can always change the literals I use.
[Answer]
# Bash
```
#
# some comments to fill some lines...
#
echo "Hello World, from line $LINENO!"
```
## Output
```
Hello World, from line 4!
```
[Answer]
## D
```
void main ()
{
    import std.stdio;
    writefln("Hello World, from line %d", __LINE__);
}
```
[Answer]
# C or C++, and AWK
lineno.c:
```
// code or comments
// ....
#error Hello World, from line
// other code or comments
```
Usage:
```
gcc lineno.c 2>&1 | awk '{ split($0,a,":"); ; printf("%s %s!\n", gensub(".*#error ","",1), a[2]); exit; }'
```
Output:
Hello, World, from line 3
Notes:
* No user written code searches the file.
* g++ will work on a c++ file.
[Answer]
Kind of boring in Ruby:
```
puts "Hello World, from line #{__LINE__}!"
```
This isn't cheating, right?
[Answer]
## Javascript
One line using stack trace.
```
(function (o) { console.log("Hello World, from line " + (Error.captureStackTrace(o) || o.stack.match(/\d+/)[0] - !!__commandLineAPI) + "!"); })({});
```
[Answer]
# Cobra
```
class Program
    def main
        print 'Hello World, from line [System.Diagnostics.StackFrame(true).getFileLineNumber]!'
```
[Answer]
# Ruby
```
File.write "hello.rb", "x=2\n"+"x+=1\n"*rand(rand(100))+'puts "Hello World, from line #{x}!"'
system "ruby hello.rb"
File.delete "hello.rb"
```
[Answer]
# PowerShell
## Cheap Move
```
Function LemmeGetDatError() {
    "Too busy chuggin along"
    "Then all of a sudden, I meet a new programmer"
    "And he's all like"
    Write-Output "$(Try {"Hello World from"; Throw "error" } Catch {$_.ScriptStackTrace.Split(":")[1]})"
}
LemmeGetDatError
```
[Answer]
# Powershell
```
$l=(Get-PSCallStack | ForEach{$_.Location})[0].split(' ')[-1]; "Hello World, from line $l!"
```
And:
```
try{ I AM ERROR. } catch { $l=$error[0].InvocationInfo.ScriptLineNumber; "Hello World, from line $l!" }
```
Both work like this:
```
PS C:\MyFolder> .\helloworld.ps1
Hello World, from line 1!
```
[Answer]
**Python**
```
import traceback
print 'Hello World, from line %i!' % traceback.extract_stack()[0][1]
```
Short and sweet.
[Answer]
# Perl
Another Perl one:
```
use warnings;
$SIG{__WARN__} = sub { ($line = shift) =~ s/\D//g; };
$x=$x+1; print "Hello World, form line $line!\n";
```
]