adding line numbers to a text file

I need a Perl script to read an input text file and output a file with line numbers preceding
each line of the text.

1      this is a test
2      hello folks
3      this is the time to code
4     etc cetera
Who is Participating?
TintinConnect With a Mentor Commented:
perl -pe 'print "$. "' input >output
Just a note: there's also standard unix tool called "nl"
nl -ba /etc/passwd
probably you need the \t

perl -ne 'print "$.\t$_ "' input >output
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

#!/usr/bin/perl -w
use strict;

open(FROM, "file_from.txt") || die $!;
open(TO, ">file_to.txt") || die $!;
my $index = 1;

while(<FROM>)      {
      print TO $index . "\t" . $_ . "\n";
Are we trying to see how long we can make the program?
If so, we can further expand
while(<FROM>)      {
while( defined($_=<FROM>) )      {
and we can chop off another character only to add it back with
     my $end = chop;
      print TO $index . "\t" . $_ . $end. "\n";
we can also explicitly pass $_ to chomp and chop:
 my $end = chop($_);
while we're at it, we can turn
 eval{my $temp=$index; $index = $index+1; $temp}

The answers above already solved this question. My messing up with my solution among experts, for which I apology, is based on the fact that I am a beginner and I know what people of my level need.
Chapeau, Ozo. I saw a lot of your answers. To tell you the truth, I do not know why to chop off another character and add it back. I assume it is, in addition to \n, another line terminating character.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.