in reply to How to check if a file has more than one line?

Heres something I found out, if you assign an array to a variable, it will return the total amount of lines. Then you can do a simple if statement to see if it equals what you expect.
use strict; use warnings; use File::Slurp; my @array = read_file("filename"); my $lines = @array; if ( $lines == 1 ) { print "total amount of lines are 1"; } else { print "file has $lines lines"; }

Replies are listed 'Best First'.
Re^2: How to check if a file has more than one line?
by GrandFather (Saint) on Dec 05, 2014 at 02:01 UTC

    That requires reading the whole file. For small files that's not a problem, but as a general thing you should only read as much at a time as you need. For that reason for loops and other techniques that read all the lines of a file into a list or array should be avoided unless you actually need random access to the whole file.

    Perl is the programming world's equivalent of English
      What about something like this? lol
      use strict; use warnings; open my $file, '<', "filename"; my $count_lines; my @array; while (<$file>) { $count_lines++; push @array, qw($_); last if ( $count_lines == 2 ); } my $lines = @array; print $lines; if ( $lines == 1 ) { print "this file only has 1 line"; } else { print "this file has 2 or more lines"; }

        You can be a little more succinct:

        #!C:\Perl\bin use diagnostics; use strict; my $twoLines = 2 == grep {defined <DATA>} 1 .. 2; print "Two or more lines\n" if $twoLines; __DATA__ 1 2
        Perl is the programming world's equivalent of English