开发者

How to Insert a sub string to each line in perl

开发者 https://www.devze.com 2022-12-27 00:35 出处:网络
My code as below, H开发者_开发百科ow to remove the white space after add hello. to each lines.

My code as below, H开发者_开发百科ow to remove the white space after add hello. to each lines.

#!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"

Output:

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>


One way would be to remove the leading white space from the data itself as:

__DATA__  
Member Information 
id = 0  
name = "tom" 
age = "20"

Other way would be to remove the leading white space from $line before you print:

Just add this before the print:

$line=~s/^\s+//;


If every line has 4 leading spaces, you can use:

substr $line, 0, 4, "";


I would remove the string and add hello in one go

while ( <DATA> ) {
    s/ ^ \s+ /Hello./x ;
    print ;
}

^ = anchor at start of string

\s+ = one or more space

/x = allow for extra space in the regex for clarity

or more verbosely

while(my $line = <$fh>)
{
    $line =~ s/ ^ \s+ /Hello./x ;
    print $line ;
}
0

精彩评论

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