Write a piece of code to output the line number of the print / output statement itself (in the form "Hello World, from line X!")

25

4

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

Breakthrough

Posted 2014-06-03T04:36:26.670

Reputation: 620

What do you mean by "the first line number"? Are you talking about what should happen if the statement spans multiple lines? – user2357112 supports Monica – 2014-06-04T01:34:47.253

@user2357112 yes, just to resolve any ambiguity if anyone needed to use a milti-line statement. – Breakthrough – 2014-06-04T01:58:20.697

The title is very explicit, but perhaps a bit long. – primo – 2014-06-04T05:11:44.460

@primo updated, what do you think of the new title? – Breakthrough – 2014-06-04T06:31:36.827

@Breakthrough I think it's better, because the point of the challenge is listed first (which, when the title is cropped see here, is the only thing that's visible). I might even consider removing the bit in parentheses; how it needs to be done should be detailed in the challenge description.

– primo – 2014-06-04T06:43:15.513

1The 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 – 2014-06-04T14:26:52.860

@dave that's why this is a popularity contest, and in the scoring criteria, I've asked people to consider how elaborate/interesting someone's solution is relative to the language they used (e.g. this Ruby one-liner).

– Breakthrough – 2014-06-04T14:45:09.487

why shouldn't we just put on one line? e.g. document.write('Hello World, from line 1'); – markasoftware – 2014-06-06T00:04:50.447

1@Markasoftware if a line was added before it, the output wouldn't change to reflect that. – primo – 2014-06-06T01:00:38.543

oooooohhhh, I understand now. I didn't understand the grammar in the third point of the rules, now I get it. Thanks! – markasoftware – 2014-06-06T01:27:30.800

Answers

48

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!

kitcar2000

Posted 2014-06-03T04:36:26.670

Reputation: 2 689

And by the same token, Timex/Sinclair BASIC! – Gabe – 2014-06-03T23:50:25.290

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 – 2014-06-05T18:57:07.573

@MrLister Yes, that would definitely work but I always use +s from habit. – kitcar2000 – 2014-06-05T20:06:20.483

40

BASIC

I think this does everything that was asked for:

10 PRINT "Hello World, from line 10!"

r3mainer

Posted 2014-06-03T04:36:26.670

Reputation: 19 135

Golfier? 1 PRINT"Hello World, from line 1!"-3 – Erik the Outgolfer – 2016-06-28T21:04:40.060

5If 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 – 2014-06-03T14:58:04.673

30

It may be the first line in the source code, but it's still line 10.

– r3mainer – 2014-06-03T15:01:46.757

It's a nice idea, so a plus anyway. – Bill Woodger – 2014-06-03T15:01:53.247

Now I've kind of copied it http://codegolf.stackexchange.com/a/30085/16411, only more so :-)

– Bill Woodger – 2014-06-03T15:27:04.350

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. – 2014-06-03T16:28:57.100

I really do like this answer, and it is indeed very interesting - but I have to agree with @TimS. With respect to the challenge itself, it would be nice if solutions determined the line number programmatically. – Breakthrough – 2014-06-03T17:38:29.113

18This 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 – 2014-06-03T21:36:30.457

2Clever, but I'd be disappointed if nothing else ended up with more upvotes than this one. – agweber – 2014-06-04T16:34:10.577

2@Nick There's nothing great with this answer because the line number is hard-coded. Nothing's dynamic out there. You have to modify the text to display if you need to put more than 10 lines of code before priting the message. – C.Champagne – 2014-06-05T15:50:02.557

35

Java

public class Hello{
    public static void main(String[] args) {
        System.out.println("Hello World, from line "+new Exception().getStackTrace()[0].getLineNumber()+"!");
    }
}

Baby

Posted 2014-06-03T04:36:26.670

Reputation: 481

1I'd prefer Thread.currentThread().getStackTrace() – Cruncher – 2014-06-03T15:01:50.680

