Click here to Skip to main content
15,885,039 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I decided to learn some Perl and I found this tutorial by Nik Silver: http://www.comp.leeds.ac.uk/Perl/[^].  In the Control Structures exercise, I solved the first part: putting a line number before each line, but I don't know how to solve the second part: putting a 3-digit number before each line.  Does anyone have any ideas?


Sincerely,
Mike
Posted

It would be good if you would show what you have tried, but in absence of that, I think all you likely need to do is look up printf, and use a format like %03d. Assuming you have a decent Perl installation, you should be able to find out all you need at the command line with perldoc -f sprintf. Note that sprintf and printf use the same formatting codes, and if you know C at all they should be very familiar.

An alternative would be to use Perl's format facility which is quite powerful, but mostly unused in these days of HTML and so on. I have done some pretty fancy text formatting with it in the past for report generation, and if you're working in simple text it may be worth a look.

cheers!
Don
 
Share this answer
 
Here is a program that prints line numbers:

$file = 'results.log';
open(INFO, $file);
$count = 0;
while ($line = <INFO>)
{
$count++;
print "$count $line";
}
close(INFO);

According to the tutorial, to solve the second part, one only needs to change one line by inserting an extra four characters. I was wondering if someone knew how to do this.

However, Member 4749791, I do appreciate your input. I wish to investigate the printf statement.


Mike
 
Share this answer
 
Thanks for the code. All you need to do is replace your print with this:
printf('%03d %s', $count, $line);

%03d specifies 3 characters of d format (signed integer in decimal, hence the 'd' - history sometimes gives us unlikely results) with leading zeros (but see what happens after line 999!)

%s is an unconstrained string format

I hope this helps!
Don
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900