热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

关于Perl中split的用法的更多说明-MoreclarificationabouttheusageofsplitinPerl

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 个解决方案

#1


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.

正在做你认为的事情。

#2


When you're assigning $entryN, define a default value:

当您分配$ entryN时,请定义默认值:

$entry1[$counter] = $hold_csv[0] || '';

same for other @entry

其他@entry也一样

I think there is a typo in while($map_in) { it should be while (@map_in) {.

我认为有一个拼写错误($ map_in){它应该是while(@map_in){。


推荐阅读
author-avatar
书友32368660
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有