[英]Not able to access array even though it is declared outside while loop in perl
I'm trying to read a CVS file to fetch 2nd and 3rd column in it. 我正在尝试读取CVS文件以获取其中的第二列和第三列。 I have declared empty array
@x_ax
and @dat
outside the while loop. 我在while循环外声明了空数组
@x_ax
和@dat
。 I'm using @x_ax
to store 2nd column and @dat
to store 3rd column of CSV file. 我使用
@x_ax
存储第二列和@dat
存储CSV文件的第三列。 Contents of @x_ax
and @dat
is getting printed inside while loop only but not outside. @x_ax
和@dat
内容仅在while循环内部打印,而不在外部打印。
below is my code and output. 下面是我的代码和输出。
#!/usr/bin/perl
use strict;
my @arr=();
my @x_ax=();
my @dat=();
open(FH,"new1.csv") || die "Not able to open new1.csv file $!\n";
while( my $line=<FH>)
{
if ($line =~ m/Time/)
{
exit 0;
}
else
{
@arr=split(/,/,$line);
#print "@arr[1]\n";
push(@x_ax,$arr[1]);
print "@x_ax \n";
push(@dat,$arr[2]);
}
}
print @x_ax;
print "$#x_ax and $#dat \n";
[root@localhost perl_practice]# perl test.pl
AX_1
AX_1 SAL
AX_1 SAL BAS
AX_1 SAL BAS OPT
AX_1 SAL BAS OPT LES
AX_1 SAL BAS OPT LES MSS
below is my CSV file contents 以下是我的CSV文件内容
17:00:01,AX_1,0,0,0,0,0
17:00:01,SAL,0,0,0,0,0
17:00:01,BAS,0,0,0,0,0
16:55:02,OPT,0,0,0,0,0
17:00:01,LES,0,0,0,0,0
16:55:02,MSS,0,0,0,0,0
Time,info,dat1,dat2,dat3,dat4,dat5
How to access @x_ax
and @dat
outside while loop?. 如何在while循环之外访问
@x_ax
和@dat
?
It's not that you can't access them outside the array, the problem is that your program never reaches those last print statements. 并不是说您不能在数组之外访问它们,而是问题在于您的程序永远不会到达最后的打印语句。 As you have:
如您所愿:
if ($line =~ m/Time/)
{
exit 0;
}
And the last line of your CSV has Time
, the program exits before reaching the final print. CSV的最后一行具有
Time
,程序将在到达最终打印之前退出。
If you meant the if statement to stop the loop only, you can use last
. 如果您要让if语句仅停止循环,则可以使用
last
。 Then the else
itself is not needed as well, becoming a more common loop idiom: 然后,
else
本身也不再需要,成为更常见的循环习惯用法:
while( my $line=<FH>)
{
last if ($line =~ m/Time/);
@arr = split(/,/,$line);
#print "@arr[1]\n";
push(@x_ax,$arr[1]);
print "@x_ax \n";
push(@dat,$arr[2]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.