2
#!C:\Perl\bin\perl.exe 
use strict; 
use warnings; 
use Data::Dumper;  

my $fh = \*DATA;  

while(my $line = <$fh>)
{

    $line =~ s/ ^/male /x ;
    print $line ;
}

__DATA__  
1 0104 Mike Lee 2:01:48

output

male 1 0104 Mike Lee 2:01:48

Then I tried to insert male after the racenumber(0104), I replaced the code with style.

$line =~ s/ ^\d+\s+\d+\s+ /male /x ; # but failed

Acturally I want the output. thank you.

1 0104 male Mike Lee 2:01:48
toolic
  • 57,801
  • 17
  • 75
  • 117
Nano HE
  • 9,109
  • 31
  • 97
  • 137

2 Answers2

1

Capture the beginning of the string into $1:

use strict;  
use warnings;  
 
my $fh = \*DATA;   
 
while(my $line = <$fh>) 
{ 
 
    $line =~ s/ ^(\d+\s+\d+\s+) /${1}male /x ;
    print $line ; 
} 
 
__DATA__   
1 0104 Mike Lee 2:01:48

Outputs:

1 0104 male Mike Lee 2:01:48

$1 is a special variable described in perlreref.

toolic
  • 57,801
  • 17
  • 75
  • 117
1

safe method is to

chomp $line;
@tmp = split / /, $line;

then concatenate in any way you want

jing
  • 9
  • 2