在提出问题时,您应该始终包含所有相关代码。在这种情况下,打印语句是您问题的中心。打印语句可能是最重要的信息。第二个最重要的信息是错误,您也没有包括在内。下一次,包括这两个。
print $ids 应该是一个相当难以搞砸的声明,但这是可能的。可能的原因:
-
$ids 未定义。发出警告undefined value in print
-
$ids 超出范围。使用use
strict,给出致命警告Global
variable $ids needs explicit package
name,否则为未定义
来自上方的警告。
- 您忘记了末尾的分号
线。
- 你试图做
print $ids $nIds,
在这种情况下 perl 认为 $ids
应该是一个文件句柄,并且
你会收到一个错误,例如print to
unopened filehandle。
说明
1:不应该发生。如果您执行这样的操作(假设您没有使用strict),它可能会发生:
my $var;
while (<>) {
$Var .= $_;
}
print $var;
给出未定义值的警告,因为$Var 和$var 是两个不同的变量。
2:可能会发生,如果你这样做:
if ($something) {
my $var = "something happened!";
}
print $var;
my 在当前块内声明变量。在块之外,它超出了范围。
3:足够简单,常见的错误,容易修复。使用use warnings 更容易发现。
4:也是一个常见的错误。有多种方法可以在同一 print 语句中正确打印两个变量:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
最后,给你一些 perl 魔法技巧:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
将整个文件读入数组只适用于小文件,否则会占用大量内存。通常,逐行是首选。
变化:
-
print "@file" 相当于
$ids = join(' ',@file); print $ids;
-
$#file 将返回最后一个索引
在@file。由于数组通常从 0 开始,
$#file + 1 等价于 scalar @file。
你也可以这样做:
my $ids;
do {
local $/;
$ids = <$fh>;
}
通过暂时“关闭”$/,输入记录分隔符,即换行符,您将使<$fh> 返回整个文件。 <$fh> 真正做的是读取直到找到 $/,然后返回该字符串。请注意,这将保留 $ids 中的换行符。
逐行解决:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.