从CSV或配置文件读取数组数据,而不是在Perl脚本中读取__data__



我是Perl的新手,最近学习了一个Perl脚本,它使用@flatfiledata = <DATA>;__DATA__;(底部Perl脚本中的内联数据语句(读取数组数据

数据在底部的脚本中如下所示:

__DATA__;
Arrays
@cab_method::Concentration::Dilution
@cab04_cartypes::XXXX Dye::Gag XXXXXX::LuciXXXX::Firefly LuciXXXX::Renilla LucifXXXX
__END__;

我想将这些数据保存在配置文件中,可以是csv,也可以是制表符分隔的文件然后将该数据读取到阵列中。

下面是从底部的__DATA__语句中读取该数据的当前子程序。

# read data from __DATA__ section at end of program and put data into @flatfiledata array
@flatfiledata = <DATA>;
&ReadArraysAndHashes;
sub ReadArraysAndHashes {
foreach $line (@flatfiledata) {
chomp $line;
# ok, some weird newline chars have ended up in data section, so...
$line =~ s/r|n//g;
# skip any lines that do not contain at least one '::'
# (probably blank lines or comments)
unless ( $line =~ /::/ ) { next }
#split all the elements in the line into an array
my @elements = split( /::/, $line );
# The first element is the key;
my $key = shift(@elements);
# if the key starts with a '@,' you have an array;
# if it starts with a '%,' it is a hash
# either way, delete the symbol from the key
$key =~ s/^(.)//;
my $array_or_hash = $1;
# create a hash of hashes
if ( $array_or_hash eq '@' ) {
$clrdata{array}{$key} = @elements;
@{$key} = @{ $clrdata{array}{$key} };
}
elsif ( $array_or_hash eq '%' ) {
if ( $#elements % 2 != 1 ) {
print "odd number of elements for $keyn";
}
my %hash = @elements;
$clrdata{hash}{$key} = %hash;
}
}
}

__DATA__;
Arrays
@cab_method::Concentration::Dilution
@cab04_cartypes::XXXX Dye::Gag XXXXXX::LuciXXXX::Firefly LuciXXXX::Renilla LucifXXXX
__END__;

基本答案

DATA只是一个文件句柄,因此可以很容易地用任何其他文件句柄替换它。

open my $config_fh, '<', 'some_config_file'
or die "Can't open config file: $!n";
@flatfiledata = <$config_fh>;

更多提示

我们从几十年的计算机编程中学到的一件事是,子程序访问全局变量是个坏主意。子程序使用的所有数据都应该作为参数传递给子程序,或者在子程序中创建。ReadArraysAndHashes()子例程使用全局@flatfiledata变量。您应该将数据传递到子程序中:

open my $config_fh, '<', 'some_config_file'
or die "Can't open config file: $!n";
@flatfiledata = <$config_fh>;
ReadArraysAndHashes(@flatfiledata);
# And in the subroutine
sub ReadArraysAndHashes {
my @flatfiledata = @_;
# Rest of the code is the same
...
}

或者您应该读取子程序中的数据:

ReadArraysAndHashes();
# And in the subroutine
sub ReadArraysAndHashes {
# We don't need the @flatfiledata array
# as we can read the filehandle directly
open my $config_fh, '<', 'some_config_file'
or die "Can't open config file: $!n";
foreach $line (<$config_fh>) {
# Your existing code
...
}
}

看起来您的子例程正在写入一个名为%clrdata的全局变量。这也是个坏主意。请考虑从子程序中返回该变量。

%clrdata = ReadArraysAndHashes();
# And in the subroutine
sub ReadArraysAndHashes {
# All of the code
...
return %clrdata;
}

额外读数

最后两个需要考虑的提示:

  • 使用我的来限制变量的范围
  • 不要使用与号来调用子例程

最新更新