我已将以下模块编写为将标量绑定(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进行编码。

参考一个例子:
Automatically call hash values that are subroutine references

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

return bless \$filename, $class;

否则,它要做的就是“返回”文件名而不是绑定(bind)它。

我无法完全重现您的问题-但我认为您也会隐式返回FETCH,而这实际上并没有返回@contents,而是返回了close的返回问题。

我还建议-3个参数open很好,尤其是当您正在执行此类操作时,因为否则FILE是全局变量,可能会被破坏。

关于perl - Tiescalar在Perl,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37409536/

10-12 12:54