在Perl文件句柄混乱 [英] confusing filehandle in perl
问题描述
一直在玩下面的脚本,但还是没能理解其背后的文件句柄形式两个不同的种的含义。任何有识之士将是巨大的AP preciated。
Have been playing with the following script but still couldn't understand the meaning behind the two different "kinds" of filehandle forms. Any insight will be hugely appreciated.
#! usr/bin/perl
use warnings;
use strict;
open (FH, "example.txt") or die $!;
while (<FH>) {
my @line = split (/\t/, $_); {
print "@line","\n";
}
}
的输出为预期: @line
数组包含行1,2,3 ...元素从 example.txt文件
。当有人告诉我,开放(FH,example.txt文件)
并不像好开(我$跳频,'&LT;','例如.TXT')
,我改变了它,但随后出现的混乱。
The output is as expected: @line
array contains elements from line 1,2,3 ... from example.txt
. As I was told that open (FH, example.txt)
is not as good as open (my $fh, '<', 'example.txt')
, I changed it but then confusion arose.
从我发现, $ FH
是标
并包含所有的信息例如.TXT
。当我分配一个数组 $ FH
,存储在 example.txt文件
每一行作为数组中组件的数组。然而,当我试图将组件进一步分为多个组件,我得到了错误/警告信息未初始化值
。下面是示出错误/警告消息的实际脚本。
From what I found, $fh
is scalar
and contains ALL info in example.txt
. When I assigned an array to $fh
, the array stored each line in example.txt
as a component in the array. However, when I tried to further split the component into "more components", I got the error/warning message "use of uninitialized value
". Below is the actual script that shows the error/warning message.
open (my $fh, '<', 'example.txt') or die $!;
foreach ($fh) {
my @line = <$fh>;
my $count = 0;
for $count (0..$#line) {
my @line2 = split /\t/, $line[$count];
print "@line2";
print "$line2[0]";
}
}
打印@ 2号线
显示预期产量,但打印$ 2号线[0]
调用错误/警告消息。我想如果 @ 2号线
是一个真正的数组, $ 2号线[0]
应该没问题。但是,为什么未初始化值??
print "@line2"
shows the expected output but print "$line2[0]"
invokes the error/warning message. I thought if @line2
is a true array, $line2[0]
should be okay. But why "uninitialized value" ??
任何帮助将AP preciated。非常感谢你。
Any help will be appreciated. Thank you very much.
新增 -
以下是实际的脚本(我重新运行它,并警告在那里)
Added - the following is the "actual" script (I re-ran it and the warning was there)
#! usr/bin/perl
use warnings;
use strict;
open (my $fh, '<', 'example.txt') or die $!;
foreach ($fh) {
my @line = <$fh>;
print "$line[1]";
my $count = 0;
for my $count (0..$#line) {
my @line2 = split /\t/, $line[$count];
print "@line2";
#my $line2_count = $#line2;
#print $line2_count;
print "$line2[3]";
}
}
该警告仍然未初始化值$ 2号线[3]在filename.pl线15条,与LT字符串; $ FH&GT; 3号线
。
推荐答案
在你的第二个例子,你正在阅读在列表上下文文件句柄,我认为这是你的问题的根源。
In your second example, you are reading the filehandle in a list context, which I think is the root of your problem.
my $line = <$fh>;
读取从文件句柄一行。
Reads one line from the filehandle.
my @lines = <$fh>;
读取所有的文件。
你以前的例子,由于
Reads all the file. Your former example, thanks to the
while (<FH>) {
有效地做尚属首例。
Is effectively doing the first case.
但在第二个例子中,你正在做的第二件事。
But in the second example, you are doing the second thing.
这篇关于在Perl文件句柄混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!