【问题标题】:perl: concatenate lines into a single stringperl:将行连接成一个字符串
【发布时间】:2015-11-12 00:34:50
【问题描述】:

我有一个看起来像这样的文件:

hellothisisline1
andthisisline2hi
yepthisistheline

我想将这些行连接成一个字符串

hellothisisline1andthisisline2hiyepthisistheline

print "Input file name \n";
open (FILE, <>);
$string = "";
while($line = <FILE>) {
   $string = $string . "" . $line;
}
print "$string \n";

但这似乎不起作用,输出是原始格式的文件。

【问题讨论】:

标签: perl


【解决方案1】:

如果您使用 Perl5,chomp 可用于删除字符串末尾的换行符。

print "Input file name \n";
open (FILE, <>);
$string = ""; 
while($line = <FILE>) {
    chomp($line); # add this line
    $string = $string . "" . $line;
}
print "$string \n";

【讨论】:

    【解决方案2】:

    使用chomp 函数删除换行符。 该地图将chomp 函数应用于每一行,并且连接将所有行粘在一起。

    print "Input file name \n";
    open (FILE, <>);
    $string = join('', map { chomp; $_ } <FILE>);
    print "$string \n";
    

    也可以在 slurping 文件后使用 "tr" 删除换行符:

    print "Input file name \n";
    open (FILE, <>);
    ($string = join('', <FILE>)) =~ tr/\n//d;
    print "$string \n";
    

    【讨论】:

    • 是的,一般来说,但是 chomp 需要一些东西来处理。地图提供了从 读取到 $_ 的上下文,chomp 可以处理。你可以读入一个单独的临时数组,如果你愿意的话,可以把它吃掉……只是更丑。
    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 2013-05-15
    • 2012-02-02
    • 2018-12-18
    • 2015-09-18
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多