Perl logo

Perl Refreshments ⌘

Treat - Printing Line Numbers

There are several reasons why you might want to print the line number of the currently executing line in a script.

For me, it's usually in an info-logging situation (read: debugging) as in:

print "<p style='color:orange'>[425] Init starting ...</p>";

Hard-coding the line # like this works, but as soon as code is added or deleted elsewhere in the script, those hard-coded line numbers have to be changed.

Enter the __LINE__ token. [Those are 2 underscores bookending 'LINE']

Using this will result in the same thing but no extra editing if you change the script.

Here's how the above line would be written:

print "<p style='color:orange'>[" . __LINE__ . "] Init starting ...</p>";

Note that the token is NOT included in the quotes, but has to be concatenated.

Since discovering this I have changed all my scripts to include this little nugget.

-30-