处理字符串时的神秘'1'

时间:2013-06-27 18:39:44

标签: perl

我正在尝试处理每个字符的文件字符输入,但是有一些1出现,我不知道它们来自哪里。考虑这个例子:

档案input

First row;
Second row;

Third row;

档案test.pl

#!/usr/bin/perl

open FILE, "<input";

my @characters = split //, join //, <FILE>;
for( @characters ) {
  print $_;
}

close FILE;

我希望这个脚本只打印input的内容(虽然以一种非常复杂的方式 - 它只是一个例子)。但是,当我运行./test.pl时,我得到了这个输出:

First row;
1Second row;
1
1Third row;

现在我的问题是:这些1字符来自哪里?

2 个答案:

答案 0 :(得分:14)

join //应为join ''

{p> //$_ =~ m//的缩写,是匹配运算符。由于匹配成功,因此返回了真值1

split的特殊之处在于它将split /.../视为与split qr/.../类似的内容。)

顺便说一句,请始终使用use strict; use warnings;。它在这里很有用。

答案 1 :(得分:7)

根据join的perldoc:

Beware that unlike split, join doesn't take a pattern as its first argument.

在此处查看更多内容:http://perldoc.perl.org/functions/join.html

将第一个参数更改为文字空字符串""可以正常工作:

[ben@lappy ~]$ cat test.pl
#!/usr/bin/perl

open FILE, "<input";

my @characters = split //, join "", <FILE>;
for( @characters ) {
  print $_;
}

close FILE;

[ben@lappy ~]$ perl test.pl
First row;
Second row;

Third row;