我的代码如下,如何在添加hello后删除空格。到每一行。
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
use Data::Dumper;
my $fh = \*DATA;
#my($line) = $_;
while(my $line = <$fh>)
{
print "Hello.".$line;
chomp($line);
}
__DATA__
Member Information
id = 0
name = "tom"
age = "20"
输出:
D:\learning\perl>test.pl
Hello.Member Information
Hello. id = 0 # I want to remove the white space between Hello. and id
Hello. name = "tom" # same as above
Hello. age = "20" # same
D:\learning\perl>
答案 0 :(得分:2)
一种方法是从数据本身中删除前导空格:
__DATA__
Member Information
id = 0
name = "tom"
age = "20"
其他方法是在打印之前从$line
删除前导空格:
只需在print
:
$line=~s/^\s+//;
答案 1 :(得分:2)
如果每一行都有4个前导空格,您可以使用:
substr $line, 0, 4, "";
答案 2 :(得分:1)
我会删除字符串并一次性添加hello
while ( <DATA> ) {
s/ ^ \s+ /Hello./x ;
print ;
}
^ =字符串开头的锚点
\ s + =一个或多个空格
/ x =为了清晰起见,允许在正则表达式中留出额外空间
或更详细
while(my $line = <$fh>)
{
$line =~ s/ ^ \s+ /Hello./x ;
print $line ;
}