【发布时间】:2010-03-21 10:55:57
【问题描述】:
我在使用 Perl 将数据写入文件时遇到了一些问题。
sub startNewOrder{
my $name = makeUniqueFileName();
open (ORDER, ">$name.txt") or die "can't open file: $!\n";
format ORDER_TOP =
PRODUCT<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<CODE<<<<<<<<AANTAL<<<<EENHEIDSPRIJS<<<<<<TOTAAL<<<<<<<
.
format ORDER =
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<< @<<<< @<<<<<< @<<<<<
$title, $code, $amount, $price, $total
.
close (ORDER);
}
这是我用来制作文件的子程序。 (我翻译了大部分。)
makeUniqueFileName 方法根据当前时间(“minuteshoursdayOrder”)生成文件名。
现在的问题是我必须在另一个 sub 中写入这个文件。
sub addToOrder{
print "give productcode:";
$code = <STDIN>;
chop $code;
print "Give amount:";
$amount = <STDIN>;
chop $amount;
if($inventory{$code} eq undef){ #Does the product exist?
print "This product does not exist";
}elsif($inventory{$code}[2] < $amount && !defined($inventaris{$code}[2]) ){ #Is there enough in the inventory?
print "There is not enough in stock"
}else{
$inventory{$code}[2] -= $amount;
#write in order file
open (ORDER ">>$naam.txt") or die "can't open file: $!\n";
$title = $inventory{$code}[0];
$code = $code;
$amount = $inventory{$code}[2];
$price = $inventory{$code}[1];
$total = $inventory{$code}[1];
write;
close(ORDER);
}
%inventory 是一个哈希表,其中 productcode 为 key,数组为 title、price 和 amount 作为 value。
这里有两个问题:
当我输入一个无效的产品编号时,我仍然需要输入一个金额,即使我的代码说它应该在检查是否存在具有给定代码的产品后直接打印错误。
第二个问题是写作似乎不起作用。它总是给出“没有这样的文件或目录”错误。有没有办法打开我在第一个 sub 中制作的 ORDER 文件,而不必使 $name 不是本地的?或者只是一种写入这个文件的方法?我真的不知道如何从这里开始。我真的找不到太多关于编写之前已经关闭的文件的信息,并且在不同的子目录中。
感谢任何帮助,
伤害
【问题讨论】:
标签: perl