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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Stupid question

 



adolfo
Novice

Mar 2, 2001, 12:43 PM

Post #1 of 2 (511 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...).
ie:
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



japhy
Enthusiast

Mar 2, 2001, 1:06 PM

Post #2 of 2 (510 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:


Code
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:


Code
my $line = 1; 
open FILE, $filename or die "can't read $filename: $!";
while (<FILE>) {
print "$line $_";
$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