我的配置文件如下,
Name=test
Password = test
我需要读取数据文件并将其设置为map,以便我可以设置数据。 现在,我已经尝试过这种方式,
$path_to_file ="C:\\Perl\\bin\\data.txt";
open(FILE, $path_to_file) or die("Unable to open file");
@data = <FILE>;
close(FILE);
print "data is ",$data[0],"\n";
但我没有得到理想的输出。我得到输出为Name = test。 任何机构都可以提出任何其他建议吗?谢谢你的帮助。
答案 0 :(得分:4)
尝试这样的事情:
# open FILE as usual
my %map;
while (my $line = <FILE>) {
# get rid of the line terminator
chomp $line;
# skip malformed lines. for something important you'd print an error instead
next unless $line =~ /^(.*?)\s*=\s*(.*?)$/;
# insert into %map
$map{$1} = $2;
}
# %map now has your key => value mapping
say "My name is: ", $map{Name};
请注意,这允许等号周围的空白区域。您可以轻松地修改它以在行的开头和结尾处允许它。
答案 1 :(得分:1)
您可以使用Tie::File::AsHash。
use Tie::File::AsHash;
tie my %map, Tie::File::AsHash::, $path_to_file, split => qr/\s*=\s*/, join => '='
or die "failed to open: $!";
$map{Password} = 'swordfish'; # this actually changes the file!
print 'The password is ', $map{Password}, "\n";