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, which will end in seven days (on June 10), where the highest voted answer will be declared the winner

  • 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 2 days ago
    
@user2357112 yes, just to resolve any ambiguity if anyone needed to use a milti-line statement. –  Breakthrough 2 days ago
    
The title is very explicit, but perhaps a bit long. –  primo 2 days ago
    
@primo updated, what do you think of the new title? –  Breakthrough 2 days ago
1  
@Markasoftware if a line was added before it, the output wouldn't change to reflect that. –  primo 10 hours ago
show 5 more comments

40 Answers

BASIC

I think this does everything that was asked for:

10 PRINT "Hello World, from line 10!"
share|improve this answer
3  
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 2 days ago
19  
It may be the first line in the source code, but it's still line 10. –  squeamish ossifrage 2 days ago
8  
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. 2 days ago
12  
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 2 days ago
1  
Clever, but I'd be disappointed if nothing else ended up with more upvotes than this one. –  agweber yesterday
show 4 more comments

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 2 days ago
    
Thread.getStackTrace() calls (new Exception()).getStackTrace() if called on the current thread, so it's the same thing –  DHall 2 days ago
    
weird.... 2x same answer and 2 different upvote amounts... (could be used as RNG source...) (same here: codegolf.stackexchange.com/a/30058/10801) –  masterX244 2 days ago
    
@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 2 days ago
4  
@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 2 days ago
show 1 more comment

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 2 days ago
    
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 16 hours ago
    
@MrLister Yes, that would definitely work but I always use +s from habit. –  kitcar2000 15 hours ago
add comment

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
add comment

C

#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}
share|improve this answer
2  
+1 Way too easy ;) –  awashburn 19 hours ago
add comment

Lua

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

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
add comment

Python 3

import hashlib
with open(__file__) as f:
    line_num = 0
    for line in f.readlines():
        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 7!

This self-reading code contains a self-referencing hash. The SHA256 sum of the last line 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 yesterday
1  
@dave not sure I follow you. The magic hash is what makes this solution clever. –  Tim S. yesterday
    
+1 for literal interpretation of my rules :) Very clever. –  Breakthrough yesterday
    
A working solution. But it is not even close to something someone might use in practice e.g. within a logging framework to determine the caller's line number. –  Stefan 15 hours ago
2  
@Stefan This site is all about worst practices, though. ;) –  Tim S. 15 hours ago
show 1 more comment

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 2 days ago
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 2 days ago
1  
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 2 days ago
    
@steveverrill According to google, you are correct! –  kitcar2000 14 hours ago
    
@kitcar2000 Probably. But there are other lesser-known compounds with this formula: Sodium methylaspartate or nitropentanoate, for example. –  steveverrill 14 hours ago
add comment

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
    
This is ... wizardry –  Paladine 12 hours ago
    
It took me a ... long while to see how this worked. Soo many red herrings! It's delicious. –  sehe 2 hours ago
add comment

Python

import traceback, inspect
frame = inspect.currentframe()
print("Hello World, from line "+traceback.format_stack(frame)[0].split()[3][:-1]+"!")  
share|improve this answer
add comment

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 2 days ago
1  
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 2 days ago
1  
And evryone else besides me loves seeing his stuff being changed without commenting why? Strange place... –  yeti 2 days ago
2  
It was basically a formatting fix. There's nothing really wrong with those AFAIK –  professorfish 2 days ago
add comment

D

void main ()
{
    import std.stdio;
    writefln("Hello World, from line %d", __LINE__);
}
share|improve this answer
add comment

Perl

print 'Hello World, from line '.__LINE__.'!';
share|improve this answer
10  
This is also a valid PHP solution. –  MrLore 2 days ago
add comment

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 2 days ago
1  
Sort of, except using the current Thread instead of creating a new Error to get the stack trace. There isn't any error ;) –  Cineris 2 days ago
add comment

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 2 days ago
1  
When the printing line is line 10, the question is interpreted literally. X in roman numerals is 10. –  Ourous 2 days ago
    
Roman numerals is a nice touch! –  NPSF3000 20 hours ago
add comment

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 22 hours ago
add comment

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
add comment

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 2 days ago
add comment

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 yesterday
    
Thank you for saying so! –  Ricardo A yesterday
add comment

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
add comment

Inspired by @squeamish ossifrage's answer with BASIC.

What's in a line number?

In, for instance, IBM COBOL there are (can be) arguably three source line numbers.

The first (if used, it is optional), in columns 1-6 of the punched-card, are sequence numbers for the card deck. If the deck is dropped, the otherwise-hapless programmer has some chance to get things back in order. OK, starts to go slightly floppy as soon as the program has lines added, but that's what different coloured cards are (can be) for.

The second is on the compiler listing, generated by the compiler. The compiler diagnostic messages use this line number, else no-one would have much of a clue (unless the diagnostics are embedded, which they can be) which line any particular diagnostic referred to*. These numbers for various reason (copybook code, let alone anything else) will be different from the first.

The third line number is of course the line number of the actual source file (optional, columns 73-80 if present). Other than actually reading the source file, or hard-coding a reference to a particular source line-number, it would not be possible to get this number in a program***.

So:

999999     DISPLAY "Hello, world, from line 999999!"

This can appear anywhere in the PROCEDURE DIVISION of the program, since those line numbers have no affect on the program, and are only even flagged as out of sequence (not ascending, can be gaps) if requested by compiler option.

** With compiler options SEQUENCE and NUMBER, the column 1-6 numbers will be used (modified by the compiler if necessary) for the diagnostic messages, and other data requiring source line numbers.

* OK, possible in limited circumstances. No copybooks. Then you get the editor to put the sequence numbers of the source program (yes, we have actual sequence numbers, not just counting the lines) in columns one to six, and use compiler options SEQUENCE and NUMBER and then have a DEBUG DECLARATIVE, have the DISPLAY on the same physical line as the paragraph/SECTION which is going to cause the DEBUG DECLARATIVE to execute.

share|improve this answer
add comment

Cobra

class Program
    def main
        print 'Hello World, from line [System.Diagnostics.StackFrame(true).getFileLineNumber]!'
share|improve this answer
add comment

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
add comment

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
add comment

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
add comment

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 yesterday
    
@Rynant Good point! I'll update my answers to consider that... –  darkajax yesterday
add comment

Python

import traceback

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

Short and sweet.

share|improve this answer
add comment

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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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