我已经编写了以下模块作为将我的标量绑定(bind)到特定文件内容的模块:
package Scalar;
use strict;
my $count = 0;
use Carp;
sub TIESCALAR{
print "Inside TIESCALAR function \n";
my $class = shift;
my $filename = shift;
if ( ! -e $filename )
{
croak "Filename : $filename does not exist !";
}
else
{
if ( ! -r $filename || ! -w $filename )
{
croak "Filename : $filename is not readable or writable !";
}
}
$count++;
return \$filename , $class;
}
sub FETCH {
print "Inside FETCH function \n";
my $self = shift;
croak "I am not a class method" unless ref $self;
my $myfile = $$self;
open (FILE , "<$myfile") || die "Can't open the file for read operation $! \n";
flock(FILE,1) || die "Could not apply a shared lock $!";
my @contents = <FILE>;
close FILE;
}
sub STORE {
print "Inside STORE function \n";
my $self = shift;
my $value = shift;
croak "I am not a class method" unless ref $self;
my $myfile = $$self;
open (FILE , ">>$myfile") or die "Can't open the file for write operation $! \n";
flock(FILE,2);
print FILE $value;
close FILE;
}
1;
===============
我调用这个模块的代码如下:
use strict;
use Scalar;
my $file = "test.dat";
my $filevar = undef;
tie ($filevar, "Scalar", $file) or die "Can't tie $!";
print "Trying to retrieve file contents \n";
my $contents = $filevar;
foreach (@{$contents})
{
print "$_";
}
print "Trying to add a line to file \n";
$filevar = "This is a test line added";
print "Reading contents again \n";
$contents = $filevar;
foreach (@$contents)
{
print "$_";
}
当我尝试运行此代码时,出现以下消息:
Inside TIESCALAR function
Trying to retrieve file contents
Trying to add a line to file
Reading contents again
Can't use string ("This is a test line added") as an ARRAY ref while "strict refs" in use at Scalar.pl line 21.
我认为代码不会进入模块的 FETCH 和 STORE 函数。有人可以指出这里的问题是什么吗?
最佳答案
我认为你的问题的根源在于你实际上并没有bless
你的值(value)。
引用一个例子: Automatically call hash values that are subroutine references
我认为您需要将 TIESCALAR
的最后一行更改为:
return bless \$filename, $class;
否则它所做的只是“返回”文件名而不是绑定(bind)它。
我无法完全重现您的问题 - 但我认为您也对您的 FETCH
的隐式返回有问题,它实际上不返回 @contents
而不是 close
的返回码。
我还建议 - 3 个参数 open
很好,特别是当你做这样的事情时,因为否则 FILE
是一个全局的,并且可以被破坏。
关于perl - Perl 中的 Tiescalar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37409536/