0

我有如下配置文件,

 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。任何机构都可以提出任何其他建议吗?谢谢您的帮助。

4

2 回答 2

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};

请注意,这允许等号周围有空格。您可以轻松地修改它以在行首和行尾也允许它。

于 2013-07-25T12:46:28.507 回答
2

你可以使用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";
于 2013-07-25T13:26:21.177 回答