: an empty diamond, or <>. We can make our line counter a little more flexible by using this filehandle:
#!/usr/bin/perl
# nl2.plx
use warnings;
use strict;
my $lineno = 1;
while (<>) {
print $lineno++;
print ": $_";
}
Now Perl expects us to give the name of the file on the command line:
> perl nl2.plx nlexample.txt
1: One day you're going to have to face
2: A deep dark truthful mirror,
3: And it's gonna tell you things that I still
4: Love you too much to say.
5. ####### Elvis Costello, Spike, 1988 #######
>
We can actually place a fair number of files on the command line, and they'll all be processed together. For example:
> perl nl2.plx nlexample.txt nl2.plx
1: One day you're going to have to face
2: A deep dark truthful mirror,
3: And it's gonna tell you things that I still
4: Love you too much to say.
5. ####### Elvis Costello, Spike, 1988 #######
6: #!/usr/bin/perl
7: # nl2.plx
8: use warnings;
9: use strict;
10:
11: my $lineno = 1;
12:
13: while (<>) {
14: print $lineno++;
15: print ": $_";
16: }
If we need to find out the name of the file we're currently reading, it's stored in the special variable $ARGV. We can use this to reset the counter when the file changes.
Try it out : Numbering Lines in Multiple Files
By detecting when $ARGV changes, we can reset the counter and display the name of the new file:
#!/usr/bin/perl
# nl3.plx
use warnings;
use strict;
my $lineno;
my $current = "";
while (<>) {
if ($current ne $ARGV) {
$current = $ARGV;
print "\n\t\tFile: $ARGV\n\n";
$lineno=1;
}
print $lineno++;
print ": $_";
}
And now we can run this on our example file and itself:
> perl nl3.plx nlexample.txt nl3.plx
File: nlexample.txt
1: One day you're going to have to face
2: A deep dark truthful mirror,
3: And it's gonna tell you things that I still
4: Love you too much to say.
5. ####### Elvis Costello, Spike, 1988 #######
File: nl3.plx
1: #!/usr/bin/perl
2: # nl3.plx
3: use warnings;
4: use strict;
5:
6: my $lineno;
7: my $current = "";
8:
9: while (<>) {
10: if ($current ne $ARGV) {
11: $current = $ARGV;
12: print "\n\t\tFile: $ARGV\n\n";
13: $lineno=1;
14: }
15:
16: print $lineno++;
17: print ": $_";
18: }
>