tags:

views:

55

answers:

1

So I'm running through a list of things and have code that creates an .xml files with IO::File called $doc, then I make a new writer with XML::Writer(OUTPUT => $doc). More code runs and I build a big XML file with XML::Writer. Then, near the end of the file, I find out if I need this file at all. If I do need it, I just:

 $writer->end(); $doc->close(); 

but if I don't need it, what should I enter to just delete all data I've stored/saved and move onto the next file? I tried unlink($docpath) (before and after $doc->close()), the file was not deleted.

+4  A: 

unlink will helpfully set $! and return a false value if no files were deleted. Try:

unlink $docpath or die "Can't delete $docpath: $!";

and you might gain some insight.

friedo
Ah, that dumped me something: Can't find file. Which is really weird because I'm using the exact same $docpath to declare the new file. What's up with that?$docpath = "./test/blah_blah.xml";$doc = new IO::File(">$docpath");then the unlink statement like you have.I even have print statements after declaring $docpath and before unlink, and they are exactly the same. Seriously, wtf?
Sho Minamimoto
Does your script change the working directory between creating the file and trying to delete it? What happens if you change it to an absolute path?
friedo
(working dir never changed)Ok, I sorta figured it out. What I actually did was write a method that had your unlink statement. sub deleteFile($path){unlink $path...} and then I called the method: deleteFile($docpath); This is when things broke. But when I just ran your statement where I put the method call, everything worked. So I must be missing something on declaring or calling subroutines. Do you happen to know what it is?
Sho Minamimoto
Yes, you are declaring the subroutine wrong. Arguments are passed in via the `@_` array. `sub deleteFile { my $file = $_[0]; unlink $file or die $!; }` should do it. You would have discovered this problem much sooner if you were running with `use strict;` and `use warnings;` on. See http://perldoc.perl.org/perlsub.html and http://perldoc.perl.org/strict.html for more.
friedo
***Always*** run with `use strict;` and `use warnings;`. Always.
JSBangs