我想將一個打開的文件句柄傳遞給一個方法,以便該方法可以寫入該文件。將文件句柄傳遞給Perl中的對象方法
但文件句柄似乎封閉在對象內部。
# open the file
open(MYOUTFILE, ">$dir_1/stories.txt") or die "Can't open file stories.txt"; #open for write, overwrite
print MYOUTFILE "outside"; #works
my $story = ObjectStory->new();
$story->appendToFile(\*MYOUTFILE);
close(MYOUTFILE);
對象,這應該寫入文件:
package ObjectStory;
# constructor
sub ObjectStory::new {
my ($class) = @_;
%hash =();
bless \%hash, $class;
}
# addToFile method
sub ObjectStory::appendToFile {
my ($class, $MYOUTFILE) = @_;
# check if open
if (tell($MYOUTFILE) != -1) {
print $MYOUTFILE
"\n File Handle is not open!"; # File handle is always closed...
}
print $MYOUTFILE "test";
}
# the 1 is necessary, because other scripts will require this Module.
# require MyModule results in true, only if there is a 1 at the end of the module
1;
這是一個***文件句柄*** – Borodin