我有一些代码,看起来像如何打印变量在Perl
my ($ids,$nIds);
while (<myFile>){
chomp;
$ids.= $_ . " ";
$nIds++;
}
这应该串连每一行中我myFile
和nIds
应该是我的行数。如何打印我的$ids
和$nIds
?我试过print $ids
,但Perl抱怨。
my ($ids, $nIds)
是一个列表,对吗?有两个元素?
我有一些代码,看起来像如何打印变量在Perl
my ($ids,$nIds);
while (<myFile>){
chomp;
$ids.= $_ . " ";
$nIds++;
}
这应该串连每一行中我myFile
和nIds
应该是我的行数。如何打印我的$ids
和$nIds
?我试过print $ids
,但Perl抱怨。
my ($ids, $nIds)
是一个列表,对吗?有两个元素?
如何打印出我的$ ids和$ nIds?
print "$ids\n";
print "$nIds\n";
我想简单地
print $ids
,但Perl的抱怨。
抱怨什么?未初始化的值?也许你的循环从未输入,因为打开文件时出错。请务必检查open
是否返回错误,并确保您使用的是use strict; use warnings;
。
my ($ids, $nIds)
是一个列表,对吗?有两个元素?
这是一个(非常特殊的)函数调用。 $ids,$nIds
是一个包含两个元素的列表。
你应该总是在提问时包括所有相关的代码。在这种情况下,打印语句是问题的中心。印刷声明可能是最重要的信息。第二个最重要的信息是错误,你也没有包括这个错误。下一次,包括这两个。
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.
Are you sure?当我说'$ array [500] =“yada”'我得到'scalar @ array'的值501。 – BarneySchmale 2016-08-16 17:23:26
-1“Perl的抱怨”,而不是共享实际的消息的文本。 – tadmc 2011-05-31 03:41:08