Hi Irfan, On Mon, 1 Oct 2012 01:34:51 -0700 (PDT) Irfan Sayed <irfan_sayed2...@yahoo.com> wrote:
> hi, > > i need to delete all blank lines from the text file > How do you define a blank line? Is it an empty line? Is it a line that contains only whitespace? In any case, here are a few comments on your code and after that a solution: > > wrote following code. however, all the blank lines are not getting > deleted. please suggest > > > open FILE,"+<", 'C:\Users\bvcontrolbuild\Desktop\test.txt'; 1. Use lexical filehandles. 2. In this case the "+<" mode can be replaced by "<". 3. Use "/" instead of "\", which causes less escaping problems. 4. Throw an exception on failure - or die "Cannot open $filename - $!", or alternatively use autodie.pm. > > while (<FILE>) > { > chomp; > push (@lines, "$_\n"); > } It's not a good idea to over use "$_" for loops. Use a lexical variable here. Also, you should not chomp just to add the \n again. You can do: my @lines = <$fh>; > close FILE; > > open FILE,">", 'C:\Users\bvcontrolbuild\Desktop\test.txt'; > > foreach (@lines) Again, do « foreach my $l (@lines)» > { > > if ($_ =~ m/^\n/) > { > print "hi\n"; > $_ =~ s/^\n//; > } > else > { > print FILE "$_\n"; > } This seems fine, but it won't work if the lines contain some whitespace (and only that). Now for the solution. You can use https://metacpan.org/module/File::Slurp with https://metacpan.org/module/File::Slurp#edit_file-edit_file_lines # For removing truly empty lines. edit_file_lines sub { s/\A\n\z//; }, 'filename'; # For removing lines containing only whitespace edit_file_lines sub { s/\A\s+\z//; }, 'filename'; (Untested!). Please go over this document, because you appear to keep making such mistakes: http://perl-begin.org/tutorials/bad-elements/ Regards, Shlomi Fish -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ Parody of "The Fountainhead" - http://shlom.in/towtf How many “one-liners” do I actually write? I don’t know; maybe a couple dozen a day. But I guess I must be unusual, because as we all know, AWK was a complete failure and vanished into obscurity since it didn’t address anyone’s real needs. (That was sarcasm.) — “Twelve Views of Mark Jason Dominus” Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/