简体   繁体   English

如何将数据从CSV文件添加到Perl中的数组?

[英]How do I add data from a CSV file to an array in Perl?

I've searched and searched online, but nothing I do seems to work. 我已经在网上搜索和搜索了,但是我似乎无济于事。 I'm aware that this is a stupidly easy question, but I'm really stuck... 我知道这是一个非常简单的问题,但是我真的很棘手...

I had a directory of files, and saved the names of the directories to a CSV file. 我有一个文件目录,并将目录名保存到CSV文件中。 It's just made up of one column of data eg: 它仅由一列数据组成,例如:

100
101
102
103...

I used the following code to create the file (just in case its relevant): 我使用以下代码来创建文件(以防万一其相关):

open (my $fileh, '>', '/Users/Shared/serials.csv') or die "Could not open file!";
print $fileh `ls -1 $path`;
close $fileh;
print "Saved Serials!";

Now all I want is to read in the data in the file into an array, and then loop through each value to complete a task. 现在,我要做的就是将文件中的数据读入数组,然后遍历每个值以完成任务。 I can't figure out how to do this... 我不知道该怎么做...

Currently I am entering the numbers manually in the code into an array, like: 目前,我正在将代码中的数字手动输入到数组中,例如:

@ser_list = (100,101,102,103,...);

As stated above, I instead want to automatically write the file names (numbers) using the ls command line query and read them back into the script from there. 如上所述,我想使用ls命令行查询自动写文件名(数字),然后从那里读回脚本。 If there is a way of doing this without having to make a separate file of values that would be great. 如果有一种方法可以执行此操作,而不必制作一个单独的值文件,那就太好了。

The array is called @ser_list in the example, and from there I am reading the next $ser_num from the array and working with that in the loop. 在示例中,该数组称为@ser_list,从那里我从数组中读取下一个$ ser_num并在循环中使用它。

foreach $ser_num (@ser_list) {....}

Thank you all in advance for your help and patience! 预先感谢大家的帮助和耐心!

Don't use ls in a Perl program. 不要在Perl程序中使用ls You can use glob instead: 您可以改用glob

my @files = glob "$path/*";

If you need to work with the paths and filenames, check Path::Tiny . 如果需要使用路径和文件名,请检查Path :: Tiny

To read lines with paths into an array, just use 要读取具有路径的行到数组中,只需使用

open my $fh, '<', $filename or die $!;
chomp( my @paths = <$fh> );

See open , chomp , and readline for details. 有关详细信息,请参见openchompreadline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM