我正在尝试从文本文件中删除一行.相反,我已经删除了整个文件.有人可以指出错误吗?
removeReservation("john"); sub removeTime() { my $name = shift; open( FILE,"<times.txt" ); @LINES = <FILE>; close(FILE); open( FILE,">times.txt" ); foreach $LINE (@LINES) { print NEWLIST $LINE unless ( $LINE =~ m/$name/ ); } close(FILE); print("Reservation successfully removed.<br/>"); }
示例times.txt文件:
04/15/2012&08:00:00&bob 04/15/2012&08:00:00&john
解决方法
看起来您正在打印到尚未定义的文件句柄.至少你没有在示例代码中定义它.如果启用严格和警告,您将收到以下消息:
Name "main::NEWLIST" used only once: possible typo at remove.pl line 16. print NEWLIST $LINE unless ($LINE =~ m/$name/);
此代码应该适合您:
#!/usr/bin/env perl use strict; use warnings; removeTime( "john" ); sub removeTime { my $name = shift; open( FILE,"<times.txt" ); my @LINES = <FILE>; close( FILE ); open( FILE,">times.txt" ); foreach my $LINE ( @LINES ) { print FILE $LINE unless ( $LINE =~ m/$name/ ); } close( FILE ); print( "Reservation successfully removed.<br/>" ); }
还有几点需要注意:
1)当你的意思是removeTime()时你的示例代码调用removeReservation()
2)除非您打算使用prototypes,否则不要在子程序定义中使用圆括号.请参阅上面的示例.