Perl 5: Cannot get file handle descriptor -


test.pl:

#!/usr/bin/perl  use warnings;  begin {   *core::global::close = sub (;*) {       @args = @_;       $fileno = fileno($args[0]);       print $fileno, "\n";       core::close(@args);   }; }  use lib '.'; use test; 

test.pm:

package test;  open(xxx, 'test.pl'); close(xxx);  1; 

when run program (perl test.pl), get:

use of uninitialized value $fileno in print @ test.pl line 10.  close() on unopened filehandle 1 @ test.pl line 11. 

where error?

you're passing entire @args array core::close, not file handle. need pass in correct element of array. here's example takes filename command line, , right thing:

use warnings; use strict;  begin {   *core::global::close = sub (;*) {       @args = @_;       $fileno = fileno($args[0]);       print $fileno, "\n";        # next line issue        core::close($args[0]);   }; }  die "need file param" if ! @argv;  $file = $argv[0];  open $fh, $file or die $!;  close $fh or die $!; 

i'll go further have. first, i'm going rejig things override of core function in .pm file instead of test file, i'm going switch using lexical file handles, global bareword ones won't work here:

test.pm:

package test;  begin {    *core::global::close = sub (;*) {       @args = @_;       $fileno = fileno($args[0]);       print $fileno, "\n";       core::close($args[0]);   }; }  1; 

script file:

use warnings; use strict;  use lib '.'; use test;  open $fh, 'test.pl' or die $!; close $fh or die $!; 

between migrating code , using lexical file handles, things should work expect.

output running script:

3 

...and ensure in order, i'll go default configuration, override in test script, not module:

test.pm

package test;  open $fh, 'test.pl' or die $!; close $fh or die $!;  1; 

...and script:

use warnings; use strict;  begin {   *core::global::close = sub (;*) {       @args = @_;       $fileno = fileno($args[0]);       print $fileno, "\n";       core::close($args[0]);   }; }  use lib '.'; use test; 

output:

4 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -