我在維護舊的Perl代碼,並且需要在所有模塊中啓用嚴格的編譯指示。在傳遞文件句柄作爲模塊和子文件之間的引用時遇到問題。我們有一個公共模塊,負責打開以typeglob引用傳遞的日誌文件。在其他模塊中,運行函數首先從公共模塊調用open_log(),然後將該文件句柄傳遞給其他子類。如何在perl中將模塊和子程序之間的文件句柄作爲參考傳遞
這裏我寫了一個簡單的測試來模擬這種情況。
#!/usr/bin/perl -w
use strict;
$::STATUS_OK = 0;
$::STATUS_NOT_OK = 1;
sub print_header {
our $file_handle = @_;
print { $$file_handle } "#### HEADER ####"; # reference passing fails
}
sub print_text {
my ($file_handle, $text)= @_;
print_header(\$file_handle);
print { $$file_handle } $text;
}
sub open_file_handle {
my ($file_handle, $path, $name) = @_;
my $filename = $path."\\".$name;
unless (open ($$file_handle, ">".$filename)) {
print STDERR "Failed to open file_handle $filename for writing.\n";
return $::STATUS_NOT_OK;
}
print STDERR "File $filename was opened for writing successfully.\n";
return $::STATUS_OK;
}
my $gpath = "C:\\Temp";
my $gname = "mylogfile.log";
my $gfile_handle;
if (open_file_handle(\$gfile_handle, $gpath, $gname) == $::STATUS_OK) {
my $text = "BIG SUCCESS!!!\n";
print_text(\$gfile_handle, $text);
print STDERR $text;
} else {
print STDERR "EPIC FAIL!!!!!!!!\n";
}
主函數首先調用open_file_handle
並傳遞一個文件句柄參考print_text
功能。如果我註釋掉該行:
print_header(\$file_handle);
一切工作正常,但我需要通過從print_text
功能的文件句柄參考其他功能,這是行不通的。
我是Java開發人員,Perl的引用處理對我來說並不熟悉。我不想更改open_log()
子文件來返回一個文件句柄(現在它只返回狀態),因爲我有很多模塊和數百個代碼行要在所有地方進行此更改。
如何修復我的代碼以使其工作?
非常感謝。 「我們」和double-deref只是我的試驗,試圖找出我如何使它工作。實際的錯誤似乎是在參數分配周圍沒有放置括號。我只是想了解如何在perl中引用工程。這有助於我理解其中的一些。 – edufinn 2013-05-14 09:51:30
@edufinn我很高興它的工作原理。 :)你應該閱讀我鏈接的教程。引用是非常強大的,也是Perl的一個組成部分。但是,標量的有點奇怪。嘗試使用數據結構。使用Data :: Dumper來查看一些東西,你會更快地理解它。 – simbabque 2013-05-14 10:52:07