Home > Archive > PERL Beginners > October 2006 > Re: Prefix printed lines on screen with a line number. Need advice.
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Re: Prefix printed lines on screen with a line number. Need advice.
|
|
| nobull67@gmail.com 2006-10-01, 6:58 pm |
|
Jay wrote:
> I have to write a perl script for a class which reads a file and prints
> its contents on screen and prefixes each line with a line numbers. I
> have written the following script, but it fails at the foreach
> statement. Does anyone know what is wrong or did I even write it
> correctly.
Your script seems to have nothing to do with that description.
It's so far off I can't even imagine what you think it does.
>
> #!/usr/bin/perl -w
Consider using strict and warnings. It really will make life a _lot_
less painful.
>
> unless (scalar(@ARGV==1)) {
> print "Error: Program must be executed with 1 argument.\n";
> print "Usage: linenum filename\n";
> exit 1;
> }
scalar() in the above is redundant.
>
> unless (-e ($ARGV[0])) {
> print "Error: Argument must be a file.\n";
> print "Usage: linenum filename\n";
> exit 0;
> }
>
> $lines = 0;
What you believe is the purpose of the above statement? Nothing ever
uses the value you've just put in $lines.
> open (FILE, "$ARGV[0]") or die "Can't open $ARGV[0]\n";
Use the 3 arg open unless there's a reason not to.
Do not quote varialbles for no reason.
Consider putting the reason why you can't open in the error message.
open (FILE, '<', $ARGV[0]) or die "Can't open $ARGV[0]: $!\n";
> while ($lines = <FILE> ) {
> @fields = split($line);
There is no value in $line. Perl would have told you in so many ways if
you'd allowed it. Remember what I said about pain. This is it.
What does splitting lines have to do with your stated purpose?
> $var1 = $fields[0];
> $processes{$var1}++;
What is the purpose of %processes? You never use it again.
What does counting occurances of distinct values in the first column
have to do with your stated purpose?
> }
>
> foreach $var1 {
What do you suppose that does?
> printf "%4d: ", $var1, "\n";
> }
What do you suppose that does?
| |
| Uri Guttman 2006-10-01, 9:58 pm |
| >>>>> "nc" == nobull67@gmail com <nobull67@gmail.com> writes:
nc> Or at the command line:
nc> perl -ne'print "$. $_"'
since you always print, the -p option is better (especially for
golfing :). you just need to modify $_.
perl -pe 's/^/$./'
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
|
|
|
|
|