[英]I need to refactor an ancient piece of Perl code with defined(@array) and defined(%hash)
我正在運行一個古老版本的 Movable Type,它對我來說很好用。 但是,我開始收到以下服務器錯誤:
defined(@array) is deprecated at /home/public_html/cgi-bin/mt/extlib/Locale/Maketext.pm line 623.
defined(%hash) is deprecated at /home/public_html/cgi-bin/mt/extlib/Locale/Maketext.pm line 623.
我找到了有問題的行:
if defined(%{$module . "::Lexicon"}) or defined(@{$module . "::ISA"});
以下是重構這條線的正確方法嗎?
if %{$module . "::Lexicon"} or @{$module . "::ISA"};
如果是這樣,為什么? 如果沒有,為什么不呢? 我想更好地了解defined(@array)
和defined(%hash)
發生了什么。
更新:我也在CGI.pm
第 367 行發現了一個類似的問題:
if (defined(@QUERY_PARAM) && !defined($initializer)) {
我將其重寫如下,但我仍然不確定它是否正確:
if (@QUERY_PARAM && $initializer) {
我可以看到@QUERY_PARAM
可以證實它的存在,但我可能不會設置第二個條件,即$initializer
不存在的,我不太清楚如何做到這一點。
$ perl -w -Mdiagnostics -e 'print defined(@array)'
Can't use 'defined(@array)' (Maybe you should just omit the defined()?) at -e
line 1 (#1)
(F) defined() is not useful on arrays because it
checks for an undefined scalar value. If you want to see if the
array is empty, just use if (@array) { # not empty } for example.
Uncaught exception from user code:
Can't use 'defined(@array)' (Maybe you should just omit the defined()?) at -e line 1.
$ [perldoc -f defined]
( http://metacpan.org/pod/perlfunc#defined )
...
Use of "defined" on aggregates (hashes and arrays) is no longer
supported. It used to report whether memory for that aggregate
had ever been allocated. You should instead use a simple test
for size:
if (@an_array) { print "has array elements\n" }
if (%a_hash) { print "has hash members\n" }
defined(@array)
結構從來沒有做用戶期望它做的事情,而且它實際做的事情沒有那么有用,所以它從語言中刪除(並在您使用的 Perl 版本中棄用)。 正如診斷和文檔所建議的那樣,修復它的方法是在布爾上下文中僅使用@array
而不是defined(@array)
。
正如 mob 所說,解決方案只是執行if (@array)...
或if (%hash)...
。
但是,對於任何好奇的人,您可以檢查符號表以查看該變量是否曾經被自動激活。 然而,更多的是,(幾乎)沒有理由這樣做。 它只會告訴您您是否是使用該變量的第一行代碼。 這是無用的 5 個 9。
但是對於第 6 位有效數字,您可以按照以下方法進行操作。 我什至知道的唯一用例是在Carp
,它檢查調用命名空間中的某些變量,而不會在過程中污染它。
這僅適用於全局的、非詞法的變量。 全局未聲明, use vars qw//
和our()
。 詞法是my()
和state()
。 符號表是包含包中所有符號名稱的特殊散列。
use Data::Dump qw/pp/;
pp \ %Z::;
{}
$Z::foo = "foo scalar";
pp \ %Z::;
do {
my $a = { foo => *Z::foo };
$a->{foo} = \"foo scalar";
$a;
}
print "symbol exists\n" if exists $Z::{foo};
symbol exists
print "symbol and array exists\n" if $Z::{foo} and defined *{$Z::{foo}}{ARRAY};
pp \ %Z::;
do {
my $a = { foo => *Z::foo };
$a->{foo} = \"foo scalar";
$a;
}
print "symbol and array does not exist\n" unless $Z::{foo} and defined *{$Z::{foo}}{ARRAY};
symbol and array does not exist
pp \ %Z::;
do {
my $a = { foo => *Z::foo };
$a->{foo} = \"foo scalar";
$a;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.