【发布时间】:2011-08-12 13:14:17
【问题描述】:
我有一个问题,将我的数据转换成json,我不知道为什么。
这是一些有效的代码:
#constructor
sub new {
my $class = shift;
my $Titel = shift;
my $Text = shift;
my $Time = localtime;
my $self = {};
$self->{text} = $Text;
$self->{create} = $Time;
$self->{edit} = $Time;
my $json = JSON::XS->new();
open WF, '>> $file' || die "Error : $!";
print WF $json->encode($self)."\n";
close WF;
bless $self, $class;
}
我也创建了一个“对象”并将数据保存在一个文本文件中(通过 JSON)。
我有问题,如果我尝试编辑一些数据:
sub edit {
my $self = shift;
my $Text = shift;
my $ID = shift;
my $Time = localtime;
my $json = JSON::XS->new();
$json->allow_blessed(1);
$self->{text} = $Text; #edit text
$self->{edit} = $Time; # edit date
open INPUT, '< $file' || die "Error : $!";
my @data = <INPUT>;
close(INPUT);
open WF, '> $file' || die "Error : $!";
for (my $Count=0; $Count<=$#data; $Count++){
chomp($data[$Count]);
if($Count == $ID){#if line of data found, who is going to be edited
print WF $json->encode($self)."\n";
}else{
print WF $data[$Count]."\n";
}
}
close WF;
}
我试图做的是只编辑文本文件中的一行..(如果你有更好的主意,请告诉我:D)
我发现我在第一个显示的代码中的过程与那个过程之间没有区别......
它只是在文本文件中写回“null”...
有什么想法吗?
【问题讨论】:
-
您需要在
open的第二个参数周围使用双引号,因为您现在拥有的单引号不会插入$file变量。更好的是使用 3 参数形式open INPUT, '<', $file -
我的问题是,它在行中写回“null” -->print WF $json->encode($self)."\n";
-
“子编辑”是否被称为方法?即“$thing->edit()”?
-
是的。我调试了它,当我调用编辑方法时,$self 是正确的。我也可以在我的程序中编辑值。只有文本文件中的写回不起作用(只需在较低的代码 sn-p! 中它完美地工作)。