sofdelg
sofdelg

Reputation: 111

Read lines from a file and output each line with a line number

I'm really new to Perl programming and I'm writing a program that opens a file and reads in each line of the file one by one. It then outputs the file with a line number at the beginning of each line.

As of right now I'm reading in the lines, but I don't know how to distinguish individual lines and output something at the beginning.

#!/usr/bin/perl
use strict
use warnings

my $file = 'FILENAME.txt';
open(my $txt_file, '<', $file) or die "Could not open file."

while (my $lines = <$txt_file>) {
    ...
}

Upvotes: 1

Views: 299

Answers (1)

Miller
Miller

Reputation: 35198

The $. variable holds the current line number for the last filehandle accessed:

#!/usr/bin/perl
use strict;
use warnings;
use autodie;

my $file = 'FILENAME.txt';
open my $fh, '<', $file;

while ( my $line = <$fh> ) {
    print "$. $line";
}

Upvotes: 5

Related Questions