作者:书友32368660 | 来源:互联网 | 2023-10-16 17:45
Ihavethisfollowinginputfile:我有以下输入文件:test.csvdone_cfg,,,,port<0>,clk_in,subcktA,ins
I have this following input file:
我有以下输入文件:
test.csv
done_cfg,,,,
port<0>,clk_in,subcktA,instA,
port<1>,,,,
I want to store the elements of each CSV column into an array, but I always get error when I try to fetch those "null" elements in the csv when I run the script. Here's my code:
我想将每个CSV列的元素存储到一个数组中,但是当我在运行脚本时尝试在csv中获取那些“null”元素时,我总是会收到错误。这是我的代码:
# ... assuming file was correctly opened and stored into
# ... a variable named $map_in
my $counter = 0;
while($map_in){
chomp;
@hold_csv = split(',',$_);
$entry1[$counter] = $hold_csv[0];
$entry2[$counter] = $hold_csv[1];
$entry3[$counter] = $hold_csv[2];
$entry4[$counter] = $hold_csv[3];
$counter++;
}
print "$entry1[0]\n$entry2[0]\n$entry3[0]\n$entry3[0]"; #test printing
I always got use of uninitialized value
error whenever i fetch empty CSV cells Can you help me locate the error in my code ('cause I know I have somewhat missed something on my code)?
每当我获取空的CSV单元时,我总是使用未初始化的值错误你能帮我找到我的代码中的错误(因为我知道我的代码有些遗漏了吗?)
Thanks.
2 个解决方案
This looks like CSV. So the tool for the job is really Text::CSV
.
这看起来像CSV。因此,该工作的工具实际上是Text :: CSV。
I will also suggest - having 4 different arrays with numbered names says to me that you're probably wanting a multi-dimensional data structure in the first place.
我还建议 - 有4个带编号名称的不同数组对我说,你可能首先想要一个多维数据结构。
So I'd be doing something like:
所以我会做的事情如下:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Text::CSV;
my $csv = Text::CSV->new( { binary => 1 } );
open( my $input, "<", "input.csv" ) or die $!;
my @results;
while ( my $row = $csv->getline($input) ) {
push ( @results, \@$row );
}
print join ( ",", @{$results[0]} ),"\n";
print Dumper \@results;
close($input);
If you really want separate arrays, I'd suggest naming them something different, but you could do it like this:
如果你真的想要单独的数组,我建议给它们命名不同的东西,但你可以这样做:
push ( @array1, $$row[0] ); #note - double $, because we dereference
I will note - there's an error in your code - I doubt:
我会注意到 - 你的代码中有错误 - 我怀疑:
while($map_in){
is doing what you think it is.
正在做你认为的事情。