Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

formatting line numbers 1

Status
Not open for further replies.

jjohnn

Technical User
Feb 11, 2003
43
US
My task (from a perl tutorial is to alter a program that prints line numbers on a file so that ->
"line numbers are printed as 001, 002, ..., 009, 010, 011, 012, etc. To do this you should only need to change one line by inserting an extra four characters. Perl's clever like that."
I print the line numbers easily enough:

$file = 'sta.txt';
open (TEXT, $file);
my $linenum;

while ($line = <TEXT>){
$linenum++;
print &quot;$linenum &quot;.&quot;$line&quot;;
}
The four characters to add to this script to format the line numbers mystifies me. Any suggestions?
 
Initialize $linenum as
Code:
my $linenum = &quot;000&quot;;
jaa
 
[tt]printf &quot;%03d %s&quot;, $linenum, $line;[/tt]
 
But wait; why does the &quot;000&quot; approach *not* work with the diamond operator, reading the filename off the command line?

Using <> doesn't give me the leading zeros, but the same code with the named filehandle does give me the leading zeroes.
 
<> is equivilent to <STDIN>, or what's generally the keyboard.

Unless that wasn't the question at all. What about reading a filename off the command line? For simple command line arguments, you can use the @ARGV array. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
$file = 'sta.txt';
open (TEXT, $file);
my $linenum =&quot;000&quot;;

while ($line = <TEXT>){
$linenum++;
print &quot;$linenum &quot;.&quot;$line&quot;;
}

This script formats the line numbers for the named file like 001,002...0067,0068. However, the exact same script, with the file name invoked on the command line instead:

perl linenum.pl stat.text [entered on command line]

my $linenum;

while ($line = <>){
$linenum++;
print &quot;$linenum &quot;.&quot;$line&quot;;
}
gives linenumbers as 1,2...67,68.
Why the difference with the same code?
 
&quot;linenum&quot; in that example is both the name of a variable in the script and the name of the perl script itself. Bad naming for this example.
 
The second example is missing the crucial [tt]my $linenum = &quot;000&quot;;[/tt] as Justice suggested earlier. (I personally didn't know that perl would increment that way.)

[tt]my $linenum = &quot;000&quot;;
foreach (0..2) {
$linenum++;
print &quot;$linenum\n&quot;;
}
[/tt]

gives:
[tt]001
002
003[/tt]

While:
[tt]my $linenum;
foreach (0..2) {
$linenum++;
print &quot;$linenum\n&quot;;
}
[/tt]

gives:
[tt]1
2
3[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top