print if not empty

Ken Elliott's picture

They have: 358 posts

Joined: Jun 1999

Hello, just learning perl and not doing to bad. But I have an array and I am printing the contents to a text file. Unfortunately it contains empty lines. I don't want the empty lines to be printed to text file.

code:

open (TEXTFILE, "../textfile.txt");
@doc = <TEXTFILE>;
close (TEXTFILE);

 foreach $item(@doc) {
   unless ($item =~ /A-Za-z0-9/) {
     print "$item\n";
   }
}
[/code]

I don't know whether this code would work or not. Just thought of using the unless thing. Let me know if there is a way to accomplish this. The reason is because when I read from the textfile it throws those empty lines into the array, and I don't want them.

Thanks
VulKen 

Pimpin like a pimp with an electrofied pimpin machine!

They have: 850 posts

Joined: Jul 1999

Lets say that when you went
@array = <IN>; , @array was
@array = ("hello","","how","","are","","you");

Use the following code to only print the lines that are not empty.

code:

@array = ("hello","","how","","are","","you");

foreach (@array)
{
	if($_)
	{
		print $_ , "\n";
	}
}
[/code]
The output of this would be:
hello
how
are
you

Hope that helps a little.

------------------
click here to help save lives
http://www.wiredstart.com  : The Technology Start Page

[This message has been edited by robp (edited 14 May 2000).] 

They have: 20 posts

Joined: May 2000

If you just want to skip the empty lines, you can try the following code:

open (TEXTFILE, "../textfile.txt");
@doc = <TEXTFILE>;
close (TEXTFILE);
foreach (@doc){
unless (/^\n$/){print "$item\n"}
}

[This message has been edited by hcshim (edited 18 May 2000).]

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.