Opening a file with a variable as name and checking for undefined values
- by Harm De Weirdt
I'm having some problems writing data into a file using 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);
}
This is the sub I use to make the file. (I translated most of it.)
The makeUniqueFileName method makes a fileName based upon current time("minuteshoursdayOrder").
The problem now is that I have to write to this file in another 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 is a hashtable that has the productcode as key and an array with the title, price and amount as value.
There are two problems here:
when I enter an invalid product number, I still have to enter an amount even while my code says it should print the error directly after checking if there is a product with the given code.
The second problem is that the writing doesn't seem to work. It always give's a "No such file or directory" error. Is there a way to open the ORDER file I made in the first sub without having to make $name not local? Or just a way to write in this file? I really don't know how to start here. I can't really find much info on writing a file that has been closed before, and in a different sub.
Any help is appreciated,
Harm