I need to pass a file descriptor to a function. If this function is defined in package it doesn't work!
I attach a little example.
Why it doesn't works, and how can I make it works?
thanks
use strict; use warnings;
provides a clue:
Bareword "FD" not allowed while "strict subs" in use at main.pl line 14. Bareword "FD" not allowed while "strict subs" in use at main.pl line 15. Execution of main.pl aborted due to compilation errors.
Another clue is provided by using Data::Dumper:
-----><8----- package mypack;
use Data::Dumper;
sub wrstr { print Dumper([EMAIL PROTECTED]); my ($fd, $str) = @_; print $fd "$str\n"; }
1;
package main;
use Data::Dumper;
sub wrstr { print Dumper([EMAIL PROTECTED]); my ($fd, $str) = @_; print $fd "$str\n"; }
open(FD,">","dummy");
wrstr(FD,"12345"); mypack::wrstr(FD,"12345");
close FD;
__END__
$VAR1 = [ 'FD', '12345' ]; $VAR1 = [ 'FD', '12345' ];
While it seems that you are passing file handles to the wrstr functions, perl is actually passing the *string* "FD" to those functions. In the main package this isn't a problem for perl; perl treats the string FD as a symbolic reference. Since there is a file handle in that package (file handles are local to the package in which they are declared) perl is able to resolve the reference. In the 'mypack' package, however, there is no FD handle, so perl cannot resolve it to a file handle. Since warnings are not turned on, perl fails quietly.
You can fix the problem by using a variable to hold a _reference_ to the file handle:
open(my $fd, ">", "dummy"); wrstr($fd, "12345"); mypack::wrstr($fd, "12345"); close $fd;
This is arguably the better approach anyway because it ties the file handle to a lexical variable. When the variable goes out of scope, the reference count on the file handle goes to zero, so the file handle is closed automatically.
Randy.
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>