LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl: testing for blank lines (https://www.linuxquestions.org/questions/programming-9/perl-testing-for-blank-lines-501397/)

Garda 11-14-2006 01:55 AM

Perl: testing for blank lines
 
i'm trying to find blank lines in a text file
this is the code

Code:

use strict;
use warnings;

open (FILE, '<', 'file1.txt') or die "$!";

while (<FILE>)
{
        if ($_ == "")
        {
                print "it's blank\n";
        }
        elsif ($_ != "")
        {
                print "it's NOT blank\n";
        }
}

this is file1.txt

Code:

1

2

3

4

it seems to work ok, but i keep getting warnings

i'm pretty sure that
if ($_ == "")
is the wrong way to test for an empty string, what should i be doing instead?

edit: i'm kinda confused also, because i think blank lines are actually nothing, followed by the new like character, but i still get the "it's blank" message

druuna 11-14-2006 02:10 AM

Hi,

Try this:
Code:

#!/bin/perl
use strict;
use warnings;

open (FILE, '<', 'file1.txt') or die "$!";

while (<FILE>)
{
  if ($_ =~ /^$/)
  {
    print "it's blank\n";
  }
  else
  {
    print "it's NOT blank\n"; 
  }
}

This: $_ =~ /^$/ can also be written as /^$/. Perl assumes a check against $_ in the last case.

Hope this helps.

Garda 11-14-2006 02:20 AM

thanks for that, i was pretty sure that i was checking for empty lines in the wrong way

BCarey 11-16-2006 07:26 PM

You might want to try:

Code:

/^\s*$/
if your "blank" lines may contain spaces or tabs.

Brian

matthewg42 11-16-2006 07:39 PM

You used the == to test for an empty string, but this is the numerical equality test. You should use eq for strings. Also $_ will not equal "" for a blank line - it will equal "\n". If you want to get rid of the newline character before testing, use chomp first.
Code:

while (<FILE>) {
    chomp;
    if ( $_ eq "" ) { print "empty line at input line number $.\n"; }
}

A regular expression might also be useful, matching not only completely empty lines but those with whitespace. You don't have to chomp if you're using regular expressions - they're smart enough to handle them. Personally I like to chomp anyway - I find that more often than not I don't want the \n on the end of the line, plus I like the word "chomp":
Code:

while (<FILE>) {
    chomp;  # just because!
    if ( /^\s*$/ ) {
        print "empty line, or line with only whitespace at line $.\n";
    }
}

P.S. don't forget to close your FILE handle.
P.P.S. when calling open, you don't need to separate the <. You can call it like this: open(FILE, "<myfilename") || die ...;


All times are GMT -5. The time now is 01:31 AM.