[Kde-perl] listview and filehandles

Rich scriptyrich at yahoo.co.uk
Sun Apr 25 15:12:44 CEST 2004

On Sunday 25 Apr 2004 2:50 am, Edward wrote:
> ok well. heres something really odd. when using the listView in perlqt i
> can no longer close or write to filehandles. they supposedly open fine
> but when i print to them nothing prints and when i close them using
> close FHA or die "cant close $pathname: $!";
> i get cant close /tmp/Adema.Adema: Bad file descriptor at
> /root/ui/form1.pl line 234
>     #    $pathname = "/tmp/Adema.Adema";
>     #    print "Opening file and printing to it\n";
>     #    open(FHA, "> $pathname")    or die "can't open $pathname: $!";
>     #    #flock(FH, LOCK_EX)        or die "can't flock $pathname: $!";
>     #    print FHA "hello there\n"     or die "cant print $pathname: $!";
>     #    close(FHA)            or die "cant close $pathname: $!";

This isn't going to answer your question, but a couple of suggestions:

1) Use a lexical scalar for filehandles.

On modern(ish) perls you can do the following:

open my $fh, ">", $pathname  or die "can't open $pathname: $!";   #<<<<
print $fh "hello there\n"     or die "cant print $pathname: $!";
close $fh                        or die "cant close $pathname: $!";

This is generally a good thing, as it both limits filehandle scope, and closes 
files when the handle goes out of scope, ie:

  open my $fh, ">", $pathname  or die "can't open $pathname: $!";   #<<<<
  print $fh "hello there\n"     or die "cant print $pathname: $!";

}  ## File closes here as $fh goes out of scope.

Its still a good idea to explicitly close files as soon as they're not needed 
however. You never know, that might solve your problem (but probably not).

Also note the three argument form of open is safer than the two argument form. 
perldoc -f open for lots of details (BTW the perlopentut docs for my version 
(5.8.0) seem pretty out of date as the examples dont use lexical scalars for 

2) $pathname = "/tmp/Adema.Adema";

Do you want a temporary file here? If so, you *must* use File::Temp - read the 
docs for the reasons why.

If you actually want to store data between runs, don't put the file in /tmp - 
this is for temporary files, and there's no guarantee when data in /tmp will 
be deleted. 

Instead you could use File::HomeDir to find a suitable directory, then create 
a hidden subdirectory and store data there - this will work on Unix style 
systems, for windows there would be better alternatives but I'm not in a 
position to comment.

3) If you're going to add file locking, make sure you read the docs in detail 
- there are some subtleties that make it easy to get wrong.

Sorry this doesn't answer your question, but it will make the code slightly 
more robust!
scriptyrich at yahoo.co.uk

More information about the Kde-perl mailing list