Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

share|improve this question
    
What do you mean by "the first line number"? Are you talking about what should happen if the statement spans multiple lines? –  user2357112 Jun 4 at 1:34
    
@user2357112 yes, just to resolve any ambiguity if anyone needed to use a milti-line statement. –  Breakthrough Jun 4 at 1:58
    
The title is very explicit, but perhaps a bit long. –  primo Jun 4 at 5:11
1  
The answers to this are all boring because it is such a bad question. It is like the asker didn't know of the existence of LINE. In fact I signed up specifically to down vote this I thought it was so bad. –  dave Jun 4 at 14:26
1  
@Markasoftware if a line was added before it, the output wouldn't change to reflect that. –  primo Jun 6 at 1:00

43 Answers 43

up vote 44 down vote accepted

Sinclair Basic

10 PRINT "Hello world, from line ";PEEK 23621;"!"

Hello world, from line 10!

This will work for any line by PEEKing 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!

share|improve this answer
    
And by the same token, Timex/Sinclair BASIC! –  Gabe Jun 3 at 23:50
    
I don't pretend to know this language, but can't you leave out the STR$ if you replace the + signs by semicolons? –  Mr Lister Jun 5 at 18:57
    
@MrLister Yes, that would definitely work but I always use +s from habit. –  kitcar2000 Jun 5 at 20:06

BASIC

I think this does everything that was asked for:

10 PRINT "Hello World, from line 10!"
share|improve this answer
5  
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). The intent is there. Also, that is the first line of the source, not the 10th. –  Bill Woodger Jun 3 at 14:58
28  
It may be the first line in the source code, but it's still line 10. –  squeamish ossifrage Jun 3 at 15:01
13  
I believe this falls firmly under the no longer funny category. It's really unimaginative and uninteresting, although literally it meets the requirement. Why does this have so many upvotes? (I've downvoted) –  Tim S. Jun 3 at 16:28
18  
This is a great answer because it takes a silly but specific advantage of an aspect of the BASIC language which is not commonly found in other languages (especially modern ones). It may not be the most popular (time will tell), but I can hardly see how it's less interesting than using a constant such as __LINE__ or getting debug info from the current stack frame (as most other answers currently do). –  Nick Jun 3 at 21:36
2  
Clever, but I'd be disappointed if nothing else ended up with more upvotes than this one. –  agweber Jun 4 at 16:34

Java

public class Hello{
    public static void main(String[] args) {
        System.out.println("Hello World, from line "+new Exception().getStackTrace()[0].getLineNumber()+"!");
    }
}
share|improve this answer
1  
I'd prefer Thread.currentThread().getStackTrace() –  Cruncher Jun 3 at 15:01
3  
Thread.getStackTrace() calls (new Exception()).getStackTrace() if called on the current thread, so it's the same thing –  DHall Jun 3 at 19:29
    
weird.... 2x same answer and 2 different upvote amounts... (could be used as RNG source...) (same here: codegolf.stackexchange.com/a/30058/10801) –  masterX244 Jun 3 at 19:55
    
@masterX244 those two answers aren't exactly identical; this one uses the getLineNumber() method on the stack trace, while the answer you linked to uses toString() on it to find the line number. –  Breakthrough Jun 3 at 21:21
9  
@masterX244 it's also worth noting that this answer appeared 2 hours earlier. The second time I see an answer, it isn't as interesting as the first. –  primo Jun 4 at 5:00

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.

share|improve this answer
2  
Yes, it definitely is more interesting :) –  Tal Jun 3 at 6:07

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

share|improve this answer
1  
This is ... wizardry –  Paladine Jun 5 at 22:33
    
It took me a ... long while to see how this worked. Soo many red herrings! It's delicious. –  sehe Jun 6 at 9:02

Lua

print("Hello world, from line "..debug.getinfo(1).currentline.."!")
share|improve this answer

C

#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}
share|improve this answer
2  
+1 Way too easy ;) –  awashburn Jun 5 at 16:03
    
Using defined variables like LINE, although allowed by the rules, are discouraged. –  vaxquis Jun 8 at 14:05
    
@vaxquis, yes but my answer predates that edit to the question –  gnibbler Jun 9 at 0:16
    
it's still a lousy and too obvious solution IMO. I'm wondering why people posted all kinds of variations of this solution in all languages of the world (including PHP, D, Perl) instead of even trying to do something remotely funny or intriguing? –  vaxquis Jun 9 at 1:11

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!
share|improve this answer
    
Any particular reason to use roman numerals? –  Cole Johnson Jun 3 at 23:36
4  
When the printing line is line 10, the question is interpreted literally. X in roman numerals is 10. –  Ourous Jun 3 at 23:59
    
Roman numerals is a nice touch! –  NPSF3000 Jun 5 at 15:05

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. 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) 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!
share|improve this 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

