开发者

In Perl, how can I print lines read from a file with optional leading whitespace removed?

开发者 https://www.devze.com 2023-01-16 08:20 出处:网络
#!/usr/bin/perl open(SARAN,\"first.txt\") or die \"Can\'t Open: $!\\n\"; while($line=<SARAN>) { print \"$line\\n\";
#!/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 lin开发者_高级运维es without space in front... What to do.

thanks..


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.


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.


#!/usr/bin/perl

 open(SARAN,"first.txt") or die "Can't Open: $!\n";

 @line=< SARAN>;

 $str_line = join("", @line);

 print(SARAN "$str_line");

 close SARAN;
0

精彩评论

暂无评论...
验证码 换一张
取 消