我的配置文件如下:
Name=test
Password = test
我需要读取数据文件并将其设置为地图,以便我可以设置数据。现在,我已经尝试过这种方式:
$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。
尝试这样的事情:
# 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};
请注意,这允许等号周围有空格。您可以轻松修改它以允许它出现在行的开头和结尾。
你可以使用 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";