Any better ways of doing this ? 
Author Message
 Any better ways of doing this ?

I'm relatively new to perl and I need to count the number of records
in a text file, where the format is:

        record1 record2 record3 ... recordn

This is the code I'm using at the moment:

1:      sub wc {
2:         local($file) = $_[0];

4:         open(WC_HANDLE,"$file") || die("wc: $file $!, stopped");
5:         $c = 0;
6:         while($_ = <WC_HANDLE>) {
7:            s/\s+/$;/g; study $_; $count += (split(/$;/, $_));
8:         }
9:         close(WC_HANDLE);
10:        return $count;
11:     }

Circumstances force me to use Perl4 (I'm using Perl 4.0 pl36). Is there
a better way of doing this? Are there any dangers in what I'm doing at
the moment? Thanks in advance.
--
Teoh Cy Boon                  
Electric Eye Pte Ltd          Tel   : (65) 777 7755
73 Ayer Rajah Crescent        Fax   : (65) 779 7608



Sun, 14 Feb 1999 03:00:00 GMT  
 Any better ways of doing this ?



Quote:
>I'm relatively new to perl and I need to count the number of records
>in a text file, where the format is:

>    record1 record2 record3 ... recordn
>6:     while($_ = <WC_HANDLE>) {

Just use
           while(<WC_HANDLE>)

here; the assignment to $_ is implicit.

Quote:
>7:        s/\s+/$;/g; study $_; $count += (split(/$;/, $_));

Just use
          $count += split;

which is short for

          $count += split(/\s+/, $_);

I don't know why you're bothering with $;.

Quote:
>Are there any dangers in what I'm doing at the moment?

Yes:  If the last line of the file is not terminated with a newline,
and countains only zeroes, your program will ignore it.  That's why
you should use

        while (<FH>)

instead of

        while ($_ = <FH>)

.  Also, if one of the records happens to contain an instance of $;,
your count will be incorrect.
--




Mon, 15 Feb 1999 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Seeking advice on semantics (pros / cons and best ways of) using constants across modules

2. Better ways to deal with yppasswd?

3. Better ways to do this?

4. Better ways to...

5. EDITING DATAFILES - What is best of 3 ways?

6. Can it be done better?

7. Is there a better way of doing this?

8. Is there a better way of doing this?

9. IRC: internet anarchy done good.

10. best way of doing sort|uniq (sort -u) in perl

11. Need a better way of doing things

12. Why does perl allow so many different ways of doing essentially the same thing?

 

 
Powered by phpBB® Forum Software