从文件加载时,Perl错误地拆分字符串

时间:2017-08-25 20:38:16

标签: string windows perl file

我可能错过了一些东西,因为我今天开始使用Perl,所以请原谅我这是非常明显的事情。

我想从文件中加载字符串,然后逐个字符地拆分它。 我做了以下

use strict;    
open my $fh, "<", "hello.txt" || die "Cannot open file!\n";

my $data = do { local $/ ; <$fh>};
print $data;

print  join( ', ',(split( //, $data)));

close $fh;

当我执行此脚本时,第一个print语句打印$ data没有问题,但是第二个print只打印连接字符串。

Hello, world!
, 

我在带有Strawberry Perl的Windows 7机器上运行,目前我无法访问Unix / Linux机器,因此我无法在其他地方进行测试。

1 个答案:

答案 0 :(得分:5)

这可能是回车符"\r"的问题 - Windows行结尾为\r\n,而\r本身会移回行首,覆盖什么你已经写过了。

您可以chomp $data首先删除行结尾,但这只会删除最后一行结尾。

通过应用\r\n IO层,您还可以在读取文件时将Perl转换为Windows \n行结尾为Unix :crlf行结尾:

open my $fh, "<:crlf", "hello.txt" or die "Cannot open file!\n";

(请注意,由于运营商优先规则,它必须是open … or die …open(…) || die …,而不是open … || die …。)