24
\$\begingroup\$

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

\$\endgroup\$
10
  • \$\begingroup\$ What do you mean by "the first line number"? Are you talking about what should happen if the statement spans multiple lines? \$\endgroup\$ Jun 4, 2014 at 1:34
  • \$\begingroup\$ @user2357112 yes, just to resolve any ambiguity if anyone needed to use a milti-line statement. \$\endgroup\$ Jun 4, 2014 at 1:58
  • \$\begingroup\$ The title is very explicit, but perhaps a bit long. \$\endgroup\$
    – primo
    Jun 4, 2014 at 5:11
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – dave
    Jun 4, 2014 at 14:26
  • 1
    \$\begingroup\$ @Markasoftware if a line was added before it, the output wouldn't change to reflect that. \$\endgroup\$
    – primo
    Jun 6, 2014 at 1:00

44 Answers 44

49
\$\begingroup\$

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!

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

BASIC

I think this does everything that was asked for:

10 PRINT "Hello World, from line 10!"
\$\endgroup\$
10
  • 5
    \$\begingroup\$ 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. \$\endgroup\$ Jun 3, 2014 at 14:58
  • 30
    \$\begingroup\$ It may be the first line in the source code, but it's still line 10. \$\endgroup\$
    – r3mainer
    Jun 3, 2014 at 15:01
  • 13
    \$\begingroup\$ 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) \$\endgroup\$
    – Tim S.
    Jun 3, 2014 at 16:28
  • 18
    \$\begingroup\$ 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). \$\endgroup\$
    – Nick
    Jun 3, 2014 at 21:36
  • 2
    \$\begingroup\$ Clever, but I'd be disappointed if nothing else ended up with more upvotes than this one. \$\endgroup\$
    – agweber
    Jun 4, 2014 at 16:34
35
\$\begingroup\$

Java

public class Hello{
    public static void main(String[] args) {
        System.out.println("Hello World, from line "+new Exception().getStackTrace()[0].getLineNumber()+"!");
    }
}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ I'd prefer Thread.currentThread().getStackTrace() \$\endgroup\$
    – Cruncher
    Jun 3, 2014 at 15:01
  • 3
    \$\begingroup\$ Thread.getStackTrace() calls (new Exception()).getStackTrace() if called on the current thread, so it's the same thing \$\endgroup\$
    – DHall
    Jun 3, 2014 at 19:29
  • 1
    \$\begingroup\$ weird.... 2x same answer and 2 different upvote amounts... (could be used as RNG source...) (same here: codegolf.stackexchange.com/a/30058/10801) \$\endgroup\$
    – masterX244
    Jun 3, 2014 at 19:55
  • \$\begingroup\$ @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. \$\endgroup\$ Jun 3, 2014 at 21:21
  • 9
    \$\begingroup\$ @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. \$\endgroup\$
    – primo
    Jun 4, 2014 at 5:00
29
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Yes, it definitely is more interesting :) \$\endgroup\$
    – Tal
    Jun 3, 2014 at 6:07
27
\$\begingroup\$

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

\$\endgroup\$
3
  • 3
    \$\begingroup\$ This is ... wizardry \$\endgroup\$
    – Paladine
    Jun 5, 2014 at 22:33
  • 2
    \$\begingroup\$ It took me a ... long while to see how this worked. Soo many red herrings! It's delicious. \$\endgroup\$
    – sehe
    Jun 6, 2014 at 9:02
  • 1
    \$\begingroup\$ So how does it work? \$\endgroup\$
    – David G
    Mar 27, 2015 at 21:58
16
\$\begingroup\$

Lua

print("Hello world, from line "..debug.getinfo(1).currentline.."!")
\$\endgroup\$
16
\$\begingroup\$

C

#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}
\$\endgroup\$
3
  • \$\begingroup\$ Using defined variables like LINE, although allowed by the rules, are discouraged. \$\endgroup\$
    – user18967
    Jun 8, 2014 at 14:05
  • \$\begingroup\$ @vaxquis, yes but my answer predates that edit to the question \$\endgroup\$
    – gnibbler
    Jun 9, 2014 at 0:16
  • \$\begingroup\$ 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? \$\endgroup\$
    – user18967
    Jun 9, 2014 at 1:11
16
\$\begingroup\$

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!
\$\endgroup\$
3
  • \$\begingroup\$ Any particular reason to use roman numerals? \$\endgroup\$
    – Cole Tobin
    Jun 3, 2014 at 23:36
  • 4
    \$\begingroup\$ When the printing line is line 10, the question is interpreted literally. X in roman numerals is 10. \$\endgroup\$
    – Οurous
    Jun 3, 2014 at 23:59
  • \$\begingroup\$ Roman numerals is a nice touch! \$\endgroup\$
    – NPSF3000
    Jun 5, 2014 at 15:05
15
\$\begingroup\$

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!
\$\endgroup\$
12
\$\begingroup\$

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

\$\endgroup\$
5
  • 2
    \$\begingroup\$ dat stack, hehe. Verified working on Firefox. \$\endgroup\$ Jun 3, 2014 at 13:55
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – C5H8NNaO4
    Jun 3, 2014 at 14:05
  • 2
    \$\begingroup\$ 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.) \$\endgroup\$ Jun 3, 2014 at 16:02
  • \$\begingroup\$ @steveverrill According to google, you are correct! \$\endgroup\$
    – kitcar2000
    Jun 5, 2014 at 20:41
  • \$\begingroup\$ @kitcar2000 Probably. But there are other lesser-known compounds with this formula: Sodium methylaspartate or nitropentanoate, for example. \$\endgroup\$ Jun 5, 2014 at 21:02
