My crap PERL program

Hey all,

I've been trying to learn Perl on my BSD box. When it came to printing the files out, it bothered me that the lines weren't numbered. So here's my little *crap* claim to some-form-of-fame Perl script which numbers files:


#!/usr/bin/perl

# --------------------------------------------
# Numbers and outputs the lines in a text file
# --September 2002----------------------------

while ($ln = <>) {
print $.,": ", $ln;
}


Ok, it's not the be-all and end-all of Perl scripts, but it works!!!

:slight_smile: If it only does one person any good (like me) it's worth it!

?? question ??

you can simplify it like so.

#!/usr/bin/perl -w
while (<>) { chomp ; print $.,": $_\n"; }

There's always one ...

:rolleyes: :stuck_out_tongue: :smiley:

I am old and frumpy and still prefer to do it the "old fashioned way" and not use the fancy dancy built in perl vars.

I would do it this way:

my $lineNumber = 1;

while ($ln = <>) {
  print "$lineNumber: $ln\n";
  $lineNumber++;
};

Yeah, I know it doesn't make full use of the plethora of built in Perl vars, but most any programmer can sit down and look at it and go "Ah-ha!"

Learing Perl is a good thing. I use it under Win32 at work and under *BSD at home.

Or "cat -n".
Or the shell for that matter...

#! /bin/ksh
cnt=1
while read -r line; do
   print "$cnt $line"
   ((cnt++))
done

It's all a matter of preference (unless you're worried about a silly thing like speed...)

It's nice to see that my crap thread has turned into an interesting one - where you guys are showing different ways to do the same thing!

Thanks - and keep it up if you wish to...

Well, ok, if you insist... There is a "nl" program whose only job in life is to number lines.

Very cunning Perderabo :smiley:

 nl FileName > NewFile 

cool command :slight_smile:

You can simplify it even more:

#!/usr/bin/perl -ln
print "$.: $_"

Or do it in awk:

#!/bin/awk
{ print NR ": " $0 }