Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,Dear perl Monks i am a beginner when it comes to perl programming
but i sure like it as perl is powerful coding, you can make real nice things with it . that's why i am learning it and trying to make some scripts.

I have a question related to counting lines in a data file
(i don't use any module or cpan or what so ever. Just pur perl code for as far i know ;-)

i got a data.out file containing lines like these sample;

391 | Classic Box Kite | low | 19.95
340 | 4-cell Tetra | in | 45.00
401 | Classic Dragon | in | 39.00
4110 | spitfire|low | 25.00

now my question is how can i count the lines in the data file.
above sample contains 4 lines...

then i want to do if lines in data file is more then $allowedlines = "25"; then run this subroutines {

subrotuine i canmake but i have no idea how tocount the lines
icant find it in the perl book i got as well. (cgi101 book)


Replies are listed 'Best First'.
Re: How do i count lines from data file?
by davorg (Chancellor) on Jul 07, 2003 at 12:32 UTC
Re: How do i count lines from data file?
by cchampion (Curate) on Jul 07, 2003 at 12:16 UTC

    Use the $. global variable.

    while (<>) { my_sub() if $. > $allowedlines; print; # do the rest of your stuff }

    As an alternative, you can set a variable yourself, for example if you need to reset the counter.

    my $count =0; while (<>) { if ($count++ > $allowedlines) { my_sub(); $count =0; } print; # do the rest of your stuff }

    See perldoc perlvar for more info on $.

Re: How do i count lines from data file?
by Zaxo (Archbishop) on Jul 07, 2003 at 15:10 UTC

    I think you should consider your program's design a little more. Requiring a data file to be small makes me suspect that some minor requirement has led you to the tail wagging the dog.

    Usually, limiting the utility of data is not a good thing. If you have a business reason to restrict catalog size, it may be wiser to apply the restriction elsewhere than the data file itself.

    After Compline,
    Zaxo

Re: How do i count lines from data file?
by tcf22 (Priest) on Jul 07, 2003 at 14:18 UTC
    Could try something like this.
    my $allowed = ##NUMBER ALLOWED##; my @file = <DATA>; my $lines = @file; if($lines >= $allowed){ &my_sub() for($allowed..$lines); }