使用 Perl,如何用逗号替换换行符? [英] Using Perl, how can I replace newlines with commas?

查看:75
本文介绍了使用 Perl,如何用逗号替换换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我放弃了 sed,我听说它在 Perl 中更好.

I gave up on sed and I've heard it is better in Perl.

我想要一个可以从 'unix' 命令行调用的脚本,并将输入文件中的 DOS 行结尾 CRLF 转换为输出文件中的逗号:

I would like a script that can be called from the 'unix' command line and converts DOS line endings CRLF from the input file and replaces them with commas in the output file:

喜欢

myconvert infile > outfile

infile 所在的位置:

where infile was:

1
2
3

并且会导致输出文件:

1,2,3

我更喜欢更明确的代码,在最短的可能解决方案"上有一些最少的评论,所以我可以从中学习,我没有 perl 经验.

I would prefer more explicit code with some minimal comments over "the shortest possible solution", so I can learn from it, I have no perl experience.

推荐答案

use strict;
use warnings;

my $infile = $ARGV[0] or die "$0 Usage:\n\t$0 <input file>\n\n";
open(my $in_fh , '<' , $infile) or die "$0 Error: Couldn't open $infile for reading: $!\n";
my $file_contents;
{

    local $/; # slurp in the entire file. Limit change to $/ to enclosing block.
    $file_contents = <$in_fh>

}
close($in_fh) or die "$0 Error: Couldn't close $infile after reading: $!\n";

# change DOS line endings to commas
$file_contents =~ s/\r\n/,/g;
$file_contents =~ s/,$//; # get rid of last comma

# finally output the resulting string to STDOUT
print $file_contents . "\n";

您的问题文本和示例输出不一致.如果您将所有行结尾都转换为逗号,那么从最后一行结尾开始,最后会有一个额外的逗号.但是您的示例仅显示数字之间的逗号.我假设您希望代码输出与您的示例相匹配,并且问题文本不正确,但是如果您想要最后一个逗号,只需删除带有注释去掉最后一个逗号"的行.

Your question text and example output were not consistent. If you're converting all line endings to commas, you will end up with an extra comma at the end, from the last line ending. But you example shows only commas between the numbers. I assumed you wanted the code output to match your example and that the question text was incorrect, however if you want the last comma just remove the line with the comment "get rid of last comma".

如果有任何命令不清楚,http://perldoc.perl.org/ 是你的朋友(右上角有一个搜索框).

If any command is not clear, http://perldoc.perl.org/ is your friend (there is a search box at the top right corner).

这篇关于使用 Perl,如何用逗号替换换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