这里有很多与我类似的场景的解决方案,但我无法使它们适应我的特定需求。
我有一个文件,其中每一行都包含一个名称和一个数字列表。示例行:
布拉德利·琼斯,65,69,71,72,75,71,65,74,69,71,72,75,71,65,65,69,71,72,75,71,65,74,69, 71,72,75
如何将每个逗号分隔的数据添加到数组的元素中? 这些行可能只有几个数字,也可能有更多数字。我需要知道第一个元素包含一个名称,后面的每个元素都包含一个数字,无论找到多少个。
像这样的东西怎么样
open my $fh, '<', 'input.txt';
while (<$fh>) {
chomp; # removes the newline at end of the string
my @array = split /,/; # creates the array from the line
my $name = shift @array; # removes the first element and puts it into $name
# validate
say 'Number in first column' if $name =~ /\d/;
say 'Non-number in remaining columns' if grep { /\D/ } @array;
# do something with @array
}
它将每一行变成一个数组,然后从数组中取出第一个元素并将其放入
$name
。在读取下一行之前使用 @array
执行某些操作。有一些非常基本的验证,这实际上取决于您的用例。