3Thread.getStackTrace() calls (new Exception()).getStackTrace() if called on the current thread, so it's the same thing – DHall – 2014-06-03T19:29:35.887

1

weird.... 2x same answer and 2 different upvote amounts... (could be used as RNG source...) (same here: http://codegolf.stackexchange.com/a/30058/10801)

– masterX244 – 2014-06-03T19:55:09.483

@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 – 2014-06-03T21:21:39.583

but still pretty funny how the small difference results in different upvotes... (somehow IDE refused to show linecount method for me in autocomplete) – masterX244 – 2014-06-03T21:25:37.940

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 – 2014-06-04T05:00:47.613

30

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.

primo

Posted 2014-06-03T04:36:26.670

Reputation: 30 891

3Yes, it definitely is more interesting :) – Tal – 2014-06-03T06:07:09.167

27

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

Yakk

Posted 2014-06-03T04:36:26.670

Reputation: 859

1So how does it work? – 0x499602D2 – 2015-03-27T21:58:14.370

2This is ... wizardry – Paladine – 2014-06-05T22:33:09.130

1It took me a ... long while to see how this worked. Soo many red herrings! It's delicious. – sehe – 2014-06-06T09:02:25.473

16

Lua

print("Hello world, from line "..debug.getinfo(1).currentline.."!")

mniip

Posted 2014-06-03T04:36:26.670

Reputation: 9 396

16

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!

Thomas Weller

Posted 2014-06-03T04:36:26.670

Reputation: 1 925

Any particular reason to use roman numerals? – Cole Johnson – 2014-06-03T23:36:04.010

4When the printing line is line 10, the question is interpreted literally. X in roman numerals is 10. – Οurous – 2014-06-03T23:59:23.843

Roman numerals is a nice touch! – NPSF3000 – 2014-06-05T15:05:59.130

15

C

#include <stdio.h>
main(){
printf("Hello World, from line %d!", __LINE__);
}

gnibbler

Posted 2014-06-03T04:36:26.670

Reputation: 14 170

Using defined variables like LINE, although allowed by the rules, are discouraged. – None – 2014-06-08T14:05:49.353

@vaxquis, yes but my answer predates that edit to the question – gnibbler – 2014-06-09T00:16:03.977

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? – None – 2014-06-09T01:11:00.227

14

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!

Breakthrough

Posted 2014-06-03T04:36:26.670

Reputation: 620

12

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

C5H8NNaO4

Posted 2014-06-03T04:36:26.670

Reputation: 1 340

2dat stack, hehe. Verified working on Firefox. – Breakthrough – 2014-06-03T13:55:03.330

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 – 2014-06-03T14:05:42.270

2Interesting 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.) – Level River St – 2014-06-03T16:02:08.313

@steveverrill According to google, you are correct!

– kitcar2000 – 2014-06-05T20:41:11.170

@kitcar2000 Probably. But there are other lesser-known compounds with this formula: Sodium methylaspartate or nitropentanoate, for example. – Level River St – 2014-06-05T21:02:22.097

11

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.

Tim S.

Posted 2014-06-03T04:36:26.670

Reputation: 615

couldn't you just set line_num = to -1 and have the print outside the loop and get ride of the magic hash? – dave – 2014-06-04T14:28:55.993

1@dave not sure I follow you. The magic hash is what makes this solution clever. – Tim S. – 2014-06-04T17:15:48.153

+1 for literal interpretation of my rules :) Very clever. – Breakthrough – 2014-06-04T19:01:29.327

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 – 2014-06-05T20:08:39.197

5@Stefan This site is all about worst practices, though. ;) – Tim S. – 2014-06-05T20:09:33.750

can you show a live version that works, while having the # cc46f7 comment too o.O That would be *impressive*. On my box, I had to tweak the line as well as the checksum in order to make it work :( – sehe – 2014-06-06T08:40:48.200

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. – 2014-06-06T11:49:03.960

9

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.

Bill Woodger

Posted 2014-06-03T04:36:26.670

Reputation: 1 391

8

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]+"!");
    }
}

masterX244

Posted 2014-06-03T04:36:26.670

Reputation: 3 942

8

Python

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

Hannes Karppila

Posted 2014-06-03T04:36:26.670

Reputation: 3 090

6

Perl

print 'Hello World, from line '.__LINE__.'!';

Tal

Posted 2014-06-03T04:36:26.670

Reputation: 1 358

13This is also a valid PHP solution. – MrLore – 2014-06-03T15:03:26.280

6

Java

public class HelloFrom {
    public static void main(String[] args) {
        System.out.println("Hello World, from line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + "!");
    }
}

Cineris

Posted 2014-06-03T04:36:26.670

Reputation: 161

technically the same as i did (http://codegolf.stackexchange.com/a/30058/10801)

– masterX244 – 2014-06-03T19:50:09.417

2Sort of, except using the current Thread instead of creating a new Error to get the stack trace. There isn't any error ;) – Cineris – 2014-06-04T05:10:16.167

6

Python

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

Output

Hello World from line 2!

Ricardo A

Posted 2014-06-03T04:36:26.670

Reputation: 71

1Best Python one so far! – kirbyfan64sos – 2014-06-04T14:32:51.063

6

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

AndoDaan

Posted 2014-06-03T04:36:26.670

Reputation: 2 232

No idea what this was, but I believe your output claim, so +1 ;-) – ysap – 2014-06-07T03:25:51.497

1

For those who question the power of mighty Befunge, try it out here: http://www.quirkster.com/iano/js/befunge.html

– Justin – 2014-06-10T02:27:36.410

6

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.

Walker Mills

Posted 2014-06-03T04:36:26.670

Reputation: 61

This only works if you use a constant format string. It fails if you pass in any other expression for the format string. – Snowbody – 2014-06-05T13:01:29.297

5

Bash

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

Output

Hello World, from line 4!

user19214

Posted 2014-06-03T04:36:26.670

Reputation:

@professorfish ... what's wrong with MY style to show MY answer? You should at least explain why you manipulate my artwork... :-P – None – 2014-06-03T14:22:51.113

2did 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 – None – 2014-06-03T16:11:56.050

1And evryone else besides me loves seeing his stuff being changed without commenting why? Strange place... – None – 2014-06-03T16:44:08.017

3It was basically a formatting fix. There's nothing really wrong with those AFAIK – None – 2014-06-03T16:46:54.873

Using defined variables like LINE, although allowed by the rules, are discouraged. – None – 2014-06-08T14:06:15.313

@vaxquis: OMG!!! :-P – None – 2014-06-08T16:23:52.230

@yeti yup. I hate unsurprising (read: boring) CG solutions, but hell, who am I to judge... – None – 2014-06-08T16:28:54.113

@vaxquis: The sentence about LINE probably was not part of the question (and rules) in the beginning or when I started to think about this. You can check the history of the question by clicking "edit" there. – None – 2014-06-08T20:03:44.653

a) it is now, b) it doesn't change anything regarding the fact that this CG entry is nondescript as far as they go... – None – 2014-06-08T21:21:10.727

(a) I get a notice/hint for every comment or vote but not when someone changes the question text or rules and after all: Who knows how long it will be there? It might vanish tomorrow. :P (b) I do not accept rule changes after I have answered. (c) The statement about LINE variables is not part of the rules. (d) I will not reply on further comments regarding this LINE variable topic. (e) Vote for deleting my answer if you cannot live with this. – None – 2014-06-09T06:07:54.133

5

D

void main ()
{
    import std.stdio;
    writefln("Hello World, from line %d", __LINE__);
}

Hugo Dubé

Posted 2014-06-03T04:36:26.670

Reputation: 91

Using defined variables like LINE, although allowed by the rules, are discouraged. – None – 2014-06-08T14:06:39.877

5

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.

Ken A

