views:

65

answers:

2
#!/usr/bin/perl 
open(SARAN,"first.txt") or die "Can't Open: $!\n";
while($line=<SARAN>)
{ 
print "$line\n";
} 
close SARAN;

Hi, In the above perl script, i need one functionality... in first.txt, each line starts with some space in front.. I need to print the lines without space in front... What to do.

thanks..

+7  A: 

you can do:

while($line=<SARAN>) { 
  $line=~s/^\s+//;  # delete the leading whitespace.
  print "$line\n";
}

We use the Perl's substitute operator s which allows us to find a match using a regex and replace the part of the string that matched with another string.

Here we use the regex ^\s+

  • ^ is the start anchor.
  • \s is any whitespace character.
  • + quantifier to mark one or more

Basically we match and replace the leading one or more whitespace char with nothing which effectively means deleting them.

codaddict
thanks..it works
Saranyya
+7  A: 

Your question is ambiguous: Do you want to print the lines that do not start with space(s) or print all the lines after removing any leading space(s)?

@codaddict showed how to do the latter. I will show how to do the former:

#!/usr/bin/perl 

use strict;
use warnings;

open my $SARAN, '<', "first.txt" 
    or die "Can't open 'first.txt': $!";

while (my $line = <$SARAN>) 
{ 
    print $line unless $line =~ /^\s/;
} 

close $SARAN;

Note the following:

  • use strict will help you catch programming errors.
  • use warnings will alert you to dubious constructs.
  • Bareword filehandles such as SARAN are package globals. Use lexical filehandles.
  • Prefer the three-argument form of open, especially if the filename is not hardcoded.
  • Include the filename in the error message.
  • Since you are not chomping $line, print "$line\n" would cause newlines to be doubled.
Sinan Ünür
+1 for best practices and alternate meaning of the question.
M42
Slight pedantry. That regex can be simplified to /\s/ in this case. No need to look for more than one leading whitespace character.
davorg
@davorg Correct regarding the quantifier. However, the pattern still needs to be anchored.
Sinan Ünür
Argh. Yes, I knew that. Would you believe it was a typo :-(
davorg