Perl中的Tiescalar

Perl中的Tiescalar,perl,Perl,我编写了以下模块作为将标量绑定到特定文件内容的模块: 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

我编写了以下模块作为将标量绑定到特定文件内容的模块:

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;
当我尝试运行此代码时,出现以下消息:

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函数中。有人能指出这是什么问题吗?

我认为你的问题的根源在于你实际上没有祝福你的价值观

参考一个例子:

我认为您需要将
TIESCALAR
的最后一行更改为:

return bless \$filename, $class;
否则,它所做的只是“返回”文件名,而不是绑定它

我不能完全重现您的问题-但我认为您在隐式返回
FETCH
时也会遇到问题,它实际上不会返回
@内容
,而是返回
close
的返回代码


我还建议-3参数
open
是好的,尤其是当您执行类似操作时,因为否则
FILE
是一个全局变量,可能会被删除

我在获取代码中添加了这一行:return(\@contents);结果仍然是一样的。每次代码进入获取或存储例程时,我希望它至少打印打印语句。它也没有这样做。
return bless \$filename, $class;