Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在perl中用逗号替换空格_Perl_File Handling - Fatal编程技术网

如何在perl中用逗号替换空格

如何在perl中用逗号替换空格,perl,file-handling,Perl,File Handling,我的perl程序 open(my $inFileHandle, '<', '/home/Ram/Desktop/TCR/input_file_TCR_05_0.txt') or die " $!"; open(my $outFileHandle, '>', '/home/Ram/Desktop/TCR/input_file_TCR_05_0_ram.txt') or die " $!"; while (my $line = <$inFileHandle>) {

我的perl程序

open(my $inFileHandle, '<', '/home/Ram/Desktop/TCR/input_file_TCR_05_0.txt') or die " $!";
open(my $outFileHandle, '>', '/home/Ram/Desktop/TCR/input_file_TCR_05_0_ram.txt') or die " $!";

while (my $line = <$inFileHandle>)
{
    $line =~s/05 +/,/g;   
    print $outFileHandle $line;

}

close $inFileHandle;
close $outFileHandle;`
但我想像这样出去

05,0,1–2,2,UN,praveen kumar
05,0,3,1,UN, hari krishna
05,0,4,1,UN,manju nath
05,0,5–20,16,UN,sateesh kumar

请告诉我实现我的输出需要做哪些更改。你的建议会很有价值

我猜你的实际程序不是做
s/05+/,/
,而是做
s//,/
或者
s/+/,/

如果只想将某些空格更改为
,则正则表达式替换并不理想;相反,我会:

while (my $line = <$inFileHandle>)
{
    print join ',', split / /, $line, 6;
}
while(我的$line=)
{
打印联接“,”,拆分/,$line,6;
}

不知道您的程序的输入是什么,但我认为您现在收到的输出是输入(当然,如果您可以接受
sed


您只需使用稍微复杂一点的正则表达式来匹配firstname/lastname对,并对之前的所有内容运行替换,然后连接结果以进行打印

#!/usr/bin/perl 

while (<>){
        chomp;
        if (/(.*?\s+)(\S+\s+\S+)$/){
                ($a,$b)=($1,$2);
                $a =~ s/\s+/,/g;
                $_ = $a.$b;
        }
        print $_."\n";
}
#/usr/bin/perl
而(){
咀嚼;
如果(/(.*?\s+)(\s+\s+\s+)$/){
($a,$b)=($1,$2);
$a=~s/\s+/,/g;
$\u=$a.$b;
}
打印$。“\n”;
}
$ cat test
05,0,1–2,2,UN,praveen,kumar
05,0,3,1,UN, hari,krishna
05,0,4,1,UN,manju,nath
05,0,5–20,16,UN,sateesh,kumar

$ sed -r 's/(.*),(.*)$/\1 \2/' test
05,0,1–2,2,UN,praveen kumar
05,0,3,1,UN, hari krishna
05,0,4,1,UN,manju nath
05,0,5–20,16,UN,sateesh kumar
#!/usr/bin/perl 

while (<>){
        chomp;
        if (/(.*?\s+)(\S+\s+\S+)$/){
                ($a,$b)=($1,$2);
                $a =~ s/\s+/,/g;
                $_ = $a.$b;
        }
        print $_."\n";
}