gpt4 book ai didi

perl - 如何针对子例程使用 "tied"?

转载 作者:行者123 更新时间:2023-12-03 15:03:56 26 4
gpt4 key购买 nike

我的脚本似乎有一个小问题,我需要对脚本中较早的子例程调用“tied”,以便我可以访问与哈希绑定(bind)的对象相关的函数到。问题是,当我运行脚本时,它返回错误“无法在 cbc_encrypt_test.pl 第 30 行的未受祝福的引用上调用方法“SetWriteMode””。起初我不知道它在说什么,我认为问题是由于我使用引用来指向首先返回哈希引用的子例程。因为据我了解,在这种情况下“config_file =\%cfg”。在查看了有关 perlref 的 perldoc 后,我仍然迷失了方向。我很好地阅读了该文档,但没有看到任何有关以我需要的方式引用子例程的内容。

这是迄今为止的整个脚本。

#!/usr/bin/perl

use strict;

use warnings;

use Term::ANSIColor;

use Config::IniFiles;

use Crypt::CBC;

start_script();



sub start_script {

system ("clear");

encrypt_password();

} # end start_script

sub config_file {

my $cfg_file = 'settings.ini';

my %cfg;

tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

return \%cfg;

} # end config_file

sub encrypt_password {
my $password = config_file()->{ESX}{password};
my $cipher = Crypt::CBC->new( -key => 'EF1FAD9B87F8365B242669E624FEB36CDBCCFEE0096CC45DDDCF6F5995E83F61',
-cipher => 'Rijndael'
);
my $encrypted_password = $cipher->encrypt_hex("$password");
chomp $encrypted_password;
config_file()->{ESX}{password} = $encrypted_password;
tied config_file()->SetWriteMode(0666);
tied config_file()->RewriteConfig();
return $encrypted_password;
} # end encrypt_password

最佳答案

tied 需要用于绑定(bind)变量。如果你有这样一个变量的引用,你可以这样做:

tied( %{ config_file() } )

但是在你的代码中,每次调用 config_file 都会创建一个新的绑定(bind)哈希,并且你在前一个哈希的绑定(bind)对象上调用的方法不会有任何好处,所以你需要确保 config_file() 仅是调用一次(或让它在内部记住其结果)。

关于perl - 如何针对子例程使用 "tied"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4505349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com