我有一些代码看起来像这样
my ($ids,$nIds);
while (<myFile>){
chomp;
$ids.= $_ . " ";
$nIds++;
}
这应该是将我的myFile
中的每一行连接起来,nIds
应该是我的行数。我如何打印出我的$ids
和$nIds
?我尝试了简单地使用
print $ids
,但 Perl 抱怨了。my ($ids, $nIds)
是一个列表,对吗?有两个元素?
我有一些代码看起来像这样
my ($ids,$nIds);
while (<myFile>){
chomp;
$ids.= $_ . " ";
$nIds++;
}
这应该是将我的myFile
中的每一行连接起来,nIds
应该是我的行数。我如何打印出我的$ids
和$nIds
?print $ids
,但 Perl 抱怨了。my ($ids, $nIds)
是一个列表,对吗?有两个元素?
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.
$array[500] = "yada"
时,scalar @array
的值会变成501。 - BarneySchmaleprint "$ids\n";
print "$nIds\n";