2011-05-30 67 views
15

我有一些代码,看起来像如何打印变量在Perl

my ($ids,$nIds); 
while (<myFile>){ 
    chomp; 
    $ids.= $_ . " "; 
    $nIds++; 
} 

这应该串连每一行中我myFilenIds应该是我的行数。如何打印我的$ids$nIds?我试过print $ids,但Perl抱怨。

my ($ids, $nIds) 

是一个列表,对吗?有两个元素?

+8

-1“Perl的抱怨”,而不是共享实际的消息的文本。 – tadmc 2011-05-31 03:41:08

回答

16
print "Number of lines: $nids\n"; 
print "Content: $ids\n"; 

Perl是怎么抱怨的? print $ids应该可以工作,尽管你可能最后需要一个换行符,或者明确地使用print,或者使用say-l/$\

如果你想在一个字符串内插一个变量,并有东西后立即那会看起来像变量的一部分,但不是在{}围住变量名:

print "foo${ids}bar"; 
+0

嘿,只是想知道,如果我想要在变量后立即打印什么,即我想实现这个:'print“Content:$ idsHeyIamhere”' – Juto 2013-08-12 09:30:11

+0

@Juto:加到我的答案 – ysth 2013-10-21 15:18:38

7
如何打印出我的$ ids和$ nIds?
print "$ids\n"; 
print "$nIds\n"; 
我想简单地 print $ids,但Perl的抱怨。

抱怨什么?未初始化的值?也许你的循环从未输入,因为打开文件时出错。请务必检查open是否返回错误,并确保您使用的是use strict; use warnings;

my ($ids, $nIds)是一个列表,对吗?有两个元素?

这是一个(非常特殊的)函数调用。 $ids,$nIds是一个包含两个元素的列表。

9

你应该总是在提问时包括所有相关的代码。在这种情况下,打印语句是问题的中心。印刷声明可能是最重要的信息。第二个最重要的信息是错误,你也没有包括这个错误。下一次,包括这两个。

print $ids应该是一个相当硬的声明搞乱了,但它是可能的。可能的原因:

  1. $ids未定义。给出警告undefined value in print
  2. $ids超出范围。用use strict,给出了致命的警告Global variable $ids needs explicit package name,否则从上面发出未定义的 警告。
  3. 您在线路末尾忘记了一个分号结尾的 。
  4. 你试图做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. 
+0

Are you sure?当我说'$ array [500] =“yada”'我得到'scalar @ array'的值501。 – BarneySchmale 2016-08-16 17:23:26