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

Morning. I've got a subroutine which I'm using for parsing user input from STDIN. I'd like to add functionality to restrict the number of lines a user can input, while still using 'while'. The way I'd thought I might be able to do it is like this:
if(defined($number_of_lines)) { if($#_ eq $number_of_lines) { last; } }
As I figured STDIN might be read into @_. It's giving me syntax errors though. Was that a wrong assumption about @_? And if so, how would you do it? And if it's not, is my syntax just crappy?
toeslikefingers.com - because you've got too much time on your hands

Replies are listed 'Best First'.
Re: Finding number of lines in STDIN
by castaway (Parson) on Dec 18, 2003 at 11:21 UTC
    There's a perl variable which counts lines on a filehandle, and works on STDIN, it's called $.. So just do something like:
    last if($. == $number_of_lines);
    (To compare numbers, use '==' not 'eq')

    Note: $. is the line count for the last filehandle accessed, so dont use it if you're accessing other files inbetween.

    C.

      Clarification: $. is the line count for the last filehandle accessed by and of: readline (aka <>), tell(FILEHANDLE), seek, or sysseek.

      You can access the line count for any filehandle with some_filehandle->input_line_number (but you have to use FileHandle or use IO::Handle first).

      Note that STDIN->input_line_number is tracked separately from ARGV->input_line_number even when <ARGV> or empty <> is reading from stdin.

Re: Finding number of lines in STDIN
by bart (Canon) on Dec 18, 2003 at 11:17 UTC
    Try
    while(<>) { last if $number_of_lines && $. > $number_of_lines; ... }
    $. is an automatic counter for the line numbers. (See perlvar)