CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Stupid question



Mar 2, 2001, 12:43 PM

Post #1 of 2 (1334 views)
Stupid question Can't Post

I need to print each line of a file with it number at the beginning of each line using control structures (like foreach or while...).
1 this is my file's first line
2 this is my file's second line
3 this is my file's third line
and so.....
How can I do this???
I know how to print the my file's lines without the numbered line but I dont how to do it whit it...
Please help me!!!
I started to learn Perl three hours ago.... =(
Thanks in advance


Mar 2, 2001, 1:06 PM

Post #2 of 2 (1333 views)
Re: Stupid question [In reply to] Can't Post

Since you just started learning Perl, I suggest you spend a good week or so getting familiar with Perl's handy documentation. It's a time-saver like you've never known.

Here is how I would approach your problem:

open FILE, $filename or die "can't read $filename: $!"; 
while (<FILE>) {
print "$. $_";
close FILE;

The $. variable holds the current line number of the file you're reading from. Even if this variable didn't exist, you could use a simple counter:

my $line = 1; 
open FILE, $filename or die "can't read $filename: $!";
while (<FILE>) {
print "$line $_";
close FILE;

The Perl documentation is available on this site (there's a link on the left), and on your computer (if you have perl). perldoc perl will help you get started.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives