Opening a file with a variable as name and checking for undefined values

Posted by Harm De Weirdt on Stack Overflow See other posts from Stack Overflow or by Harm De Weirdt
Published on 2010-03-21T10:55:57Z Indexed on 2010/03/21 14:11 UTC
Read the original article Hit count: 156

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about perl

Related posts about homework