11
\$\begingroup\$

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.

\$\endgroup\$
8
  • \$\begingroup\$ couldn't you just set line_num = to -1 and have the print outside the loop and get ride of the magic hash? \$\endgroup\$
    – dave
    Jun 4, 2014 at 14:28
  • 1
    \$\begingroup\$ @dave not sure I follow you. The magic hash is what makes this solution clever. \$\endgroup\$
    – Tim S.
    Jun 4, 2014 at 17:15
  • \$\begingroup\$ +1 for literal interpretation of my rules :) Very clever. \$\endgroup\$ Jun 4, 2014 at 19:01
  • 5
    \$\begingroup\$ @Stefan This site is all about worst practices, though. ;) \$\endgroup\$
    – Tim S.
    Jun 5, 2014 at 20:09
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Tim S.
    Jun 6, 2014 at 11:49
9
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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]+"!");
    }
}
\$\endgroup\$
8
\$\begingroup\$

Python

import traceback, inspect
frame = inspect.currentframe()
print("Hello World, from line "+traceback.format_stack(frame)[0].split()[3][:-1]+"!")  
\$\endgroup\$
0
7
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ No idea what this was, but I believe your output claim, so +1 ;-) \$\endgroup\$
    – ysap
    Jun 7, 2014 at 3:25
  • 1
    \$\begingroup\$ For those who question the power of mighty Befunge, try it out here: quirkster.com/iano/js/befunge.html \$\endgroup\$
    – Justin
    Jun 10, 2014 at 2:27
6
\$\begingroup\$

Perl

print 'Hello World, from line '.__LINE__.'!';
\$\endgroup\$
1
  • 13
    \$\begingroup\$ This is also a valid PHP solution. \$\endgroup\$
    – MrLore
    Jun 3, 2014 at 15:03
6
\$\begingroup\$

Java

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

Python

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

Output

Hello World from line 2!
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Best Python one so far! \$\endgroup\$ Jun 4, 2014 at 14:32
6
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ This only works if you use a constant format string. It fails if you pass in any other expression for the format string. \$\endgroup\$
    – Snowbody
    Jun 5, 2014 at 13:01
5
\$\begingroup\$

Bash

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

Output

Hello World, from line 4!
\$\endgroup\$
10
  • \$\begingroup\$ @professorfish ... what's wrong with MY style to show MY answer? You should at least explain why you manipulate my artwork... :-P \$\endgroup\$
    – user19214
    Jun 3, 2014 at 14:22
  • 2
    \$\begingroup\$ 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 \$\endgroup\$
    – user16402
    Jun 3, 2014 at 16:11
  • 1
    \$\begingroup\$ And evryone else besides me loves seeing his stuff being changed without commenting why? Strange place... \$\endgroup\$
    – user19214
    Jun 3, 2014 at 16:44
  • 3
    \$\begingroup\$ It was basically a formatting fix. There's nothing really wrong with those AFAIK \$\endgroup\$
    – user16402
    Jun 3, 2014 at 16:46
  • \$\begingroup\$ Using defined variables like LINE, although allowed by the rules, are discouraged. \$\endgroup\$
    – user18967
    Jun 8, 2014 at 14:06
5
\$\begingroup\$

D

void main ()
{
    import std.stdio;
    writefln("Hello World, from line %d", __LINE__);
}
\$\endgroup\$
1
  • \$\begingroup\$ Using defined variables like LINE, although allowed by the rules, are discouraged. \$\endgroup\$
    – user18967
    Jun 8, 2014 at 14:06
5
\$\begingroup\$

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.
\$\endgroup\$
4
\$\begingroup\$

Kind of boring in Ruby:

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

This isn't cheating, right?

\$\endgroup\$
3
  • \$\begingroup\$ 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) \$\endgroup\$ Jun 3, 2014 at 17:43
  • \$\begingroup\$ Using defined variables like LINE, although allowed by the rules, are discouraged. \$\endgroup\$
    – user18967
    Jun 8, 2014 at 14:07
  • 1
    \$\begingroup\$ @vaxquis Yeah, that statement was added after this answer. \$\endgroup\$
    – Ajedi32
    Jun 8, 2014 at 14:29
4
\$\begingroup\$

Javascript

One line using stack trace.

(function (o) { console.log("Hello World, from line " + (Error.captureStackTrace(o) || o.stack.match(/\d+/)[0] - !!__commandLineAPI) + "!"); })({});
\$\endgroup\$
3
\$\begingroup\$

Cobra

class Program
    def main
        print 'Hello World, from line [System.Diagnostics.StackFrame(true).getFileLineNumber]!'
\$\endgroup\$
3
\$\begingroup\$

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"
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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!
\$\endgroup\$
2
  • \$\begingroup\$ +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] \$\endgroup\$
    – Rynant
    Jun 4, 2014 at 13:49
  • \$\begingroup\$ @Rynant Good point! I'll update my answers to consider that... \$\endgroup\$
    – DarkAjax
    Jun 4, 2014 at 14:01
3
\$\begingroup\$

Python

import traceback

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

Short and sweet.

\$\endgroup\$
3
\$\begingroup\$

Perl

Another Perl one:

use warnings;

$SIG{__WARN__} = sub { ($line = shift) =~ s/\D//g; };

$x=$x+1; print "Hello World, form line $line!\n";
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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