share|improve this answer
2  
dat stack, hehe. Verified working on Firefox. –  Breakthrough Jun 3 at 13:55
1  
@Breakthrough :) Yes it works cross-browser (only tested with the latest Chrome,FF,IE though). Chrome needs special treatment when evaluated from within the console, as it wraps every statement in a with clause. –  C5H8NNaO4 Jun 3 at 14:05
2  
Interesting but ambiguous username. Monosodium glutamate, perhaps? (BTW, I'm thinking of doing a question on DNA and amino acids, of which glutamic acid is one.) –  steveverrill Jun 3 at 16:02
    
@steveverrill According to google, you are correct! –  kitcar2000 Jun 5 at 20:41
    
@kitcar2000 Probably. But there are other lesser-known compounds with this formula: Sodium methylaspartate or nitropentanoate, for example. –  steveverrill Jun 5 at 21:02

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 cc46f7.... When it hashes the print line, it finds that the hash matches the magic value it's searching for.

share|improve this answer
    
couldn't you just set line_num = to -1 and have the print outside the loop and get ride of the magic hash? –  dave Jun 4 at 14:28
1  
@dave not sure I follow you. The magic hash is what makes this solution clever. –  Tim S. Jun 4 at 17:15
    
+1 for literal interpretation of my rules :) Very clever. –  Breakthrough Jun 4 at 19:01
5  
@Stefan This site is all about worst practices, though. ;) –  Tim S. Jun 5 at 20:09
1  
@sehe Most likely, this was due to whitespace issues. I didn't have a newline at the end of the file when I made it. I've added a line to strip whitespace from the end of the line before hashing. It should work more consistently now. (also make sure you're not converting the spaces to tabs) I tried uploading it to ideone to show you a live version, but it can't read its own file there. –  Tim S. Jun 6 at 11:49

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 DISPLAYs which cause the start of the output, and anything after the DISPLAYs 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 PERFORMed, 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.

share|improve this answer

Python

import traceback, inspect
frame = inspect.currentframe()
print("Hello World, from line "+traceback.format_stack(frame)[0].split()[3][:-1]+"!")  
share|improve this 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]+"!");
    }
}
share|improve this answer

Java

public class HelloFrom {
    public static void main(String[] args) {
        System.out.println("Hello World, from line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + "!");
    }
}
share|improve this answer
    
technically the same as i did (codegolf.stackexchange.com/a/30058/10801) –  masterX244 Jun 3 at 19:50
2  
Sort of, except using the current Thread instead of creating a new Error to get the stack trace. There isn't any error ;) –  Cineris Jun 4 at 5:10

Python

import inspect
print ("Hello world from line %d!" % (inspect.getlineno(inspect.currentframe())))

Output

Hello World from line 2!
share|improve this answer
1  
Best Python one so far! –  kirbyfan64sos Jun 4 at 14:32
    
Thank you for saying so! –  Ricardo A Jun 4 at 20:15

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

share|improve this answer
    
No idea what this was, but I believe your output claim, so +1 ;-) –  ysap Jun 7 at 3:25
    
For those who question the power of mighty Befunge, try it out here: quirkster.com/iano/js/befunge.html –  Quincunx Jun 10 at 2:27

Bash

#
# some comments to fill some lines...
#
echo "Hello World, from line $LINENO!"

Output

Hello World, from line 4!
share|improve this answer
    
@professorfish ... what's wrong with MY style to show MY answer? You should at least explain why you manipulate my artwork... :-P –  yeti Jun 3 at 14:22
2  
did I change the code? if I did, I'm sorry. I was just worried that non-bash users wouldn't be able to tell what was the source code and what was the output –  professorfish Jun 3 at 16:11
1  
And evryone else besides me loves seeing his stuff being changed without commenting why? Strange place... –  yeti Jun 3 at 16:44
3  
It was basically a formatting fix. There's nothing really wrong with those AFAIK –  professorfish Jun 3 at 16:46
    
Using defined variables like LINE, although allowed by the rules, are discouraged. –  vaxquis Jun 8 at 14:06

D

void main ()
{
    import std.stdio;
    writefln("Hello World, from line %d", __LINE__);
}
share|improve this answer
    
Using defined variables like LINE, although allowed by the rules, are discouraged. –  vaxquis Jun 8 at 14:06

Perl

print 'Hello World, from line '.__LINE__.'!';
share|improve this answer
13  
This is also a valid PHP solution. –  MrLore Jun 3 at 15:03

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.
share|improve this 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.

share|improve this answer
    
This only works if you use a constant format string. It fails if you pass in any other expression for the format string. –  Snowbody Jun 5 at 13:01

Kind of boring in Ruby:

puts "Hello World, from line #{__LINE__}!"

This isn't cheating, right?

share|improve this answer
    
Nope, this isn't cheating! This challenge will obviously be a lot easier in some languages and more difficult in others, however, which was why I posted it :) (I see now why the inclusion of a scoring criteria is so important) –  Breakthrough Jun 3 at 17:43
    
Using defined variables like LINE, although allowed by the rules, are discouraged. –  vaxquis Jun 8 at 14:07
1  
@vaxquis Yeah, that statement was added after this answer. –  Ajedi32 Jun 8 at 14:29

Javascript

One line using stack trace.

(function (o) { console.log("Hello World, from line " + (Error.captureStackTrace(o) || o.stack.match(/\d+/)[0] - !!__commandLineAPI) + "!"); })({});
share|improve this answer

Cobra

class Program
    def main
        print 'Hello World, from line [System.Diagnostics.StackFrame(true).getFileLineNumber]!'
share|improve this 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"
share|improve this 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
share|improve this 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!
share|improve this answer
    
+1, but Write-Host doesn't write to stdout. Simply passing the string will send it to stdout. E.g. "Hello World, from line {0}!" -f (gcs| %{$_.ScriptLineNumber})[0] –  Rynant Jun 4 at 13:49
    
@Rynant Good point! I'll update my answers to consider that... –  darkajax Jun 4 at 14:01

Python

import traceback

print 'Hello World, from line %i!' % traceback.extract_stack()[0][1]

Short and sweet.

share|improve this 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";
share|improve this answer

protected by Timtech Jun 8 at 20:39

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.