我对 Perl 编程非常陌生,对编程世界也很陌生。
我正在尝试编写一个程序来打开一个 CSV 文件,将它读入一个数组,然后使用 split() 解析它。
CSV 文件的每个字段都包含四项内容:
$full_name, $user_name, $password, $con_password
我的问题是我需要访问每一行的第二个元素 (user_name)。然后我需要将所有用户名放入一个数组中,以便我可以使用它。
我已经完成了拆分,但我不知道如何确保获得每行的第二个元素。
这就是我所拥有的:
#!/usr/bin/perl
use CGI qw(:standard);
use strict;
use warnings;
print "Content-type: text/html\n\n";
my $file = '/home/2014/amosqu/public_html/cgi-bin/Members.csv';
open(my $csv, '>>', $file) or die "Could not open '$file' $!";
#i get these values from a form in an html file
my $full_name = param('full_name');
my $user_name = param('user_name');
my $password = param('password');
my $con_password = param('con_password');
#array to store user names
my @users = ();
while(my $lines = <$csv>) {
chomp $lines;
my @fields = split(/,/, $lines);
}
#access second element and put into @users ???
最佳答案
你需要写这样的东西......
my @list;
open (my $csv, '<', $file) || die "cant open";
foreach (<$csv>) {
chomp;
my @fields = split(/\,/);
push @list, $fields[1];
}
在您的代码中,文件被打开以追加而不是读取。
关于arrays - 从 CSV 文件读入数组,解析数组,访问每行的第二个元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27242628/