Posted 2014-06-03T04:36:26.670

Reputation: 585

4

Kind of boring in Ruby:

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

This isn't cheating, right?

Ajedi32

Posted 2014-06-03T04:36:26.670

Reputation: 143

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 – 2014-06-03T17:43:10.167

Using defined variables like LINE, although allowed by the rules, are discouraged. – None – 2014-06-08T14:07:51.350

1@vaxquis Yeah, that statement was added after this answer. – Ajedi32 – 2014-06-08T14:29:49.020

4

Javascript

One line using stack trace.

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

joelrobichaud

Posted 2014-06-03T04:36:26.670

Reputation: 141

3

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"

afuous

Posted 2014-06-03T04:36:26.670

Reputation: 429

3

Cobra

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

Οurous

Posted 2014-06-03T04:36:26.670

Reputation: 7 916

3

Python

import traceback

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

Short and sweet.

Hoons

Posted 2014-06-03T04:36:26.670

Reputation: 131

3

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!

DarkAjax

Posted 2014-06-03T04:36:26.670

Reputation: 669

+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 – 2014-06-04T13:49:39.443

@Rynant Good point! I'll update my answers to consider that... – DarkAjax – 2014-06-04T14:01:04.093

3

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

SomeShinyObject

Posted 2014-06-03T04:36:26.670

Reputation: 953

3

Perl

Another Perl one:

use warnings;

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

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

DarkAjax

Posted 2014-06-03T04:36:26.670

Reputation: 669

2

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.

Bill Woodger

Posted 2014-06-03T04:36:26.670

Reputation: 1 391

2

Nimrod

template lineno(): expr = instantiationInfo().line
echo "Hello, world, from line ", lineno(), "!"

It uses Nimrod's templates to generate a call to instantiationInfo, whose information is only valid when used from within a template.

Output:

Hello, world, from line 2!

kirbyfan64sos

Posted 2014-06-03T04:36:26.670

Reputation: 8 730

2

C#

using System;
using System.Runtime.CompilerServices;
namespace LineNumber
{
    class Program
    {
        int getLn([CallerLineNumber] int x){ return x; }
        public static void Main()
        {
            Console.WriteLine ("Hello World, from line " + getLn() + "!");
        }
    }
}

DLeh

Posted 2014-06-03T04:36:26.670

Reputation: 1 111

1

PHP

Shamelessly stolen from gnibbler

<?php
printf("Hello World, from line %d!", __LINE__);

Working example

eisberg

Posted 2014-06-03T04:36:26.670

Reputation: 119

1

ECMAScript (JavaScript):

alert('Hello World, from line ' + Error().lineNumber + '!');

Hello World, from line 1!

Note: I've only tested this in Firefox and Opera 10.


This should work in all current browsers:

alert('Hello World, from line ' + /^.*?@.+?:(\d+)(:\d+)?\r?\n/.exec(Error().stack)[1] + '!');

Hello World, from line 1!

Toothbrush

Posted 2014-06-03T04:36:26.670

Reputation: 3 197

1

There is more than one way to do it (Perl 5)

The boring way:

print "Hello World, from line ", __LINE__, "!\n";

A fancier way:

sub println { print @_, ", from line ", (caller)[2], "!\n" }

println "Hello World";

A sneaky way:

eval {
    die "Hello World";
};

print $@ =~ s/ at .* (line \d+)\./, from $1!/r;

An even sneakier way:

$SIG{__DIE__} = sub { exit print $_[0] =~ s/ at .* (line \d+)\./, from $1!/r };

die "Hello World";

The really sneaky way:

package Magic {
    use Filter::Simple sub { s/42/\${\\__LINE__}/g };
}
BEGIN { import Magic }

print "Hello World, from line 42!\n";

Ilmari Karonen

Posted 2014-06-03T04:36:26.670

Reputation: 19 513

1

x86 Assembly

.data
LC0:
    .ascii "hello, world! from address %x\n\0"
.text
    .global main
main:
    pushl   %ebp
    movl    %esp, %ebp
    call pop

pop:
    popl    %ebx
    leal    22(,%ebx,1), %ebx
    subl    $8, %esp
    movl    %ebx, 4(%esp)
    movl    $LC0, (%esp)
    call    printf
    movl    $0, %eax
    leave
    ret

This prints the memory address where the call to printf is located. This doesn't really work for rule 3, but I feel it's much more interesting than using __LINE__ or a stacktrace.

I should add how it works. Normally you can't get the address of the current instruction pointer by moving it into a register, so what I do is call a function "pop" which really means that the return address of the next instruction is pushed onto the stack and then a jump is executed. I pop this return address into ebx and add 22 to get the address of the printf call. The reason this won't work for rule 3 is that if you insert code before the printf call the address will not be 22 away from the address of the pop ebx.

0x41414141

Posted 2014-06-03T04:36:26.670

Reputation: 111

1

Befunge 98

This code snippet assumes that the IP comes downward into the upper left n. Otherwise, it fails.

n
>v>" enil morf ,dlroW olleH"bb+k,.@
^>:'^\1\p1+
 ][

The n (and newline) can be removed if I can assume that the stack is empty when it enters this snippet.

There is one discrepancy between this output and the one requested: instead of a ! at the end of the printed statement, this outputs a space because Befunge automatically appends a space to numbers that are outputted. I could easily add a ! after that. Fixing this would require a mess of ugly code.

You may add extra newlines anywhere and the code will still work. Spaces are more restricted, but may be added in several places. For instance, they cannot be added as the first character in any line.

Sample program:

v









n
>v>" enil morf ,dlroW olleH"bb+k,.@
^>:'^\1\p1+
 ][

Output:

Hello World, from line 12 

Justin

Posted 2014-06-03T04:36:26.670

Reputation: 19 757

0

Haskell

{-# LANGUAGE CPP #-}
main = putStrLn $ "Hello World, from line " ++ show __LINE__ ++ "!"

Hello World, from line 2!

user23409

Posted 2014-06-03T04:36:26.670

Reputation:

0

PHP

echo "Hello world, from line " . __LINE__ . "!";

jay

Posted 2014-06-03T04:36:26.670

Reputation: 121

0

Batch Script

@echo off
set /a %line%==10
echo Hello world at %line%
pause
exit

Batch Script Guy

Posted 2014-06-03T04:36:26.670

Reputation: 1

1Can you please explain how "Hello world at 10" points to the 3rd line in the script? Or, maybe there's some non-obvious batch syntax behind this? – ysap – 2014-06-07T03:29:04.877

0

JAVASCRIPT - NON-Standard

console.log('Hello World, from line %d!', (new Error).lineNumber);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/lineNumber

ankr

Posted 2014-06-03T04:36:26.670

Reputation: 131

0

POSIX SHELL:

I was going to do $LINENO but it's been done. So I'll ask an interactive POSIX-compatible shell to printout its current history line number instead:

HISTFILE= PS1='${hi}$(printf "${hi:+\!!!\n}> ")' sh -i
> hi=${on='Hello World, from line '}${off=}
Hello World, from line 2!
> hi=$off
> hi=$on
Hello World, from line 4!
>

Though it may not look like it, the shell is actually reevaluating and printing anew that $PS1 variable for every command it receives - else it wouldn't even work - so the print statement actually is printing its own line number every time it prints and not just the first.

mikeserv

Posted 2014-06-03T04:36:26.670

Reputation: 181

0

Python 2.7

# Any number of whitespace, code, etc.

# In this case, when greet() is called, it will output "Hello world, from line 4!"
def greet():print "Hello world, from line " + str(greet.func_code.co_firstlineno) + "!"

Originally I wanted to implement an overkill compiled code parser, but gave up, this is still a good one tho.

Mateon1

Posted 2014-06-03T04:36:26.670

Reputation: 323